qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
47,309
<p>I'm trying to install <a href="http://godi.camlcity.org/godi/index.html" rel="noreferrer">GODI</a> on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.</p> <pre><code>$ ./bootstrap --prefix /home/nlucaroni/godi $ ./bootstrap_stage2 .: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure! </code></pre> <p>I had added the proper directories to the path, and they show up with a quick <code>echo $path</code>, and <code>godi_confdir</code> reported as being:</p> <pre><code> /home/nlucaroni/godi/etc </code></pre> <p>(...and the directory exists, with the godi.conf file present). So, I can't figure out why <code>./bootstrap_stage2</code> isn't working.</p>
[ { "answer_id": 47655, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": false, "text": "<p>What is the output of <code>which godi_confdir</code>?</p>\n\n<p>P.S. I remember having this exact same problem, but I don't remember precisely how I fixed it.</p>\n" }, { "answer_id": 47678, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": true, "text": "<p>Hey Chris, I just figured it out. Silly mistake.</p>\n\n<p>It was just a permission issue, running everything from <code>/tmp/</code> worked fine --well after enabling <code>GODI_BASEPKG_PCRE</code> in <code>godi.conf</code>. I had been running it from my home directory, you forget simple things like that at 3:00am.</p>\n\n<p>--</p>\n\n<p>Actually I'm having another problem. Installing <code>conf-opengl-6</code>:</p>\n\n<p>GODI can't seen to find the <code>GL/gl.h</code> file, though I can --you can see that it is <code>Checking the suggestion</code>.</p>\n\n<pre><code>&gt; ===&gt; Configuring for conf-opengl-6\n&gt; Checking the suggestion\n&gt; Include=/usr/include/GL/gl.h Library=/&lt;GLU+GL&gt;\n&gt; Checking /usr:\n&gt; Include=/usr/include/GL/gl.h Library=/usr/lib/&lt;GLU+GL&gt;\n&gt; Checking /usr:\n&gt; Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/&lt;GLU+GL&gt;\n&gt; Checking /usr/local:\n&gt; Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/&lt;GLU+GL&gt;\n&gt; Exception: Failure \"Cannot find library\".\n&gt; Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code\n&gt; Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code\n\n### Error: Command fails with code 1: godi_console\n</code></pre>\n\n<p><em>edit</em> - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine. </p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157/" ]
I'm trying to install [GODI](http://godi.camlcity.org/godi/index.html) on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing. ``` $ ./bootstrap --prefix /home/nlucaroni/godi $ ./bootstrap_stage2 .: 1: godi_confdir: not found Error: Command fails with code 2: /bin/sh Failure! ``` I had added the proper directories to the path, and they show up with a quick `echo $path`, and `godi_confdir` reported as being: ``` /home/nlucaroni/godi/etc ``` (...and the directory exists, with the godi.conf file present). So, I can't figure out why `./bootstrap_stage2` isn't working.
Hey Chris, I just figured it out. Silly mistake. It was just a permission issue, running everything from `/tmp/` worked fine --well after enabling `GODI_BASEPKG_PCRE` in `godi.conf`. I had been running it from my home directory, you forget simple things like that at 3:00am. -- Actually I'm having another problem. Installing `conf-opengl-6`: GODI can't seen to find the `GL/gl.h` file, though I can --you can see that it is `Checking the suggestion`. ``` > ===> Configuring for conf-opengl-6 > Checking the suggestion > Include=/usr/include/GL/gl.h Library=/<GLU+GL> > Checking /usr: > Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL> > Checking /usr: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Checking /usr/local: > Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL> > Exception: Failure "Cannot find library". > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code > Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code ### Error: Command fails with code 1: godi_console ``` *edit* - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine.
47,329
<p>I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"):</p> <pre><code>"Default.aspx?page=1" "Default.aspx?page=2" "Default.aspx?someother=true&amp;page=2" </code></pre> <p>etc.</p> <p>Is there a simple helper method that I can use in the Render method ... uhmm ... like:</p> <pre><code>Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1"); Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2"); </code></pre> <p>That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&amp;page=2&amp;page=3?</p> <p>Rolling up my own seems like such an unappealing task.</p>
[ { "answer_id": 47344, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 2, "selected": true, "text": "<p>I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,\n /// it is added to the end of the query string\n /// &lt;/summary&gt;\n /// &lt;param name=\"queryString\"&gt;The query string that is to be manipulated&lt;/param&gt;\n /// &lt;param name=\"paramName\"&gt;The name of the parameter&lt;/param&gt;\n /// &lt;param name=\"paramValue\"&gt;The value that the parameter is to be set to&lt;/param&gt;\n /// &lt;returns&gt;The query string with the parameter set to the new value.&lt;/returns&gt;\n public static string SetParameter(string queryString, string paramName, object paramValue)\n {\n //create the regex\n //match paramname=*\n //string regex = String.Format(@\"{0}=[^&amp;]*\", paramName);\n string regex = @\"([&amp;?]{0,1})\" + String.Format(@\"({0}=[^&amp;]*)\", paramName);\n\n RegexOptions options = RegexOptions.RightToLeft;\n // Querystring has parameters...\n if (Regex.IsMatch(queryString, regex, options))\n {\n queryString = Regex.Replace(queryString, regex, String.Format(\"$1{0}={1}\", paramName, paramValue));\n }\n else\n {\n // If no querystring just return the Parameter Key/Value\n if (queryString == String.Empty)\n {\n return String.Format(\"{0}={1}\", paramName, paramValue);\n }\n else\n {\n // Append the new parameter key/value to the end of querystring\n queryString = String.Format(\"{0}&amp;{1}={2}\", queryString, paramName, paramValue);\n }\n }\n return queryString;\n }\n</code></pre>\n\n<p>Obviously you could use the QueryString <code>NameValueCollection</code> property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.</p>\n" }, { "answer_id": 47346, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 0, "selected": false, "text": "<p>Oh and we have this method too that allows you to put in a whole URL string without having to get the querystring out of it</p>\n\n<pre><code>public static string SetParameterInUrl(string url, string paramName, object paramValue)\n{\n int queryStringIndex = url.IndexOf(\"?\");\n string path;\n string queryString;\n if (queryStringIndex &gt;= 0 &amp;&amp; !url.EndsWith(\"?\"))\n {\n path = url.Substring(0, queryStringIndex);\n queryString = url.Substring(queryStringIndex + 1);\n }\n else\n {\n path = url;\n queryString = string.Empty;\n }\n return path + \"?\" + SetParameter(queryString, paramName, paramValue);\n}\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"): ``` "Default.aspx?page=1" "Default.aspx?page=2" "Default.aspx?someother=true&page=2" ``` etc. Is there a simple helper method that I can use in the Render method ... uhmm ... like: ``` Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1"); Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2"); ``` That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3? Rolling up my own seems like such an unappealing task.
I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters ``` /// <summary> /// Set a parameter value in a query string. If the parameter is not found in the passed in query string, /// it is added to the end of the query string /// </summary> /// <param name="queryString">The query string that is to be manipulated</param> /// <param name="paramName">The name of the parameter</param> /// <param name="paramValue">The value that the parameter is to be set to</param> /// <returns>The query string with the parameter set to the new value.</returns> public static string SetParameter(string queryString, string paramName, object paramValue) { //create the regex //match paramname=* //string regex = String.Format(@"{0}=[^&]*", paramName); string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName); RegexOptions options = RegexOptions.RightToLeft; // Querystring has parameters... if (Regex.IsMatch(queryString, regex, options)) { queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue)); } else { // If no querystring just return the Parameter Key/Value if (queryString == String.Empty) { return String.Format("{0}={1}", paramName, paramValue); } else { // Append the new parameter key/value to the end of querystring queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue); } } return queryString; } ``` Obviously you could use the QueryString `NameValueCollection` property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.
47,338
<p>I have a problem with a sample routing with the preview 5 of asp.net mvc.</p> <p>In the AccountController I have 2 actions: </p> <pre><code>public ActionResult Delete() public ActionResult Delete(string username) </code></pre> <p>While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods.</p> <p>The default route in the global.asax hasn't been changed.</p> <p>Shouldn't the action invoker understand what's the method to call looking in the parameters list?</p> <p>Using the preview 4 I hadn't these kind of problem performing the same operation.</p> <p>Any idea?</p>
[ { "answer_id": 47375, "author": "berko", "author_id": 4884, "author_profile": "https://Stackoverflow.com/users/4884", "pm_score": 0, "selected": false, "text": "<p>I can't say for sure why this is happening. But you might want to consider only having the Delete(string username) action and removing the parameter-less overload.</p>\n\n<p>Because string is nullable my understanding is that simply calling Account/Delete will invoke the action with a null username parameter which you can then test for at the beginning of the action method.</p>\n" }, { "answer_id": 47418, "author": "Davide Vosti", "author_id": 1812, "author_profile": "https://Stackoverflow.com/users/1812", "pm_score": 3, "selected": true, "text": "<p>Solution found!</p>\n\n<p>With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute.</p>\n\n<p>Full explanation here: <a href=\"http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx</a></p>\n" }, { "answer_id": 49187, "author": "crucible", "author_id": 3717, "author_profile": "https://Stackoverflow.com/users/3717", "pm_score": 0, "selected": false, "text": "<p>What I'd do is ditch the blank Delete(), and only use Delete(string username)</p>\n\n<p>In your url routing you'd have something similar to \"/{Controller}/{Action}/{username}/\" ?\nIf you have \"/{Controller}/{Action}/{Id}/\" you'd be better off doing Delete(string id) and that way just using the url to handle this \"/Account/Delete/davide/\"</p>\n\n<p>That said use your default route which should be something like the default Id is \"\"</p>\n\n<p>Then in your Delete(string id) method have:</p>\n\n<pre><code>public ActionResult Delete(string id)\n{\n if(string.IsNullOrEmpty(id)) return EmptyID();\n\n // Continue normal Delete method\n}\n\npublic ActionResult EmptyID()\n{\n // The method you were going to have on a blank delete.\n}\n</code></pre>\n\n<p>That or just wrap it up in the one method on an if {} else {}</p>\n\n<p>Either way I'd just be going with the one method and doing a default on your username/id in your route of an empty string and handle it that way.</p>\n\n<p>If you want to contact me on further follow up to what I mean, or whatever will help, ping me at andrew@ my domain on my info page.</p>\n\n<p>Edit: Ah pretty much what Berko said anyway, I'm not sure how Named Attributes would help - so please post a comment here detailing it for other guys who find the same issues! :)</p>\n" }, { "answer_id": 386884, "author": "Aristotle Ucab", "author_id": 31445, "author_profile": "https://Stackoverflow.com/users/31445", "pm_score": 0, "selected": false, "text": "<p>Its ambiguous because the two controller action are the same post method..\nYou can only used that in form posting scenario for example you are submitting a form data that uses HTTP post..</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1812/" ]
I have a problem with a sample routing with the preview 5 of asp.net mvc. In the AccountController I have 2 actions: ``` public ActionResult Delete() public ActionResult Delete(string username) ``` While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods. The default route in the global.asax hasn't been changed. Shouldn't the action invoker understand what's the method to call looking in the parameters list? Using the preview 4 I hadn't these kind of problem performing the same operation. Any idea?
Solution found! With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute. Full explanation here: <http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx>
47,363
<p>What is the command to list all triggers in a MySQL database?</p>
[ { "answer_id": 47364, "author": "Harry", "author_id": 4704, "author_profile": "https://Stackoverflow.com/users/4704", "pm_score": 9, "selected": true, "text": "<p>The command for listing all triggers is:</p>\n\n<pre><code>show triggers;\n</code></pre>\n\n<p>or you can access the <code>INFORMATION_SCHEMA</code> table directly by:</p>\n\n<pre><code>select trigger_schema, trigger_name, action_statement\nfrom information_schema.triggers\n</code></pre>\n\n<ul>\n<li>You can do this from version 5.0.10 onwards.</li>\n<li>More information about the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/triggers-table.html\" rel=\"noreferrer\"><code>TRIGGERS</code> table is here</a>.</li>\n</ul>\n" }, { "answer_id": 7257460, "author": "sunil", "author_id": 921665, "author_profile": "https://Stackoverflow.com/users/921665", "pm_score": 4, "selected": false, "text": "<p>For showing a particular trigger in a particular schema you can try the following:</p>\n\n<pre><code>select * from information_schema.triggers where \ninformation_schema.triggers.trigger_name like '%trigger_name%' and \ninformation_schema.triggers.trigger_schema like '%data_base_name%'\n</code></pre>\n" }, { "answer_id": 7710970, "author": "Kainda", "author_id": 987431, "author_profile": "https://Stackoverflow.com/users/987431", "pm_score": 4, "selected": false, "text": "<p>You can use below to find a particular trigger definition.</p>\n\n<pre><code>SHOW TRIGGERS LIKE '%trigger_name%'\\G\n</code></pre>\n\n<p>or the below to show all the triggers in the database. It will work for MySQL 5.0 and above.</p>\n\n<pre><code>SHOW TRIGGERS\\G\n</code></pre>\n" }, { "answer_id": 18782762, "author": "Pragnesh Karia", "author_id": 1027670, "author_profile": "https://Stackoverflow.com/users/1027670", "pm_score": 4, "selected": false, "text": "<p>I hope following code will give you more information.</p>\n\n<pre><code>select * from information_schema.triggers where \ninformation_schema.triggers.trigger_schema like '%your_db_name%'\n</code></pre>\n\n<p>This will give you total 22 Columns in <strong>MySQL version: 5.5.27</strong> and Above</p>\n\n<pre><code>TRIGGER_CATALOG \nTRIGGER_SCHEMA\nTRIGGER_NAME\nEVENT_MANIPULATION\nEVENT_OBJECT_CATALOG\nEVENT_OBJECT_SCHEMA \nEVENT_OBJECT_TABLE\nACTION_ORDER\nACTION_CONDITION\nACTION_STATEMENT\nACTION_ORIENTATION\nACTION_TIMING\nACTION_REFERENCE_OLD_TABLE\nACTION_REFERENCE_NEW_TABLE\nACTION_REFERENCE_OLD_ROW\nACTION_REFERENCE_NEW_ROW\nCREATED \nSQL_MODE\nDEFINER \nCHARACTER_SET_CLIENT\nCOLLATION_CONNECTION\nDATABASE_COLLATION\n</code></pre>\n" }, { "answer_id": 68823913, "author": "user14570900", "author_id": 14570900, "author_profile": "https://Stackoverflow.com/users/14570900", "pm_score": 1, "selected": false, "text": "<p>You can use MySQL Workbench:\nConnect to the MySQL Server\nSelect DB</p>\n<ul>\n<li>tables</li>\n<li>on the table name line click the edit icon (looks like a work tool)</li>\n<li>in the table edit window - Click the tab &quot;Triggers&quot;</li>\n<li>on the Triggers list click th eTrigger name to get its source code</li>\n</ul>\n" }, { "answer_id": 69413373, "author": "Leon Gomez", "author_id": 17055440, "author_profile": "https://Stackoverflow.com/users/17055440", "pm_score": 0, "selected": false, "text": "<p>This sentence could contribute to solving the problem:</p>\n<pre><code>select LOWER(concat('delimiter |', '\\n', 'create trigger %data_base_name%.', TRIGGER_NAME, '\\n', \n' ', ACTION_TIMING, ' ', EVENT_MANIPULATION, ' on %data_base_name%.', EVENT_OBJECT_TABLE, ' for each row', '\\n',\nACTION_STATEMENT, '\\n',\n'|')) AS TablaTriggers from information_schema.triggers where \ninformation_schema.triggers.trigger_schema like '%data_base_name%'\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4704/" ]
What is the command to list all triggers in a MySQL database?
The command for listing all triggers is: ``` show triggers; ``` or you can access the `INFORMATION_SCHEMA` table directly by: ``` select trigger_schema, trigger_name, action_statement from information_schema.triggers ``` * You can do this from version 5.0.10 onwards. * More information about the [`TRIGGERS` table is here](http://dev.mysql.com/doc/refman/5.0/en/triggers-table.html).
47,374
<p>Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this:</p> <p>User -> MessageDetail &lt;- Message &lt;- MessageCategory</p> <p>MessageDetail is a join table that also contains an IsRead flag.</p> <p>The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code:</p> <pre><code>protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var db = new DataContext(); // parse the input strings from the web form int categoryIDFilter; DateTime dateFilter; string catFilterString = MessagesCategoryFilter.SelectedValue; string dateFilterString = MessagesDateFilter.SelectedValue; // TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"): // DateTime.MinValue for dates, 0 for int DateTime.TryParse(dateFilterString, out dateFilter); Int32.TryParse(catFilterString, out categoryIDFilter); bool showRead = MessagesReadFilter.Checked; var messages = from detail in db.MessageDetails where detail.UserID == (int)Session["UserID"] where detail.Message.IsPublished where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0) where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue) // is unread, showRead filter is on, or message was marked read today where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today orderby detail.Message.PublishDate descending group detail by detail.Message.MessageCategory into categories orderby categories.Key.Name select new { MessageCategory = categories.Key, MessageDetails = categories.Select(d =&gt; d) }; e.Result = messages; } </code></pre> <p>This code <em>works</em>, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. </p> <p>It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data?</p> <p>Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated.</p>
[ { "answer_id": 47383, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>Regardless of LINQ, I think that mixing presentation code with database-relaed code is not a good idea. I would create a simple DB abstraction layer on top of LINQ queries. In my opinion LINQ is just a convenient tool, that doesn't have a serious impact on traditional application design.</p>\n" }, { "answer_id": 130400, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": true, "text": "<p>All your LINQ querys should be in a <strong>business logic class</strong>, no change from older methodologies like ADO.</p>\n\n<p>If you are a <strong>purist</strong> you should always return List(of T) from your methods in the business class, in fact, the datacontext should only be visible to the business classes.\nThen you can manipulate the list in the user interface.</p>\n\n<p>If you are a <strong>pragmatist</strong>, you can return a IQueryable object and make some manipulations in the user interface.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160/" ]
Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this: User -> MessageDetail <- Message <- MessageCategory MessageDetail is a join table that also contains an IsRead flag. The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code: ``` protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e) { var db = new DataContext(); // parse the input strings from the web form int categoryIDFilter; DateTime dateFilter; string catFilterString = MessagesCategoryFilter.SelectedValue; string dateFilterString = MessagesDateFilter.SelectedValue; // TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"): // DateTime.MinValue for dates, 0 for int DateTime.TryParse(dateFilterString, out dateFilter); Int32.TryParse(catFilterString, out categoryIDFilter); bool showRead = MessagesReadFilter.Checked; var messages = from detail in db.MessageDetails where detail.UserID == (int)Session["UserID"] where detail.Message.IsPublished where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0) where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue) // is unread, showRead filter is on, or message was marked read today where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today orderby detail.Message.PublishDate descending group detail by detail.Message.MessageCategory into categories orderby categories.Key.Name select new { MessageCategory = categories.Key, MessageDetails = categories.Select(d => d) }; e.Result = messages; } ``` This code *works*, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data? Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated.
All your LINQ querys should be in a **business logic class**, no change from older methodologies like ADO. If you are a **purist** you should always return List(of T) from your methods in the business class, in fact, the datacontext should only be visible to the business classes. Then you can manipulate the list in the user interface. If you are a **pragmatist**, you can return a IQueryable object and make some manipulations in the user interface.
47,400
<p>With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).</p> <p>One of the main issues with testing forms is that only a few controls have a <code>hwnd</code> handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.</p> <p>Any experience to share?</p>
[ { "answer_id": 47404, "author": "Knox", "author_id": 4873, "author_profile": "https://Stackoverflow.com/users/4873", "pm_score": 2, "selected": false, "text": "<p>I would design the application to have as much work as possible done in queries and in vba subroutines so that your testing could be made up of populating test databases, running sets of the production queries and vba against those databases and then looking at the output and comparing to make sure the output is good. This approach doesn't test the GUI obviously, so you could augment the testing with a series of test scripts (here I mean like a word document that says open form 1, and click control 1) that are manually executed.</p>\n\n<p>It depends on the scope of the project as the level of automation necessary for the testing aspect.</p>\n" }, { "answer_id": 47407, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "<p>I have not tried this, but you could attempt to <a href=\"http://office.microsoft.com/en-us/access/HA101314691033.aspx\" rel=\"nofollow noreferrer\">publish your access forms as data access web pages to something like sharepoint</a> or <a href=\"http://office.microsoft.com/en-us/access/HA010547311033.aspx\" rel=\"nofollow noreferrer\">just as web pages</a> and then use an tool such as <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">selenium</a> to drive the browser with a suite of tests.</p>\n\n<p>Obviously this is not as ideal as driving the code directly through unit tests, but it may get you part of the way. good luck</p>\n" }, { "answer_id": 67541, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": -1, "selected": false, "text": "<p>Data Access Pages have been deprecated by MS for quite some time, and never really worked in the first place (they were dependent on the Office Widgets being installed, and worked only in IE, and only badly then).</p>\n\n<p>It is true that Access controls that can get focus only have a window handle when they have the focus (and those that can't get focus, such as labels, never have a window handle at all). This makes Access singularly inappropriate to window handle-driven testing regimes.</p>\n\n<p>Indeed, I question why you want to do this kind of testing in Access. It sounds to me like your basic Extreme Programming dogma, and not all of the principles and practices of XP can be adapted to work with Access applications -- square peg, round hole.</p>\n\n<p>So, step back and ask yourself what you're trying to accomplish and consider that you may need to utilize completely different methods than those that are based on the approaches that just can't work in Access.</p>\n\n<p>Or whether that kind of automated testing is valid at all or even useful with an Access application.</p>\n" }, { "answer_id": 69026, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Access is a COM application. Use COM, not Windows API. to test things in Access.</p>\n\n<p>The best Test environment for an Access Application is Access. All of your Forms/Reports/Tables/Code/Queries are available, there is a scripting language similar to MS Test (Ok, you probably don't remember MS Test), there is database environment for holding your test scripts and test results, and the skills you build here are transferable to your application.</p>\n" }, { "answer_id": 70572, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 4, "selected": false, "text": "<p>I appreciated knox's and david's answers. My answer will be somewhere between theirs: just make <strong><em>forms that do not need to be debugged</em></strong>!</p>\n\n<p>I think that forms should be exclusively used as what they are basically, meaning graphic interface <strong><em>only</em></strong>, meaning here that they do not have to be debugged! The debugging job is then limited to your VBA modules and objects, which is a lot easier to handle. </p>\n\n<p>There is of course a natural tendency to add VBA code to forms and/or controls, specially when Access offers you these great \"after Update\" and \"on change\" events, but I definitely advise you <strong>not</strong> to put any form or control specific code in the form's module. This makes further maintenance and upgrade very costy, where your code is split between VBA modules and forms/controls modules.</p>\n\n<p>This does not mean you cannot use anymore this <code>AfterUpdate</code> event! Just put standard code in the event, like this:</p>\n\n<pre><code>Private Sub myControl_AfterUpdate() \n CTLAfterUpdate myControl\n On Error Resume Next\n Eval (\"CTLAfterUpdate_MyForm()\")\n On Error GoTo 0 \nEnd sub\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li><p><code>CTLAfterUpdate</code> is a standard procedure run each time a control is updated in a form</p></li>\n<li><p><code>CTLAfterUpdateMyForm</code> is a specific procedure run each time a control is updated on MyForm</p></li>\n</ul>\n\n<p>I have then 2 modules. The first one is </p>\n\n<ul>\n<li><code>utilityFormEvents</code><br>\n where I will have my CTLAfterUpdate generic event</li>\n</ul>\n\n<p>The second one is </p>\n\n<ul>\n<li><code>MyAppFormEvents</code><br>\n containing the specific code of all specific forms of the MyApp application\n and including the CTLAfterUpdateMyForm procedure. Of course, CTLAfterUpdateMyForm\n might not exist if there are no specific code to run. This is why we turn the \n \"On error\" to \"resume next\" ...</li>\n</ul>\n\n<p>Choosing such a generic solution means a lot. It means you are reaching a high level of code normalization (meaning painless maintenance of code). And when you say that you do not have any form-specific code, it also means that form modules are fully standardized, and their production can be <strong><em>automated</em></strong>: just say which events you want to manage at the form/control level, and define your generic/specific procedures terminology.<br>\nWrite your automation code, once for all.<br>\nIt takes a few days of work but it give exciting results. I have been using this solution for the last 2 years and it is clearly the right one: my forms are fully and automatically created from scratch with a \"Forms Table\", linked to a \"Controls Table\".<br>\nI can then spend my time working on the specific procedures of the form, if any.</p>\n\n<p>Code normalization, even with MS Access, is a long process. But it is really worth the pain!</p>\n" }, { "answer_id": 74393, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "<p>Another advantage of <a href=\"https://stackoverflow.com/questions/47400/best-way-to-test-a-ms-access-application#69026\">Access being a COM application</a> is that you can create an <a href=\"http://support.microsoft.com/kb/317114/en-us\" rel=\"nofollow noreferrer\">.NET application to run and test an Access application via Automation</a>. The advantage of this is that then you can use a more powerful testing framework such as <a href=\"http://www.nunit.org/index.php\" rel=\"nofollow noreferrer\">NUnit</a> to write automated assert tests against an Access app. </p>\n\n<p>Therefore, if you are proficient in either C# or VB.NET combined with something like NUnit then you can more easily create greater test coverage for your Access app.</p>\n" }, { "answer_id": 74492, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 2, "selected": false, "text": "<p>If your interested in testing your Access application at a more granular level specifically the VBA code itself then <a href=\"http://vb-lite-unit.sourceforge.net/\" rel=\"nofollow noreferrer\">VB Lite Unit</a> is a great unit testing framework for that purpose.</p>\n" }, { "answer_id": 1015027, "author": "Steve Mallory", "author_id": 120097, "author_profile": "https://Stackoverflow.com/users/120097", "pm_score": 2, "selected": false, "text": "<p>There are good suggestions here, but I'm surprised no one mentioned centralized error processing. You can get addins that allow for quick function/sub templating and for adding line numbers (I use MZ-tools). Then send all errors to a single function where you can log them. You can also then break on all errors by setting a single break point.</p>\n" }, { "answer_id": 6959038, "author": "mwolfe02", "author_id": 154439, "author_profile": "https://Stackoverflow.com/users/154439", "pm_score": 3, "selected": false, "text": "<p>I've taken a page out of <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow noreferrer\">Python's doctest</a> concept and implemented a DocTests procedure in Access VBA. This is obviously not a full-blown unit-testing solution. It's still relatively young, so I doubt I've worked out all the bugs, but I think it's mature enough to release into the wild.</p>\n\n<p>Just copy the following code into a standard code module and press F5 inside the Sub to see it in action:</p>\n\n<pre><code>'&gt;&gt;&gt; 1 + 1\n'2\n'&gt;&gt;&gt; 3 - 1\n'0\nSub DocTests()\nDim Comp As Object, i As Long, CM As Object\nDim Expr As String, ExpectedResult As Variant, TestsPassed As Long, TestsFailed As Long\nDim Evaluation As Variant\n For Each Comp In Application.VBE.ActiveVBProject.VBComponents\n Set CM = Comp.CodeModule\n For i = 1 To CM.CountOfLines\n If Left(Trim(CM.Lines(i, 1)), 4) = \"'&gt;&gt;&gt;\" Then\n Expr = Trim(Mid(CM.Lines(i, 1), 5))\n On Error Resume Next\n Evaluation = Eval(Expr)\n If Err.Number = 2425 And Comp.Type &lt;&gt; 1 Then\n 'The expression you entered has a function name that '' can't find.\n 'This is not surprising because we are not in a standard code module (Comp.Type &lt;&gt; 1).\n 'So we will just ignore it.\n GoTo NextLine\n ElseIf Err.Number &lt;&gt; 0 Then\n Debug.Print Err.Number, Err.Description, Expr\n GoTo NextLine\n End If\n On Error GoTo 0\n ExpectedResult = Trim(Mid(CM.Lines(i + 1, 1), InStr(CM.Lines(i + 1, 1), \"'\") + 1))\n Select Case ExpectedResult\n Case \"True\": ExpectedResult = True\n Case \"False\": ExpectedResult = False\n Case \"Null\": ExpectedResult = Null\n End Select\n Select Case TypeName(Evaluation)\n Case \"Long\", \"Integer\", \"Short\", \"Byte\", \"Single\", \"Double\", \"Decimal\", \"Currency\"\n ExpectedResult = Eval(ExpectedResult)\n Case \"Date\"\n If IsDate(ExpectedResult) Then ExpectedResult = CDate(ExpectedResult)\n End Select\n If (Evaluation = ExpectedResult) Then\n TestsPassed = TestsPassed + 1\n ElseIf (IsNull(Evaluation) And IsNull(ExpectedResult)) Then\n TestsPassed = TestsPassed + 1\n Else\n Debug.Print Comp.Name; \": \"; Expr; \" evaluates to: \"; Evaluation; \" Expected: \"; ExpectedResult\n TestsFailed = TestsFailed + 1\n End If\n End If\nNextLine:\n Next i\n Next Comp\n Debug.Print \"Tests passed: \"; TestsPassed; \" of \"; TestsPassed + TestsFailed\nEnd Sub\n</code></pre>\n\n<p>Copying, pasting, and running the above code from a module named Module1 yields:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Module: 3 - 1 evaluates to: 2 Expected: 0 \nTests passed: 1 of 2\n</code></pre>\n\n<p>A few quick notes:</p>\n\n<ul>\n<li>It has no dependencies (when used from within Access)</li>\n<li>It makes use of <code>Eval</code> which is a function in the Access.Application object model; this means you <em>could</em> use it outside of Access but it would require creating an Access.Application object and fully qualifying the <code>Eval</code> calls</li>\n<li>There are some <a href=\"https://stackoverflow.com/questions/6440912/ms-access-vba-brain-teaser\">idiosyncrasies associated with <code>Eval</code></a> to be aware of</li>\n<li>It can only be used on functions that return a result that fits on a single line</li>\n</ul>\n\n<p>Despite its limitations, I still think it provides quite a bit of bang for your buck. </p>\n\n<p><strong>Edit</strong>: Here is a simple function with \"doctest rules\" the function must satisfy.</p>\n\n<pre><code>Public Function AddTwoValues(ByVal p1 As Variant, _\n ByVal p2 As Variant) As Variant\n'&gt;&gt;&gt; AddTwoValues(1,1)\n'2\n'&gt;&gt;&gt; AddTwoValues(1,1) = 1\n'False\n'&gt;&gt;&gt; AddTwoValues(1,Null)\n'Null\n'&gt;&gt;&gt; IsError(AddTwoValues(1,\"foo\"))\n'True\n\nOn Error GoTo ErrorHandler\n\n AddTwoValues = p1 + p2\n\nExitHere:\n On Error GoTo 0\n Exit Function\n\nErrorHandler:\n AddTwoValues = CVErr(Err.Number)\n GoTo ExitHere\nEnd Function\n</code></pre>\n" }, { "answer_id": 21731961, "author": "paulroho", "author_id": 571213, "author_profile": "https://Stackoverflow.com/users/571213", "pm_score": 3, "selected": false, "text": "<p>Although that being a very old answer:</p>\n\n<p>There is <a href=\"http://accunit.access-codelib.net\" rel=\"noreferrer\">AccUnit</a>, a specialized Unit-Test framework for Microsoft Access.</p>\n" }, { "answer_id": 28347000, "author": "RubberDuck", "author_id": 3198973, "author_profile": "https://Stackoverflow.com/users/3198973", "pm_score": 6, "selected": true, "text": "<h1>1. Write Testable Code</h1>\n\n<p>First, stop writing business logic into your Form's code behind. That's not the place for it. It can't be properly tested there. In fact, you really shouldn't have to test your form itself at all. It should be a dead dumb simple view that responds to User Interaction and then delegates responsibility for responding to those actions to another class that <strong><em>is</em></strong> testable.</p>\n\n<p>How do you do that? Familiarizing yourself with the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\">Model-View-Controller pattern</a> is a good start. </p>\n\n<p><img src=\"https://i.stack.imgur.com/iY37U.png\" alt=\"Model View Controller diagram\"></p>\n\n<p>It can't be done <em>perfectly</em> in VBA due to the fact that we get either events or interfaces, never both, but you can get pretty close. Consider this simple form that has a text box and a button.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ts6jl.png\" alt=\"simple form with text box and button\"></p>\n\n<p>In the form's code behind, we'll wrap the TextBox's value in a public property and re-raise any events we're interested in.</p>\n\n<pre><code>Public Event OnSayHello()\nPublic Event AfterTextUpdate()\n\nPublic Property Let Text(value As String)\n Me.TextBox1.value = value\nEnd Property\n\nPublic Property Get Text() As String\n Text = Me.TextBox1.value\nEnd Property\n\nPrivate Sub SayHello_Click()\n RaiseEvent OnSayHello\nEnd Sub\n\nPrivate Sub TextBox1_AfterUpdate()\n RaiseEvent AfterTextUpdate\nEnd Sub\n</code></pre>\n\n<p>Now we need a model to work with. Here I've created a new class module named <code>MyModel</code>. Here lies the code we'll put under test. Note that it naturally shares a similar structure as our view.</p>\n\n<pre><code>Private mText As String\nPublic Property Let Text(value As String)\n mText = value\nEnd Property\n\nPublic Property Get Text() As String\n Text = mText\nEnd Property\n\nPublic Function Reversed() As String\n Dim result As String\n Dim length As Long\n\n length = Len(mText)\n\n Dim i As Long\n For i = 0 To length - 1\n result = result + Mid(mText, (length - i), 1)\n Next i\n\n Reversed = result\nEnd Function\n\nPublic Sub SayHello()\n MsgBox Reversed()\nEnd Sub\n</code></pre>\n\n<p>Finally, our controller wires it all together. The controller listens for form events and communicates changes to the model and triggers the model's routines.</p>\n\n<pre><code>Private WithEvents view As Form_Form1\nPrivate model As MyModel\n\nPublic Sub Run()\n Set model = New MyModel\n Set view = New Form_Form1\n view.Visible = True\nEnd Sub\n\nPrivate Sub view_AfterTextUpdate()\n model.Text = view.Text\nEnd Sub\n\nPrivate Sub view_OnSayHello()\n model.SayHello\n view.Text = model.Reversed()\nEnd Sub\n</code></pre>\n\n<p>Now this code can be run from any other module. For the purposes of this example, I've used a standard module. I highly encourage you to build this yourself using the code I've provided and see it function.</p>\n\n<pre><code>Private controller As FormController\n\nPublic Sub Run()\n Set controller = New FormController\n controller.Run\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>So, that's great and all <strong><em>but what does it have to do with testing?!</em></strong> Friend, it has <strong><em>everything</em></strong> to do with testing. What we've done is make our code <em>testable</em>. In the example I've provided, there is no reason what-so-ever to even try to test the GUI. The only thing we really need to test is the <code>model</code>. That's where all of the real logic is. </p>\n\n<p>So, on to step two.</p>\n\n<h1>2. Choose a Unit Testing Framework</h1>\n\n<p>There aren't a lot of options here. Most frameworks require installing COM Add-ins, lots of boiler plate, weird syntax, writing tests as comments, etc. That's why I got involved in <a href=\"https://github.com/rubberduck-vba/Rubberduck\" rel=\"noreferrer\">building one myself</a>, so this part of my answer isn't impartial, but I'll try to give a fair summary of what's available.</p>\n\n<ol>\n<li><p><a href=\"http://accunit.access-codelib.net/\" rel=\"noreferrer\">AccUnit</a></p>\n\n<ul>\n<li>Works only in Access.</li>\n<li>Requires you to write tests as a strange hybrid of comments and code. (no intellisense for the comment part.</li>\n<li>There <strong><em>is</em></strong> a graphical interface to help you write those strange looking tests though.</li>\n<li>The project has not seen any updates since 2013.</li>\n</ul></li>\n<li><p><a href=\"http://vb-lite-unit.sourceforge.net/\" rel=\"noreferrer\">VB Lite Unit</a>\nI can't say I've personally used it. It's out there, but hasn't seen an update since 2005.</p></li>\n<li><p><a href=\"http://xlvbadevtools.codeplex.com/\" rel=\"noreferrer\">xlUnit</a>\nxlUnit isn't awful, but it's not good either. It's clunky and there's lots of boiler plate code. It's the best of the worst, but it doesn't work in Access. So, that's out.</p></li>\n<li><p>Build your own framework</p>\n\n<p>I've <a href=\"https://codereview.stackexchange.com/questions/62781/unit-testing-in-vba\">been there and done that</a>. It's probably more than most people want to get into, but it is completely possible to build a Unit Testing framework in Native VBA code.</p></li>\n<li><p><a href=\"https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing\" rel=\"noreferrer\">Rubberduck VBE Add-In's Unit Testing Framework</a><br>\n<em>Disclaimer: I'm one of the co-devs</em>.</p>\n\n<p>I'm biased, but this is by far my favorite of the bunch.</p>\n\n<ul>\n<li>Little to no boiler plate code.</li>\n<li>Intellisense is available.</li>\n<li>The project is active.</li>\n<li>More documentation than most of these projects.</li>\n<li>It works in most of the major office applications, not just Access.</li>\n<li>It is, unfortunately, a COM Add-In, so it has to be installed onto your machine.</li>\n</ul></li>\n</ol>\n\n<h1>3. Start writing tests</h1>\n\n<p>So, back to our code from section 1. The only code that we <em>really</em> needed to test was the <code>MyModel.Reversed()</code> function. So, let's take a look at what that test could look like. (Example given uses Rubberduck, but it's a simple test and could translate into the framework of your choice.)</p>\n\n<pre><code>'@TestModule\nPrivate Assert As New Rubberduck.AssertClass\n\n'@TestMethod\nPublic Sub ReversedReversesCorrectly()\n\nArrange:\n Dim model As New MyModel\n Const original As String = \"Hello\"\n Const expected As String = \"olleH\"\n Dim actual As String\n\n model.Text = original\n\nAct:\n actual = model.Reversed\n\nAssert:\n Assert.AreEqual expected, actual\n\nEnd Sub\n</code></pre>\n\n<h2>Guidelines for Writing Good Tests</h2>\n\n<ol>\n<li>Only test one thing at a time.</li>\n<li>Good tests only fail when there is a bug introduced into the system or the requirements have changed.</li>\n<li>Don't include external dependencies such as databases and file systems. These external dependencies can make tests fail for reasons outside of your control. Secondly, they slow your tests down. If your tests are slow, you won't run them.</li>\n<li>Use test names that describe what the test is testing. Don't worry if it gets long. It's most important that it is descriptive.</li>\n</ol>\n\n<hr>\n\n<p>I know that answer was a little long, and late, but hopefully it helps some people get started in writing unit tests for their VBA code.</p>\n" }, { "answer_id": 32775460, "author": "AndrewM", "author_id": 3133514, "author_profile": "https://Stackoverflow.com/users/3133514", "pm_score": 2, "selected": false, "text": "<p>I find that there are relatively few opportunities for unit testing in my applications. Most of the code that I write interacts with table data or the filing system so is fundamentally hard to unit test. Early on, I tried an approach that may be similar to mocking (spoofing) where I created code that had an optional parameter. If the parameter was used, then the procedure would use the parameter instead of fetching data from the database. It is quite easy to set up a user defined type that has the same field types as a row of data and to pass that to a function. I now have a way of getting test data into the procedure that I want to test. Inside each procedure there was some code that swapped out the real data source for the test data source. This allowed me to use unit testing on a wider variety of function, using my own unit testing functions. Writing unit test is easy, it is just repetitive and boring. In the end, I gave up with unit tests and started using a different approach.</p>\n\n<p>I write in-house applications for myself mainly so I can afford wait till issues find me rather than having to have perfect code. If I do write applications for customers, generally the customer is not fully aware of how much software development costs so I need a low cost way of getting results. Writing unit tests is all about writing a test that pushes bad data at a procedure to see if the procedure can handle it appropriately. Unit tests also confirm that good data is handled appropriately. My current approach is based on writing input validation into every procedure within an application and raising a success flag when the code has completed successfully. Each calling procedure checks for the success flag before using the result. If an issue occurs, it is reported by way of an error message. Each function has a success flag, a return value, an error message, a comment and an origin. A user defined type (fr for function return) contains the data members. Any given function many populate only some of the data members in the user defined type. When a function is run, it usually returns success = true and a return value and sometimes a comment. If a function fails, it returns success = false and an error message. If a chain of functions fails, the error messages are daisy changed but the result is actually a lot more readable that a normal stack trace. The origins are also chained so I know where the issue occurred. The application rarely crashes and accurately reports any issues. The result is a hell of a lot better than standard error handling. </p>\n\n<pre><code>Public Function GetOutputFolder(OutputFolder As eOutputFolder) As FunctRet\n\n '///Returns a full path when provided with a target folder alias. e.g. 'temp' folder\n\n Dim fr As FunctRet\n\n Select Case OutputFolder\n Case 1\n fr.Rtn = \"C:\\Temp\\\"\n fr.Success = True\n Case 2\n fr.Rtn = TrailingSlash(Application.CurrentProject.path)\n fr.Success = True\n Case 3\n fr.EM = \"Can't set custom paths – not yet implemented\"\n Case Else\n fr.EM = \"Unrecognised output destination requested\"\n End Select\n\n exitproc:\n GetOutputFolder = fr\n\n End Function\n</code></pre>\n\n<p>Code explained.\neOutputFolder is a user defined Enum as below</p>\n\n<pre><code>Public Enum eOutputFolder\n eDefaultDirectory = 1\n eAppPath = 2\n eCustomPath = 3\nEnd Enum\n</code></pre>\n\n<p>I am using Enum for passing parameters to functions as this creates a limited set of known choices that a function can accept. Enums also provide intellisense when entering parameters into functions. I suppose they provide a rudimentary interface for a function.</p>\n\n<pre><code>'Type FunctRet is used as a generic means of reporting function returns\nPublic Type FunctRet\n Success As Long 'Boolean flag for success, boolean not used to avoid nulls\n Rtn As Variant 'Return Value\n EM As String 'Error message\n Cmt As String 'Comments\n Origin As String 'Originating procedure/function\nEnd Type\n</code></pre>\n\n<p>A user defined type such as a FunctRet also provides code completion which helps. Within the procedure, I usually store internal results to an anonymous internal variable (fr) before assigning the results to the return variable (GetOutputFolder). This makes renaming procedures very easy as only the top and bottom have be changed. </p>\n\n<p>So in summary, I have developed a framework with ms-access that covers all operations that involve VBA. The testing is permanently written into the procedures, rather than a development time unit test. In practice, the code still runs very fast. I am very careful to optimise lower level functions that can be called ten thousand times a minute. Furthermore, I can use the code in production as it is being developed. If an error occurs, it is user friendly and the source and reason for the error are usually obvious. Errors are reported from the calling form, not from some module in the business layer, which is an important principal of application design. Furthermore, I don't have the burden of maintaining unit testing code, which is really important when I am evolving a design rather than coding a clearly conceptualised design. </p>\n\n<p>There are some potential issues. The testing is not automated and new bad code is only detected when the application is run. The code does not look like standard VBA code (it is usually shorter). Still, the approach has some advantages. It is far better that using an error handler just to log an error as the users will usually contact me and give me a meaningful error message. It can also handle procedures that work with external data. JavaScript reminds me of VBA, I wonder why JavaScript is the land of frameworks and VBA in ms-access is not.</p>\n\n<p>A few days after writing this post, I found an <a href=\"http://www.codeproject.com/Articles/1032569/Handling-Errors-and-Exceptions-Part-Intro\" rel=\"nofollow\">article on The CodeProject</a> that comes close to what I have written above. The article compares and contrasts exception handling and error handling. What I have suggested above is akin to exception handling.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3811/" ]
With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007). One of the main issues with testing forms is that only a few controls have a `hwnd` handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on. Any experience to share?
1. Write Testable Code ====================== First, stop writing business logic into your Form's code behind. That's not the place for it. It can't be properly tested there. In fact, you really shouldn't have to test your form itself at all. It should be a dead dumb simple view that responds to User Interaction and then delegates responsibility for responding to those actions to another class that ***is*** testable. How do you do that? Familiarizing yourself with the [Model-View-Controller pattern](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) is a good start. ![Model View Controller diagram](https://i.stack.imgur.com/iY37U.png) It can't be done *perfectly* in VBA due to the fact that we get either events or interfaces, never both, but you can get pretty close. Consider this simple form that has a text box and a button. ![simple form with text box and button](https://i.stack.imgur.com/ts6jl.png) In the form's code behind, we'll wrap the TextBox's value in a public property and re-raise any events we're interested in. ``` Public Event OnSayHello() Public Event AfterTextUpdate() Public Property Let Text(value As String) Me.TextBox1.value = value End Property Public Property Get Text() As String Text = Me.TextBox1.value End Property Private Sub SayHello_Click() RaiseEvent OnSayHello End Sub Private Sub TextBox1_AfterUpdate() RaiseEvent AfterTextUpdate End Sub ``` Now we need a model to work with. Here I've created a new class module named `MyModel`. Here lies the code we'll put under test. Note that it naturally shares a similar structure as our view. ``` Private mText As String Public Property Let Text(value As String) mText = value End Property Public Property Get Text() As String Text = mText End Property Public Function Reversed() As String Dim result As String Dim length As Long length = Len(mText) Dim i As Long For i = 0 To length - 1 result = result + Mid(mText, (length - i), 1) Next i Reversed = result End Function Public Sub SayHello() MsgBox Reversed() End Sub ``` Finally, our controller wires it all together. The controller listens for form events and communicates changes to the model and triggers the model's routines. ``` Private WithEvents view As Form_Form1 Private model As MyModel Public Sub Run() Set model = New MyModel Set view = New Form_Form1 view.Visible = True End Sub Private Sub view_AfterTextUpdate() model.Text = view.Text End Sub Private Sub view_OnSayHello() model.SayHello view.Text = model.Reversed() End Sub ``` Now this code can be run from any other module. For the purposes of this example, I've used a standard module. I highly encourage you to build this yourself using the code I've provided and see it function. ``` Private controller As FormController Public Sub Run() Set controller = New FormController controller.Run End Sub ``` --- So, that's great and all ***but what does it have to do with testing?!*** Friend, it has ***everything*** to do with testing. What we've done is make our code *testable*. In the example I've provided, there is no reason what-so-ever to even try to test the GUI. The only thing we really need to test is the `model`. That's where all of the real logic is. So, on to step two. 2. Choose a Unit Testing Framework ================================== There aren't a lot of options here. Most frameworks require installing COM Add-ins, lots of boiler plate, weird syntax, writing tests as comments, etc. That's why I got involved in [building one myself](https://github.com/rubberduck-vba/Rubberduck), so this part of my answer isn't impartial, but I'll try to give a fair summary of what's available. 1. [AccUnit](http://accunit.access-codelib.net/) * Works only in Access. * Requires you to write tests as a strange hybrid of comments and code. (no intellisense for the comment part. * There ***is*** a graphical interface to help you write those strange looking tests though. * The project has not seen any updates since 2013. 2. [VB Lite Unit](http://vb-lite-unit.sourceforge.net/) I can't say I've personally used it. It's out there, but hasn't seen an update since 2005. 3. [xlUnit](http://xlvbadevtools.codeplex.com/) xlUnit isn't awful, but it's not good either. It's clunky and there's lots of boiler plate code. It's the best of the worst, but it doesn't work in Access. So, that's out. 4. Build your own framework I've [been there and done that](https://codereview.stackexchange.com/questions/62781/unit-testing-in-vba). It's probably more than most people want to get into, but it is completely possible to build a Unit Testing framework in Native VBA code. 5. [Rubberduck VBE Add-In's Unit Testing Framework](https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing) *Disclaimer: I'm one of the co-devs*. I'm biased, but this is by far my favorite of the bunch. * Little to no boiler plate code. * Intellisense is available. * The project is active. * More documentation than most of these projects. * It works in most of the major office applications, not just Access. * It is, unfortunately, a COM Add-In, so it has to be installed onto your machine. 3. Start writing tests ====================== So, back to our code from section 1. The only code that we *really* needed to test was the `MyModel.Reversed()` function. So, let's take a look at what that test could look like. (Example given uses Rubberduck, but it's a simple test and could translate into the framework of your choice.) ``` '@TestModule Private Assert As New Rubberduck.AssertClass '@TestMethod Public Sub ReversedReversesCorrectly() Arrange: Dim model As New MyModel Const original As String = "Hello" Const expected As String = "olleH" Dim actual As String model.Text = original Act: actual = model.Reversed Assert: Assert.AreEqual expected, actual End Sub ``` Guidelines for Writing Good Tests --------------------------------- 1. Only test one thing at a time. 2. Good tests only fail when there is a bug introduced into the system or the requirements have changed. 3. Don't include external dependencies such as databases and file systems. These external dependencies can make tests fail for reasons outside of your control. Secondly, they slow your tests down. If your tests are slow, you won't run them. 4. Use test names that describe what the test is testing. Don't worry if it gets long. It's most important that it is descriptive. --- I know that answer was a little long, and late, but hopefully it helps some people get started in writing unit tests for their VBA code.
47,402
<p>Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.</p> <p>Example input and output:</p> <pre><code>&gt;&gt;&gt; reverse_words("this is a string") 'string a is this' </code></pre> <p>It should be O(N) time and O(1) space (<code>split()</code> and pushing on / popping off the stack are not allowed).</p> <p>The puzzle is taken from <a href="http://halcyon.usc.edu/~kiran/msqs.html#programming" rel="noreferrer" title="Microsoft Interview Questions">here</a>.</p>
[ { "answer_id": 47416, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>In pseudo code:</p>\n\n<pre><code>reverse input string\nreverse each word (you will need to find word boundaries)\n</code></pre>\n" }, { "answer_id": 47419, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Push each word onto a stack. Pop all the words off the stack.</p>\n" }, { "answer_id": 47423, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 1, "selected": false, "text": "<p>In C: (C99)</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nvoid reverseString(char* string, int length)\n{\n char swap;\n for (int i = 0; i &lt; length/2; i++)\n {\n swap = string[length - 1 - i];\n string[length - 1 - i] = string[i];\n string[i] = swap;\n } \n}\n\nint main (int argc, const char * argv[]) {\n char teststring[] = &quot;Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.&quot;;\n printf(&quot;%s\\n&quot;, teststring);\n int length = strlen(teststring);\n reverseString(teststring, length);\n int i = 0;\n while (i &lt; length)\n {\n int wordlength = strspn(teststring + i, &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;);\n reverseString(teststring + i, wordlength);\n i += wordlength + 1;\n }\n printf(&quot;%s\\n&quot;, teststring);\n return 0;\n}\n</code></pre>\n<p>This gives output:</p>\n<blockquote>\n<p>Given an array of characters which\nform a sentence of words, give an\nefficient algorithm to reverse the\norder of the words (not characters) in\nit.</p>\n<p>.it in )characters not( words the\nof order the reverse to algorithm\nefficient an give ,words of sentence a\nform which characters of array an\nGiven</p>\n</blockquote>\n<p>This takes at most 4N time, with small constant space.\nUnfortunately, It doesn't handle punctuation or case gracefully.</p>\n" }, { "answer_id": 47424, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "<p>O(N) in space and O(N) in time solution in Python:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def reverse_words_nosplit(str_):\n \"\"\"\n &gt;&gt;&gt; f = reverse_words_nosplit\n &gt;&gt;&gt; f(\"this is a string\")\n 'string a is this'\n \"\"\"\n iend = len(str_)\n s = \"\"\n while True:\n ispace = str_.rfind(\" \", 0, iend)\n if ispace == -1:\n s += str_[:iend]\n break\n s += str_[ispace+1:iend]\n s += \" \"\n iend = ispace\n return s\n</code></pre>\n" }, { "answer_id": 47426, "author": "Thomas Watnedal", "author_id": 4059, "author_profile": "https://Stackoverflow.com/users/4059", "pm_score": 6, "selected": true, "text": "<p>A solution in C/C++:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void swap(char* str, int i, int j){\n char t = str[i];\n str[i] = str[j];\n str[j] = t;\n}\n\nvoid reverse_string(char* str, int length){\n for(int i=0; i&lt;length/2; i++){\n swap(str, i, length-i-1);\n }\n}\nvoid reverse_words(char* str){\n int l = strlen(str);\n //Reverse string\n reverse_string(str,strlen(str));\n int p=0;\n //Find word boundaries and reverse word by word\n for(int i=0; i&lt;l; i++){\n if(str[i] == ' '){\n reverse_string(&amp;str[p], i-p);\n p=i+1;\n }\n }\n //Finally reverse the last word.\n reverse_string(&amp;str[p], l-p);\n}\n</code></pre>\n\n<p>This should be O(n) in time and O(1) in space.</p>\n\n<p>Edit: Cleaned it up a bit.</p>\n\n<p>The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.</p>\n" }, { "answer_id": 47434, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 1, "selected": false, "text": "<p>You would use what is known as an iterative recursive function, which is O(N) in time as it takes N (N being the number of words) iterations to complete and O(1) in space as each iteration holds its own state within the function arguments. </p>\n\n<pre class=\"lang-scm prettyprint-override\"><code>(define (reverse sentence-to-reverse)\n (reverse-iter (sentence-to-reverse \"\"))\n\n(define (reverse-iter(sentence, reverse-sentence)\n (if (= 0 string-length sentence)\n reverse-sentence\n ( reverse-iter( remove-first-word(sentence), add-first-word(sentence, reverse-sentence)))\n</code></pre>\n\n<p><em>Note: I have written this in scheme which I am a complete novice, so apologies for lack of correct string manipulation.</em></p>\n\n<p>remove-first-word finds the first word boundary of sentence, then takes that section of characters (including space and punctuation) and removes it and returns new sentence</p>\n\n<p>add-first-word finds the first word boundary of sentence, then takes that section of characters (including space and punctuation) and adds it to reverse-sentence and returns new reverse-sentence contents.</p>\n" }, { "answer_id": 47435, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>A C++ solution:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\nusing namespace std;\n\nstring revwords(string in) {\n string rev;\n int wordlen = 0;\n for (int i = in.length(); i &gt;= 0; --i) {\n if (i == 0 || iswspace(in[i-1])) {\n if (wordlen) {\n for (int j = i; wordlen--; )\n rev.push_back(in[j++]);\n wordlen = 0;\n }\n if (i &gt; 0)\n rev.push_back(in[i-1]);\n }\n else\n ++wordlen;\n }\n return rev;\n}\n\nint main() {\n cout &lt;&lt; revwords(\"this is a sentence\") &lt;&lt; \".\" &lt;&lt; endl;\n cout &lt;&lt; revwords(\" a sentence with extra spaces \") &lt;&lt; \".\" &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 47445, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>pushing a string onto a stack and then popping it off - is that still O(1)?\nessentially, that is the same as using split()...</p>\n\n<p>Doesn't O(1) mean in-place? This task gets easy if we can just append strings and stuff, but that uses space...</p>\n\n<p><strong>EDIT</strong>: Thomas Watnedal is right. The following algorithm is O(n) in time and O(1) in space:</p>\n\n<ol>\n<li>reverse string in-place (first iteration over string)</li>\n<li>reverse each (reversed) word in-place (another two iterations over string)\n\n<ol>\n<li>find first word boundary</li>\n<li>reverse inside this word boundary</li>\n<li>repeat for next word until finished</li>\n</ol></li>\n</ol>\n\n<p>I guess we would need to prove that step 2 is really only O(2n)...</p>\n" }, { "answer_id": 47455, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<pre><code>using System;\n\nnamespace q47407\n{\n class MainClass\n {\n public static void Main(string[] args)\n {\n string s = Console.ReadLine();\n string[] r = s.Split(' ');\n for(int i = r.Length-1 ; i &gt;= 0; i--)\n Console.Write(r[i] + \" \");\n Console.WriteLine();\n\n }\n }\n}\n</code></pre>\n\n<p>edit: i guess i should read the whole question... carry on.</p>\n" }, { "answer_id": 47509, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;string&gt;\n#include &lt;boost/next_prior.hpp&gt;\n\nvoid reverse(std::string&amp; foo) {\n using namespace std;\n std::reverse(foo.begin(), foo.end());\n string::iterator begin = foo.begin();\n while (1) {\n string::iterator space = find(begin, foo.end(), ' ');\n std::reverse(begin, space);\n begin = boost::next(space);\n if (space == foo.end())\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 47565, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "<p>@Daren Thomas</p>\n\n<p>Implementation of your algorithm (O(N) in time, O(1) in space) in D (Digital Mars): </p>\n\n<pre><code>#!/usr/bin/dmd -run\n/**\n * to compile &amp; run:\n * $ dmd -run reverse_words.d\n * to optimize:\n * $ dmd -O -inline -release reverse_words.d\n */\nimport std.algorithm: reverse;\nimport std.stdio: writeln;\nimport std.string: find;\n\nvoid reverse_words(char[] str) {\n // reverse whole string\n reverse(str);\n\n // reverse each word\n for (auto i = 0; (i = find(str, \" \")) != -1; str = str[i + 1..length])\n reverse(str[0..i]);\n\n // reverse last word\n reverse(str);\n}\n\nvoid main() {\n char[] str = cast(char[])(\"this is a string\");\n writeln(str);\n reverse_words(str);\n writeln(str);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre>this is a string\nstring a is this</pre>\n" }, { "answer_id": 78071, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>in Ruby</p>\n\n<blockquote>\n <blockquote>\n <p>\"this is a string\".split.reverse.join(\" \")</p>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 1010975, "author": "Demi", "author_id": 67985, "author_profile": "https://Stackoverflow.com/users/67985", "pm_score": 0, "selected": false, "text": "<p>in C#, in-place, O(n), and tested:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static char[] ReverseAllWords(char[] in_text)\n{\n int lindex = 0;\n int rindex = in_text.Length - 1;\n if (rindex &gt; 1)\n {\n //reverse complete phrase\n in_text = ReverseString(in_text, 0, rindex);\n\n //reverse each word in resultant reversed phrase\n for (rindex = 0; rindex &lt;= in_text.Length; rindex++)\n {\n if (rindex == in_text.Length || in_text[rindex] == ' ')\n {\n in_text = ReverseString(in_text, lindex, rindex - 1);\n lindex = rindex + 1;\n }\n }\n }\n return in_text;\n}\n\nstatic char[] ReverseString(char[] intext, int lindex, int rindex)\n{\n char tempc;\n while (lindex &lt; rindex)\n {\n tempc = intext[lindex];\n intext[lindex++] = intext[rindex];\n intext[rindex--] = tempc;\n }\n return intext;\n}\n</code></pre>\n" }, { "answer_id": 1011107, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Efficient in terms of my time: took under 2 minutes to write in REBOL:</p>\n\n<pre><code>reverse_words: func [s [string!]] [form reverse parse s none]\n</code></pre>\n\n<p>Try it out:\n reverse_words \"this is a string\"\n \"string a is this\"</p>\n" }, { "answer_id": 3337552, "author": "Anurag", "author_id": 165737, "author_profile": "https://Stackoverflow.com/users/165737", "pm_score": 0, "selected": false, "text": "<p>A Ruby solution.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code># Reverse all words in string\ndef reverse_words(string)\n return string if string == ''\n\n reverse(string, 0, string.size - 1)\n\n bounds = next_word_bounds(string, 0)\n\n while bounds.all? { |b| b &lt; string.size }\n reverse(string, bounds[:from], bounds[:to])\n bounds = next_word_bounds(string, bounds[:to] + 1)\n end\n\n string\nend\n\n# Reverse a single word between indices \"from\" and \"to\" in \"string\"\ndef reverse(s, from, to)\n half = (from - to) / 2 + 1\n\n half.times do |i|\n s[from], s[to] = s[to], s[from]\n from, to = from.next, to.next\n end\n\n s\nend\n\n# Find the boundaries of the next word starting at index \"from\"\ndef next_word_bounds(s, from)\n from = s.index(/\\S/, from) || s.size\n to = s.index(/\\s/, from + 1) || s.size\n\n return { from: from, to: to - 1 }\nend\n</code></pre>\n" }, { "answer_id": 3711850, "author": "Shivkrish22", "author_id": 401275, "author_profile": "https://Stackoverflow.com/users/401275", "pm_score": 2, "selected": false, "text": "<p>Here is my answer. No library calls and no temp data structures.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nvoid reverse(char* string, int length){\n int i;\n for (i = 0; i &lt; length/2; i++){\n string[length - 1 - i] ^= string[i] ;\n string[i] ^= string[length - 1 - i];\n string[length - 1 - i] ^= string[i];\n } \n}\n\nint main () {\nchar string[] = \"This is a test string\";\nchar *ptr;\nint i = 0;\nint word = 0;\nptr = (char *)&amp;string;\nprintf(\"%s\\n\", string);\nint length=0;\nwhile (*ptr++){\n ++length;\n}\nreverse(string, length);\nprintf(\"%s\\n\", string);\n\nfor (i=0;i&lt;length;i++){\n if(string[i] == ' '){\n reverse(&amp;string[word], i-word);\n word = i+1;\n }\n} \nreverse(&amp;string[word], i-word); //for last word \nprintf(\"\\n%s\\n\", string);\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 23667400, "author": "vran freelancer", "author_id": 1092823, "author_profile": "https://Stackoverflow.com/users/1092823", "pm_score": 0, "selected": false, "text": "<p>This problem can be solved with O(n) in time and O(1) in space. The sample code looks as mentioned below:</p>\n\n<pre><code> public static string reverseWords(String s)\n {\n\n char[] stringChar = s.ToCharArray();\n int length = stringChar.Length, tempIndex = 0;\n\n Swap(stringChar, 0, length - 1);\n\n for (int i = 0; i &lt; length; i++)\n {\n if (i == length-1)\n {\n Swap(stringChar, tempIndex, i);\n tempIndex = i + 1;\n }\n else if (stringChar[i] == ' ')\n {\n Swap(stringChar, tempIndex, i-1);\n tempIndex = i + 1;\n }\n }\n\n return new String(stringChar);\n }\n\n private static void Swap(char[] p, int startIndex, int endIndex)\n {\n while (startIndex &lt; endIndex)\n {\n p[startIndex] ^= p[endIndex];\n p[endIndex] ^= p[startIndex];\n p[startIndex] ^= p[endIndex];\n startIndex++;\n endIndex--;\n }\n }\n</code></pre>\n" }, { "answer_id": 27279070, "author": "aady", "author_id": 2047752, "author_profile": "https://Stackoverflow.com/users/2047752", "pm_score": 0, "selected": false, "text": "<p>A one liner:</p>\n\n<pre><code>l=\"Is this as expected ??\"\n\" \".join(each[::-1] for each in l[::-1].split())\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>'?? expected as this Is'\n</code></pre>\n" }, { "answer_id": 27602891, "author": "zoha khan", "author_id": 3209871, "author_profile": "https://Stackoverflow.com/users/3209871", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Algorithm:\n 1).Reverse each word of the string.\n 2).Reverse resultant String.</p>\n</blockquote>\n\n<pre><code>public class Solution {\npublic String reverseWords(String p) {\n String reg=\" \";\n if(p==null||p.length()==0||p.equals(\"\"))\n{\n return \"\";\n}\nString[] a=p.split(\"\\\\s+\");\nStringBuilder res=new StringBuilder();;\nfor(int i=0;i&lt;a.length;i++)\n{\n\n String temp=doReverseString(a[i]);\n res.append(temp);\n res.append(\" \");\n}\nString resultant=doReverseString(res.toString());\nSystem.out.println(res);\nreturn resultant.toString().replaceAll(\"^\\\\s+|\\\\s+$\", \"\"); \n}\n\n\npublic String doReverseString(String s)`{`\n\n\nchar str[]=s.toCharArray();\nint start=0,end=s.length()-1;\nwhile(start&lt;end)\n{\nchar temp=str[start];\nstr[start]=str[end];\nstr[end]=temp;\nstart++;\nend--;\n}\nString a=new String(str);\nreturn a;\n\n}\n\npublic static void main(String[] args)\n{\nSolution r=new Solution();\nString main=r.reverseWords(\"kya hua\");\n//System.out.println(re);\nSystem.out.println(main);\n}\n}\n</code></pre>\n" }, { "answer_id": 37529508, "author": "Himanshu Mahajan", "author_id": 1624283, "author_profile": "https://Stackoverflow.com/users/1624283", "pm_score": 0, "selected": false, "text": "<p>The algorithm to solve this problem is based on two steps process, first step will reverse the individual words of string,then in second step, reverse whole string. Implementation of algorithm will take O(n) time and O(1) space complexity.</p>\n\n<pre><code> #include &lt;stdio.h&gt;\n #include &lt;string.h&gt;\n\n void reverseStr(char* s, int start, int end);\n\n int main()\n {\n char s[] = \"This is test string\";\n\n int start = 0;\n int end = 0;\n int i = 0;\n\n while (1) {\n\n if (s[i] == ' ' || s[i] == '\\0')\n {\n reverseStr(s, start, end-1);\n start = i + 1;\n end = start;\n }\n else{\n end++;\n }\n\n if(s[i] == '\\0'){\n break;\n }\n i++;\n }\n\n reverseStr(s, 0, strlen(s)-1);\n printf(\"\\n\\noutput= %s\\n\\n\", s);\n\n return 0;\n }\n\n void reverseStr(char* s, int start, int end)\n {\n char temp;\n int j = end;\n int i = start;\n\n for (i = start; i &lt; j ; i++, j--) {\n temp = s[i];\n s[i] = s[j];\n s[j] = temp;\n }\n }\n</code></pre>\n" }, { "answer_id": 37877392, "author": "Sundara Moorthy Anandh", "author_id": 6477821, "author_profile": "https://Stackoverflow.com/users/6477821", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p><strong><em>THIS PROGRAM IS TO REVERSE THE SENTENCE USING POINTERS IN \"C language\" By Vasantha kumar &amp; Sundaramoorthy from KONGU ENGG COLLEGE, Erode.</em></strong></p>\n</blockquote>\n\n<p><strong>NOTE</strong>: Sentence must end with <strong>dot(.)</strong>\n because NULL character is not assigned automatically\n at the end of the sentence*</p>\n\n<pre><code> #include&lt;stdio.h&gt;\n #include&lt;string.h&gt;\n\nint main()\n{\nchar *p,*s=\"this is good.\",*t;\nint i,j,a,l,count=0;\n\nl=strlen(s);\n\np=&amp;s[l-1];\n\nt=&amp;s[-1];\nwhile(*t)\n {\n if(*t==' ')\n count++;\n t++;\n }\n a=count;\n while(l!=0)\n {\nfor(i=0;*p!=' '&amp;&amp;t!=p;p--,i++);\n p++;\n\n for(;((*p)!='.')&amp;&amp;(*p!=' ');p++)\n printf(\"%c\",*p);\n printf(\" \");\n if(a==count)\n {\n p=p-i-1;\n l=l-i;\n }\n else\n {\n p=p-i-2;\n l=l-i-1;\n }\n\ncount--;\n }\n\nreturn 0; \n}\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. Example input and output: ``` >>> reverse_words("this is a string") 'string a is this' ``` It should be O(N) time and O(1) space (`split()` and pushing on / popping off the stack are not allowed). The puzzle is taken from [here](http://halcyon.usc.edu/~kiran/msqs.html#programming "Microsoft Interview Questions").
A solution in C/C++: ```cpp void swap(char* str, int i, int j){ char t = str[i]; str[i] = str[j]; str[j] = t; } void reverse_string(char* str, int length){ for(int i=0; i<length/2; i++){ swap(str, i, length-i-1); } } void reverse_words(char* str){ int l = strlen(str); //Reverse string reverse_string(str,strlen(str)); int p=0; //Find word boundaries and reverse word by word for(int i=0; i<l; i++){ if(str[i] == ' '){ reverse_string(&str[p], i-p); p=i+1; } } //Finally reverse the last word. reverse_string(&str[p], l-p); } ``` This should be O(n) in time and O(1) in space. Edit: Cleaned it up a bit. The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.
47,413
<p>It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?</p>
[ { "answer_id": 47431, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 2, "selected": true, "text": "<p>The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine.</p>\n\n<pre><code>select * \nfrom table \nwhere account+time in (select account+max(time) \n from table \n group by account \n order by time) \n</code></pre>\n" }, { "answer_id": 47443, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 2, "selected": false, "text": "<p>could you not do:</p>\n\n<pre><code>select account,last(value),max(time)\nfrom table\ngroup by account\n</code></pre>\n\n<p>I tested this (granted for a very small, almost trivial record set) and it produced proper results.</p>\n\n<p>Edit:</p>\n\n<p>that also doesn't work after some more testing. I did a fair bit of access programming in a past life and feel like there is a way to do what your asking in 1 query, but im drawing a blank at the moment. sorry.</p>\n" }, { "answer_id": 47456, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 1, "selected": false, "text": "<p>This is a good trick for returning the last record in a table: </p>\n\n<pre><code>SELECT TOP 1 * FROM TableName ORDER BY Time DESC \n</code></pre>\n\n<p>Check out <a href=\"http://www.quackit.com/sql/tutorial/sql_top.cfm\" rel=\"nofollow noreferrer\">this site</a> for more info.</p>\n" }, { "answer_id": 47502, "author": "Knox", "author_id": 4873, "author_profile": "https://Stackoverflow.com/users/4873", "pm_score": 0, "selected": false, "text": "<p>@shs<br>\nyes, that select last(value) SHOULD work, but it doesn't... My understanding although I can't produce an authorative source is that the last(value) gives the last physical record in the access file, which means it could be the first one timewise but the last one physically. So I don't think you should use last(value) for anything other than a really bad random row.</p>\n" }, { "answer_id": 47511, "author": "Knox", "author_id": 4873, "author_profile": "https://Stackoverflow.com/users/4873", "pm_score": 1, "selected": false, "text": "<p>@Tom\nIt might be easier for me in general to do the \"In\" query that you've suggested. Generally I do something like</p>\n\n<pre><code>select T1.account, T1.value\nfrom table T as T1\nwhere T1 = (select max(T2.time) from table T as T2 where T1.account = T2.Account) \n</code></pre>\n" }, { "answer_id": 86354, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Perhaps the following SQL is clumsy, but it seems to work correctly in Access. </p>\n\n<pre><code>SELECT\n a.account,\n a.time,\n a.value\nFROM\n tablename AS a INNER JOIN [\n SELECT\n account,\n Max(time) AS MaxOftime\n FROM\n tablename\n GROUP BY\n account\n ]. AS b\n ON\n (a.time = b.MaxOftime)\n AND (a.account = b.account)\n;\n</code></pre>\n" }, { "answer_id": 447895, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm trying to find the latest date in a group using the Access 2003 query builder, and ran into the same problem trying to use LAST for a date field. But it looks like using MAX finds the lates date.</p>\n" }, { "answer_id": 17624209, "author": "pghcpa", "author_id": 149572, "author_profile": "https://Stackoverflow.com/users/149572", "pm_score": 2, "selected": false, "text": "<p>After literally years of searching I finally found the answer at the link below #3. The sub-queries above will work, but are very slow -- debilitatingly slow for my purposes.</p>\n\n<p>The more popular answer is a tri-level query: 1st level finds the max, 2nd level gets the field values based on the 1st query. The result is then joined in as a table to the main query. Fast but complicated and time-consuming to code/maintain.</p>\n\n<p>This link works, still runs pretty fast and is a lot less work to code/maintain. Thanks to the authors of this site.</p>\n\n<p><a href=\"http://access.mvps.org/access/queries/qry0020.htm\" rel=\"nofollow\">http://access.mvps.org/access/queries/qry0020.htm</a></p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4873/" ]
It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?
The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine. ``` select * from table where account+time in (select account+max(time) from table group by account order by time) ```
47,433
<p>Consider the following 2 queries:</p> <pre><code>select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null </code></pre> <p>Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.</p>
[ { "answer_id": 47439, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>From my observations, MSSQL server produces same query plan for these queries.</p>\n" }, { "answer_id": 47448, "author": "Mike Polen", "author_id": 212, "author_profile": "https://Stackoverflow.com/users/212", "pm_score": 0, "selected": false, "text": "<p>I created a simple query similar to the ones in the question on MSSQL2005 and the explain plans were different. The first query appears to be faster. I am not a SQL expert but the estimated explain plan had 37% for query 1 and 63% for the query 2. It appears that the biggest cost for query 2 is the join. Both queries had two table scans.</p>\n" }, { "answer_id": 47449, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 5, "selected": true, "text": "<p>RDBMSs \"rewrite\" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most \"good\" databases.</p>\n\n<p>I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity.</p>\n" }, { "answer_id": 48255, "author": "andy47", "author_id": 2661, "author_profile": "https://Stackoverflow.com/users/2661", "pm_score": 2, "selected": false, "text": "<p>I second Tom's answer that you should pick the one that is easier to understand and maintain.</p>\n\n<p>The query plan of any query in any database cannot be predicted because you haven't given us indexes or data distributions. The only way to predict which is faster is to run them against <em>your</em> database.</p>\n\n<p>As a rule of thumb I tend to use sub-selects when I do not need to include any columns from tblB in my select clause. I would definitely go for a sub-select when I want to use the 'in' predicate (and usually for the 'not in' that you included in the question), for the simple reason that these are easier to understand when you or someone else has come back and change them. </p>\n" }, { "answer_id": 57744, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 1, "selected": false, "text": "<p>The first query will be faster in SQL Server which I think is slighty counter intuitive - Sub queries <em>seem</em> like they should be slower. In some cases (as data volumes increase) an <code>exists</code> may be faster than an <code>in</code>.</p>\n" }, { "answer_id": 64443, "author": "Andy Irving", "author_id": 8553, "author_profile": "https://Stackoverflow.com/users/8553", "pm_score": 2, "selected": false, "text": "<p>non-correlated sub queries are fine. you should go with what describes the data you're wanting. as has been noted, this likely gets rewritten into the same plan, but isn't guaranteed to! what's more, if table A and B are not 1:1 you will get duplicate tuples from the join query (as the IN clause performs an implicit DISTINCT sort), so it's always best to code what you want and actually think about the outcome.</p>\n" }, { "answer_id": 64982, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>It should be noted that these queries will produce different results if TblB.a is not unique.</p>\n" }, { "answer_id": 70363, "author": "Piotr Anders", "author_id": 11377, "author_profile": "https://Stackoverflow.com/users/11377", "pm_score": 2, "selected": false, "text": "<p>Well, it depends on the datasets. From my experience, if You have small dataset then go for a NOT IN if it's large go for a LEFT JOIN. The NOT IN clause seems to be very slow on large datasets.</p>\n\n<p>One other thing I might add is that the explain plans might be misleading. I've seen several queries where explain was sky high and the query run under 1s. On the other hand I've seen queries with excellent explain plan and they could run for hours.</p>\n\n<p>So all in all do test on your data and see for yourself.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
Consider the following 2 queries: ``` select tblA.a,tblA.b,tblA.c,tblA.d from tblA where tblA.a not in (select tblB.a from tblB) select tblA.a,tblA.b,tblA.c,tblA.d from tblA left outer join tblB on tblA.a = tblB.a where tblB.a is null ``` Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.
RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases. I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity.
47,447
<p>I am trying to create a horizontal menu with the elements represented by <code>&lt;span&gt;</code>'s. The menu itself (parent <code>&lt;div&gt;</code>) has a fixed width, but the elements number is always different.</p> <p>I would like to have child <code>&lt;span&gt;</code>'s of the same width, independently of how many of them are there.</p> <p>What I've done so far: added a <code>float: left;</code> style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent <code>&lt;div&gt;</code>, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine.</p> <p>What else could I try?</p> <p>It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.</p>
[ { "answer_id": 47465, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 2, "selected": false, "text": "<p>If you have a fixed width container, then you are losing some of the effectiveness of a percentage width child span.</p>\n\n<p>For your case of 33% you could add a class to the first and every 4th child span to set the correct width as necessary.</p>\n\n<pre><code>&lt;div&gt;\n&lt;span class=\"first-in-row\"&gt;/&lt;span&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;span class=\"first-in-row\"&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;&lt;/span&gt;...\n&lt;/div&gt;\n</code></pre>\n\n<p>where </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.first-in-row { width:auto; /* or */ width:XXX px; }\n</code></pre>\n" }, { "answer_id": 47466, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "<p>You might try a table with a fixed table layout. It should calculate the column widths without concerning itself with the cell contents.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>table.ClassName {\n table-layout: fixed\n}\n</code></pre>\n" }, { "answer_id": 47474, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 0, "selected": false, "text": "<p>have you tried the decimal values, like setting width to 33.33%?</p>\n\n<p>As specified in the CSS syntax, the width property (<a href=\"http://www.w3.org/TR/CSS21/visudet.html#the-width-property\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS21/visudet.html#the-width-property</a>) can be given as &lt;percentage&gt; (<a href=\"http://www.w3.org/TR/CSS21/syndata.html#value-def-percentage\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS21/syndata.html#value-def-percentage</a>), which is stated to be a &lt;number&gt;.</p>\n\n<p>As said at the number definition (<a href=\"http://www.w3.org/TR/CSS21/syndata.html#value-def-number\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS21/syndata.html#value-def-number</a>), there some value types that must be integers, and are stated as &lt;integer&gt;, and the others are real numbers, stated as &lt;number&gt;. The percentage is defined as &lt;number&gt;, not as &lt;integer&gt; so it might work.</p>\n\n<p>It will depend on the browser's ability to solve this situation if it can't divide the parent's box by 3 without remaining, will it draw a 1- or 2-pixel space, or make 1 or 2 spans out of three wider than the rest.</p>\n" }, { "answer_id": 47492, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>In reference to Xian's answer, there's also the :first-child pseudo-element. Rather than having first-in-row class, you'd have this.</p>\n\n<pre><code>span:first-child {\n width: auto;\n}\n</code></pre>\n\n<p>Obviously, this is only applicable to a single line menu.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3894/" ]
I am trying to create a horizontal menu with the elements represented by `<span>`'s. The menu itself (parent `<div>`) has a fixed width, but the elements number is always different. I would like to have child `<span>`'s of the same width, independently of how many of them are there. What I've done so far: added a `float: left;` style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent `<div>`, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine. What else could I try? It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.
You might try a table with a fixed table layout. It should calculate the column widths without concerning itself with the cell contents. ```css table.ClassName { table-layout: fixed } ```
47,475
<p>If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?</p> <p>ie </p> <pre><code>[Test] public void ShouldValidateUserNameIsLessThan100Characters() {} </code></pre> <p>verse </p> <pre><code>[Test] public void UserNameTestValidation1() {} </code></pre>
[ { "answer_id": 47477, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 1, "selected": false, "text": "<p>i wouldn't put conditions that test needs to meet in the name, because conditions may change in time. in your example, i'd recommend naming like</p>\n\n<pre><code>UserNameLengthValidate()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>UserNameLengthTest()\n</code></pre>\n\n<p>or something similar to explain what the test does, but not presuming the testing/validation parameters.</p>\n" }, { "answer_id": 47478, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 5, "selected": true, "text": "<p>The name of any method should make it clear what it does.</p>\n\n<p>IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put \"100\" in the name, as that's very likely to change. What about:</p>\n\n<pre><code>public void validateUserNameLength()\n</code></pre>\n\n<p>If the test changes, the name should be updated accordingly. </p>\n" }, { "answer_id": 47479, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>I think if one can not find a good concise name for a test method it's a sign that design of this test is incorrect. Also good method name helps you to find out what happened in less time.</p>\n" }, { "answer_id": 47480, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>The name needs to matter within reason. I don't want an email from the build saying that test 389fb2b5-28ad3 failed, but just knowing that it was a UserName test as opposed to something else would help ensure the right person gets to do the diagnosis.</p>\n" }, { "answer_id": 47507, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 1, "selected": false, "text": "<p>Yes, the names of the code under test (methods, properties, whatever) can change, but I contend your existing tests should fail if the expectations change. That is the true value of having well-constructed tests, not perusing a list of test names. That being said, well named test methods are great tools for getting new developers on board, helping them locate \"executable documentation\" with which they can kick the tires of existing code -- so I would keep the names of test methods up to date just as I would keep the assertions made by the test methods up to date.</p>\n\n<p>I name my test using the following pattern. Each test fixture attempts to focus on one class and is usually name {ClassUnderTest}Test. I name each test method {MemberUnderTest}_{Assertion}.</p>\n\n<pre><code>[TestFixture]\npublic class IndexableFileTest\n{\n [Test]\n public void Connect_InitializesReadOnlyProperties()\n {\n // ...\n }\n\n [Test,ExpectedException(typeof(NotInitializedException))]\n public void IsIndexable_ErrorWhenNotConnected()\n {\n // ...\n }\n\n [Test]\n public void IsIndexable_True()\n {\n // ...\n }\n\n [Test]\n public void IsIndexable_False()\n {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 47539, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "<p><strong>Very. Equally important as choosing good method and variable names.</strong><br>\nMuch more if your test suite is going to referred to by new devs in the future.</p>\n\n<p>As for your original question, definitely Answer1. Typing in a few more characters is a small price to pay for </p>\n\n<ul>\n<li>the readability. For you and others. It'll eliminate the 'what was I thinking here?' as well as 'WTF is this guy getting at in this test?'</li>\n<li>Quick zoom in when you're in to fix something someone else wrote</li>\n<li>instant update for any test-suite visitor. If done correctly, just going over the names of the test cases will inform the reader of the specs for the unit.</li>\n</ul>\n" }, { "answer_id": 47550, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 3, "selected": false, "text": "<p>Yes.</p>\n\n<pre><code> [Test]\n public void UsernameValidator_LessThanLengthLimit_ShouldValidate() {}\n</code></pre>\n\n<p>Put the test subject first, the test statement next, and the expected result last.<br>\nThat way, you get a clear indication of what it is doing, and you can easily sort by name :)</p>\n" }, { "answer_id": 47588, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "<p>Yes, the whole point of the test name is that it tells you what doesn't work when the test fails.</p>\n" }, { "answer_id": 47627, "author": "JC.", "author_id": 3615, "author_profile": "https://Stackoverflow.com/users/3615", "pm_score": 0, "selected": false, "text": "<pre><code>[RowTest]\n[Row(\"GoodName\")]\n[Row(\"GoodName2\")]\npublic void Should_validate_username()\n{\n}\n\n[RowTest]\n[Row(\"BadUserName\")]\n[Row(\"Bad%!Name\")]\npublic void Should_invalidate_username()\n{\n}\n</code></pre>\n\n<p>This might make more sense for more complex types of validation really.</p>\n" }, { "answer_id": 47643, "author": "VanOrman", "author_id": 4550, "author_profile": "https://Stackoverflow.com/users/4550", "pm_score": 0, "selected": false, "text": "<p>Yes, they are. I'd personally recommend looking at <a href=\"http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterUnitTests.aspx\" rel=\"nofollow noreferrer\">SSW's rules to better unit tests</a>. It contains some very helpful naming guidelines.</p>\n" }, { "answer_id": 47650, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 3, "selected": false, "text": "<p>Yes, the names are totally important, specially when you are running the tests in console or continuous integration servers. Jay Fields wrote a <a href=\"http://blog.jayfields.com/2008/05/testing-value-of-test-names.html\" rel=\"nofollow noreferrer\">post about it</a>.</p>\n\n<p>Moreover, put good test names with <a href=\"http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html\" rel=\"nofollow noreferrer\">one assertion per test</a> and your suite will give you great reports when a test fails.</p>\n" }, { "answer_id": 47825, "author": "Johan", "author_id": 4804, "author_profile": "https://Stackoverflow.com/users/4804", "pm_score": 1, "selected": false, "text": "<p>Having a very descriptive name helps to instantly see what is not working correctly, so that you don't actually need to look at the unit test code.\nAlso, a list of all the unit tests describes the intended behavior of the unit, and can be used (more or less) as documentation to the behavior of the unit under test.</p>\n\n<p>Note, this only works when unit tests are very specific and do not validate too much within one unit test. </p>\n\n<p>So for example:</p>\n\n<pre><code>[Test]\nvoid TestThatExceptionIsRaisedWhenStringLengthLargerThen100()\n\n[Test]\nvoid TestThatStringLengthOf99IsAccepted()\n</code></pre>\n" }, { "answer_id": 60230, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 3, "selected": false, "text": "<p>In <a href=\"http://amazon.com/o/ASIN/0132350882\" rel=\"noreferrer\">Clean Code</a>, page 124, <a href=\"http://www.objectmentor.com/omTeam/martin_r.html\" rel=\"noreferrer\">Robert C. Martin</a> writes:</p>\n\n<blockquote>\n <p>The moral of the story is simple: <em>Test code is just as important as production code.</em> It is not a second-class citizen. It requires thought, design, and care. It must be kept as clean as production code.</p>\n</blockquote>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4642/" ]
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names? ie ``` [Test] public void ShouldValidateUserNameIsLessThan100Characters() {} ``` verse ``` [Test] public void UserNameTestValidation1() {} ```
The name of any method should make it clear what it does. IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put "100" in the name, as that's very likely to change. What about: ``` public void validateUserNameLength() ``` If the test changes, the name should be updated accordingly.
47,487
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css">Avoiding repeated constants in CSS</a> </p> </blockquote> <p>We have some "theme colors" that are reused in our CSS sheet.</p> <p>Is there a way to set a variable and then reuse it?</p> <p>E.g.</p> <pre><code>.css OurColor: Blue H1 { color:OurColor; } </code></pre>
[ { "answer_id": 47490, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually to produce static CSS output based on some dynamic pseudo-CSS, or that is hooked up to the web server and preprocesses the CSS prior to sending it to the client.</p>\n" }, { "answer_id": 47494, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>Since CSS does not have that (yet, I believe the next version will), follow Konrad Rudolphs advice for preprocesing. You probably want to use one that allready exists: m4</p>\n\n<p><a href=\"http://www.gnu.org/software/m4/m4.html\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/m4/m4.html</a></p>\n" }, { "answer_id": 47497, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "<p>You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: <a href=\"http://cafe.elharo.com/web/css-repeats-itself/\" rel=\"noreferrer\">http://cafe.elharo.com/web/css-repeats-itself/</a>. You could use JSP, or its equivalent, to generate the CSS at runtime.</p>\n" }, { "answer_id": 47505, "author": "Tim Sullivan", "author_id": 722, "author_profile": "https://Stackoverflow.com/users/722", "pm_score": 3, "selected": false, "text": "<p>No, but <a href=\"http://sass-lang.com\" rel=\"nofollow noreferrer\">Sass</a> does this. It's a CSS preprocessor, allowing you to use a lot of shortcuts to reduce the amount of CSS you need to write. </p>\n\n<p>For example:</p>\n\n<pre><code>$blue: #3bbfce;\n$margin: 16px;\n\n.content-navigation {\n border-color: $blue;\n color:\n darken($blue, 9%);\n}\n\n.border {\n padding: $margin / 2;\n margin: $margin / 2;\n border-color: $blue;\n}\n</code></pre>\n\n<p>Beyond variables, it provides the ability to nest selectors, keeping things logically grouped:</p>\n\n<pre><code>table.hl {\n margin: 2em 0;\n td.ln {\n text-align: right;\n }\n}\n\nli {\n font: {\n family: serif;\n weight: bold;\n size: 1.2em;\n }\n}\n</code></pre>\n\n<p>There's more: mixins that act kind of like functions, and the ability to inherit one selector from another. It's very clever and very useful.</p>\n\n<p>If you're coding in Ruby on Rails, it'll even automatically compile it to CSS for you, but there's also a general purpose compiler that can do it for you on-demand.</p>\n" }, { "answer_id": 47508, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 8, "selected": true, "text": "<p>There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so <em>flip it around</em>:</p>\n\n<pre><code>/* Theme color: text */\nH1, P, TABLE, UL\n{ color: blue; }\n\n/* Theme color: emphasis */\nB, I, STRONG, EM\n{ color: #00006F; }\n\n/* ... */\n\n/* Theme font: header */\nH1, H2, H3, H4, H5, H6\n{ font-family: Comic Sans MS; }\n\n/* ... */\n\n/* H1-specific styles */\nH1\n{ \n font-size: 2em; \n margin-bottom: 1em;\n}\n</code></pre>\n\n<p>This way, you avoid repeating styles that are <em>conceptually</em> the same, while also making it clear which parts of the document they affect. </p>\n\n<p>Note the emphasis on \"conceptually\" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: <strong>two attributes sharing the same value does not necessarily mean they represent the same <em>concept</em></strong>. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors <em>will</em> vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will <em>always</em> share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid <em>value</em> repetition risks making future changes to styling incredibly error-prone; always focus on the <em>contextual meaning</em> of styles when looking to reduce repetition, ignoring their <em>current values</em>. </p>\n" }, { "answer_id": 47513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You're making it too complicated. This is the reason the cascade exists. Simply provide your element selectors and class your color:</p>\n\n<pre><code>h1 {\n color: #000;\n}\n.a-theme-color {\n color: #333;\n}\n</code></pre>\n\n<p>Then apply it to the elements in the HTML, overriding when you need to use your theme colors.</p>\n\n<pre><code>&lt;h1&gt;This is my heading.&lt;/h1&gt;\n&lt;h1 class=\"a-theme-color\"&gt;This is my theme heading.&lt;/h1&gt;\n</code></pre>\n" }, { "answer_id": 47528, "author": "Farinha", "author_id": 2841, "author_profile": "https://Stackoverflow.com/users/2841", "pm_score": 2, "selected": false, "text": "<p>That's not supported at the moment unless you use some script to produce the CSS based on some variables defined by you.</p>\n\n<p>It seems, though, that at least some people from the browser world are <a href=\"http://ajaxian.com/archives/css-variables-are-here\" rel=\"nofollow noreferrer\">working on it</a>. So, if it really becomes a standard sometime in the future, then we'll have to wait until it is implemented in all the browsers (it will be unusable until then).</p>\n" }, { "answer_id": 47564, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 1, "selected": false, "text": "<p>See also <a href=\"https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css\">Avoiding repeated constants in CSS</a>. As Farinha said, a CSS Variables proposal has been made, but for the time being, you want to use a preprocessor.</p>\n" }, { "answer_id": 47785, "author": "Simon Forrest", "author_id": 4733, "author_profile": "https://Stackoverflow.com/users/4733", "pm_score": 1, "selected": false, "text": "<p>You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:</p>\n\n<pre><code>.ourColor { color: blue; }\n.ourBorder { border: 1px solid blue; }\n.bigText { font-size: 1.5em; }\n</code></pre>\n\n<p>and then combine the classes as required:</p>\n\n<pre><code>&lt;h1 class=\"ourColor\"&gt;Blue Header&lt;/h1&gt;\n&lt;div class=\"ourColor bigText\"&gt;Some big blue text.&lt;/div&gt;\n&lt;div class=\"ourColor ourBorder\"&gt;Some blue text with blue border.&lt;/div&gt;\n</code></pre>\n\n<p>That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.</p>\n" }, { "answer_id": 47816, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 1, "selected": false, "text": "<p>This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:</p>\n\n<pre><code>a {\n color: ${colors.blue};\n}\n\n a:hover {\n color: ${colors.blue.light};\n }\n\np {\n padding: ${padding.normal};\n}\n</code></pre>\n\n<p>And then add a step to your build that assigns all the property values (I use external buildfiles and &lt;include&gt; them) and uses the &lt;expandproperties&gt; filter to generate the actual CSS:</p>\n\n<pre><code>&lt;property name=\"colors.blue\" value=\"#0066FF\" /&gt;\n&lt;property name=\"colors.blue.light\" value=\"#0099FF\" /&gt;\n&lt;property name=\"padding.normal\" value=\"0.5em\" /&gt;\n\n&lt;copy file=\"styles.css.template\" tofile=\"styles.css\" overwrite=\"true\"&gt;\n &lt;filterchain&gt;\n &lt;expandproperties/&gt;\n &lt;/filterchain&gt;\n&lt;/copy&gt;\n</code></pre>\n\n<p>The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.</p>\n\n<p>However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.</p>\n" }, { "answer_id": 69558, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.</p>\n\n<p>Here are two major approaches to achieve more dynamic style handling:</p>\n\n<ul>\n<li>Server-side variables in inline css<br>\nExample (using PHP): \n\n<blockquote>\n <p><code>&lt;style&gt; .myclass{color:&lt;?php echo $color; ?&gt;;} &lt;/style&gt;</code></p>\n</blockquote></li>\n</ul>\n\n<p>&nbsp;</p>\n\n<ul>\n<li><p>DOM manipulation with javascript to change css client-side<br>\nExamples (using jQuery library):</p>\n\n<blockquote>\n <p><code>$('.myclass').css('color', 'blue');</code> </p>\n \n <p>OR</p>\n \n <p><code>//The jsvarColor could be set with the original page response javascript<br>\n // in the DOM or retrieved on demand (AJAX) based on user action.\n $('.myclass').css('color', jsvarColor);</code></p>\n</blockquote></li>\n</ul>\n" }, { "answer_id": 112781, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "<p>I've written a macro (in Visual Studio) that allows me to not only code CSS for named colors but to easily calculate shades or blends of those colors. It also handles fonts. It fires on save and outputs a separate version of the CSS file. This is in line with <a href=\"http://www.w3.org/People/Bos/CSS-variables#implementation\" rel=\"nofollow noreferrer\">Bert Bos's argument</a> that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation. </p>\n\n<p>The full setup along with all the code would be a bit too complicated to post here, but might be appropriate for a blog post down the road. Here's the comment section from the macro which should be enough to get started. </p>\n\n<hr>\n\n<p>The goals of this approach are as follows:</p>\n\n<ol>\n<li><p>Allow base colors, fonts, etc. to be defined in a central location, so that an entire pallete or typographical treatment can be easily tweaked without having to use search/replace</p></li>\n<li><p>Avoid having to map the .CSS extension in IIS</p></li>\n<li><p>Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode</p></li>\n<li><p>Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested</p></li>\n<li><p>Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow </p></li>\n</ol>\n\n<p>With this approach, colors, shades of colors, and font families are all represented with shorthand tokens that refer to a list of values in an XML file.</p>\n\n<p>The XML file containing the color and font definitions must be called Constants.xml and must reside in the same folder as the CSS files. </p>\n\n<p>The ProcessCSS method is fired by EnvironmentEvents whenever VisualStudio saves a CSS file. The CSS file is expanded, and the expanded, static version of the file is saved in the /css/static/ folder. (All HTML pages should reference the /css/static/ versions of the CSS files). </p>\n\n<p>The Constants.xml file might look something like this: </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;cssconstants&gt;\n &lt;colors&gt;\n &lt;color name=\"Red\" value=\"BE1E2D\" /&gt;\n &lt;color name=\"Orange\" value=\"E36F1E\" /&gt;\n ...\n &lt;/colors&gt;\n &lt;fonts&gt;\n &lt;font name=\"Text\" value=\"'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif\" /&gt;\n &lt;font name=\"Serif\" value=\"Georgia,'Times New Roman',Times,serif\" /&gt;\n ...\n &lt;/fonts&gt;\n&lt;/cssconstants&gt;\n</code></pre>\n\n<p>In the CSS file, you can then have definitions like:</p>\n\n<pre><code> font-family:[[f:Text]];\n background:[[c:Background]]; \n border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */\n</code></pre>\n" }, { "answer_id": 2571142, "author": "Giorgi", "author_id": 239438, "author_profile": "https://Stackoverflow.com/users/239438", "pm_score": 4, "selected": false, "text": "<p>You can achieve it and much more by using <a href=\"http://lesscss.org/\" rel=\"noreferrer\">Less CSS</a>.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
> > **Possible Duplicate:** > > [Avoiding repeated constants in CSS](https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css) > > > We have some "theme colors" that are reused in our CSS sheet. Is there a way to set a variable and then reuse it? E.g. ``` .css OurColor: Blue H1 { color:OurColor; } ```
There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so *flip it around*: ``` /* Theme color: text */ H1, P, TABLE, UL { color: blue; } /* Theme color: emphasis */ B, I, STRONG, EM { color: #00006F; } /* ... */ /* Theme font: header */ H1, H2, H3, H4, H5, H6 { font-family: Comic Sans MS; } /* ... */ /* H1-specific styles */ H1 { font-size: 2em; margin-bottom: 1em; } ``` This way, you avoid repeating styles that are *conceptually* the same, while also making it clear which parts of the document they affect. Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: **two attributes sharing the same value does not necessarily mean they represent the same *concept***. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors *will* vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will *always* share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid *value* repetition risks making future changes to styling incredibly error-prone; always focus on the *contextual meaning* of styles when looking to reduce repetition, ignoring their *current values*.
47,519
<p>I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has</p> <pre><code>font-size: 11px; font-family: Arial, Helvetica, sans-serif; </code></pre> <p>I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms:</p> <pre><code>letter-spacing: -1.5px; </code></pre> <p>but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it.</p> <p>The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!</p>
[ { "answer_id": 47523, "author": "thekidder", "author_id": 1631, "author_profile": "https://Stackoverflow.com/users/1631", "pm_score": 0, "selected": false, "text": "<p>I find the easiest way to solve font sizing problems between browsers is to simply leave room for error. Make divs slightly larger or fonts slightly smaller so that platform variation doesn't change wrapping or clipping considerably.</p>\n" }, { "answer_id": 47525, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Have you tried it in FF3 on windows?</p>\n\n<p>Personally, I find a good CSS Reset goes a long way in making your page look the same in all browsers.</p>\n" }, { "answer_id": 47531, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 3, "selected": false, "text": "<p>A List Apart has a pretty <a href=\"http://www.alistapart.com/articles/howtosizetextincss\" rel=\"nofollow noreferrer\">comprehensive article on sizing fonts in CSS</a>. Their conclusion is to use \"<code>ems</code>\" to size text, since it generally gives the most consistent sizing across browsers. They make no direct mention of different OSes, but you should try using ems. It might solve your problem.</p>\n" }, { "answer_id": 47584, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 1, "selected": true, "text": "<p>Sizing/spacing differences are usually difficult to catch. What you can do is create a Linux-specific CSS file that will contain these values adjusted for Linux, then do a simple JS-based detect to inject that CSS if the User agent is a Linux one.</p>\n\n<p>This is probably not the cleanest approach, but it will work, and with the least intrusion into your otherwise clean HTML/CSS.</p>\n" }, { "answer_id": 48603, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<p>Unless your site is expecting an above-normal amount of Linux-based traffic, you're probably going to adversely affect more people if you \"sacrifice the user’s ability to adjust his or her reading environment\" as opposed to just not caring about the Linux experience.</p>\n\n<p>Having said that, if you <strong>do</strong> want a nice Linux experience, you should address the reasons behind why your design breaks under small variations in font spacing, given that these issues are difficult to control under current CSS implementations.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3206/" ]
I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has ``` font-size: 11px; font-family: Arial, Helvetica, sans-serif; ``` I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms: ``` letter-spacing: -1.5px; ``` but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it. The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!
Sizing/spacing differences are usually difficult to catch. What you can do is create a Linux-specific CSS file that will contain these values adjusted for Linux, then do a simple JS-based detect to inject that CSS if the User agent is a Linux one. This is probably not the cleanest approach, but it will work, and with the least intrusion into your otherwise clean HTML/CSS.
47,521
<p>Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :</p> <pre><code>public IEnumerable&lt;object&gt; ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } </code></pre> <p>Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? </p> <p>Here is an example that would not close the connection, if I understand yield correctly..</p> <pre><code>foreach(object obj in ExecuteSelect(commandText)) { break; } </code></pre> <p>For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?</p>
[ { "answer_id": 47529, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Connection will be closed automatically since you're using it inside \"using\" block.</p>\n" }, { "answer_id": 47699, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>Judging from <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx\" rel=\"nofollow noreferrer\">this technical explanation</a>, your code will not work as expected, but abort on the second item, because the connection was already closed when returning the first item.</p>\n\n<p>@Joel Gauvreau : Yes, I should have read on. <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx\" rel=\"nofollow noreferrer\">Part 3</a> of this series explains that the compiler adds special handling for finally blocks to trigger only at the <em>real</em> end.</p>\n" }, { "answer_id": 47746, "author": "Joel Gauvreau", "author_id": 4789, "author_profile": "https://Stackoverflow.com/users/4789", "pm_score": 2, "selected": false, "text": "<p>From the simple test I have tried, aku is right, dispose is called as soon as the foreach block exit. </p>\n\n<p>@David : However call stack is kept between call, so the connection would not be closed because on the next call we would return to the next instruction after the yield, which is the while block.</p>\n\n<p>My understanding is that when the iterator is disposed, the connection would also be disposed with it. I also think that the Connection.Close would not be needed because it would be taken care of when the object is disposed because of the using clause.</p>\n\n<p>Here is a simple program I tried to test the behavior...</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n foreach (int v in getValues())\n {\n Console.WriteLine(v);\n }\n Console.ReadKey();\n\n foreach (int v in getValues())\n {\n Console.WriteLine(v);\n break;\n }\n Console.ReadKey();\n }\n\n public static IEnumerable&lt;int&gt; getValues()\n {\n using (TestDisposable t = new TestDisposable())\n {\n for(int i = 0; i&lt;10; i++)\n yield return t.GetValue();\n }\n }\n}\n\npublic class TestDisposable : IDisposable\n{\n private int value;\n\n public void Dispose()\n {\n Console.WriteLine(\"Disposed\");\n }\n\n public int GetValue()\n {\n value += 1;\n return value;\n }\n}\n</code></pre>\n" }, { "answer_id": 47799, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 5, "selected": true, "text": "<p>The Iterator that the compiler synthesises implements <code>IDisposable</code>, which <code>foreach</code> calls when the <code>foreach</code> loop is exited.</p>\n\n<p>The Iterator's <code>Dispose()</code> method will clean up the <code>using</code> statements on early exit.</p>\n\n<p>As long as you use the iterator in a <code>foreach</code> loop, <code>using()</code> block, or call the <code>Dispose()</code> method in some other way, the cleanup of the Iterator will happen.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4789/" ]
Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around : ``` public IEnumerable<object> ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } ``` Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? Here is an example that would not close the connection, if I understand yield correctly.. ``` foreach(object obj in ExecuteSelect(commandText)) { break; } ``` For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?
The Iterator that the compiler synthesises implements `IDisposable`, which `foreach` calls when the `foreach` loop is exited. The Iterator's `Dispose()` method will clean up the `using` statements on early exit. As long as you use the iterator in a `foreach` loop, `using()` block, or call the `Dispose()` method in some other way, the cleanup of the Iterator will happen.
47,535
<p>Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?</p> <p>This works fine</p> <pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER </code></pre> <p>I want this to work:</p> <pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 </code></pre> <p>Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!</p>
[ { "answer_id": 47552, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 4, "selected": true, "text": "<p>Tools -&gt; Options -&gt; Tables/Queries -&gt; (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.</p>\n\n<p>then you can execute your query:</p>\n\n<pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0\n</code></pre>\n" }, { "answer_id": 69144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>How are you connecting to the database to run the update SQL? You can use the ODBC compatible mode through ADO. Without opening the database in Access.</p>\n" }, { "answer_id": 624863, "author": "mike nelson", "author_id": 23616, "author_profile": "https://Stackoverflow.com/users/23616", "pm_score": 0, "selected": false, "text": "<p>You may find Sql Server Compatible Syntax is already turned on, so definately worth just trying to run the sql statement mentioned above (via an ADO connection from ASP) before resorting to taking the db offline. Thanks, this helped me out.</p>\n" }, { "answer_id": 6066172, "author": "HansUp", "author_id": 77335, "author_profile": "https://Stackoverflow.com/users/77335", "pm_score": 3, "selected": false, "text": "<p>With ADO, you can execute a DDL statement to create a field and set its default value.</p>\n\n<pre><code>CurrentProject.Connection.Execute _\n \"ALTER TABLE discardme ADD COLUMN membersOnly SHORT DEFAULT 0\"\n</code></pre>\n" }, { "answer_id": 25262897, "author": "user3921919", "author_id": 3921919, "author_profile": "https://Stackoverflow.com/users/3921919", "pm_score": -1, "selected": false, "text": "<p>Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.</p>\n\n<p>is not found on MS Access 2010</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas? This works fine ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER ``` I want this to work: ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 ``` Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!
Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database. then you can execute your query: ``` ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0 ```
47,589
<p>I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.</p> <p>I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.</p> <p>Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?</p>
[ { "answer_id": 47597, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "<p>First, you should <a href=\"http://us.php.net/error_reporting\" rel=\"nofollow noreferrer\">turn warnings off</a> so that your visitors don't see your <strong>MySQL</strong> errors. Second, when you call <a href=\"http://us.php.net/mysql_query\" rel=\"nofollow noreferrer\"><code>mysql_query()</code></a>, you should check to see if it returned false. If it did, call <a href=\"http://us.php.net/manual/en/function.mysql-errno.php\" rel=\"nofollow noreferrer\"><code>mysql_errno()</code></a> to find out what went wrong. Match the number returned to the error codes on <a href=\"http://dev.mysql.com/doc/refman/4.1/en/error-messages-server.html\" rel=\"nofollow noreferrer\">this page</a>.</p>\n<p>It looks like this is the error number you're looking for:</p>\n<blockquote>\n<p>Error: 1169 SQLSTATE: 23000 (ER_DUP_UNIQUE)</p>\n<p>Message: Can't write, because of unique constraint, to table '%s'</p>\n</blockquote>\n" }, { "answer_id": 47606, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "<p>Updated to remove the stuff about errno functions which I now realize don't apply in your situation...</p>\n\n<p>One thing in MySQL to be wary of for <code>UPDATE</code> statements: <code>mysqli_affected_rows()</code> will return zero even if the <code>WHERE</code> clause matched rows, but the <code>SET</code> clause didn't actually change the data values. I only mention this because that behaviour caused a bug in a system I once looked at--the programmer used that return value to check for errors after an update, assuming a zero meant that some error had occurred. It just meant that the user didn't change any existing values before clicking the update button.</p>\n\n<p>So I guess using <code>mysqli_affected_rows()</code> can't be relied upon to find such warnings either, unless you have something like an <code>update_time</code> column in your table that will always be assigned a new timestamp value when updated. That sort of workaround seems kinda kludgey though.</p>\n" }, { "answer_id": 47608, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 0, "selected": false, "text": "<p>depending on what (if any) framework you're using, I suggest you do a query to check for the jobname yourself and create the proper information to user in with the rest of the validations for the form.</p>\n\n<p>Depending on the number of jobnames, you could send the names to the view that contains the form and use javascript to tell use which is taken.</p>\n\n<p>If this doesnt make sense to you, then to sum my view it's this: dont design your program and / or user to try to do illegal things and catch the errors when they do and handle it then. It is much better, imho, to design your system to not create errors. Keep the errors to actual bugs :)</p>\n" }, { "answer_id": 47662, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 5, "selected": true, "text": "<p>For warnings to be \"flagged\" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings:</p>\n\n<pre><code>$warningCountResult = mysql_query(\"SELECT @@warning_count\");\nif ($warningCountResult) {\n $warningCount = mysql_fetch_row($warningCountResult );\n if ($warningCount[0] &gt; 0) {\n //Have warnings\n $warningDetailResult = mysql_query(\"SHOW WARNINGS\");\n if ($warningDetailResult ) {\n while ($warning = mysql_fetch_assoc($warningDetailResult) {\n //Process it\n }\n }\n }//Else no warnings\n}\n</code></pre>\n\n<p>Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).</p>\n\n<p>For reference, <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-warnings.html\" rel=\"nofollow noreferrer\">MySQL SHOW WARNINGS</a> </p>\n\n<p>Of course, you could dispense with the initial query for the <code>SELECT @@warning_count</code>, which would save you a query per execution, but I included it for pedantic completeness.</p>\n" }, { "answer_id": 929065, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can detect Unique key violations using mysqli statement error no. The mysqli statement returns error 1062 , that is ER_DUP_ENTRY. You can look for error 1062 and print a suitable error message. If you want to print your column (jobName) also as part of your error message then you should parse the statement error string.</p>\n\n<pre>\n if($stmt = $mysqli->prepare($sql)){\n $stmt->bind_param(\"sss\",\n $name,\n $identKey,\n $domain);\n\n\n $stmt->execute();\n if($mysqli->affected_rows != 1) {\n //This will return errorno 1062\n trigger_error('mysql error >> '.$stmt->errno .'::' .$stmt->error, E_USER_ERROR);\n exit(1);\n }\n $stmt->close();\n } else {\n\n trigger_error('mysql error >> '. $mysqli->errno.'::'.$mysqli->error,E_USER_ERROR);\n }\n</pre>\n" }, { "answer_id": 2029953, "author": "tomsv", "author_id": 246622, "author_profile": "https://Stackoverflow.com/users/246622", "pm_score": 0, "selected": false, "text": "<p>It is possible to get the warnings, and in a more efficient way with mysqli than with mysql.</p>\n\n<p>Here is the code suggested on the manual <a href=\"http://www.php.net/manual/en/mysqli.warning-count.php\" rel=\"nofollow noreferrer\">page</a> on php.net for the property mysqli->warning_count:</p>\n\n<pre><code>$mysqli-&gt;query($query);\n\nif ($mysqli-&gt;warning_count) {\n if ($result = $mysqli-&gt;query(\"SHOW WARNINGS\")) {\n $row = $result-&gt;fetch_row();\n printf(\"%s (%d): %s\\n\", $row[0], $row[1], $row[2]);\n $result-&gt;close();\n }\n}\n</code></pre>\n" }, { "answer_id": 5058649, "author": "AG3", "author_id": 593260, "author_profile": "https://Stackoverflow.com/users/593260", "pm_score": 0, "selected": false, "text": "<p>Note on suppressing warnings: Generally, it is not a good idea to prevent warnings from being displayed since you might be missing something important. If you absolutely must hide warnings for some reason, you can do it on an individual basis by placing an <code>@</code> sign in front of the statement. That way you don't have to turn off all warning reporting and can limit it to a specific instance.</p>\n\n<p>Example:</p>\n\n<pre><code> // this suppresses warnings that might result if there is no field titled \"field\" in the result\n $field_value = @mysql_result($result, 0, \"field\");\n</code></pre>\n" }, { "answer_id": 8032033, "author": "Gigi", "author_id": 1033016, "author_profile": "https://Stackoverflow.com/users/1033016", "pm_score": 2, "selected": false, "text": "<pre><code>ini_set('mysql.trace_mode', 1)\n</code></pre>\n\n<p>may be what you are looking for.</p>\n\n<p>The PHP errors can then be handled with a custom PHP error handler, but you can also just turn off displaying php errors as they are usually logged into a log file (depends on your php configuration).</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056/" ]
I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it. Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings: ``` $warningCountResult = mysql_query("SELECT @@warning_count"); if ($warningCountResult) { $warningCount = mysql_fetch_row($warningCountResult ); if ($warningCount[0] > 0) { //Have warnings $warningDetailResult = mysql_query("SHOW WARNINGS"); if ($warningDetailResult ) { while ($warning = mysql_fetch_assoc($warningDetailResult) { //Process it } } }//Else no warnings } ``` Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them). For reference, [MySQL SHOW WARNINGS](http://dev.mysql.com/doc/refman/5.0/en/show-warnings.html) Of course, you could dispense with the initial query for the `SELECT @@warning_count`, which would save you a query per execution, but I included it for pedantic completeness.
47,591
<p>Specifically, I am looking to use CA on properties of types other than </p> <ul> <li>integers and doubles</li> <li>CGRect, CGPoint, CGSize, and CGAffineTransform structures</li> <li>CATransform3D data structures</li> <li>CGColor and CGImage references</li> </ul> <p>and in objects other than CALayers or NSViews</p>
[ { "answer_id": 48564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well, it seems I cannot do that. What I should be doing is [subclassing NSAnimation](<a href=\"https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html\" rel=\"nofollow noreferrer\">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html</a> subclassing NSAnimation). This will work on a MacOS 10.4+ app, but not on Cocoa Touch, in which I cannot find any alternatives apart from using a NSTimer.</p>\n" }, { "answer_id": 59168, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 1, "selected": false, "text": "<p>If you can do the changes yourself and the class you use is custom, you might want to add a setProgress:(float) f method to your class and use CA to animate it, then modify the desired properties as needed as a function of f.</p>\n\n<p>Just do a</p>\n\n<pre><code>[[someObject animator] setValue:[NSNumber numberWithFloat:1.0] forKeyPath:@\"someCustomProperty.progress\"];\n</code></pre>\n\n<p>or if the object doesn't have an animator, create the correct CAAnimation yourself.</p>\n" }, { "answer_id": 242173, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>I am not sure exactly what you are trying to do, but if you want to use CA on other properties that is not an issue. You just need to register appropriate actions for the key path. There is an example of doing this in Apple's Core Animation documentaation, using <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/Actions.html#//apple_ref/doc/uid/TP40006095\" rel=\"nofollow noreferrer\">CAAction</a>. Specifically you implement actionForLayer:forKey: to configure the default animation behaviour of that key, and if you want to make the property animation implicitly you implement runActionForKey:object:arguments: .</p>\n\n<p>As for animating objects other than CALayers, I really don't understand. Layers are the root visual entity in Core Animation. Additionally, on the iPhone every single UIView is backed on a layer, I do not believe there is anything on the iPhone's screen that is not in a layer, so I don't understand why you are worried about using animation on something that is not a CALayer.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Specifically, I am looking to use CA on properties of types other than * integers and doubles * CGRect, CGPoint, CGSize, and CGAffineTransform structures * CATransform3D data structures * CGColor and CGImage references and in objects other than CALayers or NSViews
If you can do the changes yourself and the class you use is custom, you might want to add a setProgress:(float) f method to your class and use CA to animate it, then modify the desired properties as needed as a function of f. Just do a ``` [[someObject animator] setValue:[NSNumber numberWithFloat:1.0] forKeyPath:@"someCustomProperty.progress"]; ``` or if the object doesn't have an animator, create the correct CAAnimation yourself.
47,605
<p>Assuming String a and b:</p> <pre><code>a += b a = a.concat(b) </code></pre> <p>Under the hood, are they the same thing?</p> <p>Here is concat decompiled as reference. I'd like to be able to decompile the <code>+</code> operator as well to see what that does.</p> <pre><code>public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } } </code></pre>
[ { "answer_id": 47615, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 2, "selected": false, "text": "<p>The <strong>+ operator</strong> can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.</p>\n\n<p>The <strong>concat operator</strong> can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.</p>\n\n<p>Except this, the code you provided does the same stuff.</p>\n" }, { "answer_id": 47624, "author": "Bartosz Bierkowski", "author_id": 3666, "author_profile": "https://Stackoverflow.com/users/3666", "pm_score": 2, "selected": false, "text": "<p>I don't think so.</p>\n\n<p><code>a.concat(b)</code> is implemented in String and I think the implementation didn't change much since early java machines. The <code>+</code> operation implementation depends on Java version and compiler. Currently <code>+</code> is implemented using <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html\" rel=\"nofollow noreferrer\"><code>StringBuffer</code></a> to make the operation as fast as possible. Maybe in the future, this will change. In earlier versions of java <code>+</code> operation on Strings was much slower as it produced intermediate results.</p>\n\n<p>I guess that <code>+=</code> is implemented using <code>+</code> and similarly optimized.</p>\n" }, { "answer_id": 47626, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 7, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/47615/662581\">Niyaz</a> is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts</p>\n\n<pre><code>String a = b + c + d;\n</code></pre>\n\n<p>into</p>\n\n<pre><code>String a = new StringBuilder(b).append(c).append(d).toString();\n</code></pre>\n\n<p>which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.</p>\n\n<p>However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html#concat(java.lang.String)\" rel=\"noreferrer\">the concat documentation</a> to confirm this.</p>\n\n<p>So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.</p>\n" }, { "answer_id": 47628, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 10, "selected": true, "text": "<p>No, not quite.</p>\n\n<p>Firstly, there's a slight difference in semantics. If <code>a</code> is <code>null</code>, then <code>a.concat(b)</code> throws a <code>NullPointerException</code> but <code>a+=b</code> will treat the original value of <code>a</code> as if it were <code>null</code>. Furthermore, the <code>concat()</code> method only accepts <code>String</code> values while the <code>+</code> operator will silently convert the argument to a String (using the <code>toString()</code> method for objects). So the <code>concat()</code> method is more strict in what it accepts.</p>\n\n<p>To look under the hood, write a simple class with <code>a += b;</code></p>\n\n<pre><code>public class Concat {\n String cat(String a, String b) {\n a += b;\n return a;\n }\n}\n</code></pre>\n\n<p>Now disassemble with <code>javap -c</code> (included in the Sun JDK). You should see a listing including:</p>\n\n<pre><code>java.lang.String cat(java.lang.String, java.lang.String);\n Code:\n 0: new #2; //class java/lang/StringBuilder\n 3: dup\n 4: invokespecial #3; //Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n 7: aload_1\n 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 11: aload_2\n 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;\n 18: astore_1\n 19: aload_1\n 20: areturn\n</code></pre>\n\n<p>So, <code>a += b</code> is the equivalent of</p>\n\n<pre><code>a = new StringBuilder()\n .append(a)\n .append(b)\n .toString();\n</code></pre>\n\n<p>The <code>concat</code> method should be faster. However, with more strings the <code>StringBuilder</code> method wins, at least in terms of performance.</p>\n\n<p>The source code of <code>String</code> and <code>StringBuilder</code> (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final <code>String</code>. In practice memory allocation is surprisingly fast.</p>\n\n<p><strong>Update:</strong> As Pawel Adamski notes, performance has changed in more recent HotSpot. <code>javac</code> still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing <code>System.identityHashCode</code> (not <code>String.hashCode</code>) shows the <code>StringBuffer</code> code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From <a href=\"https://twitter.com/lukaseder\" rel=\"noreferrer\">@lukaseder</a>, <a href=\"https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc\" rel=\"noreferrer\">a list of HotSpot JVM intrinsics</a>.</p>\n" }, { "answer_id": 47694, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 4, "selected": false, "text": "<p>How about some simple testing? Used the code below:</p>\n\n<pre><code>long start = System.currentTimeMillis();\n\nString a = \"a\";\n\nString b = \"b\";\n\nfor (int i = 0; i &lt; 10000000; i++) { //ten million times\n String c = a.concat(b);\n}\n\nlong end = System.currentTimeMillis();\n\nSystem.out.println(end - start);\n</code></pre>\n\n<ul>\n<li>The <code>\"a + b\"</code> version executed in <strong>2500ms</strong>.</li>\n<li>The <code>a.concat(b)</code> executed in <strong>1200ms</strong>.</li>\n</ul>\n\n<p>Tested several times. The <code>concat()</code> version execution took half of the time on average.</p>\n\n<p>This result surprised me because the <code>concat()</code> method always creates a new string (it returns a \"<code>new String(result)</code>\". It's well known that:</p>\n\n<pre><code>String a = new String(\"a\") // more than 20 times slower than String a = \"a\"\n</code></pre>\n\n<p>Why wasn't the compiler capable of optimize the string creation in \"a + b\" code, knowing the it always resulted in the same string? It could avoid a new string creation.\nIf you don't believe the statement above, test for your self. </p>\n" }, { "answer_id": 47716, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 5, "selected": false, "text": "<p>Tom is correct in describing exactly what the + operator does. It creates a temporary <code>StringBuilder</code>, appends the parts, and finishes with <code>toString()</code>.</p>\n\n<p>However, all of the answers so far are ignoring the effects of HotSpot runtime optimizations. Specifically, these temporary operations are recognized as a common pattern and are replaced with more efficient machine code at run-time.</p>\n\n<p>@marcio: You've created a <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp02225.html\" rel=\"noreferrer\">micro-benchmark</a>; with modern JVM's this is not a valid way to profile code.</p>\n\n<p>The reason run-time optimization matters is that many of these differences in code -- even including object-creation -- are completely different once HotSpot gets going. The only way to know for sure is profiling your code <i>in situ</i>.</p>\n\n<p>Finally, all of these methods are in fact incredibly fast. This might be a case of premature optimization. If you have code that concatenates strings a lot, the way to get maximum speed probably has nothing to do with which operators you choose and instead the algorithm you're using!</p>\n" }, { "answer_id": 47758, "author": "ckpwong", "author_id": 2551, "author_profile": "https://Stackoverflow.com/users/2551", "pm_score": 6, "selected": false, "text": "<p>I ran a similar test as @marcio but with the following loop instead:</p>\n\n<pre><code>String c = a;\nfor (long i = 0; i &lt; 100000L; i++) {\n c = c.concat(b); // make sure javac cannot skip the loop\n // using c += b for the alternative\n}\n</code></pre>\n\n<p>Just for good measure, I threw in <code>StringBuilder.append()</code> as well. Each test was run 10 times, with 100k reps for each run. Here are the results:</p>\n\n<ul>\n<li><code>StringBuilder</code> wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.</li>\n<li><code>a += b</code> takes about 40000ms (40s) for each run.</li>\n<li><code>concat</code> only requires 10000ms (10s) per run.</li>\n</ul>\n\n<p>I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect <code>a += b</code> spends much of the time creating new objects of <code>StringBuilder</code> and then converting them back to <code>String</code>.</p>\n" }, { "answer_id": 25378169, "author": "Deepak Sharma", "author_id": 1047565, "author_profile": "https://Stackoverflow.com/users/1047565", "pm_score": 3, "selected": false, "text": "<p>Basically, there are two important differences between + and the <code>concat</code> method.</p>\n\n<ol>\n<li><p>If you are using the <strong>concat</strong> method then you would only be able to concatenate strings while in case of the <strong>+</strong> operator, you can also concatenate the string with any data type.</p>\n\n<p><strong>For Example:</strong></p>\n\n<pre><code>String s = 10 + \"Hello\";\n</code></pre>\n\n<p>In this case, the output should be <strong>10Hello</strong>.</p>\n\n<pre><code>String s = \"I\";\nString s1 = s.concat(\"am\").concat(\"good\").concat(\"boy\");\nSystem.out.println(s1);\n</code></pre>\n\n<p>In the above case you have to provide two strings mandatory.</p></li>\n<li><p>The second and main difference between <strong>+</strong> and <strong>concat</strong> is that:</p>\n\n<p><strong>Case 1:</strong>\nSuppose I concat the same strings with <strong>concat</strong> operator in this way</p>\n\n<pre><code>String s=\"I\";\nString s1=s.concat(\"am\").concat(\"good\").concat(\"boy\");\nSystem.out.println(s1);\n</code></pre>\n\n<p>In this case total number of objects created in the pool are 7 like this:</p>\n\n<pre><code>I\nam\ngood\nboy\nIam\nIamgood\nIamgoodboy\n</code></pre>\n\n<p><strong>Case 2:</strong></p>\n\n<p>Now I am going to concatinate the same strings via <strong>+</strong> operator</p>\n\n<pre><code>String s=\"I\"+\"am\"+\"good\"+\"boy\";\nSystem.out.println(s);\n</code></pre>\n\n<p>In the above case total number of objects created are only 5.</p>\n\n<p>Actually when we concatinate the strings via <strong>+</strong> operator then it maintains a StringBuffer class to perform the same task as follows:-</p>\n\n<pre><code>StringBuffer sb = new StringBuffer(\"I\");\nsb.append(\"am\");\nsb.append(\"good\");\nsb.append(\"boy\");\nSystem.out.println(sb);\n</code></pre>\n\n<p>In this way it will create only five objects.</p></li>\n</ol>\n\n<p>So guys these are the basic differences between <strong>+</strong> and the <strong>concat</strong> method.\nEnjoy :)</p>\n" }, { "answer_id": 28428596, "author": "iamreza", "author_id": 4537488, "author_profile": "https://Stackoverflow.com/users/4537488", "pm_score": 1, "selected": false, "text": "<p>When using +, the speed decreases as the string's length increases, but when using concat, the speed is more stable, and the best option is using the StringBuilder class which has stable speed in order to do that.</p>\n\n<p>I guess you can understand why. But the totally best way for creating long strings is using StringBuilder() and append(), either speed will be unacceptable.</p>\n" }, { "answer_id": 43030370, "author": "dingalapadum", "author_id": 2995907, "author_profile": "https://Stackoverflow.com/users/2995907", "pm_score": 3, "selected": false, "text": "<p>For the sake of completeness, I wanted to add that the definition of the '+' operator can be found in the <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1\" rel=\"nofollow noreferrer\">JLS SE8 15.18.1</a>:</p>\n<blockquote>\n<p><em>If only one operand expression is of type String, then string\nconversion (§5.1.11) is performed on the other operand to produce a\nstring at run time.</em></p>\n<p><em>The result of string concatenation is a reference to a String object\nthat is the concatenation of the two operand strings. The characters\nof the left-hand operand precede the characters of the right-hand\noperand in the newly created string.</em></p>\n<p><em>The String object is newly created (§12.5) unless the expression is a\nconstant expression (§15.28)</em></p>\n</blockquote>\n<p>About the implementation the JLS says the following:</p>\n<blockquote>\n<p><em>An implementation may choose to perform conversion and concatenation\nin one step to avoid creating and then discarding an intermediate\nString object. To increase the performance of repeated string\nconcatenation, a Java compiler may use the StringBuffer class or a\nsimilar technique to reduce the number of intermediate String objects\nthat are created by evaluation of an expression.</em></p>\n<p><em>For primitive types, an implementation may also optimize away the\ncreation of a wrapper object by converting directly from a primitive\ntype to a string.</em></p>\n</blockquote>\n<p>So judging from the 'a Java compiler may use the StringBuffer class or a similar technique to reduce', different compilers could produce different byte-code.</p>\n" }, { "answer_id": 46485284, "author": "Paweł Adamski", "author_id": 1268294, "author_profile": "https://Stackoverflow.com/users/1268294", "pm_score": 5, "selected": false, "text": "<p>Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8 <code>+</code> is around two times faster than <code>concat</code>. </p>\n\n<p>My benchmark:</p>\n\n<pre><code>@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)\n@Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)\npublic class StringConcatenation {\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State2 {\n public String a = \"abc\";\n public String b = \"xyz\";\n }\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State3 {\n public String a = \"abc\";\n public String b = \"xyz\";\n public String c = \"123\";\n }\n\n\n @org.openjdk.jmh.annotations.State(Scope.Thread)\n public static class State4 {\n public String a = \"abc\";\n public String b = \"xyz\";\n public String c = \"123\";\n public String d = \"!@#\";\n }\n\n @Benchmark\n public void plus_2(State2 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b);\n }\n\n @Benchmark\n public void plus_3(State3 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b+state.c);\n }\n\n @Benchmark\n public void plus_4(State4 state, Blackhole blackhole) {\n blackhole.consume(state.a+state.b+state.c+state.d);\n }\n\n @Benchmark\n public void stringbuilder_2(State2 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());\n }\n\n @Benchmark\n public void stringbuilder_3(State3 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());\n }\n\n @Benchmark\n public void stringbuilder_4(State4 state, Blackhole blackhole) {\n blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());\n }\n\n @Benchmark\n public void concat_2(State2 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b));\n }\n\n @Benchmark\n public void concat_3(State3 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b.concat(state.c)));\n }\n\n\n @Benchmark\n public void concat_4(State4 state, Blackhole blackhole) {\n blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Benchmark Mode Cnt Score Error Units\nStringConcatenation.concat_2 thrpt 50 24908871.258 ± 1011269.986 ops/s\nStringConcatenation.concat_3 thrpt 50 14228193.918 ± 466892.616 ops/s\nStringConcatenation.concat_4 thrpt 50 9845069.776 ± 350532.591 ops/s\nStringConcatenation.plus_2 thrpt 50 38999662.292 ± 8107397.316 ops/s\nStringConcatenation.plus_3 thrpt 50 34985722.222 ± 5442660.250 ops/s\nStringConcatenation.plus_4 thrpt 50 31910376.337 ± 2861001.162 ops/s\nStringConcatenation.stringbuilder_2 thrpt 50 40472888.230 ± 9011210.632 ops/s\nStringConcatenation.stringbuilder_3 thrpt 50 33902151.616 ± 5449026.680 ops/s\nStringConcatenation.stringbuilder_4 thrpt 50 29220479.267 ± 3435315.681 ops/s\n</code></pre>\n" }, { "answer_id": 70535824, "author": "Christian Meyer", "author_id": 5759656, "author_profile": "https://Stackoverflow.com/users/5759656", "pm_score": 0, "selected": false, "text": "<p>Note that <code>s.concat(&quot;hello&quot;);</code> would result in a <code>NullPointereException</code> when s is null. In Java, the behavior of the + operator is usually determined by the left operand:</p>\n<p><code>System.out.println(3 + 'a'); //100</code></p>\n<p>However, Strings are an exception. If either operand is a String, the result is expected to be a String. This is the reason null is converted into &quot;null&quot;, even though you might expect a <code>RuntimeException</code>.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
Assuming String a and b: ``` a += b a = a.concat(b) ``` Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the `+` operator as well to see what that does. ``` public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } } ```
No, not quite. Firstly, there's a slight difference in semantics. If `a` is `null`, then `a.concat(b)` throws a `NullPointerException` but `a+=b` will treat the original value of `a` as if it were `null`. Furthermore, the `concat()` method only accepts `String` values while the `+` operator will silently convert the argument to a String (using the `toString()` method for objects). So the `concat()` method is more strict in what it accepts. To look under the hood, write a simple class with `a += b;` ``` public class Concat { String cat(String a, String b) { a += b; return a; } } ``` Now disassemble with `javap -c` (included in the Sun JDK). You should see a listing including: ``` java.lang.String cat(java.lang.String, java.lang.String); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V 7: aload_1 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 11: aload_2 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String; 18: astore_1 19: aload_1 20: areturn ``` So, `a += b` is the equivalent of ``` a = new StringBuilder() .append(a) .append(b) .toString(); ``` The `concat` method should be faster. However, with more strings the `StringBuilder` method wins, at least in terms of performance. The source code of `String` and `StringBuilder` (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final `String`. In practice memory allocation is surprisingly fast. **Update:** As Pawel Adamski notes, performance has changed in more recent HotSpot. `javac` still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing `System.identityHashCode` (not `String.hashCode`) shows the `StringBuffer` code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From [@lukaseder](https://twitter.com/lukaseder), [a list of HotSpot JVM intrinsics](https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc).
47,612
<p>I've got a C# class with a <code>Dispose</code> function via <code>IDisposable</code>. It's intended to be used inside a <code>using</code> block so the expensive resource it handles can be released right away.</p> <p>The problem is that a bug occurred when an exception was thrown before <code>Dispose</code> was called, and the programmer neglected to use <code>using</code> or <code>finally</code>.</p> <p>In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use <code>using</code>.</p> <p>Is there any way to for a <code>using</code> block to be automatically used in C#?</p> <p>Many thanks.</p> <p>UPDATE:</p> <p>I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.</p> <p>Here's the bug I found, reduced to the essentials...</p> <pre><code>try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); </code></pre> <p>Using <code>FXCop</code> is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?</p>
[ { "answer_id": 47617, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "<pre><code>~ClassName()\n{\n}\n</code></pre>\n\n<p>EDIT (bold):</p>\n\n<p>If will get called when the object is moved out of scope and is tidied by the garbage collector <strong>however this is not deterministic and is not guaranteed to happen at any particular time</strong>.\nThis is called a Finalizer. All objects with a finaliser get put on a special finalise queue by the garbage collector where the finalise method is invoked on them (so it's technically a performance hit to declare empty finalisers).</p>\n\n<p>The \"accepted\" dispose pattern as per the Framework Guidelines is as follows with unmanaged resources:</p>\n\n<pre><code> public class DisposableFinalisableClass : IDisposable\n {\n ~DisposableFinalisableClass()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposing)\n {\n // tidy managed resources\n }\n\n // tidy unmanaged resources\n }\n }\n</code></pre>\n\n<p>So the above means that if someone calls Dispose the unmanaged resources are tidied. However in the case of someone forgetting to call Dispose or an exception preventing Dispose from being called the unmanaged resources will still be tidied away, only slightly later on when the GC gets its grubby mitts on it (which includes the application closing down or unexpectedly ending).</p>\n" }, { "answer_id": 47618, "author": "Ben Childs", "author_id": 2925, "author_profile": "https://Stackoverflow.com/users/2925", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :).</p>\n\n<p>Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.</p>\n" }, { "answer_id": 47632, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>This is no different from a programmer forgetting to use <em>delete</em> in C++, except that at least here the garbage collector will still eventually catch up with it.</p>\n\n<p>And you never need to use IDisposable if the only resource you're worried about is memory. The framework will handle that on it's own. IDisposable is only for unmanaged resources like database connections, filestreams, sockets, and the like.</p>\n" }, { "answer_id": 47637, "author": "Andrew Burns", "author_id": 3683, "author_profile": "https://Stackoverflow.com/users/3683", "pm_score": 2, "selected": false, "text": "<p>@Quarrelsome </p>\n\n<blockquote>\n <p>If will get called when the object is moved out of scope and is tidied by the garbage collector.</p>\n</blockquote>\n\n<p>This statement is misleading and how I read it incorrect: There is absolutely no guarantee when the finalizer will be called. You are absolutely correct that billpg should implement a finalizer; however it will not be called automaticly when the object goes out of scope like he wants. <a href=\"http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx\" rel=\"nofollow noreferrer\">Evidence</a>, the first bullet point under <em>Finalize operations have the following limitations</em>.</p>\n\n<p>In fact Microsoft gave a grant to Chris Sells to create an implementation of .NET that used reference counting instead of garbage collection <a href=\"http://www.sellsbrothers.com/spout/default.aspx?content=archive.htm#refCountRotor\" rel=\"nofollow noreferrer\">Link</a>. As it turned out there was a <em>considerable</em> performance hit.</p>\n" }, { "answer_id": 47652, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>A better design is to make this class release the expensive resource on its own, before its disposed.</p>\n\n<p>For example, If its a database connection, only connect when needed and release immediately, long before the actual class gets disposed.</p>\n" }, { "answer_id": 47665, "author": "Hershi", "author_id": 1596, "author_profile": "https://Stackoverflow.com/users/1596", "pm_score": 3, "selected": false, "text": "<p>Where I work we use the following guidelines:</p>\n\n<ul>\n<li>Each IDisposable class <strong>must</strong> have a finalizer</li>\n<li>Whenever using an IDisposable object, it must be used inside a \"using\" block. The only exception is if the object is a member of another class, in which case the containing class must be IDisposable and must call the member's 'Dispose' method in its own implementation of 'Dispose'. This means 'Dispose' should never be called by the developer except for inside another 'Dispose' method, eliminating the bug described in the question.</li>\n<li>The code in each Finalizer must begin with a warning/error log notifying us that the finalizer has been called. This way you have an extremely good chance of spotting such bugs as described above before releasing the code, plus it might be a hint for bugs occuring in your system.</li>\n</ul>\n\n<p>To make our lives easier, we also have a SafeDispose method in our infrastructure, which calls the the Dispose method of its argument within a try-catch block (with error logging), just in case (although Dispose methods are not supposed to throw exceptions).</p>\n\n<p>See also: <a href=\"http://blogs.msdn.com/clyon/archive/2004/09/23/233464.aspx\" rel=\"noreferrer\">Chris Lyon</a>'s suggestions regarding IDisposable</p>\n\n<p>Edit:\n@Quarrelsome: One thing you ought to do is call GC.SuppressFinalize inside 'Dispose', so that if the object was disposed, it wouldn't be \"re-disposed\".</p>\n\n<p>It is also usually advisable to hold a flag indicating whether the object has already been disposed or not. The follwoing pattern is usually pretty good:</p>\n\n<pre><code>class MyDisposable: IDisposable {\n public void Dispose() {\n lock(this) {\n if (disposed) {\n return;\n }\n\n disposed = true;\n }\n\n GC.SuppressFinalize(this);\n\n // Do actual disposing here ...\n }\n\n private bool disposed = false;\n}\n</code></pre>\n\n<p>Of course, locking is not always necessary, but if you're not sure if your class would be used in a multi-threaded environment or not, it is advisable to keep it.</p>\n" }, { "answer_id": 48557, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>The best practice is to use a finaliser in your class and always use <code>using</code> blocks.</p>\n\n<p>There isn't really a direct equivalent though, finalisers look like C destructors, but behave differently.</p>\n\n<p>You're supposed to nest <code>using</code> blocks, that's why the C# code layout defaults to putting them on the same line...</p>\n\n<pre><code>using (SqlConnection con = new SqlConnection(\"DB con str\") )\nusing (SqlCommand com = new SqlCommand( con, \"sql query\") )\n{\n //now code is indented one level\n //technically we're nested twice\n}\n</code></pre>\n\n<p>When you're not using <code>using</code> you can just do what it does under the hood anyway:</p>\n\n<pre><code>PleaseDisposeMe a;\ntry\n{\n a = new PleaseDisposeMe();\n throw new Exception();\n}\ncatch (Exception ex) { Log(ex); } \nfinally { \n //this always executes, even with the exception\n a.Dispose(); \n}\n</code></pre>\n\n<p>With managed code C# is very very good at looking after its own memory, even when stuff is poorly disposed. If you're dealing with unmanaged resources a lot it's not so strong.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3568/" ]
I've got a C# class with a `Dispose` function via `IDisposable`. It's intended to be used inside a `using` block so the expensive resource it handles can be released right away. The problem is that a bug occurred when an exception was thrown before `Dispose` was called, and the programmer neglected to use `using` or `finally`. In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use `using`. Is there any way to for a `using` block to be automatically used in C#? Many thanks. UPDATE: I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors. Here's the bug I found, reduced to the essentials... ``` try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); ``` Using `FXCop` is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?
Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :). Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.
47,658
<p>I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.</p> <p>I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.</p> <p>I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?</p> <ul> <li><p>How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.</p></li> <li><p>Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?</p></li> </ul> <p>What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:</p> <pre><code>&lt;com|org|...&gt;.&lt;company&gt;.&lt;app&gt;.&lt;layer&gt;.&lt;function&gt;.ClassName </code></pre> <p>I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.</p>
[ { "answer_id": 47664, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 1, "selected": false, "text": "<p>It obviously varies depending on languages and technologies. By the look of your example name space I am going to guess java, in which case <a href=\"http://java.sun.com/docs/codeconv/\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/codeconv/</a> is a really good place to start. You might also want to look at something like maven's standard directory structure which will make all your projects look similar. </p>\n" }, { "answer_id": 48107, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": true, "text": "<p>First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review.</p>\n\n<p>If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.</p>\n\n<p>In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having <i>any</i> standard is the key.</p>\n" }, { "answer_id": 48119, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 2, "selected": false, "text": "<p>I'm going to second Jason's suggestion.</p>\n\n<p>I just completed a standards document for a team of 10-12 that work mostly in perl. The document says to use \"perltidy-like indentation for complex data structures.\" We also provided everyone with example perltidy settings that would clean up their code to meet this standard. It was very clear and very much industry-standard for the language so we had great buyoff on it by the team.</p>\n\n<p>When setting out to write this document, I asked around for some examples of great code in our repository and googled a bit to find other standards documents that smarter architects than I to construct a template. It was tough being concise and pragmatic without crossing into micro-manager territory but very much worth it; having <em>any</em> standard is indeed key.</p>\n\n<p>Hope it works out!</p>\n" }, { "answer_id": 48121, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>Coming from the automotive industry, here's a few style standards used for concrete reasons:</p>\n\n<p>Always used braces in control structures, and place them on separate lines. This eliminates problems with people adding code and including it or not including it mistakenly inside a control structure.</p>\n\n<pre><code>if(...)\n{\n\n}\n</code></pre>\n\n<p>All switches/selects have a default case. The default case logs an error if it's not a valid path.</p>\n\n<p>For the same reason as above, any if...elseif... control structures MUST end with a default else that also logs an error if it's not a valid path. A single if statement does not require this.</p>\n\n<p>In the occasional case where a loop or control structure is intentionally empty, a semicolon is always placed within to indicate that this is intentional.</p>\n\n<pre><code>while(stillwaiting())\n{\n ;\n}\n</code></pre>\n\n<p>Naming standards have very different styles for typedefs, defined constants, module global variables, etc. Variable names include type. You can look at the name and have a good idea of what module it pertains to, its scope, and type. This makes it easy to detect errors related to types, etc.</p>\n\n<p>There are others, but these are the top off my head.</p>\n\n<p>-Adam</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4910/" ]
I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards. I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size. I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards? * How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc. * Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class? What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like: ``` <com|org|...>.<company>.<app>.<layer>.<function>.ClassName ``` I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.
First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review. If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it. In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having *any* standard is the key.
47,683
<p>We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.</p>
[ { "answer_id": 47963, "author": "Todd", "author_id": 3803, "author_profile": "https://Stackoverflow.com/users/3803", "pm_score": 4, "selected": true, "text": "<p>You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception.</p>\n\n<p>Some code might look like this:</p>\n\n<pre><code> public void onException (JMSException jsme)\n {\n if (!closeRequested)\n {\n this.disconnect();\n this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector);\n } \n else\n {\n //Client requested close so do not try to reconnect\n }\n }\n</code></pre>\n\n<p>In your \"establishConnection\" code, you would then implement a <code>while(!initialized)</code> construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions.</p>\n\n<p>We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection.</p>\n" }, { "answer_id": 72859, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 3, "selected": false, "text": "<p>I'd highly recommend you use the <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/jms.html#jms-mdp\" rel=\"noreferrer\">Spring abstractions for JMS such as the MessageListenerContainer</a> to deal with reconnection, transactions and pooling for you. You just need to supply a MessageListener and configure the MessageListenerContainer with the ConnectionFactory and the container does the rest.</p>\n" }, { "answer_id": 117503, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 3, "selected": false, "text": "<p>If you're purely a listener and do <em>no</em> other JMS calls other than connection setup, then the \"onException() handler\" answer is correct.</p>\n\n<p>If you do any JMS calls in your code, just using onException() callback isn't sufficient. Problems are relayed from the JMS provider to the app <em>either</em> via an exception on a JMS method call <em>or</em> through the onException() callback. Not both.</p>\n\n<p>So if you call any JMS methods from your code, you'll also want to invoke that reconnection logic if you get any exceptions on those calls.</p>\n" }, { "answer_id": 118477, "author": "user13229", "author_id": 13229, "author_profile": "https://Stackoverflow.com/users/13229", "pm_score": 1, "selected": false, "text": "<p>Piece of advice from personal experience. <strong>Upgrade to <a href=\"http://www.jboss.org/jbossmessaging/\" rel=\"nofollow noreferrer\">JBoss Messaging</a>.</strong> I've seen it in production for 4 months without problems. It has fully transparent failover - amongst many other features.</p>\n\n<p>Also, if you do go with Spring, be <a href=\"http://wiki.jboss.org/wiki/JBMSpringJMSTemplateNotes\" rel=\"nofollow noreferrer\">very</a> <a href=\"http://activemq.apache.org/jmstemplate-gotchas.html\" rel=\"nofollow noreferrer\">careful</a> with the <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/jms.html#jms-jmstemplate\" rel=\"nofollow noreferrer\">JmsTemplate</a>. </p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3098/" ]
We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.
You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception. Some code might look like this: ``` public void onException (JMSException jsme) { if (!closeRequested) { this.disconnect(); this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector); } else { //Client requested close so do not try to reconnect } } ``` In your "establishConnection" code, you would then implement a `while(!initialized)` construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions. We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection.
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
[ { "answer_id": 47744, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 0, "selected": false, "text": "<p>What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id.\nYou can either output the process id via logging or using something like Task Manager.\nOnce that is achieved it will be possible to inspect individual threads and their call stacks.</p>\n\n<p>EDIT: I don't have any experience with GNU Debugger (GDB), which is cross platform, however I found this <a href=\"http://wiki.python.org/moin/DebuggingWithGdb\" rel=\"nofollow noreferrer\">link</a> and it may start you on the right path. It explains how to add debug symbols (handy for reading stack traces) and how to instruct gdb to attach to a running python process.</p>\n" }, { "answer_id": 56510, "author": "asksol", "author_id": 5577, "author_profile": "https://Stackoverflow.com/users/5577", "pm_score": 5, "selected": true, "text": "<p>Yeah, gdb is good for lower level debugging.</p>\n\n<p>You can change threads with the <em>thread</em> command.</p>\n\n<p>e.g</p>\n\n<pre><code>(gdb) thr 2\n[Switching to thread 2 (process 6159 thread 0x3f1b)]\n(gdb) backtrace\n....\n</code></pre>\n\n<p>You could also check out Python specific debuggers like <a href=\"http://winpdb.org/about/\" rel=\"noreferrer\">Winpdb</a>, or <a href=\"http://bashdb.sourceforge.net/pydb/\" rel=\"noreferrer\">pydb</a>. Both platform independent. </p>\n" }, { "answer_id": 59179, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 2, "selected": false, "text": "<p>If you mean the pydb, there is no way to do it. There was some effort in that direction:\n<a href=\"http://svn.python.org/projects/sandbox/trunk/pdb/mpdb.py\" rel=\"nofollow noreferrer\">see the svn commit</a>, but it was abandoned. Supposedly <a href=\"http://winpdb.org/docs/launch-time/\" rel=\"nofollow noreferrer\">winpdb supports it</a>.</p>\n" }, { "answer_id": 277800, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>My experience debugging multi-threaded programs in PyDev (Eclipse on Windows XP) is, threads created using thread.start_new_thread could not be hooked, but thread created using threading.Thread could be hooked. Hope the information is helpful.</p>\n" }, { "answer_id": 550795, "author": "Peter S Magnusson", "author_id": 31024, "author_profile": "https://Stackoverflow.com/users/31024", "pm_score": 3, "selected": false, "text": "<p>You can attach a debugger to a multi-threaded Python process, but you need to do it at the C level. To make sense of what's going on, you need the Python interpreter to be compiled with symbols. If you don't have one, you need to download source from python.org and build it yourself:</p>\n\n<pre><code>./configure --prefix=/usr/local/pydbg\nmake OPT=-g\nsudo make install\nsudo ln -s /usr/local/pydbg/bin/python /usr/local/bin/dbgpy\n</code></pre>\n\n<p>Make sure your workload is running on that version of the interpreter. You can then attach to it with GDB at any time. The Python folks have included a sample \".gdbinit\" in their Misc directory, which has some useful macros. However it's broken for multi-threaded debugging (!). You need to replace lines like this</p>\n\n<pre><code>while $pc &lt; Py_Main || $pc &gt; Py_GetArgcArgv\n</code></pre>\n\n<p>with the following:</p>\n\n<pre><code>while ($pc &lt; Py_Main || $pc &gt; Py_GetArgcArgv) &amp;&amp; ($pc &lt; t_bootstrap || $pc &gt; thread_PyThread_start_new_thread)\n</code></pre>\n\n<p>Otherwise commands like <code>pystack</code> won't terminate on threads other than the main thread. With this stuff in place, you can do stuff like</p>\n\n<pre><code>gdb&gt; attach &lt;PID&gt;\ngdb&gt; info threads\ngdb&gt; thread &lt;N&gt;\ngdb&gt; bt\ngdb&gt; pystack\ngdb&gt; detach\n</code></pre>\n\n<p>and see what's going on. Kind of.</p>\n\n<p>You can parse what the objects are with the \"pyo\" macro. <a href=\"http://chrismiles.livejournal.com/20226.html\" rel=\"noreferrer\">Chris has some examples</a> on his blog.</p>\n\n<p>Good luck.</p>\n\n<p>(Shoutout for <a href=\"http://mcfunley.com/cs/blogs/dan/archive/2007/10/19/1530.aspx\" rel=\"noreferrer\">Dan's blog</a> for some key information for me, notably the threading fix!)</p>\n" }, { "answer_id": 553633, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": false, "text": "<p>Use <a href=\"http://winpdb.org/\" rel=\"nofollow noreferrer\">Winpdb</a>. It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p>\n\n<p>Features:</p>\n\n<ul>\n<li>GPL license. Winpdb is Free Software.</li>\n<li>Compatible with CPython 2.3 through 2.6 and Python 3000</li>\n<li>Compatible with wxPython 2.6 through 2.8</li>\n<li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li>\n<li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/HKYjO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HKYjO.jpg\" alt=\"Screenshot\"></a><br>\n<sub>(source: <a href=\"http://winpdb.org/images/screenshot_winpdb_small.jpg\" rel=\"nofollow noreferrer\">winpdb.org</a>)</sub> </p>\n" }, { "answer_id": 29093342, "author": "Tarnay Kálmán", "author_id": 55267, "author_profile": "https://Stackoverflow.com/users/55267", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/dcramer/pdbinject\" rel=\"nofollow\">pdbinject</a> allows you to inject pdb into an already running python process.</p>\n\n<p>The pdbinject executable only works under python2, but can inject into python3 just fine too. </p>\n" }, { "answer_id": 29354135, "author": "Dmitry Trofimov", "author_id": 429873, "author_profile": "https://Stackoverflow.com/users/429873", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://www.jetbrains.com/pycharm/\" rel=\"nofollow\">PyCharm IDE</a> allows attaching to a running Python process since version 4.0. </p>\n\n<p><a href=\"https://www.jetbrains.com/pycharm/help/attaching-to-process.html\" rel=\"nofollow\">Here</a> is described how to do that.</p>\n" }, { "answer_id": 59023050, "author": "Błażej Michalik", "author_id": 2146491, "author_profile": "https://Stackoverflow.com/users/2146491", "pm_score": 0, "selected": false, "text": "<p>This can be used as a dead simple \"remote\" debugger:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nimport socket\nimport pdb\n\ndef remote_trace():\n server = socket.socket()\n server.bind(('0.0.0.0', 12345))\n server.listen()\n client, _= server.accept()\n stream = client.makefile('rw')\n sys.stdin = sys.stdout = sys.stderr = stream\n pdb.set_trace()\n\nremote_trace()\n\n# Execute in the shell: `telnet 127.0.0.1 12345`\n</code></pre>\n\n<p><em>On Windows it's easier to use Netcat instead of Telnet (which will also work on linux).</em></p>\n" }, { "answer_id": 71794451, "author": "gobenji", "author_id": 1327601, "author_profile": "https://Stackoverflow.com/users/1327601", "pm_score": 1, "selected": false, "text": "<p>python3 provides <a href=\"https://devguide.python.org/gdb/\" rel=\"nofollow noreferrer\">gdb extensions</a>. Using\nthem, gdb can attach to a running program, select a thread and print its\npython backtrace.</p>\n<p>On Debian (since at least Buster) the extensions are part of the\npython3.<em>x</em>-dbg package (ex. <code>python3.10-dbg</code> installs\n<code>/usr/share/gdb/auto-load/usr/bin/python3.10-gdb.py</code>) and gdb auto-loads them.</p>\n<p>Example with a simple threaded python script:</p>\n<pre><code>#!/usr/bin/env python3\n\nimport signal\nimport threading\n\ndef a():\n while True:\n pass\n\ndef b():\n while True:\n signal.pause()\n\nthreading.Thread(target=a).start()\nthreading.Thread(target=b).start()\n</code></pre>\n<p>Running gdb:</p>\n<pre><code>user@vsid:~$ ps -C python3 -L\n PID LWP TTY TIME CMD\n 1215 1215 pts/0 00:00:00 python3\n 1215 1216 pts/0 00:00:19 python3\n 1215 1217 pts/0 00:00:00 python3\nuser@vsid:~$ gdb -p 1215\nGNU gdb (Debian 10.1-2+b1) 10.1.90.20210103-git\nCopyright (C) 2021 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;\n[...]\n(gdb) info auto-load python-scripts\nLoaded Script\nYes /usr/share/gdb/auto-load/usr/bin/python3.10-gdb.py\n(gdb) info threads\n Id Target Id Frame\n* 1 Thread 0x7f2f034b4740 (LWP 1215) &quot;python3&quot; 0x00007f2f036a60fa in __futex_abstimed_wait_common64 (futex_word=futex_word@entry=0x7f2ef4000b60, expected=expected@entry=0,\n clockid=clockid@entry=0, abstime=abstime@entry=0x0, private=&lt;optimized out&gt;,\n cancel=cancel@entry=true) at ../sysdeps/nptl/futex-internal.c:74\n 2 Thread 0x7f2f02ea7640 (LWP 1216) &quot;python3&quot; 0x000000000051b858 in _PyEval_EvalFrameDefault\n (tstate=&lt;optimized out&gt;, f=&lt;optimized out&gt;, throwflag=&lt;optimized out&gt;)\n at ../Python/ceval.c:3850\n 3 Thread 0x7f2f026a6640 (LWP 1217) &quot;python3&quot; 0x00007f2f036a3932 in __libc_pause ()\n at ../sysdeps/unix/sysv/linux/pause.c:29\n(gdb) thread 2\n(gdb) py-bt\nTraceback (most recent call first):\n File &quot;/root/./threaded.py&quot;, line 7, in a\n while True:\n File &quot;/usr/lib/python3.10/threading.py&quot;, line 946, in run\n self._target(*self._args, **self._kwargs)\n File &quot;/usr/lib/python3.10/threading.py&quot;, line 1009, in _bootstrap_inner\n self.run()\n File &quot;/usr/lib/python3.10/threading.py&quot;, line 966, in _bootstrap\n self._bootstrap_inner()\n(gdb)\n</code></pre>\n<p>We can confirm that thread <code>1216</code> which used the most cpu time according to\n<code>ps</code> is indeed the thread running function <code>a()</code> that is busy-looping.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)
Yeah, gdb is good for lower level debugging. You can change threads with the *thread* command. e.g ``` (gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace .... ``` You could also check out Python specific debuggers like [Winpdb](http://winpdb.org/about/), or [pydb](http://bashdb.sourceforge.net/pydb/). Both platform independent.
47,752
<p>Anyone have a quick method for de-duplicating a generic List in C#?</p>
[ { "answer_id": 47755, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": false, "text": "<p>Sort it, then check two and two next to each others, as the duplicates will clump together.</p>\n\n<p>Something like this:</p>\n\n<pre><code>list.Sort();\nInt32 index = list.Count - 1;\nwhile (index &gt; 0)\n{\n if (list[index] == list[index - 1])\n {\n if (index &lt; list.Count - 1)\n (list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);\n list.RemoveAt(list.Count - 1);\n index--;\n }\n else\n index--;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>Comparison is done from back to front, to avoid having to resort list after each removal</li>\n<li>This example now uses C# Value Tuples to do the swapping, substitute with appropriate code if you can't use that</li>\n<li>The end-result is no longer sorted</li>\n</ul>\n" }, { "answer_id": 47757, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 9, "selected": true, "text": "<p>Perhaps you should consider using a <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"noreferrer\">HashSet</a>.</p>\n\n<p>From the MSDN link:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n HashSet&lt;int&gt; evenNumbers = new HashSet&lt;int&gt;();\n HashSet&lt;int&gt; oddNumbers = new HashSet&lt;int&gt;();\n\n for (int i = 0; i &lt; 5; i++)\n {\n // Populate numbers with just even numbers.\n evenNumbers.Add(i * 2);\n\n // Populate oddNumbers with just odd numbers.\n oddNumbers.Add((i * 2) + 1);\n }\n\n Console.Write(\"evenNumbers contains {0} elements: \", evenNumbers.Count);\n DisplaySet(evenNumbers);\n\n Console.Write(\"oddNumbers contains {0} elements: \", oddNumbers.Count);\n DisplaySet(oddNumbers);\n\n // Create a new HashSet populated with even numbers.\n HashSet&lt;int&gt; numbers = new HashSet&lt;int&gt;(evenNumbers);\n Console.WriteLine(\"numbers UnionWith oddNumbers...\");\n numbers.UnionWith(oddNumbers);\n\n Console.Write(\"numbers contains {0} elements: \", numbers.Count);\n DisplaySet(numbers);\n }\n\n private static void DisplaySet(HashSet&lt;int&gt; set)\n {\n Console.Write(\"{\");\n foreach (int i in set)\n {\n Console.Write(\" {0}\", i);\n }\n Console.WriteLine(\" }\");\n }\n}\n\n/* This example produces output similar to the following:\n * evenNumbers contains 5 elements: { 0 2 4 6 8 }\n * oddNumbers contains 5 elements: { 1 3 5 7 9 }\n * numbers UnionWith oddNumbers...\n * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }\n */\n</code></pre>\n" }, { "answer_id": 47761, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "<p>In Java (I assume C# is more or less identical):</p>\n\n<pre><code>list = new ArrayList&lt;T&gt;(new HashSet&lt;T&gt;(list))\n</code></pre>\n\n<p>If you really wanted to mutate the original list:</p>\n\n<pre><code>List&lt;T&gt; noDupes = new ArrayList&lt;T&gt;(new HashSet&lt;T&gt;(list));\nlist.clear();\nlist.addAll(noDupes);\n</code></pre>\n\n<p>To preserve order, simply replace HashSet with LinkedHashSet.</p>\n" }, { "answer_id": 47763, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "<p>If you don't care about the order you can just shove the items into a <code>HashSet</code>, if you <em>do</em> want to maintain the order you can do something like this:</p>\n<pre><code>var unique = new List&lt;T&gt;();\nvar hs = new HashSet&lt;T&gt;();\nforeach (T t in list)\n if (hs.Add(t))\n unique.Add(t);\n</code></pre>\n<p>Or the Linq way:</p>\n<pre><code>var hs = new HashSet&lt;T&gt;();\nlist.All( x =&gt; hs.Add(x) );\n</code></pre>\n<p><strong>Edit:</strong> The <code>HashSet</code> method is <code>O(N)</code> time and <code>O(N)</code> space while sorting and then making unique (as suggested by @<a href=\"https://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in-c#47755\">lassevk</a> and others) is <code>O(N*lgN)</code> time and <code>O(1)</code> space so it's not so clear to me (as it was at first glance) that the sorting way is inferior</p>\n" }, { "answer_id": 47776, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 8, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>var noDupes = list.Distinct().ToList();\n</code></pre>\n\n<p>In .net 3.5?</p>\n" }, { "answer_id": 47777, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 10, "selected": false, "text": "<p>If you're using .Net 3+, you can use Linq.</p>\n\n<pre><code>List&lt;T&gt; withDupes = LoadSomeData();\nList&lt;T&gt; noDupes = withDupes.Distinct().ToList();\n</code></pre>\n" }, { "answer_id": 48275, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": false, "text": "<p>As kronoz said in .Net 3.5 you can use <code>Distinct()</code>.</p>\n\n<p>In .Net 2 you could mimic it:</p>\n\n<pre><code>public IEnumerable&lt;T&gt; DedupCollection&lt;T&gt; (IEnumerable&lt;T&gt; input) \n{\n var passedValues = new HashSet&lt;T&gt;();\n\n // Relatively simple dupe check alg used as example\n foreach(T item in input)\n if(passedValues.Add(item)) // True if item is new\n yield return item;\n}\n</code></pre>\n\n<p>This could be used to dedupe any collection and will return the values in the original order.</p>\n\n<p>It's normally much quicker to filter a collection (as both <code>Distinct()</code> and this sample does) than it would be to remove items from it.</p>\n" }, { "answer_id": 1792582, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 7, "selected": false, "text": "<p><strong>Simply initialize a HashSet with a List of the same type:</strong></p>\n\n<pre><code>var noDupes = new HashSet&lt;T&gt;(withDupes);\n</code></pre>\n\n<p><strong>Or, if you want a List returned:</strong></p>\n\n<pre><code>var noDupsList = new HashSet&lt;T&gt;(withDupes).ToList();\n</code></pre>\n" }, { "answer_id": 2571314, "author": "Geoff Taylor", "author_id": 308300, "author_profile": "https://Stackoverflow.com/users/308300", "pm_score": 4, "selected": false, "text": "<p>An extension method might be a decent way to go... something like this:</p>\n\n<pre><code>public static List&lt;T&gt; Deduplicate&lt;T&gt;(this List&lt;T&gt; listToDeduplicate)\n{\n return listToDeduplicate.Distinct().ToList();\n}\n</code></pre>\n\n<p>And then call like this, for example:</p>\n\n<pre><code>List&lt;int&gt; myFilteredList = unfilteredList.Deduplicate();\n</code></pre>\n" }, { "answer_id": 4954239, "author": "Bhasin", "author_id": 610952, "author_profile": "https://Stackoverflow.com/users/610952", "pm_score": 2, "selected": false, "text": "<p>Another way in .Net 2.0</p>\n\n<pre><code> static void Main(string[] args)\n {\n List&lt;string&gt; alpha = new List&lt;string&gt;();\n\n for(char a = 'a'; a &lt;= 'd'; a++)\n {\n alpha.Add(a.ToString());\n alpha.Add(a.ToString());\n }\n\n Console.WriteLine(\"Data :\");\n alpha.ForEach(delegate(string t) { Console.WriteLine(t); });\n\n alpha.ForEach(delegate (string v)\n {\n if (alpha.FindAll(delegate(string t) { return t == v; }).Count &gt; 1)\n alpha.Remove(v);\n });\n\n Console.WriteLine(\"Unique Result :\");\n alpha.ForEach(delegate(string t) { Console.WriteLine(t);});\n Console.ReadKey();\n }\n</code></pre>\n" }, { "answer_id": 5114231, "author": "gary", "author_id": 63844, "author_profile": "https://Stackoverflow.com/users/63844", "pm_score": 3, "selected": false, "text": "<p>Here's an extension method for removing adjacent duplicates in-situ. Call Sort() first and pass in the same IComparer. This should be more efficient than Lasse V. Karlsen's version which calls RemoveAt repeatedly (resulting in multiple block memory moves).</p>\n\n<pre><code>public static void RemoveAdjacentDuplicates&lt;T&gt;(this List&lt;T&gt; List, IComparer&lt;T&gt; Comparer)\n{\n int NumUnique = 0;\n for (int i = 0; i &lt; List.Count; i++)\n if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))\n List[NumUnique++] = List[i];\n List.RemoveRange(NumUnique, List.Count - NumUnique);\n}\n</code></pre>\n" }, { "answer_id": 5609895, "author": "Ravi Ganesan", "author_id": 700589, "author_profile": "https://Stackoverflow.com/users/700589", "pm_score": 2, "selected": false, "text": "<p>There are many ways to solve - the duplicates issue in the List, below is one of them:</p>\n\n<pre><code>List&lt;Container&gt; containerList = LoadContainer();//Assume it has duplicates\nList&lt;Container&gt; filteredList = new List&lt;Container&gt;();\nforeach (var container in containerList)\n{ \n Container duplicateContainer = containerList.Find(delegate(Container checkContainer)\n { return (checkContainer.UniqueId == container.UniqueId); });\n //Assume 'UniqueId' is the property of the Container class on which u r making a search\n\n if(!containerList.Contains(duplicateContainer) //Add object when not found in the new class object\n {\n filteredList.Add(container);\n }\n }\n</code></pre>\n\n<p>Cheers\nRavi Ganesan</p>\n" }, { "answer_id": 9276761, "author": "David J.", "author_id": 1209045, "author_profile": "https://Stackoverflow.com/users/1209045", "pm_score": 2, "selected": false, "text": "<p>Here's a simple solution that doesn't require any hard-to-read LINQ or any prior sorting of the list.</p>\n\n<pre><code> private static void CheckForDuplicateItems(List&lt;string&gt; items)\n {\n if (items == null ||\n items.Count == 0)\n return;\n\n for (int outerIndex = 0; outerIndex &lt; items.Count; outerIndex++)\n {\n for (int innerIndex = 0; innerIndex &lt; items.Count; innerIndex++)\n {\n if (innerIndex == outerIndex) continue;\n if (items[outerIndex].Equals(items[innerIndex]))\n {\n // Duplicate Found\n }\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 11255357, "author": "Chris", "author_id": 1490135, "author_profile": "https://Stackoverflow.com/users/1490135", "pm_score": 2, "selected": false, "text": "<p>Might be easier to simply make sure that duplicates are not added to the list.</p>\n\n<pre><code>if(items.IndexOf(new_item) &lt; 0) \n items.add(new_item)\n</code></pre>\n" }, { "answer_id": 11694032, "author": "Eric", "author_id": 803629, "author_profile": "https://Stackoverflow.com/users/803629", "pm_score": 5, "selected": false, "text": "<p>I like to use this command:</p>\n<pre><code>List&lt;Store&gt; myStoreList = Service.GetStoreListbyProvince(provinceId)\n .GroupBy(s =&gt; s.City)\n .Select(grp =&gt; grp.FirstOrDefault())\n .OrderBy(s =&gt; s.City)\n .ToList();\n</code></pre>\n<p>I have these fields in my list: Id, StoreName, City, PostalCode\nI wanted to show list of cities in a dropdown which has duplicate values.\nsolution: Group by city then pick the first one for the list.</p>\n" }, { "answer_id": 13404160, "author": "Hossein Sarshar", "author_id": 1202836, "author_profile": "https://Stackoverflow.com/users/1202836", "pm_score": 5, "selected": false, "text": "<p>It worked for me. simply use</p>\n\n<pre><code>List&lt;Type&gt; liIDs = liIDs.Distinct().ToList&lt;Type&gt;();\n</code></pre>\n\n<p>Replace \"Type\" with your desired type e.g. int.</p>\n" }, { "answer_id": 19516222, "author": "Guest", "author_id": 2906798, "author_profile": "https://Stackoverflow.com/users/2906798", "pm_score": 2, "selected": false, "text": "<p>David J.'s answer is a good method, no need for extra objects, sorting, etc. It can be improved on however:</p>\n\n<p><code>for (int innerIndex = items.Count - 1; innerIndex &gt; outerIndex ; innerIndex--)</code></p>\n\n<p>So the outer loop goes top bottom for the entire list, but the inner loop goes bottom \"until the outer loop position is reached\".</p>\n\n<p>The outer loop makes sure the entire list is processed, the inner loop finds the actual duplicates, those can only happen in the part that the outer loop hasn't processed yet.</p>\n\n<p>Or if you don't want to do bottom up for the inner loop you could have the inner loop start at outerIndex + 1.</p>\n" }, { "answer_id": 23652999, "author": "Paul Richards", "author_id": 2282723, "author_profile": "https://Stackoverflow.com/users/2282723", "pm_score": 1, "selected": false, "text": "<pre><code> public static void RemoveDuplicates&lt;T&gt;(IList&lt;T&gt; list )\n {\n if (list == null)\n {\n return;\n }\n int i = 1;\n while(i&lt;list.Count)\n {\n int j = 0;\n bool remove = false;\n while (j &lt; i &amp;&amp; !remove)\n {\n if (list[i].Equals(list[j]))\n {\n remove = true;\n }\n j++;\n }\n if (remove)\n {\n list.RemoveAt(i);\n }\n else\n {\n i++;\n }\n } \n }\n</code></pre>\n" }, { "answer_id": 27004677, "author": "Grant", "author_id": 1618538, "author_profile": "https://Stackoverflow.com/users/1618538", "pm_score": 3, "selected": false, "text": "<p>As a helper method (without Linq):</p>\n\n<pre><code>public static List&lt;T&gt; Distinct&lt;T&gt;(this List&lt;T&gt; list)\n{\n return (new HashSet&lt;T&gt;(list)).ToList();\n}\n</code></pre>\n" }, { "answer_id": 42813216, "author": "dush88c", "author_id": 5097602, "author_profile": "https://Stackoverflow.com/users/5097602", "pm_score": 3, "selected": false, "text": "<p>Installing the <a href=\"https://morelinq.github.io/\" rel=\"noreferrer\">MoreLINQ</a> package via Nuget, you can easily distinct object list by a property </p>\n\n<pre><code>IEnumerable&lt;Catalogue&gt; distinctCatalogues = catalogues.DistinctBy(c =&gt; c.CatalogueCode); \n</code></pre>\n" }, { "answer_id": 45533433, "author": "flagamba", "author_id": 2352444, "author_profile": "https://Stackoverflow.com/users/2352444", "pm_score": 2, "selected": false, "text": "<p>You can use Union</p>\n\n<pre><code>obj2 = obj1.Union(obj1).ToList();\n</code></pre>\n" }, { "answer_id": 48767398, "author": "WonderWorker", "author_id": 1271898, "author_profile": "https://Stackoverflow.com/users/1271898", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Use Linq's <strong>Union</strong> method.</p>\n</blockquote>\n\n<p><em>Note: This solution requires no knowledge of Linq, aside from that it exists.</em></p>\n\n<p><strong>Code</strong></p>\n\n<p>Begin by adding the following to the top of your class file:</p>\n\n<pre><code>using System.Linq;\n</code></pre>\n\n<p>Now, you can use the following to remove duplicates from an object called, <code>obj1</code>:</p>\n\n<pre><code>obj1 = obj1.Union(obj1).ToList();\n</code></pre>\n\n<p><em>Note: Rename <code>obj1</code> to the name of your object.</em></p>\n\n<p><strong>How it works</strong></p>\n\n<ol>\n<li><p>The Union command lists one of each entry of two source objects. Since obj1 is both source objects, this reduces obj1 to one of each entry.</p></li>\n<li><p>The <code>ToList()</code> returns a new List. This is necessary, because Linq commands like <code>Union</code> returns the result as an IEnumerable result instead of modifying the original List or returning a new List.</p></li>\n</ol>\n" }, { "answer_id": 49916992, "author": "Moctar Haiz", "author_id": 3142365, "author_profile": "https://Stackoverflow.com/users/3142365", "pm_score": 2, "selected": false, "text": "<p>A simple intuitive implementation:</p>\n\n<pre><code>public static List&lt;PointF&gt; RemoveDuplicates(List&lt;PointF&gt; listPoints)\n{\n List&lt;PointF&gt; result = new List&lt;PointF&gt;();\n\n for (int i = 0; i &lt; listPoints.Count; i++)\n {\n if (!result.Contains(listPoints[i]))\n result.Add(listPoints[i]);\n }\n\n return result;\n }\n</code></pre>\n" }, { "answer_id": 53579622, "author": "Reza Jenabi", "author_id": 9549856, "author_profile": "https://Stackoverflow.com/users/9549856", "pm_score": 3, "selected": false, "text": "<p>If you have tow classes <code>Product</code> and <code>Customer</code> and we want to remove duplicate items from their list</p>\n\n<pre><code>public class Product\n{\n public int Id { get; set; }\n public string ProductName { get; set; }\n}\n\npublic class Customer\n{\n public int Id { get; set; }\n public string CustomerName { get; set; }\n\n}\n</code></pre>\n\n<p>You must define a generic class in the form below</p>\n\n<pre><code>public class ItemEqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt; where T : class\n{\n private readonly PropertyInfo _propertyInfo;\n\n public ItemEqualityComparer(string keyItem)\n {\n _propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);\n }\n\n public bool Equals(T x, T y)\n {\n var xValue = _propertyInfo?.GetValue(x, null);\n var yValue = _propertyInfo?.GetValue(y, null);\n return xValue != null &amp;&amp; yValue != null &amp;&amp; xValue.Equals(yValue);\n }\n\n public int GetHashCode(T obj)\n {\n var propertyValue = _propertyInfo.GetValue(obj, null);\n return propertyValue == null ? 0 : propertyValue.GetHashCode();\n }\n}\n</code></pre>\n\n<p>then, You can remove duplicate items in your list.</p>\n\n<pre><code>var products = new List&lt;Product&gt;\n {\n new Product{ProductName = \"product 1\" ,Id = 1,},\n new Product{ProductName = \"product 2\" ,Id = 2,},\n new Product{ProductName = \"product 2\" ,Id = 4,},\n new Product{ProductName = \"product 2\" ,Id = 4,},\n };\nvar productList = products.Distinct(new ItemEqualityComparer&lt;Product&gt;(nameof(Product.Id))).ToList();\n\nvar customers = new List&lt;Customer&gt;\n {\n new Customer{CustomerName = \"Customer 1\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n new Customer{CustomerName = \"Customer 2\" ,Id = 5,},\n };\nvar customerList = customers.Distinct(new ItemEqualityComparer&lt;Customer&gt;(nameof(Customer.Id))).ToList();\n</code></pre>\n\n<p>this code remove duplicate items by <code>Id</code> if you want remove duplicate items by other property, you can change <code>nameof(YourClass.DuplicateProperty)</code> same <code>nameof(Customer.CustomerName)</code> then remove duplicate items by <code>CustomerName</code> Property.</p>\n" }, { "answer_id": 55140260, "author": "Alfred Udah", "author_id": 6468488, "author_profile": "https://Stackoverflow.com/users/6468488", "pm_score": 4, "selected": false, "text": "<p>This takes distinct (the elements without duplicating elements) and convert it into a list again:</p>\n\n<pre><code>List&lt;type&gt; myNoneDuplicateValue = listValueWithDuplicate.Distinct().ToList();\n</code></pre>\n" }, { "answer_id": 56344965, "author": "Darkgaze", "author_id": 772739, "author_profile": "https://Stackoverflow.com/users/772739", "pm_score": 2, "selected": false, "text": "<p>All answers copy lists, or create a new list, or use slow functions, or are just painfully slow.</p>\n\n<p>To my understanding, this is the <strong>fastest and cheapest method</strong> I know (also, backed by a very experienced programmer specialized on real-time physics optimization).</p>\n\n<pre><code>// Duplicates will be noticed after a sort O(nLogn)\nlist.Sort();\n\n// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...\nint lastItem = -1;\nint currItem = -1;\n\nint size = list.Count;\n\n// Store the index pointing to the last item we want to keep in the list\nint last = size - 1;\n\n// Travel the items from last to first O(n)\nfor (int i = last; i &gt;= 0; --i)\n{\n currItem = list[i];\n\n // If this item was the same as the previous one, we don't want it\n if (currItem == lastItem)\n {\n // Overwrite last in current place. It is a swap but we don't need the last\n list[i] = list[last];\n\n // Reduce the last index, we don't want that one anymore\n last--;\n }\n\n // A new item, we store it and continue\n else\n lastItem = currItem;\n}\n\n// We now have an unsorted list with the duplicates at the end.\n\n// Remove the last items just once\nlist.RemoveRange(last + 1, size - last - 1);\n\n// Sort again O(n logn)\nlist.Sort();\n</code></pre>\n\n<p>Final cost is:</p>\n\n<p>nlogn + n + nlogn = n + 2nlogn = <strong>O(nlogn)</strong> which is pretty nice.</p>\n\n<p><em>Note about RemoveRange:</em>\nSince we cannot set the count of the list and avoid using the Remove funcions, I don't know exactly the speed of this operation but I guess it is the fastest way. </p>\n" }, { "answer_id": 63762013, "author": "user3150241", "author_id": 3150241, "author_profile": "https://Stackoverflow.com/users/3150241", "pm_score": 0, "selected": false, "text": "<p>I think the simplest way is:</p>\n<p>Create a new list and add unique item.</p>\n<p>Example:</p>\n<pre><code> class MyList{\n int id;\n string date;\n string email;\n }\n \n List&lt;MyList&gt; ml = new Mylist();\n\nml.Add(new MyList(){\nid = 1;\ndate = &quot;2020/09/06&quot;;\nemail = &quot;zarezadeh@gmailcom&quot;\n});\n\nml.Add(new MyList(){\nid = 2;\ndate = &quot;2020/09/01&quot;;\nemail = &quot;zarezadeh@gmailcom&quot;\n});\n\n List&lt;MyList&gt; New_ml = new Mylist();\n\nforeach (var item in ml)\n {\n if (New_ml.Where(w =&gt; w.email == item.email).SingleOrDefault() == null)\n {\n New_ml.Add(new MyList()\n {\n id = item.id,\n date = item.date,\n email = item.email\n });\n }\n }\n</code></pre>\n" }, { "answer_id": 68057196, "author": "Lahiru Gamage", "author_id": 4991516, "author_profile": "https://Stackoverflow.com/users/4991516", "pm_score": 2, "selected": false, "text": "<p>Using <a href=\"https://www.delftstack.com/howto/csharp/csharp-remove-duplicates-from-list/\" rel=\"nofollow noreferrer\"><strong>HashSet</strong></a> this can be done easily.</p>\n<pre><code>List&lt;int&gt; listWithDuplicates = new List&lt;int&gt; { 1, 2, 1, 2, 3, 4, 5 };\nHashSet&lt;int&gt; hashWithoutDuplicates = new HashSet&lt;int&gt; ( listWithDuplicates );\nList&lt;int&gt; listWithoutDuplicates = hashWithoutDuplicates.ToList();\n</code></pre>\n" }, { "answer_id": 68962170, "author": "Shravankumar Prajapati", "author_id": 16772141, "author_profile": "https://Stackoverflow.com/users/16772141", "pm_score": 0, "selected": false, "text": "<p>As per remove duplicate, We have to apply below logic so It will remove duplicate in fast ways.</p>\n<pre><code>public class Program\n{\n\n public static void Main(string[] arges)\n {\n List&lt;string&gt; cities = new List&lt;string&gt;() { &quot;Chennai&quot;, &quot;Kolkata&quot;, &quot;Mumbai&quot;, &quot;Mumbai&quot;,&quot;Chennai&quot;, &quot;Delhi&quot;, &quot;Delhi&quot;, &quot;Delhi&quot;, &quot;Chennai&quot;, &quot;Kolkata&quot;, &quot;Mumbai&quot;, &quot;Chennai&quot; };\n cities = RemoveDuplicate(cities);\n\n foreach (var city in cities)\n {\n Console.WriteLine(city);\n }\n }\n\n public static List&lt;string&gt; RemoveDuplicate(List&lt;string&gt; cities)\n {\n if (cities.Count &lt; 2)\n {\n return cities;\n }\n\n int size = cities.Count;\n for (int i = 0; i &lt; size; i++)\n {\n for (int j = i+1; j &lt; size; j++)\n {\n if (cities[i] == cities[j])\n {\n cities.RemoveAt(j);\n size--;\n j--;\n }\n }\n }\n return cities;\n }\n}\n</code></pre>\n" }, { "answer_id": 69658860, "author": "Infosunny", "author_id": 10070007, "author_profile": "https://Stackoverflow.com/users/10070007", "pm_score": 1, "selected": false, "text": "<p>Using HashSet:\n<code>list = new HashSet&lt;T&gt;(list).ToList();</code></p>\n" }, { "answer_id": 70162977, "author": "Onat Korucu", "author_id": 10037278, "author_profile": "https://Stackoverflow.com/users/10037278", "pm_score": 1, "selected": false, "text": "<p>If you need to compare complex objects, you will need to pass a Comparer object inside the Distinct() method.</p>\n<pre><code>private void GetDistinctItemList(List&lt;MyListItem&gt; _listWithDuplicates)\n{\n //It might be a good idea to create MyListItemComparer \n //elsewhere and cache it for performance.\n List&lt;MyListItem&gt; _listWithoutDuplicates = _listWithDuplicates.Distinct(new MyListItemComparer()).ToList();\n \n //Choose the line below instead, if you have a situation where there is a chance to change the list while Distinct() is running.\n //ToArray() is used to solve &quot;Collection was modified; enumeration operation may not execute&quot; error.\n //List&lt;MyListItem&gt; _listWithoutDuplicates = _listWithDuplicates.ToArray().Distinct(new MyListItemComparer()).ToList();\n\n return _listWithoutDuplicates;\n}\n</code></pre>\n<p>Assuming you have 2 other classes like:</p>\n<pre><code>public class MyListItemComparer : IEqualityComparer&lt;MyListItem&gt;\n{\n public bool Equals(MyListItem x, MyListItem y)\n {\n return x != null \n &amp;&amp; y != null \n &amp;&amp; x.A == y.A \n &amp;&amp; x.B.Equals(y.B); \n &amp;&amp; x.C.ToString().Equals(y.C.ToString());\n }\n\n public int GetHashCode(MyListItem codeh)\n {\n return codeh.GetHashCode();\n }\n}\n</code></pre>\n<p>And:</p>\n<pre><code>public class MyListItem\n{\n public int A { get; }\n public string B { get; }\n public MyEnum C { get; }\n\n public MyListItem(int a, string b, MyEnum c)\n {\n A = a;\n B = b;\n C = c;\n }\n}\n</code></pre>\n" }, { "answer_id": 73453803, "author": "Hasan Tuna Oruç", "author_id": 4578450, "author_profile": "https://Stackoverflow.com/users/4578450", "pm_score": 0, "selected": false, "text": "<p>I have my own way. I am 2 looping same list for compare list items. And then remove second one.</p>\n<pre><code> for(int i1 = 0; i1 &lt; lastValues.Count; i1++)\n {\n for(int i2 = 0; i2 &lt; lastValues.Count; i2++)\n {\n if(lastValues[i1].UserId == lastValues[i2].UserId)\n {\n lastValues.RemoveAt(i2);\n }\n }\n }\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
Anyone have a quick method for de-duplicating a generic List in C#?
Perhaps you should consider using a [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx). From the MSDN link: ``` using System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> evenNumbers = new HashSet<int>(); HashSet<int> oddNumbers = new HashSet<int>(); for (int i = 0; i < 5; i++) { // Populate numbers with just even numbers. evenNumbers.Add(i * 2); // Populate oddNumbers with just odd numbers. oddNumbers.Add((i * 2) + 1); } Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count); DisplaySet(evenNumbers); Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count); DisplaySet(oddNumbers); // Create a new HashSet populated with even numbers. HashSet<int> numbers = new HashSet<int>(evenNumbers); Console.WriteLine("numbers UnionWith oddNumbers..."); numbers.UnionWith(oddNumbers); Console.Write("numbers contains {0} elements: ", numbers.Count); DisplaySet(numbers); } private static void DisplaySet(HashSet<int> set) { Console.Write("{"); foreach (int i in set) { Console.Write(" {0}", i); } Console.WriteLine(" }"); } } /* This example produces output similar to the following: * evenNumbers contains 5 elements: { 0 2 4 6 8 } * oddNumbers contains 5 elements: { 1 3 5 7 9 } * numbers UnionWith oddNumbers... * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 } */ ```
47,762
<p>I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing.</p> <p>problem statement: </p> <ul> <li>a user enters several keywords/tokens</li> <li>the application searches for matches to the tokens</li> <li>need one result for each token <ul> <li>ie, if an entry has 3 tokens, i need the entry id 3 times</li> </ul></li> <li>rank the results <ul> <li>assign X points for token match</li> <li>sort the entry ids based on points</li> <li>if point values are the same, use date to sort results</li> </ul></li> </ul> <p>What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked.</p> <p>Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those?</p> <p><strong>edit</strong><br> I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this:</p> <pre><code>'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3 </code></pre>
[ { "answer_id": 47796, "author": "Robin Barnes", "author_id": 1349865, "author_profile": "https://Stackoverflow.com/users/1349865", "pm_score": 4, "selected": true, "text": "<p>you could achive this in one query using 'UNION ALL' in MySQL.</p>\n\n<p>Just loop through the tokens in PHP creating a UNION ALL for each token:</p>\n\n<p>e.g if the tokens are 'x', 'y' and 'z' your query may look something like this</p>\n\n<pre><code>SELECT * FROM `entries` \nWHERE token like \"%x%\" union all \n SELECT * FROM `entries` \n WHERE token like \"%y%\" union all \n SELECT * FROM `entries` \n WHERE token like \"%z%\" ORDER BY score ect...\n</code></pre>\n\n<p>The order clause should operate on the entire result set as one, which is what you need.</p>\n\n<p>In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.</p>\n" }, { "answer_id": 47853, "author": "Erik", "author_id": 4484, "author_profile": "https://Stackoverflow.com/users/4484", "pm_score": 1, "selected": false, "text": "<p>If you're using the UNION ALL pattern you may also want to include the following parts to your query:</p>\n\n<pre><code>SELECT COUNT(*) AS C\n...\nGROUP BY ID\nORDER BY c DESC\n</code></pre>\n\n<p>While this is a really trivial example it does get you the frequency of the matches for each result and this could be a pseudo rank to start with.</p>\n" }, { "answer_id": 49301, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": -1, "selected": false, "text": "<p>You'll probably get much better performance if you used a data structure designed for search tasks rather than a database. For example, you might try looking at building an <a href=\"http://en.wikipedia.org/wiki/Inverted_index\" rel=\"nofollow noreferrer\">inverted index</a>. Rather than writing it youself, however, you might also want to look into something like <a href=\"http://en.wikipedia.org/wiki/Lucene\" rel=\"nofollow noreferrer\">Lucene</a> which does most of the work for you.</p>\n" }, { "answer_id": 49388, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 2, "selected": false, "text": "<p>I know this isn't strictly an answer to the question you're asking <strong>but if your table is thousands rather than millions of rows</strong>, then a FULLTEXT solution might be the best way to go here.</p>\n\n<p>In MySQL when you use MATCH on your indexed column, each keyword you supply will be given a relevance score (calculated roughly by the number of times each keyword was mentioned) that will be more accurate than your method and certainly more effecient for multiple keywords.</p>\n\n<p>See here:\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html</a></p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4418/" ]
I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing. problem statement: * a user enters several keywords/tokens * the application searches for matches to the tokens * need one result for each token + ie, if an entry has 3 tokens, i need the entry id 3 times * rank the results + assign X points for token match + sort the entry ids based on points + if point values are the same, use date to sort results What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked. Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those? **edit** I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this: ``` 'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3 ```
you could achive this in one query using 'UNION ALL' in MySQL. Just loop through the tokens in PHP creating a UNION ALL for each token: e.g if the tokens are 'x', 'y' and 'z' your query may look something like this ``` SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE token like "%y%" union all SELECT * FROM `entries` WHERE token like "%z%" ORDER BY score ect... ``` The order clause should operate on the entire result set as one, which is what you need. In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.
47,780
<p>I have an inherited project that uses a build script (not make) to build and link the project with various libraries.</p> <p>When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.</p> <p>The script is compiling and linking with GNU tools.</p>
[ { "answer_id": 47805, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 0, "selected": false, "text": "<p>Static libraries, that makes life more difficult in this regard. In case of dynamic libraries you could just have used ldd on the resulting executable and be done with it. The best bet would be some kind of configuration file. Alternatively you could try to look for -l arguments to gcc/ld. Those are used to specify libraries. You could write a script for extracting it from the output, though I suspect that you will have to do it manually because by the time you know what the script should look for you probably already know the answer.</p>\n" }, { "answer_id": 47807, "author": "Xavier Nodet", "author_id": 4177, "author_profile": "https://Stackoverflow.com/users/4177", "pm_score": 0, "selected": false, "text": "<p>It is probably possible to do something useful using e.g. Perl, but you would have to provide more details. On the other hand, it could be easier to simply analyze the script... </p>\n" }, { "answer_id": 47809, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 1, "selected": false, "text": "<p>You might try using the <code>nm</code> tool. Given the right options, it will look at a binary (archive or linked image) and tell you what objects were linked into it.</p>\n\n<p>Actually, here's a one-liner I use at work:</p>\n\n<pre><code>#!/bin/sh\n\nnm -Ag $* | sed 's/^.*\\/\\(.*\\.a\\):/\\1/' | sort -k 3 | grep -v ' U '\n</code></pre>\n\n<p>to find the culprits for undefined symbols. Just chop off the last grep expression and it should pretty much give you what you want.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
I have an inherited project that uses a build script (not make) to build and link the project with various libraries. When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from. The script is compiling and linking with GNU tools.
You might try using the `nm` tool. Given the right options, it will look at a binary (archive or linked image) and tell you what objects were linked into it. Actually, here's a one-liner I use at work: ``` #!/bin/sh nm -Ag $* | sed 's/^.*\/\(.*\.a\):/\1/' | sort -k 3 | grep -v ' U ' ``` to find the culprits for undefined symbols. Just chop off the last grep expression and it should pretty much give you what you want.
47,786
<p>Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do:</p> <pre><code>SELECT blah FROM blah WHERE blah LIKE '%text%' </code></pre> <p>The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?</p>
[ { "answer_id": 47811, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 7, "selected": true, "text": "<p>BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table.</p>\n\n<p>In other words, every query must use an index. This is why you can only do <code>=</code>, <code>&gt;</code> and <code>&lt;</code> queries. (In fact you can also do <code>!=</code> but the API does this using a a combination of <code>&gt;</code> and <code>&lt;</code> queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your <code>index.yaml</code> file.</p>\n\n<p>There is no way to index for a <code>LIKE</code> query so it's simply not available.</p>\n\n<p>Have a watch of <a href=\"http://sites.google.com/site/io/under-the-covers-of-the-google-app-engine-datastore\" rel=\"noreferrer\">this Google IO session</a> for a much better and more detailed explanation of this.</p>\n" }, { "answer_id": 1096744, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>i'm facing the same problem, but i found something on google app engine pages:</p>\n\n<p>Tip: Query filters do not have an explicit way to match just part of a string value, but you can fake a prefix match using inequality filters:</p>\n\n<pre><code>db.GqlQuery(\"SELECT * FROM MyModel WHERE prop &gt;= :1 AND prop &lt; :2\",\n \"abc\",\n u\"abc\" + u\"\\ufffd\")\n</code></pre>\n\n<p>This matches every MyModel entity with a string property prop that begins with the characters abc. The unicode string u\"\\ufffd\" represents the largest possible Unicode character. When the property values are sorted in an index, the values that fall in this range are all of the values that begin with the given prefix.</p>\n\n<p><a href=\"http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html\" rel=\"noreferrer\">http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html</a></p>\n\n<p>maybe this could do the trick ;)</p>\n" }, { "answer_id": 2136253, "author": "jbochi", "author_id": 230636, "author_profile": "https://Stackoverflow.com/users/230636", "pm_score": 4, "selected": false, "text": "<p>Altough App Engine does not support LIKE queries, have a look at the properties <a href=\"http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ListProperty\" rel=\"noreferrer\">ListProperty</a> and <a href=\"http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#StringListProperty\" rel=\"noreferrer\">StringListProperty</a>. When an equality test is done on these properties, the test will actually be applied on all list members, e.g., <code>list_property = value</code> tests if the value appears anywhere in the list.</p>\n\n<p>Sometimes this feature might be used as a workaround to the lack of LIKE queries. For instance, it makes it possible to do <a href=\"http://www.billkatz.com/2009/6/Simple-Full-Text-Search-for-App-Engine\" rel=\"noreferrer\">simple text search, as described on this post</a>.</p>\n" }, { "answer_id": 6204951, "author": "fernandohur", "author_id": 718333, "author_profile": "https://Stackoverflow.com/users/718333", "pm_score": 2, "selected": false, "text": "<p>Have a look at Objectify <a href=\"http://code.google.com/p/objectify-appengine/wiki/FrequentlyAskedQuestions#How_do_I_do_a_like_query_%28LIKE_%22foo%%22%29\" rel=\"nofollow\">here</a> , it is like a Datastore access API. There is a FAQ with this question specifically, here is the answer</p>\n\n<blockquote>\n <p>How do I do a like query (LIKE \"foo%\")<br>\n You can do something like a startWith, or endWith if you reverse the order when stored and searched. You do a range query with the starting value you want, and a value just above the one you want.</p>\n</blockquote>\n\n<pre><code>String start = \"foo\";\n ... = ofy.query(MyEntity.class).filter(\"field &gt;=\", start).filter(\"field &lt;\", start + \"\\uFFFD\");\n</code></pre>\n" }, { "answer_id": 7529428, "author": "topchef", "author_id": 59470, "author_profile": "https://Stackoverflow.com/users/59470", "pm_score": 0, "selected": false, "text": "<p>If the <code>LIKE '%text%'</code> always compares to a word or a few (think permutations) and your data changes slowly (slowly means that it's not prohibitively expensive - both price-wise and performance-wise - to create and updates indexes) then Relation Index Entity (RIE) may be the answer. </p>\n\n<p>Yes, you will have to build additional datastore entity and populate it appropriately. Yes, there are some constraints that you will have to play around (one is 5000 limit on the length of list property in GAE datastore). But the resulting searches are lightning fast. </p>\n\n<p>For details see my <a href=\"http://novyden.blogspot.com/2011/02/efficient-keyword-search-with-relation.html\" rel=\"nofollow\">RIE with Java and Ojbectify</a> and <a href=\"http://novyden.blogspot.com/2011/09/efficient-keyword-search-with-relation.html\" rel=\"nofollow\">RIE with Python</a> posts. </p>\n" }, { "answer_id": 8281498, "author": "amit kumar", "author_id": 19501, "author_profile": "https://Stackoverflow.com/users/19501", "pm_score": 0, "selected": false, "text": "<p>\"Like\" is often uses as a poor-man's substitute for text search. For text search, it is possible to use <a href=\"https://github.com/tallstreet/Whoosh-AppEngine\" rel=\"nofollow\">Whoosh-AppEngine</a>. </p>\n" }, { "answer_id": 11112100, "author": "gzerone", "author_id": 1070813, "author_profile": "https://Stackoverflow.com/users/1070813", "pm_score": 1, "selected": false, "text": "<p>Just follow here:\ninit.py#354\">http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/search/<strong>init</strong>.py#354</p>\n\n<p>It works!</p>\n\n<pre><code>class Article(search.SearchableModel):\n text = db.TextProperty()\n ...\n\n article = Article(text=...)\n article.save()\n\nTo search the full text index, use the SearchableModel.all() method to get an\ninstance of SearchableModel.Query, which subclasses db.Query. Use its search()\nmethod to provide a search query, in addition to any other filters or sort\norders, e.g.:\n\n query = article.all().search('a search query').filter(...).order(...)\n</code></pre>\n" }, { "answer_id": 12697316, "author": "ryan", "author_id": 186123, "author_profile": "https://Stackoverflow.com/users/186123", "pm_score": 2, "selected": false, "text": "<p>App engine launched a general-purpose <a href=\"https://developers.google.com/appengine/docs/python/search/overview\" rel=\"nofollow\">full text search service</a> in version 1.7.0 that supports the datastore. </p>\n\n<p>Details in the <a href=\"http://googleappengine.blogspot.com/2012/05/looking-for-search-find-it-on-google.html\" rel=\"nofollow\">announcement</a>.</p>\n\n<p>More information on how to use this: <a href=\"https://cloud.google.com/appengine/training/fts_intro/lesson2\" rel=\"nofollow\">https://cloud.google.com/appengine/training/fts_intro/lesson2</a></p>\n" }, { "answer_id": 20204585, "author": "musketyr", "author_id": 227419, "author_profile": "https://Stackoverflow.com/users/227419", "pm_score": 3, "selected": false, "text": "<p>You need to use <a href=\"https://developers.google.com/appengine/docs/java/search/\">search service</a> to perform full text search queries similar to SQL <code>LIKE</code>.</p>\n\n<p><a href=\"http://gaelyk.appspot.com/\">Gaelyk</a> provides domain specific language to perform more <a href=\"http://gaelyk.appspot.com/tutorial/app-engine-shortcuts#advanced_fulltext_search\">user friendly search queries</a>. For example following snippet will find first ten books sorted from the latest ones with title containing <code>fern</code>\nand the genre exactly matching <code>thriller</code>:</p>\n\n<pre><code>def documents = search.search {\n select all from books\n sort desc by published, SearchApiLimits.MINIMUM_DATE_VALUE\n where title =~ 'fern'\n and genre = 'thriller'\n limit 10\n}\n</code></pre>\n\n<p>Like is written as Groovy's match operator <code>=~</code>.\nIt supports functions such as <code>distance(geopoint(lat, lon), location)</code> as well.</p>\n" }, { "answer_id": 24414573, "author": "Edy Aguirre", "author_id": 1617646, "author_profile": "https://Stackoverflow.com/users/1617646", "pm_score": 1, "selected": false, "text": "<p>I tested this with GAE Datastore low-level Java API. Me and works perfectly</p>\n\n<pre><code> Query q = new Query(Directorio.class.getSimpleName());\n\n Filter filterNombreGreater = new FilterPredicate(\"nombre\", FilterOperator.GREATER_THAN_OR_EQUAL, query);\n Filter filterNombreLess = new FilterPredicate(\"nombre\", FilterOperator.LESS_THAN, query+\"\\uFFFD\");\n Filter filterNombre = CompositeFilterOperator.and(filterNombreGreater, filterNombreLess);\n\n q.setFilter(filter);\n</code></pre>\n" }, { "answer_id": 29152005, "author": "chuycepeda", "author_id": 2178032, "author_profile": "https://Stackoverflow.com/users/2178032", "pm_score": 1, "selected": false, "text": "<p>In general, even though this is an old post, a way to produce a 'LIKE' or 'ILIKE' is to gather all results from a '>=' query, then loop results in python (or Java) for elements containing what you're looking for.</p>\n\n<p>Let's say you want to filter users given a q='luigi'</p>\n\n<pre><code>users = []\nqry = self.user_model.query(ndb.OR(self.user_model.name &gt;= q.lower(),self.user_model.email &gt;= q.lower(),self.user_model.username &gt;= q.lower()))\n\nfor _qry in qry:\n if q.lower() in _qry.name.lower() or q.lower() in _qry.email.lower() or q.lower() in _qry.username.lower():\n users.append(_qry)\n</code></pre>\n" }, { "answer_id": 38926030, "author": "Jose Salas", "author_id": 3878671, "author_profile": "https://Stackoverflow.com/users/3878671", "pm_score": 1, "selected": false, "text": "<p>It is not possible to do a LIKE search on datastore app engine, how ever creating an Arraylist would do the trick if you need to search a word in a string. </p>\n\n<pre><code>@Index\n public ArrayList&lt;String&gt; searchName;\n</code></pre>\n\n<p>and then to search in the index using objectify.</p>\n\n<pre><code>List&lt;Profiles&gt; list1 = ofy().load().type(Profiles.class).filter(\"searchName =\",search).list();\n</code></pre>\n\n<p>and this will give you a list with all the items that contain the world you did on the search</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do: ``` SELECT blah FROM blah WHERE blah LIKE '%text%' ``` The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?
BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table. In other words, every query must use an index. This is why you can only do `=`, `>` and `<` queries. (In fact you can also do `!=` but the API does this using a a combination of `>` and `<` queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your `index.yaml` file. There is no way to index for a `LIKE` query so it's simply not available. Have a watch of [this Google IO session](http://sites.google.com/site/io/under-the-covers-of-the-google-app-engine-datastore) for a much better and more detailed explanation of this.
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
[ { "answer_id": 47792, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 7, "selected": false, "text": "<p>Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.</p>\n\n<p>See <a href=\"https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions\" rel=\"noreferrer\">Generator expressions and list comprehensions</a> for more info.</p>\n" }, { "answer_id": 47793, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": false, "text": "<p>Iterating over the <em>generator expression</em> or the <em>list comprehension</em> will do the same thing. However, the <em>list comprehension</em> will create the entire list in memory first while the <em>generator expression</em> will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.</p>\n" }, { "answer_id": 47826, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 9, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/a/47792/4518341\">John's answer</a> is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:</p>\n\n<pre><code>def gen():\n return (something for something in get_some_stuff())\n\nprint gen()[:2] # generators don't support indexing or slicing\nprint [5,6] + gen() # generators can't be added to lists\n</code></pre>\n\n<p>Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.</p>\n\n<p>Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.</p>\n" }, { "answer_id": 53255, "author": "Jacob Rigby", "author_id": 5357, "author_profile": "https://Stackoverflow.com/users/5357", "pm_score": 2, "selected": false, "text": "<p>Sometimes you can get away with the <em>tee</em> function from <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\">itertools</a>, it returns multiple iterators for the same generator that can be used independently.</p>\n" }, { "answer_id": 189840, "author": "Chuck", "author_id": 23788, "author_profile": "https://Stackoverflow.com/users/23788", "pm_score": 6, "selected": false, "text": "<p>The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.</p>\n\n<p>For example:</p>\n\n<pre><code>sum(x*2 for x in xrange(256))\n\ndict( (k, some_func(k)) for k in some_list_of_keys )\n</code></pre>\n\n<p>The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)</p>\n\n<p>You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.</p>\n\n<p>For example:</p>\n\n<pre><code>reversed( [x*2 for x in xrange(256)] )\n</code></pre>\n" }, { "answer_id": 22858478, "author": "tylerl", "author_id": 86060, "author_profile": "https://Stackoverflow.com/users/86060", "pm_score": 6, "selected": false, "text": "<p>The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will \"filter\" the source material on-the-fly as you consume the bits.</p>\n\n<p>Imagine you have a 2TB log file called \"hugefile.txt\", and you want the content and length for all the lines that start with the word \"ENTRY\".</p>\n\n<p>So you try starting out by writing a list comprehension:</p>\n\n<pre><code>logfile = open(\"hugefile.txt\",\"r\")\nentry_lines = [(line,len(line)) for line in logfile if line.startswith(\"ENTRY\")]\n</code></pre>\n\n<p>This slurps up the whole file, processes each line, and stores the matching lines in your array. This array could therefore contain up to 2TB of content. That's a lot of RAM, and probably not practical for your purposes.</p>\n\n<p>So instead we can use a generator to apply a \"filter\" to our content. No data is actually read until we start iterating over the result.</p>\n\n<pre><code>logfile = open(\"hugefile.txt\",\"r\")\nentry_lines = ((line,len(line)) for line in logfile if line.startswith(\"ENTRY\"))\n</code></pre>\n\n<p>Not even a single line has been read from our file yet. In fact, say we want to filter our result even further:</p>\n\n<pre><code>long_entries = ((line,length) for (line,length) in entry_lines if length &gt; 80)\n</code></pre>\n\n<p>Still nothing has been read, but we've specified now two generators that will act on our data as we wish.</p>\n\n<p>Lets write out our filtered lines to another file:</p>\n\n<pre><code>outfile = open(\"filtered.txt\",\"a\")\nfor entry,length in long_entries:\n outfile.write(entry)\n</code></pre>\n\n<p><em>Now</em> we read the input file. As our <code>for</code> loop continues to request additional lines, the <code>long_entries</code> generator demands lines from the <code>entry_lines</code> generator, returning only those whose length is greater than 80 characters. And in turn, the <code>entry_lines</code> generator requests lines (filtered as indicated) from the <code>logfile</code> iterator, which in turn reads the file.</p>\n\n<p>So instead of \"pushing\" data to your output function in the form of a fully-populated list, you're giving the output function a way to \"pull\" data only when its needed. This is in our case much more efficient, but not quite as flexible. Generators are one way, one pass; the data from the log file we've read gets immediately discarded, so we can't go back to a previous line. On the other hand, we don't have to worry about keeping data around once we're done with it.</p>\n" }, { "answer_id": 34599335, "author": "Murphy", "author_id": 4909533, "author_profile": "https://Stackoverflow.com/users/4909533", "pm_score": 2, "selected": false, "text": "<p>I'm using the <a href=\"https://github.com/michaelfairley/mincemeatpy\" rel=\"nofollow noreferrer\">Hadoop Mincemeat module</a>. I think this is a great example to take a note of:</p>\n\n<pre><code>import mincemeat\n\ndef mapfn(k,v):\n for w in v:\n yield 'sum',w\n #yield 'count',1\n\n\ndef reducefn(k,v): \n r1=sum(v)\n r2=len(v)\n print r2\n m=r1/r2\n std=0\n for i in range(r2):\n std+=pow(abs(v[i]-m),2) \n res=pow((std/r2),0.5)\n return r1,r2,res\n</code></pre>\n\n<p>Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop's map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).</p>\n\n<p>Hadoop is a great example for using all the advantages of Generators.</p>\n" }, { "answer_id": 35964024, "author": "freaker", "author_id": 1555083, "author_profile": "https://Stackoverflow.com/users/1555083", "pm_score": 4, "selected": false, "text": "<p>When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:</p>\n\n<pre><code>&gt;&gt;&gt; mylist = [\"a\", \"b\", \"c\"]\n&gt;&gt;&gt; gen = (elem + \"1\" for elem in mylist)\n&gt;&gt;&gt; mylist.clear()\n&gt;&gt;&gt; for x in gen: print (x)\n# nothing\n</code></pre>\n\n<p>If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.</p>\n" }, { "answer_id": 62709748, "author": "kevin_theinfinityfund", "author_id": 8419574, "author_profile": "https://Stackoverflow.com/users/8419574", "pm_score": 4, "selected": false, "text": "<p>Python 3.7:</p>\n<p><strong>List comprehensions are faster.</strong></p>\n<p><a href=\"https://i.stack.imgur.com/laJz8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/laJz8.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Generators are more memory efficient.</strong>\n<a href=\"https://i.stack.imgur.com/mIcuz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mIcuz.png\" alt=\"enter image description here\" /></a></p>\n<p>As all others have said, if you're looking to scale infinite data, you'll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.</p>\n" }, { "answer_id": 65724791, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 2, "selected": false, "text": "<p>List comprehensions are eager but generators are lazy.</p>\n<p>In list comprehensions all objects are created right away, it takes longer to create and return the list. In generator expressions, object creation is delayed until request by <code>next()</code>. Upon <code>next()</code> generator object is created and returned immediately.</p>\n<p>Iteration is faster in list comprehensions because objects are already created.</p>\n<p>If you iterate all the elements in list comprehension and generator expression, time performance is about the same. Even though generator expression return generator object right away, it does not create all the elements. Everytime you iterate over a new element, it will create and return it.</p>\n<p>But if you do not iterate through all the elements generator are more efficient. Let's say you need to create a list comprehensions that contains millions of items but you are using only 10 of them. You still have to create millions of items. You are just wasting time for making millions of calculations to create millions of items to use only 10. Or if you are making millions of api requests but end up using only 10 of them. Since generator expressions are lazy, it does not make all the calculations or api calls unless it is requested. In this case using generator expressions will be more efficient.</p>\n<p>In list comprehensions entire collection is loaded to the memory. But generator expressions, once it returns a value to you upon your <code>next()</code> call, it is done with it and it does not need to store it in the memory any more. Only a single item is loaded to the memory. If you are iterating over a huge file in disk, if file is too big you might get memory issue. In this case using generator expression is more efficient.</p>\n" }, { "answer_id": 70421574, "author": "Praise", "author_id": 12643112, "author_profile": "https://Stackoverflow.com/users/12643112", "pm_score": 1, "selected": false, "text": "<p>There is something that I think most of the answers have missed. List comprehension basically creates a list and adds it to the stack. In cases where the list object is extremely large, your script process would be killed. A generator would be more preferred in this case as its values are not stored in memory but rather stored as a stateful function. Also speed of creation; list comprehension are slower than generator comprehension</p>\n<p>In short;\nuse list comprehension when the size of the obj is not excessively large else use generator comprehension</p>\n" }, { "answer_id": 70735656, "author": "JayS", "author_id": 1812942, "author_profile": "https://Stackoverflow.com/users/1812942", "pm_score": 0, "selected": false, "text": "<p>For functional programming, we want to use as little indexing as possible. For this reason, If we want to continue using the elements after we take the first slice of elements, islice() is a better choice since the iterator state is saved.</p>\n<pre><code>from itertools import islice\n\ndef slice_and_continue(sequence):\n ret = []\n seq_i = iter(sequence) #create an iterator from the list\n\n seq_slice = islice(seq_i,3) #take first 3 elements and print\n for x in seq_slice: print(x),\n\n for x in seq_i: print(x**2), #square the rest of the numbers\n\nslice_and_continue([1,2,3,4,5])\n</code></pre>\n<p>output: 1 2 3 16 25</p>\n" }, { "answer_id": 73214760, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 1, "selected": false, "text": "<p>Some notes for built-in Python functions:</p>\n<p>Use a generator expression if you need to <a href=\"https://stackoverflow.com/questions/17246388\">exploit the short-circuiting behaviour of <code>any</code> or <code>all</code></a>. These functions are designed to stop iterating when the answer is known, but a list comprehension must evaluate every element before the function can be called. (<code>any</code> and <code>all</code> will still stop checking elements for <a href=\"https://stackoverflow.com/questions/39983695/\">truthiness</a> when they have the answer, given a list from a list comprehension; however, this is usually trivial compared to the work of actually computing the elements.)</p>\n<p>Generator expressions are of course more memory efficient where they can be used. List comprehensions will be <em>slightly</em> faster with the non-short-circuiting <code>min</code>, <code>max</code> and <code>sum</code> (timings for <code>max</code> shown here):</p>\n<pre><code>$ python -m timeit &quot;max(_ for _ in range(1))&quot;\n500000 loops, best of 5: 476 nsec per loop\n$ python -m timeit &quot;max([_ for _ in range(1)])&quot;\n500000 loops, best of 5: 425 nsec per loop\n$ python -m timeit &quot;max(_ for _ in range(100))&quot;\n50000 loops, best of 5: 4.42 usec per loop\n$ python -m timeit &quot;max([_ for _ in range(100)])&quot;\n100000 loops, best of 5: 3.79 usec per loop\n$ python -m timeit &quot;max(_ for _ in range(10000))&quot;\n500 loops, best of 5: 468 usec per loop\n$ python -m timeit &quot;max([_ for _ in range(10000)])&quot;\n500 loops, best of 5: 442 usec per loop\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
[John's answer](https://stackoverflow.com/a/47792/4518341) is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: ``` def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists ``` Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization" rel="noreferrer">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/" rel="noreferrer">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
[ { "answer_id": 52136, "author": "elarson", "author_id": 5434, "author_profile": "https://Stackoverflow.com/users/5434", "pm_score": 1, "selected": false, "text": "<p>I don't think AuthKit is actively maintained anymore. It does use the Paste (<a href=\"http://pythonpaste.org\" rel=\"nofollow noreferrer\">http://pythonpaste.org</a>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication. </p>\n\n<p>There is also OpenID which is very easy to setup. The python-openid libs have an excellent example that is easy to translate to WSGI for wrapping a Pylons app. You can look at an example:</p>\n\n<p><a href=\"http://ionrock.org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth.py\" rel=\"nofollow noreferrer\">http://ionrock.org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth.py</a></p>\n" }, { "answer_id": 61614, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 0, "selected": false, "text": "<p>This actually got me interested:<a href=\"http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en\" rel=\"nofollow noreferrer\">Check out this mailing on the pylons list</a>. So AuthKit is being developed, and I will follow the book and get back on the results.</p>\n" }, { "answer_id": 139574, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 2, "selected": false, "text": "<p>Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats:</p>\n\n<ol>\n<li>sqlalchemy has to be in 0.5 version</li>\n<li>authkit has to be the dev version from svn (easy_install authkit==dev)</li>\n</ol>\n\n<p>I managed to get it working fine.</p>\n" }, { "answer_id": 948216, "author": "Tony", "author_id": 76815, "author_profile": "https://Stackoverflow.com/users/76815", "pm_score": 2, "selected": false, "text": "<p>I gave up on authkit and rolled my own:\n<a href=\"http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/\" rel=\"nofollow noreferrer\">http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/</a></p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons? I tried downloading the [SimpleSiteTemplate](http://pypi.python.org/pypi/SimpleSiteTemplate/) from the cheeseshop but wasn't able to run the setup-app command. It throws up an error: ``` File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' ``` I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.
Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats: 1. sqlalchemy has to be in 0.5 version 2. authkit has to be the dev version from svn (easy\_install authkit==dev) I managed to get it working fine.
47,824
<p>Using core jQuery, how do you remove all the options of a select box, then add one option and select it?</p> <p>My select box is the following.</p> <pre><code>&lt;Select id="mySelect" size="9"&gt; &lt;/Select&gt; </code></pre> <p>EDIT: The following code was helpful with chaining. However, (in Internet&nbsp;Explorer) <code>.val('whatever')</code> did not select the option that was added. (I did use the same 'value' in both <code>.append</code> and <code>.val</code>.)</p> <pre><code>$('#mySelect').find('option').remove().end() .append('&lt;option value="whatever"&gt;text&lt;/option&gt;').val('whatever'); </code></pre> <p>EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. <code>.focus()</code> was closer, but the option did not appear selected like it does with <code>.selected= "true"</code>. Nothing is wrong with my existing code - I am just trying to learn jQuery.</p> <pre><code>var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; </code></pre> <p>EDIT: selected answer was close to what I needed. This worked for me:</p> <pre><code>$('#mySelect').children().remove().end() .append('&lt;option selected value="whatever"&gt;text&lt;/option&gt;') ; </code></pre> <p>But both answers led me to my final solution..</p>
[ { "answer_id": 47829, "author": "Matt", "author_id": 2338, "author_profile": "https://Stackoverflow.com/users/2338", "pm_score": 12, "selected": true, "text": "<pre><code>$('#mySelect')\n .find('option')\n .remove()\n .end()\n .append('&lt;option value=\"whatever\"&gt;text&lt;/option&gt;')\n .val('whatever')\n;\n</code></pre>\n" }, { "answer_id": 50412, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 6, "selected": false, "text": "<p>Not sure exactly what you mean by \"add one and select it\", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:</p>\n\n<pre><code>$('select').children().remove();\n$('select').append('&lt;option id=\"foo\"&gt;foo&lt;/option&gt;');\n$('#foo').focus();\n</code></pre>\n\n<p><strong>Response to \"EDIT\"</strong>: Can you clarify what you mean by \"This select box is populated by a set of radio buttons\"? A <code>&lt;select&gt;</code> element cannot (legally) contain <code>&lt;input type=\"radio\"&gt;</code> elements.</p>\n" }, { "answer_id": 53013, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 4, "selected": false, "text": "<p>Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including \"selected\" in the option that I wanted selected.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function() {\r\n $('#mySelect').children().remove().end().append('&lt;option selected value=\"One\"&gt;One option&lt;/option&gt;') ; // clear the select box, then add one option which is selected\r\n $(\"input[name='myRadio']\").filter( \"[value='1']\" ).attr( \"checked\", \"checked\" ); // select radio button with value 1\r\n // Bind click event to each radio button.\r\n $(\"input[name='myRadio']\").bind(\"click\",\r\n function() {\r\n switch(this.value) {\r\n case \"1\":\r\n $('#mySelect').find('option').remove().end().append('&lt;option selected value=\"One\"&gt;One option&lt;/option&gt;') ;\r\n break ;\r\n case \"2\":\r\n $('#mySelect').find('option').remove() ;\r\n var items = [\"Item1\", \"Item2\", \"Item3\"] ; // Set locally for demo\r\n var options = '' ;\r\n for (var i = 0; i &lt; items.length; i++) {\r\n if (i==0) {\r\n options += '&lt;option selected value=\"' + items[i] + '\"&gt;' + items[i] + '&lt;/option&gt;';\r\n }\r\n else {\r\n options += '&lt;option value=\"' + items[i] + '\"&gt;' + items[i] + '&lt;/option&gt;';\r\n }\r\n }\r\n $('#mySelect').html(options); // Populate select box with array\r\n break ;\r\n } // Switch end\r\n } // Bind function end\r\n ); // bind end\r\n}); // Event listener end</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;label&gt;One&lt;input name=\"myRadio\" type=\"radio\" value=\"1\" /&gt;&lt;/label&gt;\r\n&lt;label&gt;Two&lt;input name=\"myRadio\" type=\"radio\" value=\"2\" /&gt;&lt;/label&gt;\r\n&lt;select id=\"mySelect\" size=\"9\"&gt;&lt;/select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 947152, "author": "Hayden Chambers", "author_id": 61509, "author_profile": "https://Stackoverflow.com/users/61509", "pm_score": 5, "selected": false, "text": "<pre><code>$('#mySelect')\n .empty()\n .append('&lt;option value=\"whatever\"&gt;text&lt;/option&gt;')\n .find('option:first')\n .attr(\"selected\",\"selected\")\n;\n</code></pre>\n" }, { "answer_id": 1917744, "author": "Mahzilla", "author_id": 233288, "author_profile": "https://Stackoverflow.com/users/233288", "pm_score": 10, "selected": false, "text": "<pre><code>$('#mySelect')\n .empty()\n .append('&lt;option selected=\"selected\" value=\"whatever\"&gt;text&lt;/option&gt;')\n;\n</code></pre>\n" }, { "answer_id": 2040837, "author": "row1", "author_id": 79835, "author_profile": "https://Stackoverflow.com/users/79835", "pm_score": 6, "selected": false, "text": "<p>I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the <em>select</em> in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the <em>select</em> had been cleared and had the new items, but visually the <em>select</em> still showed the old items - even though you could not select them.</p>\n\n<p>The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.</p>\n\n<pre><code>$('#mySelect')[0].options.length = 0;\n</code></pre>\n" }, { "answer_id": 5481232, "author": "jvarandas", "author_id": 487966, "author_profile": "https://Stackoverflow.com/users/487966", "pm_score": 5, "selected": false, "text": "<pre><code>$(\"#control\").html(\"&lt;option selected=\\\"selected\\\"&gt;The Option...&lt;/option&gt;\");\n</code></pre>\n" }, { "answer_id": 15655982, "author": "mauretto", "author_id": 487545, "author_profile": "https://Stackoverflow.com/users/487545", "pm_score": 7, "selected": false, "text": "<p>If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:</p>\n\n<pre><code>$('#mySelect').find('option:not(:first)').remove();\n</code></pre>\n" }, { "answer_id": 19444202, "author": "Barun", "author_id": 1251570, "author_profile": "https://Stackoverflow.com/users/1251570", "pm_score": 2, "selected": false, "text": "<p>This will replace your existing mySelect with a new mySelect.</p>\n\n<pre><code>$('#mySelect').replaceWith('&lt;Select id=\"mySelect\" size=\"9\"&gt;\n &lt;option value=\"whatever\" selected=\"selected\" &gt;text&lt;/option&gt;\n &lt;/Select&gt;');\n</code></pre>\n" }, { "answer_id": 19962931, "author": "Shawn", "author_id": 1807604, "author_profile": "https://Stackoverflow.com/users/1807604", "pm_score": 7, "selected": false, "text": "<p>why not just use plain javascript?</p>\n\n<pre><code>document.getElementById(\"selectID\").options.length = 0;\n</code></pre>\n" }, { "answer_id": 21497276, "author": "mehrdad", "author_id": 2053048, "author_profile": "https://Stackoverflow.com/users/2053048", "pm_score": 2, "selected": false, "text": "<p>Uses the jquery <a href=\"http://api.jquery.com/prop/\" rel=\"nofollow\">prop()</a> to clear the selected option</p>\n\n<pre><code>$('#mySelect option:selected').prop('selected', false);\n</code></pre>\n" }, { "answer_id": 26886200, "author": "Shiv", "author_id": 1197461, "author_profile": "https://Stackoverflow.com/users/1197461", "pm_score": 3, "selected": false, "text": "<p>How about just changing the html to new data.</p>\n\n<pre><code>$('#mySelect').html('&lt;option value=\"whatever\"&gt;text&lt;/option&gt;');\n</code></pre>\n\n<p>Another example:</p>\n\n<pre><code>$('#mySelect').html('\n &lt;option value=\"1\" selected&gt;text1&lt;/option&gt;\n &lt;option value=\"2\"&gt;text2&lt;/option&gt;\n &lt;option value=\"3\" disabled&gt;text3&lt;/option&gt;\n');\n</code></pre>\n" }, { "answer_id": 29511141, "author": "marioosh", "author_id": 404395, "author_profile": "https://Stackoverflow.com/users/404395", "pm_score": 3, "selected": false, "text": "<p>I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than <code>.empty()</code> or <code>.find().remove()</code> from jQuery.</p>\n\n<pre><code>var ClearOptionsFast = function(id) {\n var selectObj = document.getElementById(id);\n var selectParentNode = selectObj.parentNode;\n var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy\n selectParentNode.replaceChild(newSelectObj, selectObj);\n return newSelectObj;\n}\n</code></pre>\n\n<p>More info <a href=\"http://www.somacon.com/p542.php\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 30917315, "author": "humbads", "author_id": 553396, "author_profile": "https://Stackoverflow.com/users/553396", "pm_score": 3, "selected": false, "text": "<p>Building on mauretto's answer, this is a little easier to read and understand:</p>\n\n<pre><code>$('#mySelect').find('option').not(':first').remove();\n</code></pre>\n\n<p>To remove all the options except one with a specific value, you can use this:</p>\n\n<pre><code>$('#mySelect').find('option').not('[value=123]').remove();\n</code></pre>\n\n<p>This would be better if the option to be added was already there.</p>\n" }, { "answer_id": 32859761, "author": "Jaydeep Shil", "author_id": 3428626, "author_profile": "https://Stackoverflow.com/users/3428626", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>First clear all exisiting option execpt the first one(--Select--)</p></li>\n<li><p>Append new option values using loop one by one</p>\n\n<pre><code>$('#ddlCustomer').find('option:not(:first)').remove();\nfor (var i = 0; i &lt; oResult.length; i++) {\n $(\"#ddlCustomer\").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 39842290, "author": "Nadeem Manzoor", "author_id": 1308493, "author_profile": "https://Stackoverflow.com/users/1308493", "pm_score": 2, "selected": false, "text": "<p>You can do simply by replacing html</p>\n\n<pre><code>$('#mySelect')\n.html('&lt;option value=\"whatever\" selected&gt;text&lt;/option&gt;')\n.trigger('change');\n</code></pre>\n" }, { "answer_id": 40199412, "author": "Md. Russel Hussain", "author_id": 4295653, "author_profile": "https://Stackoverflow.com/users/4295653", "pm_score": 1, "selected": false, "text": "<p>Hope it will work</p>\n\n<pre><code>$('#myselect').find('option').remove()\n.append($('&lt;option&gt;&lt;/option&gt;').val('value1').html('option1'));\n</code></pre>\n" }, { "answer_id": 45085734, "author": "Jhon Intriago Thoth", "author_id": 5598325, "author_profile": "https://Stackoverflow.com/users/5598325", "pm_score": 3, "selected": false, "text": "<p>Another way:</p>\n\n<pre><code>$('#select').empty().append($('&lt;option&gt;').text('---------').attr('value',''));\n</code></pre>\n\n<p>Under this link, there are good practices <a href=\"https://api.jquery.com/select/\" rel=\"noreferrer\">https://api.jquery.com/select/</a></p>\n" }, { "answer_id": 51920107, "author": "LN Nitharsan", "author_id": 10222327, "author_profile": "https://Stackoverflow.com/users/10222327", "pm_score": 1, "selected": false, "text": "<pre><code>var select = $('#mySelect');\nselect.find('option').remove().end()\n.append($('&lt;option/&gt;').val('').text('Select'));\nvar data = [{\"id\":1,\"title\":\"Option one\"}, {\"id\":2,\"title\":\"Option two\"}];\nfor(var i in data) {\n var d = data[i];\n var option = $('&lt;option/&gt;').val(d.id).text(d.title);\n select.append(option);\n}\nselect.val('');\n</code></pre>\n" }, { "answer_id": 52148696, "author": "Nifemi Sola-Ojo", "author_id": 6155890, "author_profile": "https://Stackoverflow.com/users/6155890", "pm_score": 2, "selected": false, "text": "<ul>\n<li>save the option values to be appended in an object</li>\n<li>clear existing options in the select tag</li>\n<li>iterate the list object and append the contents to the intended select tag</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};\r\n\r\n$('#selectID').empty();\r\n\r\n$.each(listToAppend, function(val, text) {\r\n $('#selectID').append( new Option(text,val) );\r\n });</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52776203, "author": "Devkinandan Chauhan", "author_id": 9715631, "author_profile": "https://Stackoverflow.com/users/9715631", "pm_score": 3, "selected": false, "text": "<pre><code>$(\"#id option\").remove();\n$(\"#id\").append('&lt;option value=\"testValue\" &gt;TestText&lt;/option&gt;');\n</code></pre>\n\n<p>The first line of code will remove all the options of a select box as no option find criteria has been mentioned.</p>\n\n<p>The second line of code will add the Option with the specified value(\"testValue\") and Text(\"TestText\").</p>\n" }, { "answer_id": 54360083, "author": "michael01angelo", "author_id": 5775650, "author_profile": "https://Stackoverflow.com/users/5775650", "pm_score": 2, "selected": false, "text": "<p>I saw this code in Select2 - \n<a href=\"https://select2.org/programmatic-control/add-select-clear-items#clearing-selections\" rel=\"nofollow noreferrer\">Clearing Selections</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$('#mySelect').val(null).trigger('change');\n</code></pre>\n\n<p>This code works well with jQuery even without Select2</p>\n" }, { "answer_id": 57069759, "author": "Kaushik shrimali", "author_id": 9106811, "author_profile": "https://Stackoverflow.com/users/9106811", "pm_score": 4, "selected": false, "text": "<blockquote>\n<p>Just one line to remove all options from the select tag and after you can add any options then make second line to add options.</p>\n</blockquote>\n<pre><code>$('.ddlsl').empty();\n\n$('.ddlsl').append(new Option('Select all', 'all'));\n</code></pre>\n<blockquote>\n<p>One more short way but didn't tried</p>\n</blockquote>\n<pre><code>$('.ddlsl').empty().append(new Option('Select all', 'all'));\n</code></pre>\n" }, { "answer_id": 63236844, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "<p>Try</p>\n<pre><code>mySelect.innerHTML = `&lt;option selected value=&quot;whatever&quot;&gt;text&lt;/option&gt;`\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function setOne() {\n console.log({mySelect});\n mySelect.innerHTML = `&lt;option selected value=\"whatever\"&gt;text&lt;/option&gt;`;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button onclick=\"setOne()\" &gt;set one&lt;/button&gt;\n&lt;Select id=\"mySelect\" size=\"9\"&gt; \n &lt;option value=\"1\"&gt;old1&lt;/option&gt;\n &lt;option value=\"2\"&gt;old2&lt;/option&gt;\n &lt;option value=\"3\"&gt;old3&lt;/option&gt;\n&lt;/Select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68149249, "author": "double_u1", "author_id": 11914028, "author_profile": "https://Stackoverflow.com/users/11914028", "pm_score": 0, "selected": false, "text": "<p>The shortest answer:</p>\n<pre><code>$('#mySelect option').remove().append('&lt;option selected value=&quot;whatever&quot;&gt;text&lt;/option&gt;');\n</code></pre>\n" }, { "answer_id": 68623771, "author": "Kazeem Quadri", "author_id": 11084443, "author_profile": "https://Stackoverflow.com/users/11084443", "pm_score": 2, "selected": false, "text": "<p>I used vanilla javascript</p>\n<pre><code>let select = document.getElementById(&quot;mySelect&quot;);\nselect.innerHTML = &quot;&quot;;\n</code></pre>\n" }, { "answer_id": 70946153, "author": "Carlos", "author_id": 10145865, "author_profile": "https://Stackoverflow.com/users/10145865", "pm_score": 2, "selected": false, "text": "<p>Cleaner give me Like it</p>\n<pre><code> let data= []\n\n let inp = $('#mySelect')\n inp.empty()\n\n data.forEach(el=&gt; inp.append( new Option(el.Nombre, el.Id) ))\n</code></pre>\n" }, { "answer_id": 72759663, "author": "rsmdh", "author_id": 10995048, "author_profile": "https://Stackoverflow.com/users/10995048", "pm_score": 0, "selected": false, "text": "<p>Try</p>\n<pre><code>$('#mySelect')\n.html('&lt;option value=&quot;whatever&quot;&gt;text&lt;/option&gt;')\n.find('option:first')\n.attr(&quot;selected&quot;,&quot;selected&quot;);\n</code></pre>\n<p>OR</p>\n<pre><code>$('#mySelect').html('&lt;option value=&quot;4&quot;&gt;Value 4&lt;/option&gt;\n &lt;option value=&quot;5&quot;&gt;Value 5&lt;/option&gt;\n&lt;option value=&quot;6&quot;&gt;Value 6&lt;/option&gt;\n&lt;option value=&quot;7&quot;&gt;Value 7&lt;/option&gt;\n&lt;option value=&quot;8&quot;&gt;Value 8&lt;/option&gt;')\n.find('option:first')\n.prop(&quot;selected&quot;,true);\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
Using core jQuery, how do you remove all the options of a select box, then add one option and select it? My select box is the following. ``` <Select id="mySelect" size="9"> </Select> ``` EDIT: The following code was helpful with chaining. However, (in Internet Explorer) `.val('whatever')` did not select the option that was added. (I did use the same 'value' in both `.append` and `.val`.) ``` $('#mySelect').find('option').remove().end() .append('<option value="whatever">text</option>').val('whatever'); ``` EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. `.focus()` was closer, but the option did not appear selected like it does with `.selected= "true"`. Nothing is wrong with my existing code - I am just trying to learn jQuery. ``` var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; ``` EDIT: selected answer was close to what I needed. This worked for me: ``` $('#mySelect').children().remove().end() .append('<option selected value="whatever">text</option>') ; ``` But both answers led me to my final solution..
``` $('#mySelect') .find('option') .remove() .end() .append('<option value="whatever">text</option>') .val('whatever') ; ```
47,833
<p>I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?</p>
[ { "answer_id": 47839, "author": "Joe Ratzer", "author_id": 4092, "author_profile": "https://Stackoverflow.com/users/4092", "pm_score": 3, "selected": false, "text": "<p>What's wrong with</p>\n\n<p>(aDataSet.Tables.Count == 0)</p>\n\n<p>?</p>\n" }, { "answer_id": 47840, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 0, "selected": false, "text": "<p>To be clear, you would first need to look at all the DataTables, and then look at the count of Rows for each DataTable.</p>\n" }, { "answer_id": 47841, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 5, "selected": true, "text": "<p>I would suggest something like:-</p>\n\n<pre><code> bool nonEmptyDataSet = dataSet != null &amp;&amp; \n (from DataTable t in dataSet.Tables where t.Rows.Count &gt; 0 select t).Any();\n</code></pre>\n\n<p><strong>Edits:</strong> I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any().</p>\n\n<p>In line with Keith's suggestion, here is an extension method version of this approach:-</p>\n\n<pre><code>public static class ExtensionMethods {\n public static bool IsEmpty(this DataSet dataSet) {\n return dataSet == null ||\n !(from DataTable t in dataSet.Tables where t.Rows.Count &gt; 0 select t).Any();\n }\n }\n</code></pre>\n\n<p>Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.</p>\n" }, { "answer_id": 47979, "author": "dance2die", "author_id": 4035, "author_profile": "https://Stackoverflow.com/users/4035", "pm_score": 2, "selected": false, "text": "<p>I have created a small static util class just for that purpose</p>\n\n<p>Below code should read like an English sentence.</p>\n\n<pre><code> public static bool DataSetIsEmpty(DataSet ds)\n {\n return !DataTableExists(ds) &amp;&amp; !DataRowExists(ds.Tables[0].Rows);\n }\n\n public static bool DataTableExists(DataSet ds)\n {\n return ds.Tables != null &amp;&amp; ds.Tables.Count &gt; 0;\n }\n\n public static bool DataRowExists(DataRowCollection rows)\n {\n return rows != null &amp;&amp; rows.Count &gt; 0;\n }\n</code></pre>\n\n<p>I would just put something like below code and be done with it.\nWriting a <strong>readable code</strong> does count.</p>\n\n<pre><code> if (DataAccessUtil.DataSetIsEmpty(ds)) {\n return null;\n }\n</code></pre>\n" }, { "answer_id": 48547, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>I think this is a place where you could use an extension method in C# 3 to improve legibility.</p>\n\n<p>Using kronoz's idea...</p>\n\n<pre><code>public static bool IsNotEmpty ( this dataset ) \n{\n return dataSet != null &amp;&amp; (\n from DataTable t in dataSet.Tables \n where t.Rows.AsQueryable().Any()\n select t).AsQueryable().Any();\n}\n\n//then the check would be\nDataSet ds = /* get data */;\n\nds.IsNotEmpty();\n</code></pre>\n\n<p>Due to the fact that extension methods are always expanded by the compiler this will even work if the dataset being checked is null.</p>\n\n<p>At compile time this is changed:</p>\n\n<pre><code>ds.IsNotEmpty();\n\n//becomes\n\nDataSetExtensions.IsNotEmpty( ds );\n</code></pre>\n" }, { "answer_id": 11556606, "author": "Milan Barać", "author_id": 1537223, "author_profile": "https://Stackoverflow.com/users/1537223", "pm_score": 0, "selected": false, "text": "<pre><code>#region Extension methods\n\npublic static class ExtensionMethods\n{\n public static bool IsEmpty(this DataSet dataSet)\n {\n return dataSet == null || dataSet.Tables.Count == 0 || !dataSet.Tables.Cast&lt;DataTable&gt;().Any(i =&gt; i.Rows.Count &gt; 0);\n }\n}\n\n#endregion\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445815/" ]
I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
I would suggest something like:- ``` bool nonEmptyDataSet = dataSet != null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); ``` **Edits:** I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any(). In line with Keith's suggestion, here is an extension method version of this approach:- ``` public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); } } ``` Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
47,837
<p>I'm struggling to find the right terminology here, but if you have jQuery object...</p> <pre><code>$('#MyObject') </code></pre> <p>...is it possible to extract the base element? Meaning, the equivalent of this:</p> <pre><code>document.getElementById('MyObject') </code></pre>
[ { "answer_id": 47844, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 7, "selected": true, "text": "<p>Yes, use <code>.get(index)</code>. According to the <a href=\"https://api.jquery.com/get/#get1\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>The <code>.get()</code> method grants access to the DOM nodes underlying each jQuery object.</p>\n</blockquote>\n" }, { "answer_id": 47848, "author": "Aaron Wagner", "author_id": 3909, "author_profile": "https://Stackoverflow.com/users/3909", "pm_score": 7, "selected": false, "text": "<pre><code>$('#MyObject').get(0);\n</code></pre>\n\n<p>I think that's what you want. I think you can also reference it like a regular array with:</p>\n\n<pre><code>$('#MyObject')[0];\n</code></pre>\n\n<p>But I'm not sure if that will always work. Stick with the first syntax.</p>\n" }, { "answer_id": 47874, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<p>A jQuery object is a set of elements. In your case, a set of one element. This differs from certain other libraries, which wrap single elements and provide alternate syntax for selectors that return multiple matches. </p>\n\n<p><em><a href=\"https://stackoverflow.com/questions/47837/getting-the-base-element-from-a-jquery-object#47848\">Aaron W</a> and <a href=\"https://stackoverflow.com/questions/47837/getting-the-base-element-from-a-jquery-object#47844\">VolkerK</a> already explained how to access the first (index 0) element in the set.</em></p>\n" }, { "answer_id": 16839707, "author": "VeeTheSecond", "author_id": 652876, "author_profile": "https://Stackoverflow.com/users/652876", "pm_score": 3, "selected": false, "text": "<p>I tested Aaron's statements on all the browsers I have available on my box:</p>\n\n<pre><code>$('#MyObject').get(0);\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>$('#MyObject')[0];\n</code></pre>\n\n<p><strong>As far as I can tell, it is only a matter of personal preference.</strong></p>\n\n<p>Functionally, both these statements are equivalent for both existing and non-existing elements. I tested the following browsers: Chrome 27.0, FF 21.0, IE10, IE9, IE8, IE7, IE6. </p>\n\n<p>In the speed tests that I ran, it was not always possible to tell which variation was faster; the outcome was not always consistent, even on the same browser. For the speed tests, I only tested existing elements. My test results are <a href=\"http://jsperf.com/jquery-base-element\" rel=\"noreferrer\">here</a>.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923/" ]
I'm struggling to find the right terminology here, but if you have jQuery object... ``` $('#MyObject') ``` ...is it possible to extract the base element? Meaning, the equivalent of this: ``` document.getElementById('MyObject') ```
Yes, use `.get(index)`. According to the [documentation](https://api.jquery.com/get/#get1): > > The `.get()` method grants access to the DOM nodes underlying each jQuery object. > > >
47,849
<p>I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.</p> <p>(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )</p>
[ { "answer_id": 47856, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 1, "selected": false, "text": "<p>You can use the WMI query language for that.\nTake a look at <a href=\"http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx</a> for examples.\nThe information you are looking for is available e.g. through the property VolumeName of the Win32_LogicalDisk class, <a href=\"http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx</a></p>\n\n<p><code>SELECT * FROM Win32_LogicalDisk WHERE VolumeName=\"MyLabel\"</code></p>\n" }, { "answer_id": 47860, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": true, "text": "<p>This bat file will give you the drive letter from a drive label:</p>\n\n<pre><code>Option Explicit\nDim num, args, objWMIService, objItem, colItems\n\nset args = WScript.Arguments\nnum = args.Count\n\nif num &lt;&gt; 1 then\n WScript.Echo \"Usage: CScript DriveFromLabel.vbs &lt;label&gt;\"\n WScript.Quit 1\nend if\n\nSet objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery(\"Select * from Win32_LogicalDisk\")\n\nFor Each objItem in colItems\n If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then\n Wscript.Echo objItem.Name\n End If\nNext\n\nWScript.Quit 0\n</code></pre>\n\n<p>Run it as:</p>\n\n<pre><code> cscript /nologo DriveFromLabel.vbs label\n</code></pre>\n" }, { "answer_id": 69542, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 1, "selected": false, "text": "<p>Here is a simple batch script getdrive.cmd to find a drive letter from a volume label. Just call \"getdrive MyLabel\" or getdrive \"My Label\".</p>\n\n<pre><code>@echo off\nsetlocal\n\n:: Initial variables\nset TMPFILE=%~dp0getdrive.tmp\nset driveletters=abcdefghijklmnopqrstuvwxyz\nset MatchLabel_res=\n\nfor /L %%g in (2,1,25) do call :MatchLabel %%g %*\n\nif not \"%MatchLabel_res%\"==\"\" echo %MatchLabel_res%\n\ngoto :END\n\n\n:: Function to match a label with a drive letter. \n::\n:: The first parameter is an integer from 1..26 that needs to be \n:: converted in a letter. It is easier looping on a number\n:: than looping on letters.\n::\n:: The second parameter is the volume name passed-on to the script\n:MatchLabel\n\n:: result already found, just do nothing \n:: (necessary because there is no break for for loops)\nif not \"%MatchLabel_res%\"==\"\" goto :eof\n\n:: get the proper drive letter\ncall set dl=%%driveletters:~%1,1%%\n\n:: strip-off the \" in the volume name to be able to add them again further\nset volname=%2\nset volname=%volname:\"=%\n\n:: get the volume information on that disk\nvol %dl%: &gt; \"%TMPFILE%\" 2&gt;&amp;1\n\n:: Drive/Volume does not exist, just quit\nif not \"%ERRORLEVEL%\"==\"0\" goto :eof\n\nset found=0\nfor /F \"usebackq tokens=3 delims=:\" %%g in (`find /C /I \"%volname%\" \"%TMPFILE%\"`) do set found=%%g\n\n:: trick to stip any whitespaces\nset /A found=%found% + 0\n\n\nif not \"%found%\"==\"0\" set MatchLabel_res=%dl%:\ngoto :eof\n\n\n\n\n\n\n\n\n:END\n\nif exist \"%TMPFILE%\" del \"%TMPFILE%\"\nendlocal\n</code></pre>\n" }, { "answer_id": 9066694, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 3, "selected": false, "text": "<p>The previous answers seem either overly complicated, and/or not particularly suited to a batch file.</p>\n\n<p>This simple one liner should place the desired drive letter in variable myDrive. Obviously change \"My Label\" to your actual label.</p>\n\n<pre><code>for /f %%D in ('wmic volume get DriveLetter^, Label ^| find \"My Label\"') do set myDrive=%%D\n</code></pre>\n\n<p>If run from the command line (not in a batch file), then %%D must be changed to %D in both places.</p>\n\n<p>Once the variable is set, you can refer to the drive using <code>%myDrive%</code>. For example</p>\n\n<pre><code>dir %myDrive%\\someFolder\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel. (This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )
This bat file will give you the drive letter from a drive label: ``` Option Explicit Dim num, args, objWMIService, objItem, colItems set args = WScript.Arguments num = args.Count if num <> 1 then WScript.Echo "Usage: CScript DriveFromLabel.vbs <label>" WScript.Quit 1 end if Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk") For Each objItem in colItems If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then Wscript.Echo objItem.Name End If Next WScript.Quit 0 ``` Run it as: ``` cscript /nologo DriveFromLabel.vbs label ```
47,862
<p>I'm loading a <strong><em>SQL Server 2000</em></strong> database into my new <strong><em>SQL Server 2005</em></strong> <strong><em>instance</em></strong>. <strong><em>As expected, the full-text catalogs don't come with it.</strong> <strong>How can I rebuild them?</em></strong></p> <p>Right-clicking my full text catalogs and hitting "<strong><em>rebuild indexes</em></strong>" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...</p>
[ { "answer_id": 47900, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": true, "text": "<p>Try it using SQL.</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms189520%28SQL.90%29.aspx\" rel=\"nofollow noreferrer\">CREATE FULLTEXT CATALOG</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms176095%28SQL.90%29.aspx\" rel=\"nofollow noreferrer\">ALTER FULLTEXT CATALOG</a></li>\n</ul>\n\n<p>Here's an example from Microsoft.</p>\n\n<pre><code>--Change to accent insensitive\nUSE AdventureWorks;\nGO\nALTER FULLTEXT CATALOG ftCatalog \nREBUILD WITH ACCENT_SENSITIVITY=OFF;\nGO\n-- Check Accentsensitivity\nSELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity');\nGO\n--Returned 0, which means the catalog is not accent sensitive.\n</code></pre>\n" }, { "answer_id": 47959, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 0, "selected": false, "text": "<p>Thanks, that helped because it showed what was wrong: My file paths were different. Here's how I fixed it:</p>\n\n<p>1) Load database from SQL 2000 backup</p>\n\n<p>2) Set compatibility mode to SQL 2005</p>\n\n<pre><code>USE mydb\nGO\n\nALTER DATABASE mydb SET COMPATIBILITY_LEVEL = 90\nGO\n</code></pre>\n\n<p>3) Get the filegroup names</p>\n\n<pre><code>SELECT name \n FROM sys.master_files mf \n WHERE type = 4 \n AND EXISTS( SELECT * \n FROM sys.databases db \n WHERE db.database_id = mf.database_id \n AND name = 'mydb')\n</code></pre>\n\n<p>4) Then for each name (I did this in a little script)</p>\n\n<pre><code>ALTER DATABASE mydb \nMODIFY FILE( NAME = {full text catalog name}, FILENAME=\"N:\\ew\\path\\to\\wherever\")\n</code></pre>\n\n<p>5) Then collect all the \"readable\" names of the catalogs:</p>\n\n<pre><code>SELECT name FROM sys.sysfulltextcatalogs\n</code></pre>\n\n<p>6) Finally, now you can rebuild each one:</p>\n\n<pre><code>ALTER FULLTEXT CATALOG {full text catalog name} REBUILD\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590/" ]
I'm loading a ***SQL Server 2000*** database into my new ***SQL Server 2005*** ***instance***. ***As expected, the full-text catalogs don't come with it.*** **How can I rebuild them?** Right-clicking my full text catalogs and hitting "***rebuild indexes***" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...
Try it using SQL. * [CREATE FULLTEXT CATALOG](http://msdn.microsoft.com/en-us/library/ms189520%28SQL.90%29.aspx) * [ALTER FULLTEXT CATALOG](http://msdn.microsoft.com/en-us/library/ms176095%28SQL.90%29.aspx) Here's an example from Microsoft. ``` --Change to accent insensitive USE AdventureWorks; GO ALTER FULLTEXT CATALOG ftCatalog REBUILD WITH ACCENT_SENSITIVITY=OFF; GO -- Check Accentsensitivity SELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity'); GO --Returned 0, which means the catalog is not accent sensitive. ```
47,864
<p>ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="nofollow noreferrer">here</a>, but that does not work with ASP.net AJAX properly.</p> <p>Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.</p> <p>So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?</p>
[ { "answer_id": 48831, "author": "Sara Chipps", "author_id": 4140, "author_profile": "https://Stackoverflow.com/users/4140", "pm_score": 0, "selected": false, "text": "<p>hmmmm, it seems you would need to find some sort of JavaScript to check for html input or a client side validator. </p>\n" }, { "answer_id": 50586, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 1, "selected": false, "text": "<p>That's what I would like to avoid if possible, but this seems to be much more complicated than expected.</p>\n\n<p>Normally, everyone advises using the AsyncPostBackError of the ScriptManager, but this does not work if called on the Global.asax. Unfortunately, as the HttpRequestValidationException is emitted by the runtime, it never enters my code and I cannot do much within the Application_Error.</p>\n\n<p>So yes, it needs to be indeed done in the JavaScript, I just hope there is a way to add a \"hook\" like the BeginRequestHandler-Function so that I don't have to \"hack\" Microsoft code. If I find a solution before someone else, i'll put it up here :-)</p>\n" }, { "answer_id": 50671, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": true, "text": "<p>Found it and <a href=\"http://www.stum.de/2008/09/08/gracefully-handling-httprequestvalidationexception-with-aspnet-ajax/\" rel=\"nofollow noreferrer\">blogged about it</a>. Basically, the EndRequestHandler and the args.set_errorHandled are our friends here.</p>\n\n<pre><code>&lt;script type=\"text/javascript\" language=\"javascript\"&gt;\nvar prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(EndRequestHandler);\n\nfunction EndRequestHandler(sender, args) {\n if (args.get_error() != undefined)\n {\n var errorMessage;\n if (args.get_response().get_statusCode() == '200')\n {\n errorMessage = args.get_error().message;\n }\n else\n {\n // Error occurred somewhere other than the server page.\n errorMessage = 'An unspecified error occurred. ';\n }\n args.set_errorHandled(true);\n $get('&lt;%= this.newsletterLabel.ClientID %&gt;').innerHTML = errorMessage;\n }\n}\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully [here](http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html), but that does not work with ASP.net AJAX properly. Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up. So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?
Found it and [blogged about it](http://www.stum.de/2008/09/08/gracefully-handling-httprequestvalidationexception-with-aspnet-ajax/). Basically, the EndRequestHandler and the args.set\_errorHandled are our friends here. ``` <script type="text/javascript" language="javascript"> var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(EndRequestHandler); function EndRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage; if (args.get_response().get_statusCode() == '200') { errorMessage = args.get_error().message; } else { // Error occurred somewhere other than the server page. errorMessage = 'An unspecified error occurred. '; } args.set_errorHandled(true); $get('<%= this.newsletterLabel.ClientID %>').innerHTML = errorMessage; } } </script> ```
47,882
<p>What is a magic number?</p> <p>Why should it be avoided?</p> <p>Are there cases where it's appropriate?</p>
[ { "answer_id": 47885, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "<p>A magic number is a sequence of characters at the start of a file format, or protocol exchange. This number serves as a sanity check.</p>\n\n<p>Example:\nOpen up any GIF file, you will see at the very start: GIF89. \"GIF89\" being the magic number.</p>\n\n<p>Other programs can read the first few characters of a file and properly identify GIFs. </p>\n\n<p>The danger is that random binary data can contain these same characters. But it is very unlikely. </p>\n\n<p>As for protocol exchange, you can use it to quickly identify that the current 'message' that is being passed to you is corrupted or not valid. </p>\n\n<p>Magic numbers are still useful.</p>\n" }, { "answer_id": 47888, "author": "somas1", "author_id": 412, "author_profile": "https://Stackoverflow.com/users/412", "pm_score": 5, "selected": false, "text": "<p>Have you taken a look at the Wikipedia entry for <a href=\"http://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic number?</a></p>\n\n<p>It goes into a bit of detail about all of the ways the magic number reference is made. Here's a quote about magic number as a bad programming practice </p>\n\n<blockquote>\n <p>The term magic number also refers to the bad programming practice of using numbers directly in source code without explanation. In most cases this makes programs harder to read, understand, and maintain. Although most guides make an exception for the numbers zero and one, it is a good idea to define all other numbers in code as named constants.</p>\n</blockquote>\n" }, { "answer_id": 47889, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 3, "selected": false, "text": "<p>I assume this is a response to my <a href=\"https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data#47880\">answer</a> to your earlier question. In programming, a magic number is an embedded numerical constant that appears without explanation. If it appears in two distinct locations, it can lead to circumstances where one instance is changed and not another. For both these reasons, it's important to isolate and define the numerical constants outside the places where they're used.</p>\n" }, { "answer_id": 47890, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 7, "selected": false, "text": "<p>A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.</p>\n\n<p>For example, let's say you have a Page that displays the last 50 Orders in a \"Your Orders\" Overview Page. 50 is the Magic Number here, because it's not set through standard or convention, it's a number that you made up for reasons outlined in the spec.</p>\n\n<p>Now, what you do is you have the 50 in different places - your SQL script (<code>SELECT TOP 50 * FROM orders</code>), your Website (Your Last 50 Orders), your order login (<code>for (i = 0; i &lt; 50; i++)</code>) and possibly many other places.</p>\n\n<p>Now, what happens when someone decides to change 50 to 25? or 75? or 153? You now have to replace the 50 in all the places, and you are very likely to miss it. Find/Replace may not work, because 50 may be used for other things, and blindly replacing 50 with 25 can have some other bad side effects (i.e. your <code>Session.Timeout = 50</code> call, which is also set to 25 and users start reporting too frequent timeouts).</p>\n\n<p>Also, the code can be hard to understand, i.e. \"<code>if a &lt; 50 then bla</code>\" - if you encounter that in the middle of a complicated function, other developers who are not familiar with the code may ask themselves \"WTF is 50???\"</p>\n\n<p>That's why it's best to have such ambiguous and arbitrary numbers in exactly 1 place - \"<code>const int NumOrdersToDisplay = 50</code>\", because that makes the code more readable (\"<code>if a &lt; NumOrdersToDisplay</code>\", it also means you only need to change it in 1 well defined place.</p>\n\n<p>Places where Magic Numbers are appropriate is everything that is defined through a standard, i.e. <code>SmtpClient.DefaultPort = 25</code> or <code>TCPPacketSize = whatever</code> (not sure if that is standardized). Also, everything only defined within 1 function might be acceptable, but that depends on Context.</p>\n" }, { "answer_id": 47895, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": 4, "selected": false, "text": "<p>In programming, a \"magic number\" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.</p>\n\n<p>It's bad for the same reason SPOT (Single Point of Truth) is good: If you wanted to change this constant later, you would have to hunt through your code to find every instance. It is also bad because it might not be clear to other programmers what this number represents, hence the \"magic\".</p>\n\n<p>People sometimes take magic number elimination further, by moving these constants into separate files to act as configuration. This is sometimes helpful, but can also create more complexity than it's worth.</p>\n" }, { "answer_id": 47902, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 10, "selected": true, "text": "\n\n<p>A magic number is a direct usage of a number in the code.</p>\n\n<p>For example, if you have (in Java):</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Foo {\n public void setPassword(String password) {\n // don't do this\n if (password.length() &gt; 7) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n</code></pre>\n\n<p>This should be refactored to:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Foo {\n public static final int MAX_PASSWORD_SIZE = 7;\n\n public void setPassword(String password) {\n if (password.length() &gt; MAX_PASSWORD_SIZE) {\n throw new InvalidArgumentException(\"password\");\n }\n }\n}\n</code></pre>\n\n<p>It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.</p>\n\n<p>The JDK is full of examples like in <code>Integer</code>, <code>Character</code> and <code>Math</code> classes.</p>\n\n<p>PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.</p>\n" }, { "answer_id": 47923, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 2, "selected": false, "text": "<p>It is worth noting that sometimes you do want non-configurable \"hard-coded\" numbers in your code. There are a number of <a href=\"http://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">famous ones</a> including 0x5F3759DF which is used in the optimized inverse square root algorithm. </p>\n\n<p>In the rare cases where I find the need to use such Magic Numbers, I set them as a const in my code, and document why they are used, how they work, and where they came from.</p>\n" }, { "answer_id": 47936, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 0, "selected": false, "text": "<p>@eed3si9n: I'd even suggest that '1' is a magic number. :-)</p>\n\n<p>A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.</p>\n" }, { "answer_id": 48068, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "<p>I've always used the term \"magic number\" differently, as an obscure value stored within a data structure which can be verified as a quick validity check. For example gzip files contain 0x1f8b08 as their first three bytes, Java class files start with 0xcafebabe, etc.</p>\n\n<p>You often see magic numbers embedded in file formats, because files can be sent around rather promiscuously and lose any metadata about how they were created. However magic numbers are also sometimes used for in-memory data structures, like ioctl() calls.</p>\n\n<p>A quick check of the magic number before processing the file or data structure allows one to signal errors early, rather than schlep all the way through potentially lengthy processing in order to announce that the input was complete balderdash.</p>\n" }, { "answer_id": 48220, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "<p>A magic number can also be a number with special, hardcoded semantics. For example, I once saw a system where record IDs > 0 were treated normally, 0 itself was \"new record\", -1 was \"this is the root\" and -99 was \"this was created in the root\". 0 and -99 would cause the WebService to supply a new ID.</p>\n\n<p>What's bad about this is that you're reusing a space (that of signed integers for record IDs) for special abilities. Maybe you'll never want to create a record with ID 0, or with a negative ID, but even if not, every person who looks either at the code or at the database might stumble on this and be confused at first. It goes without saying those special values weren't well-documented.</p>\n\n<p>Arguably, <a href=\"http://thedailywtf.com/Articles/Classic-WTF-The-Phantom-of-The-System.aspx\" rel=\"noreferrer\">22, 7, -12 and 620</a> count as magic numbers, too. ;-)</p>\n" }, { "answer_id": 364532, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>A problem that has not been mentioned with using magic numbers...</p>\n\n<p>If you have very many of them, the odds are reasonably good that you have two different <em>purposes</em> that you're using magic numbers for, where the <em>values</em> happen to be the same.</p>\n\n<p>And then, sure enough, you need to change the value... for only one purpose.</p>\n" }, { "answer_id": 1554616, "author": "Ascalonian", "author_id": 65230, "author_profile": "https://Stackoverflow.com/users/65230", "pm_score": 1, "selected": false, "text": "<p>What about initializing a variable at the top of the class with a default value? For example:</p>\n\n<pre><code>public class SomeClass {\n private int maxRows = 15000;\n ...\n // Inside another method\n for (int i = 0; i &lt; maxRows; i++) {\n // Do something\n }\n\n public void setMaxRows(int maxRows) {\n this.maxRows = maxRows;\n }\n\n public int getMaxRows() {\n return this.maxRows;\n }\n</code></pre>\n\n<p>In this case, 15000 is a magic number (according to CheckStyles). To me, setting a default value is okay. I don't want to have to do:</p>\n\n<pre><code>private static final int DEFAULT_MAX_ROWS = 15000;\nprivate int maxRows = DEFAULT_MAX_ROWS;\n</code></pre>\n\n<p>Does that make it more difficult to read? I never considered this until I installed CheckStyles.</p>\n" }, { "answer_id": 18184180, "author": "Oskytar", "author_id": 400120, "author_profile": "https://Stackoverflow.com/users/400120", "pm_score": -1, "selected": false, "text": "<p>What about return variables?</p>\n\n<p>I specially find it challenging when implementing <strong>stored procedures</strong>.</p>\n\n<p>Imagine the next stored procedure (wrong syntax, I know, just to show an example):</p>\n\n<pre><code>int procGetIdCompanyByName(string companyName);\n</code></pre>\n\n<p>It return the Id of the company if it exists in a particular table. Otherwise, it returns -1.\nSomehow it's a magic number. Some of the recommendations I've read so far says that I'll really have to do design somthing like that:</p>\n\n<pre><code>int procGetIdCompanyByName(string companyName, bool existsCompany);\n</code></pre>\n\n<p>By the way, what should it return if the company does not exists? Ok: it will set <em>existesCompany</em> as <strong>false</strong>, but also will return -1.</p>\n\n<p>Antoher option is to make two separate functions:</p>\n\n<pre><code>bool procCompanyExists(string companyName);\nint procGetIdCompanyByName(string companyName);\n</code></pre>\n\n<p>So a pre-condition for the second stored procedure is that company exists.</p>\n\n<p>But i'm afraid of concurrency, because in this system, a company can be created by another user.</p>\n\n<p>The bottom line by the way is: what do you think about using that kind of \"magic numbers\" that are relatively known and safe to tell that something is unsuccessful or that something does not exists?</p>\n" }, { "answer_id": 30743302, "author": "jguiraud", "author_id": 3570922, "author_profile": "https://Stackoverflow.com/users/3570922", "pm_score": 0, "selected": false, "text": "<p>Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.</p>\n\n<pre><code>public class Foo {\n /** \n * Max age in year to get child rate for airline tickets\n * \n * The value of the constant is {@value}\n */\n public static final int MAX_AGE_FOR_CHILD_RATE = 2;\n\n public void computeRate() {\n if (person.getAge() &lt; MAX_AGE_FOR_CHILD_RATE) {\n applyChildRate();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 33325478, "author": "Liberty Lover", "author_id": 1096587, "author_profile": "https://Stackoverflow.com/users/1096587", "pm_score": 5, "selected": false, "text": "<h1>Magic Number Vs. Symbolic Constant: When to replace?</h1>\n<p>Magic: Unknown semantic</p>\n<p>Symbolic Constant -&gt; Provides both correct semantic and correct context for use</p>\n<p>Semantic: The meaning or purpose of a thing.</p>\n<p>&quot;Create a constant, name it after the meaning, and replace the number with it.&quot; -- Martin Fowler</p>\n<p>First, magic numbers are not just numbers. Any basic value can be &quot;magic&quot;. Basic values are manifest entities such as integers, reals, doubles, floats, dates, strings, booleans, characters, and so on. The issue is not the data type, but the &quot;magic&quot; aspect of the value as it appears in our code text.</p>\n<p>What do we mean by &quot;magic&quot;? To be precise: By &quot;magic&quot;, we intend to point to the semantics (meaning or purpose) of the value in the context of our code; that it is unknown, unknowable, unclear, or confusing. This is the notion of &quot;magic&quot;. A basic value is not magic when its semantic meaning or purpose-of-being-there is quickly and easily known, clear, and understood (not confusing) from the surround context without special helper words (e.g. symbolic constant).</p>\n<p>Therefore, we identify magic numbers by measuring the ability of a code reader to know, be clear, and understand the meaning and purpose of a basic value from its surrounding context. The less known, less clear, and more confused the reader is, the more &quot;magic&quot; the basic value is.</p>\n<h1>Basics</h1>\n<p>We have two scenarios for our magic basic values. Only the second is of primary importance for programmers and code:</p>\n<ol>\n<li>A lone basic value (e.g. number) from which its meaning is unknown, unknowable, unclear or confusing.</li>\n<li>A basic value (e.g. number) in context, but its meaning remains unknown, unknowable, unclear or confusing.</li>\n</ol>\n<p>An overarching dependency of &quot;magic&quot; is how the lone basic value (e.g. number) has no commonly known semantic (like Pi), but has a locally known semantic (e.g. your program), which is not entirely clear from context or could be abused in good or bad context(s).</p>\n<p>The semantics of most programming languages will not allow us to use lone basic values, except (perhaps) as data (i.e. tables of data). When we encounter &quot;magic numbers&quot;, we generally do so in a context. Therefore, the answer to</p>\n<blockquote>\n<p>&quot;Do I replace this magic number with a symbolic constant?&quot;</p>\n</blockquote>\n<p>is:</p>\n<blockquote>\n<p>&quot;How quickly can you assess and understand the semantic meaning of the\nnumber (its purpose for being there) in its context?&quot;</p>\n</blockquote>\n<h1>Kind of Magic, but not quite</h1>\n<p>With this thought in mind, we can quickly see how a number like Pi (3.14159) is not a &quot;magic number&quot; when placed in proper context (e.g. 2 x 3.14159 x radius or 2<em>Pi</em>r). Here, the number 3.14159 is mentally recognized Pi without the symbolic constant identifier.</p>\n<p>Still, we generally replace 3.14159 with a symbolic constant identifier like Pi because of the length and complexity of the number. The aspects of length and complexity of Pi (coupled with a need for accuracy) usually means the symbolic identifier or constant is less prone to error. Recognition of &quot;Pi&quot; as a name is a simply a convenient bonus, but is not the primary reason for having the constant.</p>\n<h1>Meanwhile: Back at the Ranch</h1>\n<p>Laying aside common constants like Pi, let's focus primarily on numbers with special meanings, but which those meanings are constrained to the universe of our software system. Such a number might be &quot;2&quot; (as a basic integer value).</p>\n<p>If I use the number 2 by itself, my first question might be: What does &quot;2&quot; mean? The meaning of &quot;2&quot; by itself is unknown and unknowable without context, leaving its use unclear and confusing. Even though having just &quot;2&quot; in our software will not happen because of language semantics, we do want to see that &quot;2&quot; by itself carries no special semantics or obvious purpose being alone.</p>\n<p>Let's put our lone &quot;2&quot; in a context of: <code>padding := 2</code>, where the context is a &quot;GUI Container&quot;. In this context the meaning of 2 (as pixels or other graphical unit) offers us a quick guess of its semantics (meaning and purpose). We might stop here and say that 2 is okay in this context and there is nothing else we need to know. However, perhaps in our software universe this is not the whole story. There is more to it, but &quot;padding = 2&quot; as a context cannot reveal it.</p>\n<p>Let's further pretend that 2 as pixel padding in our program is of the &quot;default_padding&quot; variety throughout our system. Therefore, writing the instruction <code>padding = 2</code> is not good enough. The notion of &quot;default&quot; is not revealed. Only when I write: <code>padding = default_padding</code> as a context and then elsewhere: <code>default_padding = 2</code> do I fully realize a better and fuller meaning (semantic and purpose) of 2 in our system.</p>\n<p>The example above is pretty good because &quot;2&quot; by itself could be anything. Only when we limit the range and domain of understanding to &quot;my program&quot; where 2 is the <code>default_padding</code> in the GUI UX parts of &quot;my program&quot;, do we finally make sense of &quot;2&quot; in its proper context. Here &quot;2&quot; is a &quot;magic&quot; number, which is factored out to a symbolic constant <code>default_padding</code> within the context of the GUI UX of &quot;my program&quot; in order to make it use as <code>default_padding</code> quickly understood in the greater context of the enclosing code.</p>\n<p>Thus, any basic value, whose meaning (semantic and purpose) cannot be sufficiently and quickly understood is a good candidate for a symbolic constant in the place of the basic value (e.g. magic number).</p>\n<h1>Going Further</h1>\n<p>Numbers on a scale might have semantics as well. For example, pretend we are making a D&amp;D game, where we have the notion of a monster. Our monster object has a feature called <code>life_force</code>, which is an integer. The numbers have meanings that are not knowable or clear without words to supply meaning. Thus, we begin by arbitrarily saying:</p>\n<ul>\n<li>full_life_force: INTEGER = 10 -- Very alive (and unhurt)</li>\n<li>minimum_life_force: INTEGER = 1 -- Barely alive (very hurt)</li>\n<li>dead: INTEGER = 0 -- Dead</li>\n<li>undead: INTEGER = -1 -- Min undead (almost dead)</li>\n<li>zombie: INTEGER = -10 -- Max undead (very undead)</li>\n</ul>\n<p>From the symbolic constants above, we start to get a mental picture of the aliveness, deadness, and &quot;undeadness&quot; (and possible ramifications or consequences) for our monsters in our D&amp;D game. Without these words (symbolic constants), we are left with just the numbers ranging from <code>-10 .. 10</code>. Just the range without the words leaves us in a place of possibly great confusion and potentially with errors in our game if different parts of the game have dependencies on what that range of numbers means to various operations like <code>attack_elves</code> or <code>seek_magic_healing_potion</code>.</p>\n<p>Therefore, when searching for and considering replacement of &quot;magic numbers&quot; we want to ask very purpose-filled questions about the numbers within the context of our software and even how the numbers interact semantically with each other.</p>\n<h1>Conclusion</h1>\n<p>Let's review what questions we ought to ask:</p>\n<p>You might have a magic number if ...</p>\n<ol>\n<li>Can the basic value have a special meaning or purpose in your softwares universe?</li>\n<li>Can the special meaning or purpose likely be unknown, unknowable, unclear, or confusing, even in its proper context?</li>\n<li>Can a proper basic value be improperly used with bad consequences in the wrong context?</li>\n<li>Can an improper basic value be properly used with bad consequences in the right context?</li>\n<li>Does the basic value have a semantic or purpose relationships with other basic values in specific contexts?</li>\n<li>Can a basic value exist in more than one place in our code with different semantics in each, thereby causing our reader a confusion?</li>\n</ol>\n<p>Examine stand-alone manifest constant basic values in your code text. Ask each question slowly and thoughtfully about each instance of such a value. Consider the strength of your answer. Many times, the answer is not black and white, but has shades of misunderstood meaning and purpose, speed of learning, and speed of comprehension. There is also a need to see how it connects to the software machine around it.</p>\n<p>In the end, the answer to replacement is answer the measure (in your mind) of the strength or weakness of the reader to make the connection (e.g. &quot;get it&quot;). The more quickly they understand meaning and purpose, the less &quot;magic&quot; you have.</p>\n<p>CONCLUSION: Replace basic values with symbolic constants only when the magic is large enough to cause difficult to detect bugs arising from confusions.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
What is a magic number? Why should it be avoided? Are there cases where it's appropriate?
A magic number is a direct usage of a number in the code. For example, if you have (in Java): ```java public class Foo { public void setPassword(String password) { // don't do this if (password.length() > 7) { throw new InvalidArgumentException("password"); } } } ``` This should be refactored to: ```java public class Foo { public static final int MAX_PASSWORD_SIZE = 7; public void setPassword(String password) { if (password.length() > MAX_PASSWORD_SIZE) { throw new InvalidArgumentException("password"); } } } ``` It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies. The JDK is full of examples like in `Integer`, `Character` and `Math` classes. PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.
47,883
<p>I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.</p> <p>I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.</p> <p>What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.</p>
[ { "answer_id": 47913, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 2, "selected": true, "text": "<p>You can override the path by setting the environmental variable LD_LIBRARY_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel. </p>\n\n<pre><code>crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib\n</code></pre>\n\n<p>For the includes just add -I/opt/gnu/include to your CFLAGS variable. </p>\n" }, { "answer_id": 47916, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "<p>I believe you need to add the following to the Makefile:</p>\n\n<pre><code>CFLAGS += -I/opt/gnu/include\nLDFLAGS += -L/opt/gnu/lib -R/opt/gnu/lib\n</code></pre>\n\n<p>The -I argument tell gcc where to find the include files. The -L flag tells ld where to find the libraries while linking. The -R flag writes /opt/gnu/lib into the library search path in the quadrupel binary, so it can find its libraries when it starts.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/555/" ]
I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86. I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers. What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.
You can override the path by setting the environmental variable LD\_LIBRARY\_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel. ``` crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib ``` For the includes just add -I/opt/gnu/include to your CFLAGS variable.
47,919
<p>I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).</p> <p>What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?</p> <p><a href="https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data">This</a> question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?</p>
[ { "answer_id": 47928, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 3, "selected": false, "text": "<p>Try to make each .c focus on a particular area of functionality. Use the corresponding .h file to declare those functions.</p>\n\n<p>Each .h file should have a 'header' guard around it's content. For example:</p>\n\n<pre><code>#ifndef ACCOUNTS_H\n#define ACCOUNTS_H\n....\n#endif\n</code></pre>\n\n<p>That way you can include \"accounts.h\" as many times as you want, and the first time it's seen in a particular compilation unit will be the only one that actually pulls in its content.</p>\n" }, { "answer_id": 47939, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 3, "selected": false, "text": "<p>A couple of simple rules to start:</p>\n<ol>\n<li>Put those declarations that you want to make &quot;public&quot; into the header file for the C implementation file you are creating.</li>\n<li>Only #include header files in the C file that are needed to implement the C file.</li>\n<li><h1>include header files in a header file only if required for the declarations within that header file.</h1>\n</li>\n<li>Use the include guard method described by Andrew OR use <strong>#pragma once</strong> if the compiler supports it (which does the same thing -- sometimes more efficiently)</li>\n</ol>\n" }, { "answer_id": 47943, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<h2>Compiler</h2>\n\n<p>You can see an example of a C 'module' at <a href=\"https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data\">this topic</a> - Note that there are two files - the header tea.h, and the code tea.c. You declare all the public defines, variables, and function prototypes that you want other programs to access in the header. In your main project you'll #include and that code can now access the functions and variables of the tea module that are mentioned in the header.</p>\n\n<p>It gets a little more complex after that. If you're using Visual Studio and many other IDEs that manage your build for you, then ignore this part - they take care of compiling and linking objects.</p>\n\n<h2>Linker</h2>\n\n<p>When you compile two separate C files the compiler produces individual object files - so main.c becomes main.o, and tea.c becomes tea.o. The linker's job is to look at all the object files (your main.o and tea.o), and match up the references - so when you call a tea function in main, the linker modifies that call so it actually does call the right function in tea. The linker produces the executable file.</p>\n\n<p>There is a <a href=\"http://www.cs.cf.ac.uk/Dave/C/node35.html\" rel=\"nofollow noreferrer\">great tutorial</a> that goes into more depth on this subject, including scope and other issue you'll run into.</p>\n\n<p>Good luck!</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 47945, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>Your question makes it clear that you haven't really done much serious development. The usual case is that your code will generally be far too large to fit into one file. A good rule is that you should split the functionality into logical units (.c files) and each file should contain no more than what you can easily hold in your head at one time.</p>\n\n<p>A given software product then generally includes the output from many different .c files. How this is normally done is that the compiler produces a number of object files (in unix systems \".o\" files, VC generates .obj files). It is the purpose of the \"linker\" to compose these object files into the output (either a shared library or executable).</p>\n\n<p>Generally your implementation (.c) files contain actual executable code, while the header files (.h) have the declarations of the public functions in those implementation files. You can quite easily have more header files than there are implementation files, and sometimes header files can contain inline code as well.</p>\n\n<p>It is generally quite unusual for implementation files to include each other. A good practice is to ensure that each implementation file separates its concerns from the other files.</p>\n\n<p>I would recommend you download and look at the source for the linux kernel. It is quite massive for a C program, but well organised into separate areas of functionality.</p>\n" }, { "answer_id": 47948, "author": "cschol", "author_id": 2386, "author_profile": "https://Stackoverflow.com/users/2386", "pm_score": 6, "selected": true, "text": "<p>You should regard .h files as <strong>interface files</strong> of your .c file. Every .c file represents a module with a certain amount of functionality. If functions in a .c file are used by other modules (i.e. other .c files) put the function prototype in the .h interface file. By including the interface file in your original modules .c file and every other .c file you need the function in, you make this function available to other modules. </p>\n\n<p>If you only need a function in a certain .c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. </p>\n\n<p>Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'.</p>\n\n<p>The inclusion guards in header files help to not include the same header file multiple times.</p>\n\n<p>For example:</p>\n\n<p>Module1.c:</p>\n\n<pre>\n #include \"Module1.h\"\n\n static void MyLocalFunction(void);\n static unsigned int MyLocalVariable; \n unsigned int MyExternVariable;\n\n void MyExternFunction(void)\n {\n MyLocalVariable = 1u; \n\n /* Do something */\n\n MyLocalFunction();\n }\n\n static void MyLocalFunction(void)\n {\n /* Do something */\n\n MyExternVariable = 2u;\n }\n</pre>\n\n<p>Module1.h:</p>\n\n<pre>\n #ifndef __MODULE1.H\n #define __MODULE1.H\n\n extern unsigned int MyExternVariable;\n\n void MyExternFunction(void); \n\n #endif\n</pre>\n\n<p>Module2.c</p>\n\n<pre>\n #include \"Module.1.h\"\n\n static void MyLocalFunction(void);\n\n static void MyLocalFunction(void)\n {\n MyExternVariable = 1u;\n MyExternFunction();\n }\n</pre>\n" }, { "answer_id": 47955, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 2, "selected": false, "text": "<p>To answer your additional question:</p>\n\n<blockquote>\n <p><a href=\"https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data\">This</a>\n question precipitated my inquiry. The\n tea.h file makes no reference to the\n tea.c file. Does the compiler \"know\"\n that every .h file has a corresponding\n .c file?</p>\n</blockquote>\n\n<p>The compiler is not primarily concerned with header files. Each invocation of the compiler compiles a source (.c) file into an object (.o) file. Behind the scenes (i.e. in the <code>make</code> file or project file) a command line equivalent to this is being generated:</p>\n\n<pre><code>compiler --options tea.c\n</code></pre>\n\n<p>The source file <code>#include</code>s all the header files for the resources it references, which is how the compiler finds header files.</p>\n\n<p>(I'm glossing over some details here. There is a lot to learn about building C projects.)</p>\n" }, { "answer_id": 47961, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "<p>The .h files should be used to define the prototypes for your functions. This is necessary so you can include the prototypes that you need in your C-file without declaring every function that you need all in one file. </p>\n\n<p>For instance, when you <code>#include &lt;stdio.h&gt;</code>, this provides the prototypes for printf and other IO functions. The symbols for these functions are normally loaded by the compiler by default. You can look at the system's .h files under /usr/include if you're interested in the normal idioms involved with these files. </p>\n\n<p>If you're only writing trivial applications with not many functions, it's not really necessary to modularize everything out into logical groupings of procedures. However, if you have the need to develop a large system, then you'll need to pay some consideration as to where to define each of your functions. </p>\n" }, { "answer_id": 48044, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 2, "selected": false, "text": "<p>As well as the answers supplied above, one small advantage of splinting up your code into modules (separate files) is that if you have to have any global variables, you can limit their scope to a single module by the use of the key word 'static'. (You could also apply this to functions). Note that this use of 'static' is different from its use inside a function.</p>\n" } ]
2008/09/06
[ "https://Stackoverflow.com/questions/47919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1). What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file? [This](https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data) question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?
You should regard .h files as **interface files** of your .c file. Every .c file represents a module with a certain amount of functionality. If functions in a .c file are used by other modules (i.e. other .c files) put the function prototype in the .h interface file. By including the interface file in your original modules .c file and every other .c file you need the function in, you make this function available to other modules. If you only need a function in a certain .c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'. The inclusion guards in header files help to not include the same header file multiple times. For example: Module1.c: ``` #include "Module1.h" static void MyLocalFunction(void); static unsigned int MyLocalVariable; unsigned int MyExternVariable; void MyExternFunction(void) { MyLocalVariable = 1u; /* Do something */ MyLocalFunction(); } static void MyLocalFunction(void) { /* Do something */ MyExternVariable = 2u; } ``` Module1.h: ``` #ifndef __MODULE1.H #define __MODULE1.H extern unsigned int MyExternVariable; void MyExternFunction(void); #endif ``` Module2.c ``` #include "Module.1.h" static void MyLocalFunction(void); static void MyLocalFunction(void) { MyExternVariable = 1u; MyExternFunction(); } ```
47,975
<p>More out of interest than anything else, but can you compile a DirectX app under linux?</p> <p>Obviously there's no official SDK, but I was thinking it might be possible with wine.</p> <p>Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib)</p> <p>Failing that, maybe a mingw cross compiler with the app running under wine.</p> <p>Half answered my own question here, but wondered if anyone had heard of anything like this being done?</p>
[ { "answer_id": 47978, "author": "Nicholas", "author_id": 2658, "author_profile": "https://Stackoverflow.com/users/2658", "pm_score": 0, "selected": false, "text": "<p>There is currently no way to compile DirectX code to directly target Linux. You would build your application like you normally would, then run it using a compatibility layer like Wine/Cedega.</p>\n" }, { "answer_id": 48010, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 2, "selected": false, "text": "<p>If this is not about porting but creating, you should really consider OpenGL as this API is as powerful as DirectX and much easier to port to Mac or Linux.</p>\n\n<p>I don't know your requirements so better mention it.</p>\n" }, { "answer_id": 48155, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://winehq.com\" rel=\"nofollow noreferrer\">Wine</a> is the only way to run DirectX in Linux</p>\n" }, { "answer_id": 48178, "author": "AzraelNewtype", "author_id": 4628, "author_profile": "https://Stackoverflow.com/users/4628", "pm_score": 2, "selected": false, "text": "<p>You can't link against wine as it's essentially a call interdictor/translator rather than a set of libraries you can hook into. If linux is important go OpenGL/SDL/OpenAL.</p>\n" }, { "answer_id": 48190, "author": "CiNN", "author_id": 2566, "author_profile": "https://Stackoverflow.com/users/2566", "pm_score": 0, "selected": false, "text": "<p>you can compile a directx apps in linux, but not launching it straight away.\nif you use a crosscompilator that makes windows exe and point to the windows sdk and directx sdk.</p>\n" }, { "answer_id": 66507, "author": "UK-AL", "author_id": 176514, "author_profile": "https://Stackoverflow.com/users/176514", "pm_score": 2, "selected": false, "text": "<p>I believe(I've never tried this) you can can compile Linux binarys against winelib. So it works just like a Linux executable, but with the windows libraries.</p>\n\n<p><a href=\"http://www.winehq.org/site/docs/winelib-guide/index\" rel=\"nofollow noreferrer\">http://www.winehq.org/site/docs/winelib-guide/index</a></p>\n" }, { "answer_id": 70695, "author": "Nick", "author_id": 4949, "author_profile": "https://Stackoverflow.com/users/4949", "pm_score": 4, "selected": true, "text": "<p>I've had some luck with this. I've managed to compile <a href=\"http://www.directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B5.aspx\" rel=\"nofollow noreferrer\">this simple Direct3D example</a>.</p>\n\n<p>I used winelib for this (wine-dev package on Ubuntu). Thanks to <a href=\"https://stackoverflow.com/users/9554/alastair\">alastair</a> for pointing me to winelib.</p>\n\n<p>I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running.</p>\n\n<p>I then compiled the source with the following:</p>\n\n<pre><code>wineg++ -ld3d9 -ld3dx9 triangle.cpp\n</code></pre>\n\n<p>This generates an a.out.exe.so binary, as well as an a.out script to run it under wine.</p>\n" }, { "answer_id": 15586569, "author": "Guest1337", "author_id": 2202177, "author_profile": "https://Stackoverflow.com/users/2202177", "pm_score": 1, "selected": false, "text": "<p>go to the directory with the source and type in:</p>\n\n<pre><code>winemaker --lower-uppercase -icomdlg32 -ishell32 -ishlwapi -iuser32 -igdi32 -iadvapi32 -ld3d9 .\nmake\nwine yourexecutable.exe.so\n</code></pre>\n\n<p>If you get this Error:</p>\n\n<pre><code>main.c:95:5: error: ‘struct IDirect3D9’ has no member named ‘CreateDevice’\n</code></pre>\n\n<p>make sure you have named your file main.cpp and not main.c.</p>\n" }, { "answer_id": 60591593, "author": "Julian Kirsch", "author_id": 10654548, "author_profile": "https://Stackoverflow.com/users/10654548", "pm_score": 0, "selected": false, "text": "<p>Although this question is dated, I decided to updated on it, because it keeps popping up for me as the first suggestion for this particular problem.</p>\n\n<p>As the previous answers already suggested you can compile against winelib. However, there are yet another two solutions.</p>\n\n<p>The first solution would be either to use the MinGW provided for your distributions. MinGW is a 'cross-compiler', that compiles either from macOS or linux to windows and has support for DirectX. Note, that C++ libraries compiled with MinGW are not compatible with the MSVC compiler's ABI, thus cannot be consumed. However, the resulting binaries can be executed using Wine.</p>\n\n<p>The second solution would be to <a href=\"https://stackoverflow.com/questions/23248989/clang-c-cross-compiler-generating-windows-executable-from-mac-os-x\">use clang as a cross compiler</a>. Clang usually includes the Compiler and Linker needed for Windows out of the box. However, it'll require you to include provide the headers and libraries yourself. On the other hand, libraries compiled this way are compatible with MSVC and, thus, can be consumed by it.</p>\n\n<p>Side note:\nLatter allows you to setup an CI server using linux (I did so on a raspberry pi), which creates compatible binaries for end users.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/47975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4949/" ]
More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib) Failing that, maybe a mingw cross compiler with the app running under wine. Half answered my own question here, but wondered if anyone had heard of anything like this being done?
I've had some luck with this. I've managed to compile [this simple Direct3D example](http://www.directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B5.aspx). I used winelib for this (wine-dev package on Ubuntu). Thanks to [alastair](https://stackoverflow.com/users/9554/alastair) for pointing me to winelib. I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running. I then compiled the source with the following: ``` wineg++ -ld3d9 -ld3dx9 triangle.cpp ``` This generates an a.out.exe.so binary, as well as an a.out script to run it under wine.
47,981
<p>How do I set, clear, and toggle a bit?</p>
[ { "answer_id": 47990, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 13, "selected": true, "text": "<h1>Setting a bit</h1>\n<p>Use the bitwise OR operator (<code>|</code>) to set a bit.</p>\n<pre><code>number |= 1UL &lt;&lt; n;\n</code></pre>\n<p>That will set the <code>n</code>th bit of <code>number</code>. <code>n</code> should be zero, if you want to set the <code>1</code>st bit and so on upto <code>n-1</code>, if you want to set the <code>n</code>th bit.</p>\n<p>Use <code>1ULL</code> if <code>number</code> is wider than <code>unsigned long</code>; promotion of <code>1UL &lt;&lt; n</code> doesn't happen until after evaluating <code>1UL &lt;&lt; n</code> where it's undefined behaviour to shift by more than the width of a <code>long</code>. The same applies to all the rest of the examples.</p>\n<h1>Clearing a bit</h1>\n<p>Use the bitwise AND operator (<code>&amp;</code>) to clear a bit.</p>\n<pre><code>number &amp;= ~(1UL &lt;&lt; n);\n</code></pre>\n<p>That will clear the <code>n</code>th bit of <code>number</code>. You must invert the bit string with the bitwise NOT operator (<code>~</code>), then AND it.</p>\n<h1>Toggling a bit</h1>\n<p>The XOR operator (<code>^</code>) can be used to toggle a bit.</p>\n<pre><code>number ^= 1UL &lt;&lt; n;\n</code></pre>\n<p>That will toggle the <code>n</code>th bit of <code>number</code>.</p>\n<h1>Checking a bit</h1>\n<p>You didn't ask for this, but I might as well add it.</p>\n<p>To check a bit, shift the number n to the right, then bitwise AND it:</p>\n<pre><code>bit = (number &gt;&gt; n) &amp; 1U;\n</code></pre>\n<p>That will put the value of the <code>n</code>th bit of <code>number</code> into the variable <code>bit</code>.</p>\n<h1>Changing the <em>n</em>th bit to <em>x</em></h1>\n<p>Setting the <code>n</code>th bit to either <code>1</code> or <code>0</code> can be achieved with the following on a 2's complement C++ implementation:</p>\n<pre><code>number ^= (-x ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>Bit <code>n</code> will be set if <code>x</code> is <code>1</code>, and cleared if <code>x</code> is <code>0</code>. If <code>x</code> has some other value, you get garbage. <code>x = !!x</code> will booleanize it to 0 or 1.</p>\n<p>To make this independent of 2's complement negation behaviour (where <code>-1</code> has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.</p>\n<pre><code>number ^= (-(unsigned long)x ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>or</p>\n<pre><code>unsigned long newbit = !!x; // Also booleanize to force 0 or 1\nnumber ^= (-newbit ^ number) &amp; (1UL &lt;&lt; n);\n</code></pre>\n<p>It's generally a good idea to use unsigned types for portable bit manipulation.</p>\n<p>or</p>\n<pre><code>number = (number &amp; ~(1UL &lt;&lt; n)) | (x &lt;&lt; n);\n</code></pre>\n<p><code>(number &amp; ~(1UL &lt;&lt; n))</code> will clear the <code>n</code>th bit and <code>(x &lt;&lt; n)</code> will set the <code>n</code>th bit to <code>x</code>.</p>\n<p>It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like <a href=\"https://stackoverflow.com/a/263738/52074\">the community wiki answer further down</a>) or some sort of encapsulation.</p>\n" }, { "answer_id": 50691, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 7, "selected": false, "text": "<p>It is sometimes worth using an <code>enum</code> to <em>name</em> the bits:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum ThingFlags = {\n ThingMask = 0x0000,\n ThingFlag0 = 1 &lt;&lt; 0,\n ThingFlag1 = 1 &lt;&lt; 1,\n ThingError = 1 &lt;&lt; 8,\n}\n</code></pre>\n<p>Then use the <em>names</em> later on. I.e. write</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>thingstate |= ThingFlag1;\nthingstate &amp;= ~ThingFlag0;\nif (thing &amp; ThingError) {...}\n</code></pre>\n<p>to set, clear and test. This way you hide the magic numbers from the rest of your code.</p>\n<p>Other than that, I endorse <a href=\"https://stackoverflow.com/questions/47981/how-do-i-set-clear-and-toggle-a-single-bit/47990#47990\">Paige Ruten's solution</a>.</p>\n" }, { "answer_id": 55584, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 8, "selected": false, "text": "<p>The other option is to use bit fields:</p>\n\n<pre><code>struct bits {\n unsigned int a:1;\n unsigned int b:1;\n unsigned int c:1;\n};\n\nstruct bits mybits;\n</code></pre>\n\n<p>defines a 3-bit field (actually, it's three 1-bit felds). Bit operations now become a bit (haha) simpler:</p>\n\n<p>To set or clear a bit:</p>\n\n<pre><code>mybits.b = 1;\nmybits.c = 0;\n</code></pre>\n\n<p>To toggle a bit:</p>\n\n<pre><code>mybits.a = !mybits.a;\nmybits.b = ~mybits.b;\nmybits.c ^= 1; /* all work */\n</code></pre>\n\n<p>Checking a bit:</p>\n\n<pre><code>if (mybits.c) //if mybits.c is non zero the next line below will execute\n</code></pre>\n\n<p>This only works with fixed-size bit fields. Otherwise you have to resort to the bit-twiddling techniques described in previous posts.</p>\n" }, { "answer_id": 79163, "author": "yogeesh", "author_id": 9030, "author_profile": "https://Stackoverflow.com/users/9030", "pm_score": 6, "selected": false, "text": "<h2>From <a href=\"http://snippets.org/code/temp/snip-c.zip\" rel=\"noreferrer\">snip-c.zip</a>'s bitops.h:</h2>\n\n<pre><code>/*\n** Bit set, clear, and test operations\n**\n** public domain snippet by Bob Stout\n*/\n\ntypedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;\n\n#define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L &lt;&lt; (posn)))\n#define BitClr(arg,posn) ((arg) &amp; ~(1L &lt;&lt; (posn)))\n#define BitTst(arg,posn) BOOL((arg) &amp; (1L &lt;&lt; (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L &lt;&lt; (posn)))\n</code></pre>\n\n<p>OK, let's analyze things...</p>\n\n<p>The common expression that you seem to be having problems with in all of these is \"(1L &lt;&lt; (posn))\". All this does is create a mask with a single bit on\nand which will work with any integer type. The \"posn\" argument specifies the\nposition where you want the bit. If posn==0, then this expression will\nevaluate to:</p>\n\n<pre><code>0000 0000 0000 0000 0000 0000 0000 0001 binary.\n</code></pre>\n\n<p>If posn==8, it will evaluate to:</p>\n\n<pre><code>0000 0000 0000 0000 0000 0001 0000 0000 binary.\n</code></pre>\n\n<p>In other words, it simply creates a field of 0's with a 1 at the specified\nposition. The only tricky part is in the BitClr() macro where we need to set\na single 0 bit in a field of 1's. This is accomplished by using the 1's\ncomplement of the same expression as denoted by the tilde (~) operator.</p>\n\n<p>Once the mask is created it's applied to the argument just as you suggest,\nby use of the bitwise and (&amp;), or (|), and xor (^) operators. Since the mask\nis of type long, the macros will work just as well on char's, short's, int's,\nor long's.</p>\n\n<p>The bottom line is that this is a general solution to an entire class of\nproblems. It is, of course, possible and even appropriate to rewrite the\nequivalent of any of these macros with explicit mask values every time you\nneed one, but why do it? Remember, the macro substitution occurs in the\npreprocessor and so the generated code will reflect the fact that the values\nare considered constant by the compiler - i.e. it's just as efficient to use\nthe generalized macros as to \"reinvent the wheel\" every time you need to do\nbit manipulation. </p>\n\n<p>Unconvinced? Here's some test code - I used Watcom C with full optimization\nand without using _cdecl so the resulting disassembly would be as clean as\npossible:</p>\n\n<p>----[ TEST.C ]----------------------------------------------------------------</p>\n\n<pre><code>#define BOOL(x) (!(!(x)))\n\n#define BitSet(arg,posn) ((arg) | (1L &lt;&lt; (posn)))\n#define BitClr(arg,posn) ((arg) &amp; ~(1L &lt;&lt; (posn)))\n#define BitTst(arg,posn) BOOL((arg) &amp; (1L &lt;&lt; (posn)))\n#define BitFlp(arg,posn) ((arg) ^ (1L &lt;&lt; (posn)))\n\nint bitmanip(int word)\n{\n word = BitSet(word, 2);\n word = BitSet(word, 7);\n word = BitClr(word, 3);\n word = BitFlp(word, 9);\n return word;\n}\n</code></pre>\n\n<p>----[ TEST.OUT (disassembled) ]-----------------------------------------------</p>\n\n<pre><code>Module: C:\\BINK\\tst.c\nGroup: 'DGROUP' CONST,CONST2,_DATA,_BSS\n\nSegment: _TEXT BYTE 00000008 bytes \n 0000 0c 84 bitmanip_ or al,84H ; set bits 2 and 7\n 0002 80 f4 02 xor ah,02H ; flip bit 9 of EAX (bit 1 of AH)\n 0005 24 f7 and al,0f7H\n 0007 c3 ret \n\nNo disassembly errors\n</code></pre>\n\n<p>----[ finis ]----------------------------------------------------------------- </p>\n" }, { "answer_id": 83645, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": 4, "selected": false, "text": "<p>If you're doing a lot of bit twiddling you might want to use masks which will make the whole thing quicker. The following functions are very fast and are still flexible (they allow bit twiddling in bit maps of any size).</p>\n\n<pre><code>const unsigned char TQuickByteMask[8] =\n{\n 0x01, 0x02, 0x04, 0x08,\n 0x10, 0x20, 0x40, 0x80,\n};\n\n\n/** Set bit in any sized bit mask.\n *\n * @return none\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TSetBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] |= TQuickByteMask[n]; // Set bit.\n}\n\n\n/** Reset bit in any sized mask.\n *\n * @return None\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TResetBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] &amp;= (~TQuickByteMask[n]); // Reset bit.\n}\n\n\n/** Toggle bit in any sized bit mask.\n *\n * @return none\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nvoid TToggleBit( short bit, unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n bitmap[x] ^= TQuickByteMask[n]; // Toggle bit.\n}\n\n\n/** Checks specified bit.\n *\n * @return 1 if bit set else 0.\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nshort TIsBitSet( short bit, const unsigned char *bitmap)\n{\n short n, x;\n\n x = bit / 8; // Index to byte.\n n = bit % 8; // Specific bit in byte.\n\n // Test bit (logigal AND).\n if (bitmap[x] &amp; TQuickByteMask[n])\n return 1;\n\n return 0;\n}\n\n\n/** Checks specified bit.\n *\n * @return 1 if bit reset else 0.\n *\n * @param bit - Bit number.\n * @param bitmap - Pointer to bitmap.\n */\nshort TIsBitReset( short bit, const unsigned char *bitmap)\n{\n return TIsBitSet(bit, bitmap) ^ 1;\n}\n\n\n/** Count number of bits set in a bitmap.\n *\n * @return Number of bits set.\n *\n * @param bitmap - Pointer to bitmap.\n * @param size - Bitmap size (in bits).\n *\n * @note Not very efficient in terms of execution speed. If you are doing\n * some computationally intense stuff you may need a more complex\n * implementation which would be faster (especially for big bitmaps).\n * See (http://graphics.stanford.edu/~seander/bithacks.html).\n */\nint TCountBits( const unsigned char *bitmap, int size)\n{\n int i, count = 0;\n\n for (i=0; i&lt;size; i++)\n if (TIsBitSet(i, bitmap))\n count++;\n\n return count;\n}\n</code></pre>\n\n<p>Note, to set bit 'n' in a 16 bit integer you do the following:</p>\n\n<pre><code>TSetBit( n, &amp;my_int);\n</code></pre>\n\n<p>It's up to you to ensure that the bit number is within the range of the bit map that you pass. Note that for little endian processors that bytes, words, dwords, qwords, etc., map correctly to each other in memory (main reason that little endian processors are 'better' than big-endian processors, ah, I feel a flame war coming on...).</p>\n" }, { "answer_id": 88934, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 9, "selected": false, "text": "<p>Using the Standard C++ Library: <a href=\"http://en.cppreference.com/w/cpp/utility/bitset\" rel=\"noreferrer\"><code>std::bitset&lt;N&gt;</code></a>.</p>\n\n<p>Or the <a href=\"http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"noreferrer\">Boost</a> version: <a href=\"http://www.boost.org/doc/libs/release/libs/dynamic_bitset/dynamic_bitset.html\" rel=\"noreferrer\"><code>boost::dynamic_bitset</code></a>.</p>\n\n<p>There is no need to roll your own:</p>\n\n<pre><code>#include &lt;bitset&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n std::bitset&lt;5&gt; x;\n\n x[1] = 1;\n x[2] = 0;\n // Note x[0-4] valid\n\n std::cout &lt;&lt; x &lt;&lt; std::endl;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>[Alpha:] &gt; ./a.out\n00010\n</code></pre>\n\n<p>The Boost version allows a runtime sized bitset compared with a <a href=\"https://en.wikipedia.org/wiki/C%2B%2B_Standard_Library\" rel=\"noreferrer\">standard library</a> compile-time sized bitset.</p>\n" }, { "answer_id": 263738, "author": "Steve Karg", "author_id": 9016, "author_profile": "https://Stackoverflow.com/users/9016", "pm_score": 8, "selected": false, "text": "<p>I use macros defined in a header file to handle bit set and clear:</p>\n<pre><code>/* a=target variable, b=bit number to act upon 0-n */\n#define BIT_SET(a,b) ((a) |= (1ULL&lt;&lt;(b)))\n#define BIT_CLEAR(a,b) ((a) &amp;= ~(1ULL&lt;&lt;(b)))\n#define BIT_FLIP(a,b) ((a) ^= (1ULL&lt;&lt;(b)))\n#define BIT_CHECK(a,b) (!!((a) &amp; (1ULL&lt;&lt;(b)))) // '!!' to make sure this returns 0 or 1\n\n#define BITMASK_SET(x, mask) ((x) |= (mask))\n#define BITMASK_CLEAR(x, mask) ((x) &amp;= (~(mask)))\n#define BITMASK_FLIP(x, mask) ((x) ^= (mask))\n#define BITMASK_CHECK_ALL(x, mask) (!(~(x) &amp; (mask)))\n#define BITMASK_CHECK_ANY(x, mask) ((x) &amp; (mask))\n</code></pre>\n" }, { "answer_id": 268356, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 5, "selected": false, "text": "<p>The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.</p>\n\n<pre><code>struct HwRegister {\n unsigned int errorFlag:1; // one-bit flag field\n unsigned int Mode:3; // three-bit mode field\n unsigned int StatusCode:4; // four-bit status code\n};\n\nstruct HwRegister CR3342_AReg;\n</code></pre>\n\n<p>You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.</p>\n\n<p>You can then read, write, test the individual values as before.</p>\n" }, { "answer_id": 410101, "author": "John Zwinck", "author_id": 4323, "author_profile": "https://Stackoverflow.com/users/4323", "pm_score": 5, "selected": false, "text": "<h2>Check a bit at an arbitrary location in a variable of arbitrary type:</h2>\n\n<pre><code>#define bit_test(x, y) ( ( ((const char*)&amp;(x))[(y)&gt;&gt;3] &amp; 0x80 &gt;&gt; ((y)&amp;0x07)) &gt;&gt; (7-((y)&amp;0x07) ) )\n</code></pre>\n\n<p><strong>Sample usage:</strong></p>\n\n<pre><code>int main(void)\n{\n unsigned char arr[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };\n\n for (int ix = 0; ix &lt; 64; ++ix)\n printf(\"bit %d is %d\\n\", ix, bit_test(arr, ix));\n\n return 0;\n}\n</code></pre>\n\n<p><strong>Notes:</strong>\nThis is designed to be fast (given its flexibility) and non-branchy. It results in efficient SPARC machine code when compiled Sun Studio 8; I've also tested it using MSVC++ 2008 on amd64. It's possible to make similar macros for setting and clearing bits. The key difference of this solution compared with many others here is that it works for any location in pretty much any type of variable.</p>\n" }, { "answer_id": 740953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Use this:</p>\n\n<pre><code>int ToggleNthBit ( unsigned char n, int num )\n{\n if(num &amp; (1 &lt;&lt; n))\n num &amp;= ~(1 &lt;&lt; n);\n else\n num |= (1 &lt;&lt; n);\n\n return num;\n}\n</code></pre>\n" }, { "answer_id": 991546, "author": "bill", "author_id": 121958, "author_profile": "https://Stackoverflow.com/users/121958", "pm_score": 5, "selected": false, "text": "<p>More general, for arbitrary sized bitmaps:</p>\n\n<pre><code>#define BITS 8\n#define BIT_SET( p, n) (p[(n)/BITS] |= (0x80&gt;&gt;((n)%BITS)))\n#define BIT_CLEAR(p, n) (p[(n)/BITS] &amp;= ~(0x80&gt;&gt;((n)%BITS)))\n#define BIT_ISSET(p, n) (p[(n)/BITS] &amp; (0x80&gt;&gt;((n)%BITS)))\n</code></pre>\n" }, { "answer_id": 3234773, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 5, "selected": false, "text": "<p>Here's my favorite bit arithmetic macro, which works for any type of unsigned integer array from <code>unsigned char</code> up to <code>size_t</code> (which is the biggest type that should be efficient to work with):</p>\n\n<pre><code>#define BITOP(a,b,op) \\\n ((a)[(size_t)(b)/(8*sizeof *(a))] op ((size_t)1&lt;&lt;((size_t)(b)%(8*sizeof *(a)))))\n</code></pre>\n\n<p>To set a bit:</p>\n\n<pre><code>BITOP(array, bit, |=);\n</code></pre>\n\n<p>To clear a bit:</p>\n\n<pre><code>BITOP(array, bit, &amp;=~);\n</code></pre>\n\n<p>To toggle a bit:</p>\n\n<pre><code>BITOP(array, bit, ^=);\n</code></pre>\n\n<p>To test a bit:</p>\n\n<pre><code>if (BITOP(array, bit, &amp;)) ...\n</code></pre>\n\n<p>etc.</p>\n" }, { "answer_id": 9488379, "author": "Gokul Naathan", "author_id": 1190788, "author_profile": "https://Stackoverflow.com/users/1190788", "pm_score": 4, "selected": false, "text": "<p>This program is to change any data bit from 0 to 1 or 1 to 0:</p>\n\n<pre><code>{\n unsigned int data = 0x000000F0;\n int bitpos = 4;\n int bitvalue = 1;\n unsigned int bit = data;\n bit = (bit&gt;&gt;bitpos)&amp;0x00000001;\n int invbitvalue = 0x00000001&amp;(~bitvalue);\n printf(\"%x\\n\",bit);\n\n if (bitvalue == 0)\n {\n if (bit == 0)\n printf(\"%x\\n\", data);\n else\n {\n data = (data^(invbitvalue&lt;&lt;bitpos));\n printf(\"%x\\n\", data);\n }\n }\n else\n {\n if (bit == 1)\n printf(\"elseif %x\\n\", data);\n else\n {\n data = (data|(bitvalue&lt;&lt;bitpos));\n printf(\"else %x\\n\", data);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10899060, "author": "kapilddit", "author_id": 555911, "author_profile": "https://Stackoverflow.com/users/555911", "pm_score": 5, "selected": false, "text": "<p>For the beginner I would like to explain a bit more with an example:</p>\n\n<p>Example:</p>\n\n<pre><code>value is 0x55;\nbitnum : 3rd.\n</code></pre>\n\n<p>The <code>&amp;</code> operator is used check the bit:</p>\n\n<pre><code>0101 0101\n&amp;\n0000 1000\n___________\n0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)\n</code></pre>\n\n<p>Toggle or Flip:</p>\n\n<pre><code>0101 0101\n^\n0000 1000\n___________\n0101 1101 (Flip the third bit without affecting other bits)\n</code></pre>\n\n<p><code>|</code> operator: set the bit</p>\n\n<pre><code>0101 0101\n|\n0000 1000\n___________\n0101 1101 (set the third bit without affecting other bits)\n</code></pre>\n" }, { "answer_id": 11036329, "author": "John U", "author_id": 1389218, "author_profile": "https://Stackoverflow.com/users/1389218", "pm_score": 5, "selected": false, "text": "<p>As this is tagged \"embedded\" I'll assume you're using a microcontroller. All of the above suggestions are valid &amp; work (read-modify-write, unions, structs, etc.).</p>\n\n<p>However, during a bout of oscilloscope-based debugging I was amazed to find that these methods have a considerable overhead in CPU cycles compared to writing a value directly to the micro's PORTnSET / PORTnCLEAR registers which makes a real difference where there are tight loops / high-frequency ISR's toggling pins.</p>\n\n<p>For those unfamiliar: In my example, the micro has a general pin-state register PORTn which reflects the output pins, so doing PORTn |= BIT_TO_SET results in a read-modify-write to that register. However, the PORTnSET / PORTnCLEAR registers take a '1' to mean \"please make this bit 1\" (SET) or \"please make this bit zero\" (CLEAR) and a '0' to mean \"leave the pin alone\". so, you end up with two port addresses depending whether you're setting or clearing the bit (not always convenient) but a <em>much</em> faster reaction and smaller assembled code.</p>\n" }, { "answer_id": 14087800, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Visual C 2010, and perhaps many other compilers, have direct support for boolean operations built in. A bit has two possible values, just like a boolean, so we can use booleans instead - even if they take up more space than a single bit in memory in this representation. This works, even the <code>sizeof()</code> operator works properly. </p>\n\n<pre><code>bool IsGph[256], IsNotGph[256];\n\n// Initialize boolean array to detect printable characters\nfor(i=0; i&lt;sizeof(IsGph); i++) {\n IsGph[i] = isgraph((unsigned char)i);\n}\n</code></pre>\n\n<p>So, to your question, <code>IsGph[i] =1</code>, or <code>IsGph[i] =0</code> make setting and clearing bools easy.</p>\n\n<p>To find unprintable characters:</p>\n\n<pre><code>// Initialize boolean array to detect UN-printable characters, \n// then call function to toggle required bits true, while initializing a 2nd\n// boolean array as the complement of the 1st.\nfor(i=0; i&lt;sizeof(IsGph); i++) {\n if(IsGph[i]) {\n IsNotGph[i] = 0;\n } else {\n IsNotGph[i] = 1;\n }\n}\n</code></pre>\n\n<p>Note there is nothing \"special\" about this code. It treats a bit like an integer - which technically, it is. A 1 bit integer that can hold 2 values, and 2 values only.</p>\n\n<p>I once used this approach to find duplicate loan records, where loan_number was the ISAM key, using the 6-digit loan number as an index into the bit array. Savagely fast, and after 8 months, proved that the mainframe system we were getting the data from was in fact malfunctioning. The simplicity of bit arrays makes confidence in their correctness very high - vs a searching approach for example.</p>\n" }, { "answer_id": 23532806, "author": "kendotwill", "author_id": 1713375, "author_profile": "https://Stackoverflow.com/users/1713375", "pm_score": 4, "selected": false, "text": "<p>Expanding on the <code>bitset</code> answer:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;bitset&gt;\n#include &lt;string&gt;\n\nusing namespace std;\nint main() {\n bitset&lt;8&gt; byte(std::string(\"10010011\");\n\n // Set Bit\n byte.set(3); // 10010111\n\n // Clear Bit\n byte.reset(2); // 10010101\n\n // Toggle Bit\n byte.flip(7); // 00010101\n\n cout &lt;&lt; byte &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 23888594, "author": "Vincet", "author_id": 3679614, "author_profile": "https://Stackoverflow.com/users/3679614", "pm_score": -1, "selected": false, "text": "<p>Try one of these functions in the C language to change n bit:</p>\n\n<pre><code>char bitfield;\n\n// Start at 0th position\n\nvoid chang_n_bit(int n, int value)\n{\n bitfield = (bitfield | (1 &lt;&lt; n)) &amp; (~( (1 &lt;&lt; n) ^ (value &lt;&lt; n) ));\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>void chang_n_bit(int n, int value)\n{\n bitfield = (bitfield | (1 &lt;&lt; n)) &amp; ((value &lt;&lt; n) | ((~0) ^ (1 &lt;&lt; n)));\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>void chang_n_bit(int n, int value)\n{\n if(value)\n bitfield |= 1 &lt;&lt; n;\n else\n bitfield &amp;= ~0 ^ (1 &lt;&lt; n);\n}\n\nchar get_n_bit(int n)\n{\n return (bitfield &amp; (1 &lt;&lt; n)) ? 1 : 0;\n}\n</code></pre>\n" }, { "answer_id": 28376414, "author": "sam msft", "author_id": 640259, "author_profile": "https://Stackoverflow.com/users/640259", "pm_score": 3, "selected": false, "text": "<p>Here are some macros I use:</p>\n\n<pre><code>SET_FLAG(Status, Flag) ((Status) |= (Flag))\nCLEAR_FLAG(Status, Flag) ((Status) &amp;= ~(Flag))\nINVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) &amp; ~(ulAllowed))\nTEST_FLAGS(t,ulMask, ulBit) (((t)&amp;(ulMask)) == (ulBit))\nIS_FLAG_SET(t,ulMask) TEST_FLAGS(t,ulMask,ulMask)\nIS_FLAG_CLEAR(t,ulMask) TEST_FLAGS(t,ulMask,0)\n</code></pre>\n" }, { "answer_id": 37488546, "author": "Jeegar Patel", "author_id": 775964, "author_profile": "https://Stackoverflow.com/users/775964", "pm_score": 4, "selected": false, "text": "<p>If you want to perform this all operation with C programming in the <strong>Linux kernel</strong> then I suggest to use standard APIs of the Linux kernel.</p>\n\n<p>See <a href=\"https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html\" rel=\"nofollow noreferrer\">https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html</a></p>\n\n<pre><code>set_bit Atomically set a bit in memory\nclear_bit Clears a bit in memory\nchange_bit Toggle a bit in memory\ntest_and_set_bit Set a bit and return its old value\ntest_and_clear_bit Clear a bit and return its old value\ntest_and_change_bit Change a bit and return its old value\ntest_bit Determine whether a bit is set\n</code></pre>\n\n<p>Note: Here the whole operation happens in a single step. So these all are guaranteed to be <strong>atomic</strong> even on SMP computers and are useful\nto keep coherence across processors.</p>\n" }, { "answer_id": 46454677, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>How do you set, clear, and toggle a single bit?</p>\n</blockquote>\n\n<p>To address a common coding pitfall when attempting to form the mask:<br>\n<strong><code>1</code> is not always wide enough</strong></p>\n\n<p>What problems happen when <code>number</code> is a wider type than <code>1</code>?<br>\n<code>x</code> may be too great for the shift <code>1 &lt;&lt; x</code> leading to <em>undefined behavior</em> (UB). Even if <code>x</code> is not too great, <code>~</code> may not flip enough most-significant-bits.</p>\n\n<pre><code>// assume 32 bit int/unsigned\nunsigned long long number = foo();\n\nunsigned x = 40; \nnumber |= (1 &lt;&lt; x); // UB\nnumber ^= (1 &lt;&lt; x); // UB\nnumber &amp;= ~(1 &lt;&lt; x); // UB\n\nx = 10;\nnumber &amp;= ~(1 &lt;&lt; x); // Wrong mask, not wide enough\n</code></pre>\n\n<hr>\n\n<p><strong>To insure 1 is wide enough:</strong></p>\n\n<p>Code could use <code>1ull</code> or pedantically <code>(uintmax_t)1</code> and let the compiler optimize.</p>\n\n<pre><code>number |= (1ull &lt;&lt; x);\nnumber |= ((uintmax_t)1 &lt;&lt; x);\n</code></pre>\n\n<p>Or cast - which makes for coding/review/maintenance issues keeping the cast correct and up-to-date.</p>\n\n<pre><code>number |= (type_of_number)1 &lt;&lt; x;\n</code></pre>\n\n<p>Or gently promote the <code>1</code> by forcing a math operation that is as least as wide as the type of <code>number</code>.</p>\n\n<pre><code>number |= (number*0 + 1) &lt;&lt; x;\n</code></pre>\n\n<hr>\n\n<p>As with most bit manipulations, best to work with <em>unsigned</em> types rather than <em>signed</em> ones</p>\n" }, { "answer_id": 48725080, "author": "Joakim L. Christiansen", "author_id": 4216153, "author_profile": "https://Stackoverflow.com/users/4216153", "pm_score": 2, "selected": false, "text": "<p>A templated version (put in a header file) with support for changing multiple bits (works on AVR microcontrollers btw):</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace bit {\n template &lt;typename T1, typename T2&gt;\n constexpr inline T1 bitmask(T2 bit) \n {return (T1)1 &lt;&lt; bit;}\n template &lt;typename T1, typename T3, typename ...T2&gt;\n constexpr inline T1 bitmask(T3 bit, T2 ...bits) \n {return ((T1)1 &lt;&lt; bit) | bitmask&lt;T1&gt;(bits...);}\n\n /** Set these bits (others retain their state) */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline void set (T1 &amp;variable, T2 ...bits) \n {variable |= bitmask&lt;T1&gt;(bits...);}\n /** Set only these bits (others will be cleared) */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline void setOnly (T1 &amp;variable, T2 ...bits) \n {variable = bitmask&lt;T1&gt;(bits...);}\n /** Clear these bits (others retain their state) */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline void clear (T1 &amp;variable, T2 ...bits) \n {variable &amp;= ~bitmask&lt;T1&gt;(bits...);}\n /** Flip these bits (others retain their state) */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline void flip (T1 &amp;variable, T2 ...bits) \n {variable ^= bitmask&lt;T1&gt;(bits...);}\n /** Check if any of these bits are set */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline bool isAnySet(const T1 &amp;variable, T2 ...bits) \n {return variable &amp; bitmask&lt;T1&gt;(bits...);}\n /** Check if all these bits are set */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline bool isSet (const T1 &amp;variable, T2 ...bits) \n {return ((variable &amp; bitmask&lt;T1&gt;(bits...)) == bitmask&lt;T1&gt;(bits...));}\n /** Check if all these bits are not set */\n template &lt;typename T1, typename ...T2&gt;\n constexpr inline bool isNotSet (const T1 &amp;variable, T2 ...bits) \n {return ((variable &amp; bitmask&lt;T1&gt;(bits...)) != bitmask&lt;T1&gt;(bits...));}\n}\n</code></pre>\n<p>Example of use:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;bitset&gt; // for console output of binary values\n\n// and include the code above of course\n\nusing namespace std;\n\nint main() {\n uint8_t v = 0b1111'1100;\n bit::set(v, 0);\n cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n bit::clear(v, 0,1);\n cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n bit::flip(v, 0,1);\n cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n bit::clear(v, 0,1,2,3,4,5,6,7);\n cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n\n bit::flip(v, 0,7);\n cout &lt;&lt; bitset&lt;8&gt;(v) &lt;&lt; endl;\n}\n</code></pre>\n<p>BTW: It turns out that constexpr and inline is not used if not sending the optimizer argument (e.g.: -O3) to the compiler. Feel free to try the code at <a href=\"https://godbolt.org/\" rel=\"nofollow noreferrer\">https://godbolt.org/</a> and look at the ASM output.</p>\n" }, { "answer_id": 48906086, "author": "Sazzad Hissain Khan", "author_id": 1084174, "author_profile": "https://Stackoverflow.com/users/1084174", "pm_score": 3, "selected": false, "text": "<pre><code>int set_nth_bit(int num, int n){ \n return (num | 1 &lt;&lt; n);\n}\n\nint clear_nth_bit(int num, int n){ \n return (num &amp; ~( 1 &lt;&lt; n));\n}\n\nint toggle_nth_bit(int num, int n){ \n return num ^ (1 &lt;&lt; n);\n}\n\nint check_nth_bit(int num, int n){ \n return num &amp; (1 &lt;&lt; n);\n}\n</code></pre>\n" }, { "answer_id": 56521123, "author": "Pankaj Prakash", "author_id": 2401088, "author_profile": "https://Stackoverflow.com/users/2401088", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p><strong>Let suppose few things first</strong><br>\n <code>num = 55</code> Integer to perform bitwise operations (set, get, clear, toggle).<br>\n <code>n = 4</code> 0 based bit position to perform bitwise operations. </p>\n</blockquote>\n\n<h1>How to get a bit?</h1>\n\n<ol>\n<li>To get the <code>nth</code> bit of num right shift <code>num</code>, <code>n</code> times. Then perform bitwise AND <code>&amp;</code> with 1.</li>\n</ol>\n\n<pre><code>bit = (num &gt;&gt; n) &amp; 1;\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code> 0011 0111 (55 in decimal)\n &gt;&gt; 4 (right shift 4 times)\n-----------------\n 0000 0011\n &amp; 0000 0001 (1 in decimal)\n-----------------\n =&gt; 0000 0001 (final result)\n</code></pre>\n\n<h1>How to set a bit?</h1>\n\n<ol>\n<li>To set a particular bit of number. Left shift 1 <code>n</code> times. Then perform bitwise OR <code>|</code> operation with <code>num</code>.</li>\n</ol>\n\n<pre><code>num |= (1 &lt;&lt; n); // Equivalent to; num = (1 &lt;&lt; n) | num;\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code> 0000 0001 (1 in decimal)\n &lt;&lt; 4 (left shift 4 times)\n-----------------\n 0001 0000\n | 0011 0111 (55 in decimal)\n-----------------\n =&gt; 0001 0000 (final result)\n</code></pre>\n\n<h1>How to clear a bit?</h1>\n\n<ol>\n<li>Left shift 1, <code>n</code> times i.e. <code>1 &lt;&lt; n</code>.</li>\n<li>Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. <code>~ (1 &lt;&lt; n)</code>.</li>\n<li>Finally, perform bitwise AND <code>&amp;</code> operation with the above result and <code>num</code>. The above three steps together can be written as <code>num &amp; (~ (1 &lt;&lt; n))</code>;</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/mf8hm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mf8hm.png\" alt=\"Steps to clear a bit\"></a></p>\n\n<pre><code>num &amp;= (~(1 &lt;&lt; n)); // Equivalent to; num = num &amp; (~(1 &lt;&lt; n));\n</code></pre>\n\n<p><strong>How it works?</strong></p>\n\n<pre><code> 0000 0001 (1 in decimal)\n &lt;&lt; 4 (left shift 4 times)\n-----------------\n ~ 0001 0000\n-----------------\n 1110 1111\n &amp; 0011 0111 (55 in decimal)\n-----------------\n =&gt; 0010 0111 (final result)\n</code></pre>\n\n<h1>How to toggle a bit?</h1>\n\n<p>To toggle a bit we use bitwise XOR <code>^</code> operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0. </p>\n\n<p>Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1. </p>\n\n<pre><code>num ^= (1 &lt;&lt; n); // Equivalent to; num = num ^ (1 &lt;&lt; n);\n</code></pre>\n\n<p><strong>How it works?</strong> </p>\n\n<ul>\n<li>If the bit to toggle is 0 then, <code>0 ^ 1 =&gt; 1</code>. </li>\n<li>If the bit to toggle is 1 then, <code>1 ^ 1 =&gt; 0</code>.</li>\n</ul>\n\n<pre><code> 0000 0001 (1 in decimal)\n &lt;&lt; 4 (left shift 4 times)\n-----------------\n 0001 0000\n ^ 0011 0111 (55 in decimal)\n-----------------\n =&gt; 0010 0111 (final result)\n</code></pre>\n\n<p>Recommended reading - <a href=\"https://codeforwin.org/2016/01/bitwise-operator-programming-exercises-and-solutions-in-c.html\" rel=\"noreferrer\">Bitwise operator exercises</a></p>\n" }, { "answer_id": 61374583, "author": "Balaji Boggaram Ramanarayan", "author_id": 2101290, "author_profile": "https://Stackoverflow.com/users/2101290", "pm_score": 2, "selected": false, "text": "<p>This program is based out of @Jeremy's above solution. If someone wish to quickly play around.</p>\n\n<pre><code>public class BitwiseOperations {\n\n public static void main(String args[]) {\n\n setABit(0, 4); // set the 4th bit, 0000 -&gt; 1000 [8]\n clearABit(16, 5); // clear the 5th bit, 10000 -&gt; 00000 [0]\n toggleABit(8, 4); // toggle the 4th bit, 1000 -&gt; 0000 [0]\n checkABit(8,4); // check the 4th bit 1000 -&gt; true \n }\n\n public static void setABit(int input, int n) {\n input = input | ( 1 &lt;&lt; n-1);\n System.out.println(input);\n }\n\n\n public static void clearABit(int input, int n) {\n input = input &amp; ~(1 &lt;&lt; n-1);\n System.out.println(input);\n }\n\n public static void toggleABit(int input, int n) {\n input = input ^ (1 &lt;&lt; n-1);\n System.out.println(input);\n }\n\n public static void checkABit(int input, int n) {\n boolean isSet = ((input &gt;&gt; n-1) &amp; 1) == 1; \n System.out.println(isSet);\n }\n}\n\n\nOutput :\n8\n0\n0\ntrue\n</code></pre>\n" }, { "answer_id": 66075462, "author": "Dominic van der Zypen", "author_id": 8082048, "author_profile": "https://Stackoverflow.com/users/8082048", "pm_score": 0, "selected": false, "text": "<h1>Setting the nth bit to x (bit value) without using -1</h1>\n<p>Sometimes when you are not sure what -1 or the like will result in, you may wish to set the nth bit without using -1:</p>\n<pre><code>number = (((number | (1 &lt;&lt; n)) ^ (1 &lt;&lt; n))) | (x &lt;&lt; n);\n</code></pre>\n<p>Explanation: <code>((number | (1 &lt;&lt; n)</code> sets the nth bit to 1 (where <code>|</code> denotes bitwise OR), then with <code>(...) ^ (1 &lt;&lt; n)</code> we set the nth bit to 0, and finally with <code>(...) | x &lt;&lt; n)</code> we set the nth bit that was 0, to (bit value) <code>x</code>.</p>\n<p>This also works in <code>golang</code>.</p>\n" }, { "answer_id": 66667330, "author": "lckid2004", "author_id": 15412355, "author_profile": "https://Stackoverflow.com/users/15412355", "pm_score": 2, "selected": false, "text": "<p>Here is a routine in C to perform the basic bitwise operations:</p>\n<pre><code>#define INT_BIT (unsigned int) (sizeof(unsigned int) * 8U) //number of bits in unsigned int\n\nint main(void)\n{\n \n unsigned int k = 5; //k is the bit position; here it is the 5th bit from the LSb (0th bit)\n \n unsigned int regA = 0x00007C7C; //we perform bitwise operations on regA\n \n regA |= (1U &lt;&lt; k); //Set kth bit\n \n regA &amp;= ~(1U &lt;&lt; k); //Clear kth bit\n \n regA ^= (1U &lt;&lt; k); //Toggle kth bit\n \n regA = (regA &lt;&lt; k) | regA &gt;&gt; (INT_BIT - k); //Rotate left by k bits\n \n regA = (regA &gt;&gt; k) | regA &lt;&lt; (INT_BIT - k); //Rotate right by k bits\n\n return 0; \n}\n\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/47981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
How do I set, clear, and toggle a bit?
Setting a bit ============= Use the bitwise OR operator (`|`) to set a bit. ``` number |= 1UL << n; ``` That will set the `n`th bit of `number`. `n` should be zero, if you want to set the `1`st bit and so on upto `n-1`, if you want to set the `n`th bit. Use `1ULL` if `number` is wider than `unsigned long`; promotion of `1UL << n` doesn't happen until after evaluating `1UL << n` where it's undefined behaviour to shift by more than the width of a `long`. The same applies to all the rest of the examples. Clearing a bit ============== Use the bitwise AND operator (`&`) to clear a bit. ``` number &= ~(1UL << n); ``` That will clear the `n`th bit of `number`. You must invert the bit string with the bitwise NOT operator (`~`), then AND it. Toggling a bit ============== The XOR operator (`^`) can be used to toggle a bit. ``` number ^= 1UL << n; ``` That will toggle the `n`th bit of `number`. Checking a bit ============== You didn't ask for this, but I might as well add it. To check a bit, shift the number n to the right, then bitwise AND it: ``` bit = (number >> n) & 1U; ``` That will put the value of the `n`th bit of `number` into the variable `bit`. Changing the *n*th bit to *x* ============================= Setting the `n`th bit to either `1` or `0` can be achieved with the following on a 2's complement C++ implementation: ``` number ^= (-x ^ number) & (1UL << n); ``` Bit `n` will be set if `x` is `1`, and cleared if `x` is `0`. If `x` has some other value, you get garbage. `x = !!x` will booleanize it to 0 or 1. To make this independent of 2's complement negation behaviour (where `-1` has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation. ``` number ^= (-(unsigned long)x ^ number) & (1UL << n); ``` or ``` unsigned long newbit = !!x; // Also booleanize to force 0 or 1 number ^= (-newbit ^ number) & (1UL << n); ``` It's generally a good idea to use unsigned types for portable bit manipulation. or ``` number = (number & ~(1UL << n)) | (x << n); ``` `(number & ~(1UL << n))` will clear the `n`th bit and `(x << n)` will set the `n`th bit to `x`. It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like [the community wiki answer further down](https://stackoverflow.com/a/263738/52074)) or some sort of encapsulation.
48,009
<p>What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP</p> <pre><code>&lt;?php $class_name = 'SomeClassName'; $object = new $class_name; ?&gt; </code></pre> <p>This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.</p> <p>Problems that come immediately to mind are </p> <ol> <li><s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)</li> <li>Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)</li> </ol> <p>What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?</p>
[ { "answer_id": 48035, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>It looks you can still pass arguments to the constructor, here's my test code:</p>\n\n<pre><code>&lt;?php\n\nclass Test {\n function __construct($x) {\n echo $x;\n }\n}\n\n$class = 'Test';\n$object = new $class('test'); // echoes \"test\"\n\n?&gt;\n</code></pre>\n\n<p>That is what you meant, right?</p>\n\n<p>So the only other problem you mentioned and that I can think of is the security of it, but it shouldn't be too difficult to make it secure, and it's obviously a lot more secure than using eval().</p>\n" }, { "answer_id": 48077, "author": "Sam McAfee", "author_id": 577, "author_profile": "https://Stackoverflow.com/users/577", "pm_score": 2, "selected": false, "text": "<p>There may indeed be a performance hit for having to resolve the name of the variable before looking up the class definition. But, without declaring classes dynamically you have no real way to do \"dyanmic\" or \"meta\" programming. You would not be able to write code generation programs or anything like a domain-specific language construct.</p>\n\n<p>We use this convention all over the place in some of the core classes of our internal framework to make the URL to controller mappings work. I have also seen it in many commercial open source applications (I'll try and dig for an example and post it). Anyway, the point of my answer is that it seems well worth what is probably a slight performance decrease if it makes more flexible, dynamic code.</p>\n\n<p>The other trade-off that I should mention, though, is that performance aside, it does make the code slightly less obvious and readable unless you are very careful with your variable names. Most code is written once, and re-read and modified many times, so readability is important.</p>\n" }, { "answer_id": 48736, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 4, "selected": true, "text": "<p>One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff.</p>\n\n<p>As long as you don't do something like</p>\n\n<pre><code>$classname = 'SomeClassName';\nfor ($x = 0; $x &lt; 100000; $x++){\n $object = new $classname;\n}\n</code></pre>\n\n<p>you are probably fine :-)</p>\n\n<p>(my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will).</p>\n\n<p>Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.</p>\n" }, { "answer_id": 48742, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "<p>I use dynamic instantiation in my custom framework. My application controller needs to instantiate a sub-controller based on the request, and it would be simply ridiculous to use a gigantic, ever-changing switch statement to manage the loading of those controllers. As a result, I can add controller after controller to my application without having to modify the app controller to call them. As long as my URIs adhere to the conventions of my framework, the app controller can use them without having to know anything until runtime.</p>\n\n<p>I'm using this framework in a production shopping cart application right now, and the performance is quite favorable, too. That being said, I'm only using the dynamic class selection in one or two spots in the whole app. I wonder in what circumstances you would need to use it frequently, and whether or not those situations are ones that are suffering from a programmer's desire to over-abstract the application (I've been guilty of this before).</p>\n" }, { "answer_id": 49586, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "<p>Alan, there's nothing wrong with dynamic class initialisation. This technique is present also in Java language, where one can convert string to class using <code>Class.forClass('classname')</code> method. It is also quite handy to defer algorithm complexity to several classes instead of having list of if-conditions. Dynamic class names are especially well suited in situations where you want your code to remain open for extension without the need for modifications.</p>\n\n<p>I myself often use different classes in conjunction with database tables. In one column I keep class name that will be used to handle the record. This gives me great power of adding new types of records and handle them in unique way without changing a single byte in existing code.</p>\n\n<p>You shouldn't be concerned about the performance. It has almost no overhead and objects themselves are super fast in PHP. If you need to spawn thousands of identical objects, use <a href=\"http://www.dofactory.com/Patterns/PatternFlyweight.aspx\" rel=\"nofollow noreferrer\">Flyweight</a> design pattern to reduce memory footprint. Especially, you should not sacrifice your time as a developer just to save milliseconds on server. Also op-code optimisers work seamlessly with this technique. Scripts compiled with Zend Optimizer did not misbehave.</p>\n" }, { "answer_id": 62327, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 3, "selected": false, "text": "<p>I would add that you can also instanciate it with a dynamic number of parameters using :</p>\n\n<pre><code>&lt;?php\n\n$class = \"Test\";\n$args = array('a', 'b');\n$ref = new ReflectionClass($class);\n$instance = $ref-&gt;newInstanceArgs($args);\n\n?&gt;\n</code></pre>\n\n<p>But of course you add some more overhead by doing this. </p>\n\n<p>About the security issue I don't think it matters much, at least it's nothing compared to eval(). In the worst case the wrong class gets instanciated, of course this is a potential security breach but much harder to exploit, and it's easy to filter using an array of allowed classes, if you really need user input to define the class name.</p>\n" }, { "answer_id": 62360, "author": "Leonid Shevtsov", "author_id": 6678, "author_profile": "https://Stackoverflow.com/users/6678", "pm_score": 0, "selected": false, "text": "<p>One problem is that you can't address static members like that, for instance</p>\n\n<pre><code>&lt;?php\n$className = 'ClassName';\n\n$className::someStaticMethod(); //doesn't work\n?&gt;\n</code></pre>\n" }, { "answer_id": 63437, "author": "Edoardo Vacchi", "author_id": 7849, "author_profile": "https://Stackoverflow.com/users/7849", "pm_score": 0, "selected": false, "text": "<p>@coldFlame: IIRC you can use <code>call_user_func(array($className, 'someStaticMethod')</code> and <code>call_user_func_array()</code> to pass params</p>\n" }, { "answer_id": 461564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>class Test {\n function testExt() {\n print 'hello from testExt :P';\n }\n function test2Ext()\n {\n print 'hi from test2Ext :)';\n }\n}\n\n\n$class = 'Test';\n$method_1 = \"testExt\";\n$method_2 = \"test2Ext\";\n$object = new $class(); // echoes \"test\"\n$object-&gt;{$method_2}(); // will print 'hi from test2Ext :)'\n$object-&gt;{$method_1}(); // will print 'hello from testExt :P';\n</code></pre>\n\n<p>this trick works in both php4 and php5 :D enjoy..</p>\n" }, { "answer_id": 14203323, "author": "FilmJ", "author_id": 133221, "author_profile": "https://Stackoverflow.com/users/133221", "pm_score": 1, "selected": false, "text": "<p>So I've recently encountered this, and wanted to give my thoughts on the \"other\" implications of using dynamic instantiation.</p>\n\n<p>For one thing <code>func_get_args()</code> throws a bit of a wrench into things. For example I want to create a method that acts as a constructor for a specific class (e.g. a factory method). I'd need to be able to pass along the params passed to my factory method to the constructor of the class I'm instantiating.</p>\n\n<p>If you do: </p>\n\n<pre><code>public function myFactoryMethod() \n{\n $class = 'SomeClass'; // e.g. you'd get this from a switch statement\n $obj = new $class( func_get_args() );\n return $obj;\n}\n</code></pre>\n\n<p>and then call:</p>\n\n<blockquote>\n <p>$factory->myFactoryMethod('foo','bar');</p>\n</blockquote>\n\n<p>You're actually passing an array as the first/only param, which is the same as <code>new SomeClass( array( 'foo', 'bar' ) )</code> This is obviously not what we want.</p>\n\n<p>The solution (as noted by @Seldaek) requires us to convert the array into params of a constructor:</p>\n\n<pre><code>public function myFactoryMethod() \n{\n $class = 'SomeClass'; // e.g. you'd get this from a switch statement\n $ref = new ReflectionClass( $class );\n $obj = $ref-&gt;newInstanceArgs( func_get_args() );\n return $obj;\n}\n</code></pre>\n\n<p>Note: This could not be accomplished using <code>call_user_func_array</code>, because you can't use this approach to instantiate new objects. </p>\n\n<p>HTH!</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP ``` <?php $class_name = 'SomeClassName'; $object = new $class_name; ?> ``` This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement. Problems that come immediately to mind are 1. ~~You lose the ability to pass arguments into a constructor~~ (LIES. Thanks Jeremy) 2. Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?) What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?
One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff. As long as you don't do something like ``` $classname = 'SomeClassName'; for ($x = 0; $x < 100000; $x++){ $object = new $classname; } ``` you are probably fine :-) (my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will). Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.
48,053
<p>I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.</p> <p>Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?<p></p> <pre><code>const int FIZZ = 6; for(int x = 0; x &lt; MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } </code></pre> <p>vs:</p> <p>The way I am currently doing it:</p> <pre><code>const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x &lt; MAXCOUNT; x++) { if(fizzcount &gt;= FIZZ) { print("Fizz\n"); fizzcount = 0; } } </code></pre>
[ { "answer_id": 48058, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>In the embedded world, the \"modulus\" operations you need to do are often the ones that break down nicely into bit operations that you can do with <code>&amp;</code>, <code>|</code> and sometimes <code>&gt;&gt;</code>.</p>\n" }, { "answer_id": 48074, "author": "shmuelp", "author_id": 4673, "author_profile": "https://Stackoverflow.com/users/4673", "pm_score": 2, "selected": false, "text": "<p>Unless you really need high performance on multiple embedded platforms, don't change how you code for performance reasons until you profile!</p>\n\n<p>Code that's written awkwardly to optimize for performance is hard to debug and hard to maintain. Write a test case, and profile it on your target. Once you know the actual cost of modulus, then decide if the alternate solution is worth coding.</p>\n" }, { "answer_id": 48075, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 0, "selected": false, "text": "<p>Not that this is necessarily better, but you could have an inner loop which always goes up to <code>FIZZ</code>, and an outer loop which repeats it all some certain number of times. You've then perhaps got to special case the final few steps if <code>MAXCOUNT</code> is not evenly divisible by <code>FIZZ</code>.</p>\n\n<p>That said, I'd suggest doing some research and performance profiling on your intended platforms to get a clear idea of the performance constraints you're under. There may be much more productive places to spend your optimisation effort.</p>\n" }, { "answer_id": 48078, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 1, "selected": false, "text": "<p>Do you have access to any programmable hardware on the embedded device? Like counters and such? If so, you might be able to write a hardware based mod unit, instead of using the simulated %. (I did that once in VHDL. Not sure if I still have the code though.)</p>\n\n<p>Mind you, you did say that division was 5-10 times faster. Have you considered doing a division, multiplication, and subtraction to simulated the mod? (Edit: Misunderstood the original post. I did think it was odd that division was faster than mod, they are the same operation.)</p>\n\n<p>In your specific case, though, you are checking for a mod of 6. 6 = 2*3. So you could MAYBE get some small gains if you first checked if the least significant bit was a 0. Something like:</p>\n\n<pre><code>if((!(x &amp; 1)) &amp;&amp; (x % 3))\n{\n print(\"Fizz\\n\");\n}\n</code></pre>\n\n<p>If you do that, though, I'd recommend confirming that you get any gains, yay for profilers. And doing some commenting. I'd feel bad for the next guy who has to look at the code otherwise.</p>\n" }, { "answer_id": 48079, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 5, "selected": false, "text": "<p>If you are calculating a number mod some power of two, you can use the bit-wise and operator. Just subtract one from the second number. For example:</p>\n\n<pre><code>x % 8 == x &amp; 7\nx % 256 == x &amp; 255\n</code></pre>\n\n<p>A few caveats:</p>\n\n<ol>\n<li>This <strong>only works</strong> if the second number is a power of two.</li>\n<li>It's only equivalent if the modulus is always positive. The C and C++ standards don't specify the sign of the modulus when the first number is negative (until C++11, which <em>does</em> guarantee it will be negative, which is what most compilers were already doing). A bit-wise and gets rid of the sign bit, so it will always be positive (i.e. it's a true modulus, not a remainder). It sounds like that's what you want anyway though.</li>\n<li><strong>Your compiler probably already does this when it can, so in most cases it's not worth doing it manually.</strong></li>\n</ol>\n" }, { "answer_id": 48090, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 2, "selected": false, "text": "<p>@Matthew is right. Try this:</p>\n\n<pre><code>int main() {\n int i;\n for(i = 0; i&lt;=1024; i++) {\n if (!(i &amp; 0xFF)) printf(\"&amp; i = %d\\n\", i);\n if (!(i % 0x100)) printf(\"mod i = %d\\n\", i);\n }\n}\n</code></pre>\n" }, { "answer_id": 48091, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 0, "selected": false, "text": "<p>@Jeff V: I see a problem with it! (Beyond that your original code was looking for a mod 6 and now you are essentially looking for a mod 8). You keep doing an extra +1! Hopefully your compiler optimizes that away, but why not just test start at 2 and go to MAXCOUNT inclusive? Finally, you are returning true every time that (x+1) is NOT divisible by 8. Is that what you want? (I assume it is, but just want to confirm.)</p>\n" }, { "answer_id": 48093, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 1, "selected": false, "text": "<p>You should really check the embedded device you need. All the assembly language I have seen (x86, 68000) implement the modulus using a division.</p>\n\n<p>Actually, the division assembly operation returns the result of the division and the remaining in two different registers.</p>\n" }, { "answer_id": 48103, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 7, "selected": true, "text": "<p>Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder.</p>\n\n<p>Still, there is a small branch of number theory devoted to <a href=\"http://en.wikibooks.org/wiki/Discrete_mathematics/Modular_arithmetic\" rel=\"noreferrer\">Modular Arithmetic</a> which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating <a href=\"http://www.math.utah.edu/~carlson/mathcircles/magic.pdf\" rel=\"noreferrer\">magic squares</a>.</p>\n\n<p>So, in that vein, here's a <a href=\"http://piclist.org/techref/postbot.asp?by=time&amp;id=piclist/2006/08/03/065022a\" rel=\"noreferrer\">very low level look</a> at the math of modulus for an example of x, which should show you how simple it can be compared to division:</p>\n\n<hr>\n\n<p>Maybe a better way to think about the problem is in terms of number\nbases and modulo arithmetic. For example, your goal is to compute DOW\nmod 7 where DOW is the 16-bit representation of the day of the\nweek. You can write this as:</p>\n\n<pre><code> DOW = DOW_HI*256 + DOW_LO\n\n DOW%7 = (DOW_HI*256 + DOW_LO) % 7\n = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7\n = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7\n = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7\n</code></pre>\n\n<p>Expressed in this manner, you can separately compute the modulo 7\nresult for the high and low bytes. Multiply the result for the high by\n4 and add it to the low and then finally compute result modulo 7.</p>\n\n<p>Computing the mod 7 result of an 8-bit number can be performed in a\nsimilar fashion. You can write an 8-bit number in octal like so:</p>\n\n<pre><code> X = a*64 + b*8 + c\n</code></pre>\n\n<p>Where a, b, and c are 3-bit numbers.</p>\n\n<pre><code> X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7\n = (a%7 + b%7 + c%7) % 7\n = (a + b + c) % 7\n</code></pre>\n\n<p>since <code>64%7 = 8%7 = 1</code></p>\n\n<p>Of course, a, b, and c are</p>\n\n<pre><code> c = X &amp; 7\n b = (X&gt;&gt;3) &amp; 7\n a = (X&gt;&gt;6) &amp; 7 // (actually, a is only 2-bits).\n</code></pre>\n\n<p>The largest possible value for <code>a+b+c</code> is <code>7+7+3 = 17</code>. So, you'll need\none more octal step. The complete (untested) C version could be\nwritten like:</p>\n\n<pre><code>unsigned char Mod7Byte(unsigned char X)\n{\n X = (X&amp;7) + ((X&gt;&gt;3)&amp;7) + (X&gt;&gt;6);\n X = (X&amp;7) + (X&gt;&gt;3);\n\n return X==7 ? 0 : X;\n}\n</code></pre>\n\n<p>I spent a few moments writing a PIC version. The actual implementation\nis slightly different than described above</p>\n\n<pre><code>Mod7Byte:\n movwf temp1 ;\n andlw 7 ;W=c\n movwf temp2 ;temp2=c\n rlncf temp1,F ;\n swapf temp1,W ;W= a*8+b\n andlw 0x1F\n addwf temp2,W ;W= a*8+b+c\n movwf temp2 ;temp2 is now a 6-bit number\n andlw 0x38 ;get the high 3 bits == a'\n xorwf temp2,F ;temp2 now has the 3 low bits == b'\n rlncf WREG,F ;shift the high bits right 4\n swapf WREG,F ;\n addwf temp2,W ;W = a' + b'\n\n ; at this point, W is between 0 and 10\n\n\n addlw -7\n bc Mod7Byte_L2\nMod7Byte_L1:\n addlw 7\nMod7Byte_L2:\n return\n</code></pre>\n\n<p>Here's a liitle routine to test the algorithm</p>\n\n<pre><code> clrf x\n clrf count\n\nTestLoop:\n movf x,W\n RCALL Mod7Byte\n cpfseq count\n bra fail\n\n incf count,W\n xorlw 7\n skpz\n xorlw 7\n movwf count\n\n incfsz x,F\n bra TestLoop\npassed:\n</code></pre>\n\n<p>Finally, for the 16-bit result (which I have not tested), you could\nwrite:</p>\n\n<pre><code>uint16 Mod7Word(uint16 X)\n{\n return Mod7Byte(Mod7Byte(X &amp; 0xff) + Mod7Byte(X&gt;&gt;8)*4);\n}\n</code></pre>\n\n<p>Scott</p>\n\n<hr>\n" }, { "answer_id": 59461, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": -1, "selected": false, "text": "<p>The print statement will take orders of magnitude longer than even the slowest implementation of the modulus operator. So basically the comment \"slow on some systems\" should be \"slow on all systems\".</p>\n\n<p>Also, the two code snippets provided don't do the same thing. In the second one, the line</p>\n\n<pre>if(fizzcount >= FIZZ)</pre>\n\n<p>is always false so \"FIZZ\\n\" is never printed.</p>\n" }, { "answer_id": 60873, "author": "itj", "author_id": 888, "author_profile": "https://Stackoverflow.com/users/888", "pm_score": 3, "selected": false, "text": "<p>There is an overhead most of the time in using modulo that are not powers of 2.\nThis is regardless of the processor as (AFAIK) even processors with modulus operators are a few cycles slower for divide as opposed to mask operations.</p>\n\n<p>For most cases this is not an optimisation that is worth considering, and certainly not worth calculating your own shortcut operation (especially if it still involves divide or multiply).</p>\n\n<p>However, one rule of thumb is to select array sizes etc. to be powers of 2.</p>\n\n<p>so if calculating day of week, may as well use %7 regardless\nif setting up a circular buffer of around 100 entries... why not make it 128. You can then write % 128 and most (all) compilers will make this &amp; 0x7F</p>\n" }, { "answer_id": 29655945, "author": "Zeeshan", "author_id": 559017, "author_profile": "https://Stackoverflow.com/users/559017", "pm_score": 2, "selected": false, "text": "<pre><code>x%y == (x-(x/y)*y)\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 54969894, "author": "TigerTV.ru", "author_id": 9210255, "author_profile": "https://Stackoverflow.com/users/9210255", "pm_score": 0, "selected": false, "text": "<p>For modulo 6 you can change the Python code to C/C++:</p>\n\n<pre><code>def mod6(number):\n while number &gt; 7:\n number = (number &gt;&gt; 3 &lt;&lt; 1) + (number &amp; 0x7)\n if number &gt; 5:\n number -= 6\n return number\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? ``` const int FIZZ = 6; for(int x = 0; x < MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } ``` vs: The way I am currently doing it: ``` const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x < MAXCOUNT; x++) { if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; } } ```
Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder. Still, there is a small branch of number theory devoted to [Modular Arithmetic](http://en.wikibooks.org/wiki/Discrete_mathematics/Modular_arithmetic) which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating [magic squares](http://www.math.utah.edu/~carlson/mathcircles/magic.pdf). So, in that vein, here's a [very low level look](http://piclist.org/techref/postbot.asp?by=time&id=piclist/2006/08/03/065022a) at the math of modulus for an example of x, which should show you how simple it can be compared to division: --- Maybe a better way to think about the problem is in terms of number bases and modulo arithmetic. For example, your goal is to compute DOW mod 7 where DOW is the 16-bit representation of the day of the week. You can write this as: ``` DOW = DOW_HI*256 + DOW_LO DOW%7 = (DOW_HI*256 + DOW_LO) % 7 = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7 = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7 = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7 ``` Expressed in this manner, you can separately compute the modulo 7 result for the high and low bytes. Multiply the result for the high by 4 and add it to the low and then finally compute result modulo 7. Computing the mod 7 result of an 8-bit number can be performed in a similar fashion. You can write an 8-bit number in octal like so: ``` X = a*64 + b*8 + c ``` Where a, b, and c are 3-bit numbers. ``` X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7 = (a%7 + b%7 + c%7) % 7 = (a + b + c) % 7 ``` since `64%7 = 8%7 = 1` Of course, a, b, and c are ``` c = X & 7 b = (X>>3) & 7 a = (X>>6) & 7 // (actually, a is only 2-bits). ``` The largest possible value for `a+b+c` is `7+7+3 = 17`. So, you'll need one more octal step. The complete (untested) C version could be written like: ``` unsigned char Mod7Byte(unsigned char X) { X = (X&7) + ((X>>3)&7) + (X>>6); X = (X&7) + (X>>3); return X==7 ? 0 : X; } ``` I spent a few moments writing a PIC version. The actual implementation is slightly different than described above ``` Mod7Byte: movwf temp1 ; andlw 7 ;W=c movwf temp2 ;temp2=c rlncf temp1,F ; swapf temp1,W ;W= a*8+b andlw 0x1F addwf temp2,W ;W= a*8+b+c movwf temp2 ;temp2 is now a 6-bit number andlw 0x38 ;get the high 3 bits == a' xorwf temp2,F ;temp2 now has the 3 low bits == b' rlncf WREG,F ;shift the high bits right 4 swapf WREG,F ; addwf temp2,W ;W = a' + b' ; at this point, W is between 0 and 10 addlw -7 bc Mod7Byte_L2 Mod7Byte_L1: addlw 7 Mod7Byte_L2: return ``` Here's a liitle routine to test the algorithm ``` clrf x clrf count TestLoop: movf x,W RCALL Mod7Byte cpfseq count bra fail incf count,W xorlw 7 skpz xorlw 7 movwf count incfsz x,F bra TestLoop passed: ``` Finally, for the 16-bit result (which I have not tested), you could write: ``` uint16 Mod7Word(uint16 X) { return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4); } ``` Scott ---
48,070
<p>We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it.</p> <p>I'd love to hear some techniques other people have used to move ViewState to a custom provider.</p> <p>That said, a few caveats:</p> <ul> <li>We serve on average 2 Million unique visitors per hour.</li> <li>Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database.</li> <li>We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback.</li> </ul> <p>Ideas?</p>
[ { "answer_id": 48082, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 2, "selected": false, "text": "<p>I have tested many ways to remove the load of view state from the page and between all hacks and some software out there the only thing that it is truly scalable is the <a href=\"http://www.strangeloopnetworks.com/products/AS1000/default.aspx\" rel=\"nofollow noreferrer\">StrangeLoops As10000 appliance</a>. Transparent, no need to change the underlying application.</p>\n" }, { "answer_id": 48100, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/48026/good-book-on-scaling-aspnet-applications#48052\">previously stated</a>, I have used the database to store the ViewState in the past. Although this works for us, we don't come close to 2 million unique visitors per hour.</p>\n\n<p>I think a hardware solution is definitely the way to go, whether using the <a href=\"http://www.strangeloopnetworks.com/\" rel=\"nofollow noreferrer\">StrangeLoop</a> products or another product.</p>\n" }, { "answer_id": 48105, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Due to the typical organizational bloat, requesting new hardware takes eons, and requesting hardware that would involve a complete rewire of our current setup would probably get some severe resistance from the engineering department.</p>\n\n<p>I really need to come up with a software solution, because that's the only world I have some control over.</p>\n\n<p>Yay for Enterprise :(</p>\n" }, { "answer_id": 48117, "author": "Erick Sgarbi", "author_id": 4171, "author_profile": "https://Stackoverflow.com/users/4171", "pm_score": 0, "selected": false, "text": "<p>I've tried to find some of the products I had researched in the past that works just like <a href=\"http://www.strangeloopnetworks.com/products/AS1000/default.aspx\" rel=\"nofollow noreferrer\">StrangeLoops</a> (but software based) It looks like they went all out of business, the only thing from my list that still up there is <a href=\"http://www.scaleoutsoftware.com/\" rel=\"nofollow noreferrer\">ScaleOut</a> but they are specialized in session state caching. </p>\n\n<p>I understand how hard it is to sell hardware solutions to senior management but it is always a good idea to at least get management to accept listening to the hardware's sales rep. I am much rather putting some hardware that will present me with an immediate solution because it allows me (or buy me some time) to get some other real job done. </p>\n\n<p>I understand, it really sucks but the alternative is to change your code for optimization and that would maybe cost a lot more than getting an appliance.</p>\n\n<p>Let me know if you find another software based solution. </p>\n" }, { "answer_id": 48128, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>I'm going to see if I can come up with a way to leverage our current State server to contain the viewstate in memory, I should be able to use the user session ID to keep things synched up between machines.</p>\n\n<p>If I come up with a good solution, I'll remove any IP protected code and put it out for public use.</p>\n" }, { "answer_id": 48131, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 0, "selected": false, "text": "<p>Oh no, <a href=\"https://stackoverflow.com/questions/48070/moving-viewstate-out-of-the-page#48105\">red tape</a>. Well this is going to be a tall order to fill. You mentioned <a href=\"https://stackoverflow.com/questions/48026/good-book-on-scaling-aspnet-applications#48045\">here</a> that you use a state server to serve your session state. How do you have this setup? Maybe you can do something similar here also? </p>\n\n<p>Edit</p>\n\n<p>Awh @Jonathan, <a href=\"https://stackoverflow.com/questions/48070/moving-viewstate-out-of-the-page#48128\">you posted</a> while I was typing this answer up. I think going that route could be promising. One thing is that it will definitely be memory intensive.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/48070/moving-viewstate-out-of-the-page#48133\">@Mike</a> I don't think storing it in the session information will be a good idea, due to the memory intensiveness of viewstate and also how many times you will need to access the viewstate. SessionState is accessed a lot less often as the viewstate. I would keep the two separate.</p>\n\n<p>I think the ultimate solution would be storing the ViewState on the client some how and maybe worth looking at. With <a href=\"http://gears.google.com/\" rel=\"nofollow noreferrer\">Google Gears</a>, this could be possible now.</p>\n" }, { "answer_id": 48133, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 3, "selected": false, "text": "<p>How do you handle Session State? There is a built-in \"store the viewstate in the session state\" provider. If you are storing the session state in some fast, out of proc system, that might be the best option for the viewstate.</p>\n\n<p>edit: to do this add the following code to the your Page classes / global page base class</p>\n\n<pre><code> protected override PageStatePersister PageStatePersister {\n get { return new SessionPageStatePersister(this); }\n }\n</code></pre>\n\n<p>Also... this is by no means a perfect (or even good) solution to a large viewstate. As always, minimize the size of the viewstate as much as possible. However, the SessionPageStatePersister is relatively intelligent and avoids storing an unbounded number of viewstates per session as well as avoids storing only a single viewstate per session.</p>\n" }, { "answer_id": 82329, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 0, "selected": false, "text": "<p>Have you considered if you really <em>need</em> all that viewstate? For example, if you populate a datagrid from a database, all the data will be saved in viewstate by default. However, if the grid is just for presenting data, you dont need a form a all, and hence no viewstate. </p>\n\n<p>You only need viewstate when there is some interaction with the user through postbacks, and even then the actual form data may be sufficient to recreate the view. You can selectively disable viewstate for controls on the page.</p>\n\n<p>You have a very special UI if you actually <em>need</em> 100K of viewstate. If you reduce the viewstate to what is absolutely necessary, it might turn out to be the easiest and most scalable to keep the viewstate in the page.</p>\n" }, { "answer_id": 82346, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>The following works quite well for me:</p>\n\n<pre><code>string vsid;\n\nprotected override object LoadPageStateFromPersistenceMedium()\n{\n Pair vs = base.LoadPageStateFromPersistenceMedium() as Pair;\n vsid = vs.First as string;\n object result = Session[vsid];\n Session.Remove(vsid);\n return result;\n}\n\nprotected override void SavePageStateToPersistenceMedium(object state)\n{\n if (vsid == null)\n {\n vsid = Guid.NewGuid().ToString();\n }\n Session[vsid] = state;\n base.SavePageStateToPersistenceMedium(new Pair(vsid, null));\n}\n</code></pre>\n" }, { "answer_id": 271279, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "<p>I might have a simple solution for you in another post. It's a simple class to include in your app and a few lines of code in the asp.net page itself. If you combine it with a distributed caching system you could save a lot of dough as viewstate is large and costly. Microsoft’s velocity might be a good product to attach this method too. If you do use it and save a ton of money though I'd love a little mention for that. Also if you are unsure of anything let me know and I can talk with you in person.</p>\n\n<p>Here is the link to my code. <a href=\"https://stackoverflow.com/questions/271269/ideas-for-how-to-deal-with-viewstate-when-using-ajax-and-update-panels\">link text</a></p>\n\n<p>If you are concerned with scaling then using the session token as a unique identifier or storing the state in session is more or less guaranteed to work in a web farm scenario.</p>\n" }, { "answer_id": 432395, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "<p>Store the viewstate in a session object and use a distributed cache or state service to store session seperate from the we servers such as microsofts velocity.</p>\n" }, { "answer_id": 1197820, "author": "ChickenMilkBomb", "author_id": 118065, "author_profile": "https://Stackoverflow.com/users/118065", "pm_score": 0, "selected": false, "text": "<p>I know this is a little stale, but I've been working for a couple of days on an opensource \"virtual appliance\" using squid and ecap to:</p>\n\n<p>1.) gzip\n2.) handle ssl\n3.) replace viewstate with a token on request / response\n4.) memcache for object caching</p>\n\n<p>Anyways, it looks pretty promising. basically it would sit in front of the loadbalancers and should really help client performance. Doesnt seem to be very hard to set up either.</p>\n" }, { "answer_id": 1266899, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 0, "selected": false, "text": "<p>I blogged on this a while ago - the solution is at <a href=\"http://www.adverseconditionals.com/2008/06/storing-viewstate-in-memcached-ultimate.html\" rel=\"nofollow noreferrer\">http://www.adverseconditionals.com/2008/06/storing-viewstate-in-memcached-ultimate.html</a></p>\n\n<p>This lets you change the ViewState provider to one of your choice without having to change each of your Page classes, by using a custom PageAdapter. I stored the ViewState in memcached. In retrospect I think storing it in a database or on disk is better - we filled memcached up very quickly. Its a very low friction solution.</p>\n" }, { "answer_id": 5446743, "author": "saille", "author_id": 30246, "author_profile": "https://Stackoverflow.com/users/30246", "pm_score": 1, "selected": false, "text": "<p>You can always compress ViewState so you get the benefits of ViewState without so much bloat:</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page {\n\n protected override object LoadPageStateFromPersistenceMedium() {\n string viewState = Request.Form[\"__VSTATE\"];\n byte[] bytes = Convert.FromBase64String(viewState);\n bytes = Compressor.Decompress(bytes);\n LosFormatter formatter = new LosFormatter();\n return formatter.Deserialize(Convert.ToBase64String(bytes));\n }\n\n protected override void SavePageStateToPersistenceMedium(object viewState) {\n LosFormatter formatter = new LosFormatter();\n StringWriter writer = new StringWriter();\n formatter.Serialize(writer, viewState);\n string viewStateString = writer.ToString();\n byte[] bytes = Convert.FromBase64String(viewStateString);\n bytes = Compressor.Compress(bytes);\n ClientScript.RegisterHiddenField(\"__VSTATE\", Convert.ToBase64String(bytes));\n }\n\n // ...\n\n}\n\nusing System.IO;\nusing System.IO.Compression;\n\npublic static class Compressor {\n\n public static byte[] Compress(byte[] data) {\n MemoryStream output = new MemoryStream();\n GZipStream gzip = new GZipStream(output, \n CompressionMode.Compress, true);\n gzip.Write(data, 0, data.Length);\n gzip.Close();\n return output.ToArray();\n }\n\n public static byte[] Decompress(byte[] data) {\n MemoryStream input = new MemoryStream();\n input.Write(data, 0, data.Length);\n input.Position = 0;\n GZipStream gzip = new GZipStream(input, \n CompressionMode.Decompress, true);\n MemoryStream output = new MemoryStream();\n byte[] buff = new byte[64];\n int read = -1;\n read = gzip.Read(buff, 0, buff.Length);\n while(read &gt; 0) {\n output.Write(buff, 0, read);\n read = gzip.Read(buff, 0, buff.Length);\n }\n gzip.Close();\n return output.ToArray();\n }\n}\n</code></pre>\n" }, { "answer_id": 8222627, "author": "Ashish Nangla", "author_id": 973495, "author_profile": "https://Stackoverflow.com/users/973495", "pm_score": 0, "selected": false, "text": "<p>No need to buy or sell anything to eliminate viewstate bloating. Just need to extend the HiddenFieldPageStatePersister. The 100-200KB of ViewState will stay on the server and will send only a 62byte token on the page instead.</p>\n\n<p>Here is a detailed article on how this can be done:</p>\n\n<p><a href=\"http://ashishnangla.com/2011/07/21/reducing-size-of-viewstate-in-asp-net-webforms-by-writing-a-custom-viewstate-provider-pagestatepersister-part-12/\" rel=\"nofollow\">http://ashishnangla.com/2011/07/21/reducing-size-of-viewstate-in-asp-net-webforms-by-writing-a-custom-viewstate-provider-pagestatepersister-part-12/</a> </p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it. I'd love to hear some techniques other people have used to move ViewState to a custom provider. That said, a few caveats: * We serve on average 2 Million unique visitors per hour. * Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database. * We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback. Ideas?
How do you handle Session State? There is a built-in "store the viewstate in the session state" provider. If you are storing the session state in some fast, out of proc system, that might be the best option for the viewstate. edit: to do this add the following code to the your Page classes / global page base class ``` protected override PageStatePersister PageStatePersister { get { return new SessionPageStatePersister(this); } } ``` Also... this is by no means a perfect (or even good) solution to a large viewstate. As always, minimize the size of the viewstate as much as possible. However, the SessionPageStatePersister is relatively intelligent and avoids storing an unbounded number of viewstates per session as well as avoids storing only a single viewstate per session.
48,094
<p>So I have a pointer to an array of pointers. If I delete it like this:</p> <pre><code>delete [] PointerToPointers; </code></pre> <p>Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.</p> <p>(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)</p>
[ { "answer_id": 48095, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 1, "selected": false, "text": "<p>I think you're going to have to loop over I'm afraid.</p>\n" }, { "answer_id": 48098, "author": "Jeffrey", "author_id": 3259, "author_profile": "https://Stackoverflow.com/users/3259", "pm_score": 2, "selected": false, "text": "<p>Pointers are pretty much just memory references and not spiffy little self-cleaning .net objects. Creating proper destructors for each class will make the deletion a little cleaner than massive loops throughout the code.</p>\n" }, { "answer_id": 48102, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 6, "selected": true, "text": "<p>Yes you have to loop over the pointers, deleting individually.</p>\n\n<p>Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit.</p>\n\n<p>For an \"easier way,\" two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the \"smart pointer\" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code. </p>\n" }, { "answer_id": 48670, "author": "Ray", "author_id": 456786, "author_profile": "https://Stackoverflow.com/users/456786", "pm_score": 4, "selected": false, "text": "<p>I agree with Jason Cohen though we can be a bit clearer on the reason for needing to delete your pointers with the loop. For every \"new\" or dynamic memory allocation there needs to be a \"delete\" a memory de-allocation. Some times the \"delete\" can be hidden, as with smartpointers but it is still there. </p>\n\n<pre><code>int main()\n{\n int *pI = new int;\n int *pArr = new int[10];\n</code></pre>\n\n<p>so far in the code we have allocated two chunks of dynamic memory. The first is just a general int the second is an array of ints.</p>\n\n<pre><code> delete pI;\n delete [] pArr;\n</code></pre>\n\n<p>these delete statements clear the memory that was allocated by the \"new\"s</p>\n\n<pre><code> int ppArr = new int *[10];\n\n for( int indx = 0; indx &lt; 10; ++indx )\n {\n ppArr[indx] = new int;\n }\n</code></pre>\n\n<p>This bit of code is doing both of the previous allocations. First we are creating space for our int in a dynamic array. We then need to loop through and allocate an int for each spot in the array.</p>\n\n<pre><code> for( int indx = 0; indx &lt; 10; ++indx )\n {\n delete ppArr[indx];\n }\n delete [] ppArr;\n</code></pre>\n\n<p>Note the order that I allocated this memory and then that I de-allocated it in the reverse order. This is because if we were to do the delete [] ppArr; first we would lose the array that tells us what our other pointers are. That chunk or memory would be given back to the system and so can no longer be reliably read.</p>\n\n<pre><code> int a=0;\n int b=1;\n int c=2;\n\n ppArr = new int *[3];\n\n ppArr[0] = &amp;a;\n ppArr[1] = &amp;b;\n ppArr[2] = &amp;c;\n</code></pre>\n\n<p>This I think should be mentioned as well. Just because you are working with pointers does not mean that the memory those pointers point to was dynamically allocated. That is to say just because you have a pointer doesn't mean it necessarily needs to be delete. The array I created here is dynamically allocated but the pointers point to local instances of ints When we delete this we only need to delete the array.</p>\n\n<pre><code> delete [] ppArr;\n\n return 0;\n\n}\n</code></pre>\n\n<p>In the end dynamically allocated memory can be tricky and anyway you can wrap it up safely like in a smart pointer or by using stl containers rather then your own can make your life much more pleasant.</p>\n" }, { "answer_id": 59481, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html\" rel=\"nofollow noreferrer\">boost pointer container</a> for a container that does the automatic deletion of contained pointers for you, while maintaining a syntax very close to ordinary STL containers.</p>\n" }, { "answer_id": 752538, "author": "AndreasT", "author_id": 82673, "author_profile": "https://Stackoverflow.com/users/82673", "pm_score": 0, "selected": false, "text": "<p>I don't know why this was answered so confusingly long.</p>\n\n<p>If you delete the array of pointers, you will free\nthe memory used for an array of usually ints.<br>\na pointer to an object is an integer containing the adress.</p>\n\n<p>You deleted a bunch of adresses, but no objects.</p>\n\n<p>delete does not care about the content of a memory space,\nit calls a destructor(s) and marks the mem as free.</p>\n\n<p>It does not care that it just deleted a bunch of adresses\nof objects, it merely sees ints.</p>\n\n<p>That's why you have to cycle through the array first! and call delete\non every element, then you can delete the storage of the array itself.</p>\n\n<p>Well, now <em>my</em> answer got somewhat long... .... strange... ;)</p>\n\n<p>Edit:\nJason's answer is not wrong, it just fails to hit the spot. Neither\nthe compiler nor anything else in c(++) cares about you deleting stuff that is elsewhere\npointed to. You can just do it. Other program parts trying to use the deleted objects\nwill segfault on you. But no one will hinder you.\nNeither will it be a problem to destroy an array of pointers to objects, when the objects\nare referenced elsewhere.</p>\n" }, { "answer_id": 3822166, "author": "RikSaunderson", "author_id": 450460, "author_profile": "https://Stackoverflow.com/users/450460", "pm_score": 2, "selected": false, "text": "<p>Let's take a (pseudocoded) real world example .Imagine that you had a class like this:</p>\n\n<pre><code>class Street\n{\n public:\n Street();\n ~Street();\n private:\n int HouseNumbers_[];\n}\n\ntypedef *Street StreetSign;\n</code></pre>\n\n<p>If you have an array of street signs, and you delete your array of streetsigns, that doesn't mean that you automatically delete the sreets. They re still there, bricks and mortar, they just don't have those signs pointing to them any more. You have got rid of <em>those specific</em> instances of pointers to the streets.</p>\n\n<p>An array of pointers is (conceptually) a bit like an array of integers, it's an array of numbers representing the memory locations of various objects. It isn't the objects themselves. </p>\n\n<p>If you delete[] the array of pointers, all you have done is delete an array of integers. </p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
So I have a pointer to an array of pointers. If I delete it like this: ``` delete [] PointerToPointers; ``` Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question. (And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)
Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code.
48,124
<p>How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?</p>
[ { "answer_id": 48125, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 8, "selected": true, "text": "<p>First make a string with all your possible characters:</p>\n\n<pre><code> $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';\n</code></pre>\n\n<p>You could also use <a href=\"http://php.net/range\" rel=\"noreferrer\">range()</a> to do this more quickly.</p>\n\n<p>Then, in a loop, choose a random number and use it as the index to the <code>$characters</code> string to get a random character, and append it to your string:</p>\n\n<pre><code> $string = '';\n $max = strlen($characters) - 1;\n for ($i = 0; $i &lt; $random_string_length; $i++) {\n $string .= $characters[mt_rand(0, $max)];\n }\n</code></pre>\n\n<p><code>$random_string_length</code> is the length of the random string.</p>\n" }, { "answer_id": 48285, "author": "Daniel", "author_id": 416, "author_profile": "https://Stackoverflow.com/users/416", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ASCII table</a> to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.</p>\n\n<p>I find that this method is nicer compared <a href=\"https://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings#48125\">to the method described</a> where the range of characters is specifically defined within another string.</p>\n\n<pre><code>// range is numbers (48) through capital and lower case letters (122)\n$range_start = 48;\n$range_end = 122;\n$random_string = \"\";\n$random_string_length = 10;\n\nfor ($i = 0; $i &lt; $random_string_length; $i++) {\n $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range\n // finds the character represented by $ascii_no and adds it to the random string\n // study **chr** function for a better understanding\n $random_string .= chr( $ascii_no );\n}\n\necho $random_string;\n</code></pre>\n\n<p>See More:</p>\n\n<ul>\n<li><a href=\"http://au.php.net/chr\" rel=\"nofollow noreferrer\">chr</a> function</li>\n<li><a href=\"http://au.php.net/mt_rand\" rel=\"nofollow noreferrer\">mt_rand</a> function</li>\n</ul>\n" }, { "answer_id": 1037136, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 2, "selected": false, "text": "<p>You can use the following code. It is similar to existing functions except that you can force special character count:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function random_string() {\n // 8 characters: 7 lower-case alphabets and 1 digit\n $character_sets = [\n [&quot;count&quot; =&gt; 7, &quot;characters&quot; =&gt; &quot;abcdefghijklmnopqrstuvwxyz&quot;],\n [&quot;count&quot; =&gt; 1, &quot;characters&quot; =&gt; &quot;0123456789&quot;]\n ];\n $temp_array = array();\n foreach ($character_sets as $character_set) {\n for ($i = 0; $i &lt; $character_set[&quot;count&quot;]; $i++) {\n $random = random_int(0, strlen($character_set[&quot;characters&quot;]) - 1);\n $temp_array[] = $character_set[&quot;characters&quot;][$random];\n }\n }\n shuffle($temp_array);\n return implode(&quot;&quot;, $temp_array);\n}\n</code></pre>\n" }, { "answer_id": 3096086, "author": "Josh Smith", "author_id": 373496, "author_profile": "https://Stackoverflow.com/users/373496", "pm_score": 0, "selected": false, "text": "<p>Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().</p>\n\n<pre><code>&lt;?php\n$character_array = array_merge(range('a', 'z'), range(0, 9));\n$string = \"\";\n for($i = 0; $i &lt; 6; $i++) {\n $string .= $character_array[rand(0, (count($character_array) - 1))];\n }\necho $string;\n?&gt;\n</code></pre>\n\n<p>This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().</p>\n" }, { "answer_id": 3125854, "author": "Edward Fuller", "author_id": 29801, "author_profile": "https://Stackoverflow.com/users/29801", "pm_score": 2, "selected": false, "text": "<p>Maybe I missed something here, but <a href=\"http://php.net/manual/en/function.uniqid.php\" rel=\"nofollow noreferrer\">here's a way using the uniqid() function</a>.</p>\n" }, { "answer_id": 28925556, "author": "Molla Rasel", "author_id": 4646424, "author_profile": "https://Stackoverflow.com/users/4646424", "pm_score": 1, "selected": false, "text": "<pre><code>function generateRandomString($length = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $charactersLength = strlen($characters);\n $randomString = '';\n for ($i = 0; $i &lt; $length; $i++) {\n $randomString .= $characters[rand(0, $charactersLength - 1)];\n }\n return $randomString;\n}\necho generateRandomString();\n</code></pre>\n" }, { "answer_id": 33690821, "author": "diegoiglesias", "author_id": 972813, "author_profile": "https://Stackoverflow.com/users/972813", "pm_score": 2, "selected": false, "text": "<p>I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:</p>\n\n<pre><code> class RandomString\n {\n private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';\n private static $string;\n private static $length = 8; //default random string length\n\n public static function generate($length = null)\n {\n\n if($length){\n self::$length = $length;\n }\n\n $characters_length = strlen(self::$characters) - 1;\n\n for ($i = 0; $i &lt; self::$length; $i++) {\n self::$string .= self::$characters[mt_rand(0, $characters_length)];\n }\n\n return self::$string;\n\n }\n\n }\n</code></pre>\n" }, { "answer_id": 33971950, "author": "azerafati", "author_id": 3160597, "author_profile": "https://Stackoverflow.com/users/3160597", "pm_score": 4, "selected": false, "text": "<p>I like this function for the job</p>\n\n<pre><code>function randomKey($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n\n for($i=0; $i &lt; $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n\necho randomKey(20);\n</code></pre>\n" }, { "answer_id": 35605166, "author": "emix", "author_id": 997162, "author_profile": "https://Stackoverflow.com/users/997162", "pm_score": 4, "selected": false, "text": "<p>Generate cryptographically strong, random (potentially) 8-character string using the <a href=\"http://php.net/openssl_random_pseudo_bytes\" rel=\"noreferrer\">openssl_random_pseudo_bytes</a> function:</p>\n\n<pre><code>echo bin2hex(openssl_random_pseudo_bytes(4));\n</code></pre>\n\n<p>Procedural way:</p>\n\n<pre><code>function randomString(int $length): string\n{\n return bin2hex(openssl_random_pseudo_bytes($length));\n}\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>PHP7 introduced the <code>random_x()</code> functions which should be even better. If you come from PHP 5.X, use excellent <a href=\"https://packagist.org/packages/paragonie/random_compat\" rel=\"noreferrer\">paragonie/random_compat</a> library which is a polyfill for <a href=\"http://php.net/random_bytes\" rel=\"noreferrer\">random_bytes()</a> and <a href=\"http://php.net/random_int\" rel=\"noreferrer\">random_int()</a> from PHP 7.</p>\n\n<pre><code>function randomString($length)\n{\n return bin2hex(random_bytes($length));\n}\n</code></pre>\n" }, { "answer_id": 36932671, "author": "Peter", "author_id": 3169577, "author_profile": "https://Stackoverflow.com/users/3169577", "pm_score": 2, "selected": false, "text": "<p>I have made the following quick function just to play around with the <code>range()</code> function. It just might help someone sometime.</p>\n\n<pre><code>Function pseudostring($length = 50) {\n\n // Generate arrays with characters and numbers\n $lowerAlpha = range('a', 'z');\n $upperAlpha = range('A', 'Z');\n $numeric = range('0', '9');\n\n // Merge the arrays\n $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));\n $returnString = \"\";\n\n // Add random characters from the created array to a string\n for ($i = 0; $i &lt; $length; $i++) {\n $character = $workArray[rand(0, 61)];\n $returnString .= $character;\n }\n\n return $returnString;\n}\n</code></pre>\n" }, { "answer_id": 41361411, "author": "Zeeshan", "author_id": 3354721, "author_profile": "https://Stackoverflow.com/users/3354721", "pm_score": 0, "selected": false, "text": "<p>This is something I use:</p>\n\n<pre><code>$cryptoStrong = true; // can be false\n$length = 16; // Any length you want\n$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);\n$randomString = bin2hex($bytes);\n</code></pre>\n\n<p>You can see the <a href=\"http://php.net/manual/en/function.openssl-random-pseudo-bytes.php\" rel=\"nofollow noreferrer\">Docs for openssl_random_pseudo_bytes here</a>, and the <a href=\"http://php.net/manual/en/function.bin2hex.php\" rel=\"nofollow noreferrer\">Docs for bin2hex here</a></p>\n" }, { "answer_id": 43919537, "author": "HausO", "author_id": 2842514, "author_profile": "https://Stackoverflow.com/users/2842514", "pm_score": 0, "selected": false, "text": "<p>1 line:</p>\n\n<pre><code>$FROM = 0; $TO = 'zzzz';\n$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);\necho $code;\n</code></pre>\n" }, { "answer_id": 45577038, "author": "Marco Panichi", "author_id": 162049, "author_profile": "https://Stackoverflow.com/users/162049", "pm_score": 3, "selected": false, "text": "<p>One line solution:</p>\n\n<pre><code>echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );\n</code></pre>\n\n<p>You can change the substr parameter in order to set a different length for your string.</p>\n" }, { "answer_id": 49860249, "author": "DiMono", "author_id": 2069424, "author_profile": "https://Stackoverflow.com/users/2069424", "pm_score": 1, "selected": false, "text": "<p>If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:</p>\n\n<p><code>substr( sha1( time() ), 0, 15 )</code></p>\n\n<p><code>time()</code> gives you the current time in seconds since epoch, <code>sha1()</code> encrypts it to a string of 0-9a-f, and <code>substr()</code> lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.</p>\n" }, { "answer_id": 53157130, "author": "lyrixx", "author_id": 685587, "author_profile": "https://Stackoverflow.com/users/685587", "pm_score": 0, "selected": false, "text": "<p>The modern way to do that with type hint / rand_int for real randomeness </p>\n\n<pre><code>function random_string(int $size): string\n{\n $characters = array_merge(\n range(0, 9),\n range('A', 'Z')\n );\n\n $string = '';\n $max = count($characters) - 1;\n for ($i = 0; $i &lt; $size; $i++) {\n $string .= $characters[random_int(0, $max)];\n }\n\n return $string;\n}\n</code></pre>\n" }, { "answer_id": 55955195, "author": "David Young", "author_id": 11442440, "author_profile": "https://Stackoverflow.com/users/11442440", "pm_score": 2, "selected": false, "text": "<p>Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.</p>\n\n<pre><code>$str = bin2hex(random_bytes(32)); // 64 character string returned\n</code></pre>\n" }, { "answer_id": 56090016, "author": "Shravan M", "author_id": 9512364, "author_profile": "https://Stackoverflow.com/users/9512364", "pm_score": 1, "selected": false, "text": "<p>First list the desired characters</p>\n\n<pre><code>$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n</code></pre>\n\n<p>Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.</p>\n\n<pre><code>$alpha=substr(str_shuffle($chars), 0, 50);\n</code></pre>\n\n<p>50 is the Length of string.</p>\n" }, { "answer_id": 56090053, "author": "Александр Маринов", "author_id": 8847970, "author_profile": "https://Stackoverflow.com/users/8847970", "pm_score": 0, "selected": false, "text": "<pre><code>public function randomString($length = 8)\n{\n $characters = implode([\n 'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',\n 'abcdefghijklmnoprqstuwvxyz',\n '0123456789',\n //'!@#$%^&amp;*?'\n ]);\n\n $charactersLength = strlen($characters) - 1;\n $string = '';\n\n while ($length) {\n $string .= $characters[mt_rand(0, $charactersLength)];\n --$length;\n }\n\n return $string;\n}\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters: ``` $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; ``` You could also use [range()](http://php.net/range) to do this more quickly. Then, in a loop, choose a random number and use it as the index to the `$characters` string to get a random character, and append it to your string: ``` $string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string .= $characters[mt_rand(0, $max)]; } ``` `$random_string_length` is the length of the random string.
48,126
<p>Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?</p>
[ { "answer_id": 48161, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 5, "selected": true, "text": "<p>it looks like it's answered in this post:</p>\n\n<p><a href=\"http://forums.mysql.com/read.php?52,198596,198717#msg-198717\" rel=\"noreferrer\">http://forums.mysql.com/read.php?52,198596,198717#msg-198717</a></p>\n\n<p>With mysqli PHP API: </p>\n\n<p>Assume sproc myproc( IN i int, OUT j int ): </p>\n\n<pre><code>$mysqli = new mysqli( \"HOST\", \"USR\", \"PWD\", \"DBNAME\" );\n$ivalue=1;\n$res = $mysqli-&gt;multi_query( \"CALL myproc($ivalue,@x);SELECT @x\" );\nif( $res ) {\n $results = 0;\n do {\n if ($result = $mysqli-&gt;store_result()) {\n printf( \"&lt;b&gt;Result #%u&lt;/b&gt;:&lt;br/&gt;\", ++$results );\n while( $row = $result-&gt;fetch_row() ) {\n foreach( $row as $cell ) echo $cell, \"&amp;nbsp;\";\n }\n $result-&gt;close();\n if( $mysqli-&gt;more_results() ) echo \"&lt;br/&gt;\";\n }\n } while( $mysqli-&gt;next_result() );\n}\n$mysqli-&gt;close();\n</code></pre>\n" }, { "answer_id": 486430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here's an example of how to do this with mysql, mysqli, and pdo:</p>\n\n<p><a href=\"http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/\" rel=\"noreferrer\">http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/</a></p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?
it looks like it's answered in this post: <http://forums.mysql.com/read.php?52,198596,198717#msg-198717> With mysqli PHP API: Assume sproc myproc( IN i int, OUT j int ): ``` $mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" ); $ivalue=1; $res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" ); if( $res ) { $results = 0; do { if ($result = $mysqli->store_result()) { printf( "<b>Result #%u</b>:<br/>", ++$results ); while( $row = $result->fetch_row() ) { foreach( $row as $cell ) echo $cell, "&nbsp;"; } $result->close(); if( $mysqli->more_results() ) echo "<br/>"; } } while( $mysqli->next_result() ); } $mysqli->close(); ```
48,198
<p>How do I find out which process is listening on a TCP or UDP port on Windows?</p>
[ { "answer_id": 48199, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 13, "selected": true, "text": "<h1><a href=\"https://en.wikipedia.org/wiki/PowerShell\" rel=\"noreferrer\">PowerShell</a></h1>\n<h2>TCP</h2>\n<pre><code>Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess\n</code></pre>\n<h2>UDP</h2>\n<pre><code>Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess\n</code></pre>\n<h1><a href=\"https://en.wikipedia.org/wiki/Cmd.exe\" rel=\"noreferrer\">cmd</a></h1>\n<pre><code> netstat -a -b\n</code></pre>\n<p>(Add <strong>-n</strong> to stop it trying to resolve hostnames, which will make it a lot faster.)</p>\n<p>Note Dane's recommendation for <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx\" rel=\"noreferrer\">TCPView</a>. It looks very useful!</p>\n<p><strong>-a</strong> Displays all connections and listening ports.</p>\n<p><strong>-b</strong> Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.</p>\n<p><strong>-n</strong> Displays addresses and port numbers in numerical form.</p>\n<p><strong>-o</strong> Displays the owning process ID associated with each connection.</p>\n" }, { "answer_id": 48202, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": false, "text": "<p>For Windows:</p>\n\n<pre><code>netstat -aon | find /i \"listening\"\n</code></pre>\n" }, { "answer_id": 48207, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 8, "selected": false, "text": "<p>Use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx\" rel=\"noreferrer\">TCPView</a> if you want a GUI for this. It's the old <a href=\"https://en.wikipedia.org/wiki/Sysinternals\" rel=\"noreferrer\">Sysinternals</a> application that Microsoft bought out.</p>\n" }, { "answer_id": 48208, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 4, "selected": false, "text": "<p>If you'd like to use a GUI tool to do this there's <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx\" rel=\"nofollow noreferrer\">Sysinternals' TCPView</a>.</p>\n" }, { "answer_id": 13281291, "author": "Cyborg", "author_id": 1775540, "author_profile": "https://Stackoverflow.com/users/1775540", "pm_score": 6, "selected": false, "text": "<ol>\n<li><p>Open a command prompt window (as Administrator) From \"Start\\Search box\" Enter \"cmd\" then right-click on \"cmd.exe\" and select \"Run as Administrator\"</p></li>\n<li><p>Enter the following text then hit Enter.</p>\n\n<h2><code>netstat -abno</code></h2>\n\n<p><strong>-a</strong> Displays all connections and listening ports.</p>\n\n<p><strong>-b</strong> Displays the executable involved in creating each connection or\n listening port. In some cases well-known executables host\n multiple independent components, and in these cases the\n sequence of components involved in creating the connection\n or listening port is displayed. In this case the executable\n name is in [] at the bottom, on top is the component it called,\n and so forth until TCP/IP was reached. Note that this option\n can be time-consuming and will fail unless you have sufficient\n permissions.</p>\n\n<p><strong>-n</strong> Displays addresses and port numbers in numerical form.</p>\n\n<p><strong>-o</strong> Displays the owning process ID associated with each connection.</p></li>\n<li><p>Find the Port that you are listening on under \"Local Address\"</p></li>\n<li><p>Look at the process name directly under that.</p></li>\n</ol>\n\n<p>NOTE: To find the process under Task Manager</p>\n\n<ol>\n<li><p>Note the PID (process identifier) next to the port you are looking at.</p></li>\n<li><p>Open Windows Task Manager. </p></li>\n<li><p>Select the Processes tab. </p></li>\n<li><p>Look for the PID you noted when you did the netstat in step 1.</p>\n\n<ul>\n<li><p>If you don’t see a PID column, click on View / Select Columns. Select PID.</p></li>\n<li><p>Make sure “Show processes from all users” is selected.</p></li>\n</ul></li>\n</ol>\n" }, { "answer_id": 18175357, "author": "Perl Fanatic", "author_id": 2375759, "author_profile": "https://Stackoverflow.com/users/2375759", "pm_score": 3, "selected": false, "text": "<p>Follow these tools: From <strong>cmd</strong>: <code>C:\\&gt; netstat -anob</code> with <strong>Administrator</strong> privileges.</p>\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653\" rel=\"nofollow noreferrer\">Process Explorer</a></p>\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645\" rel=\"nofollow noreferrer\">Process Dump</a></p>\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896644\" rel=\"nofollow noreferrer\">Port Monitor</a></p>\n<p>All from sysinternals.com.</p>\n<p>If you just want to know process running and threads under each process, I recommend learning about <code>wmic</code>. It is a wonderful command-line tool, which gives you much more than you can know.</p>\n<p>Example:</p>\n<pre><code>c:\\&gt; wmic process list brief /every:5\n</code></pre>\n<p>The above command will show an all process list in brief every 5 seconds. To know more, you can just go with <code>/?</code> command of windows , for example,</p>\n<pre><code>c:\\&gt; wmic /?\nc:\\&gt; wmic process /?\nc:\\&gt; wmic prcess list /?\n</code></pre>\n<p>And so on and so forth. :)</p>\n" }, { "answer_id": 18199735, "author": "nisha", "author_id": 468964, "author_profile": "https://Stackoverflow.com/users/468964", "pm_score": 3, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>netstat -a -o\n</code></pre>\n\n<p>This shows the PID of the process running on a particular port.</p>\n\n<p>Keep in mind the process ID and go to Task Manager and services or details tab and end the process which has the same PID.</p>\n\n<p>Thus you can kill a process running on a particular port in Windows.</p>\n" }, { "answer_id": 19255965, "author": "Nathan24", "author_id": 1840368, "author_profile": "https://Stackoverflow.com/users/1840368", "pm_score": 7, "selected": false, "text": "<p>You can get more information if you run the following command:</p>\n\n<pre><code>netstat -aon | find /i \"listening\" |find \"port\"\n</code></pre>\n\n<p>using the 'Find' command allows you to filter the results. <code>find /i \"listening\"</code> will display only ports that are 'Listening'. Note, you need the <code>/i</code> to ignore case, otherwise you would type find \"LISTENING\". <code>| find \"port\"</code> will limit the results to only those containing the specific port number. Note, on this it will also filter in results that have the port number anywhere in the response string.</p>\n" }, { "answer_id": 22389550, "author": "Tony Delroy", "author_id": 410767, "author_profile": "https://Stackoverflow.com/users/410767", "pm_score": 4, "selected": false, "text": "<p><code>netstat -ao</code> and <code>netstat -ab</code> tell you the application, but if you're not a system administrator you'll get \"The requested operation requires elevation\".</p>\n\n<p>It's not ideal, but if you use Sysinternals' <a href=\"https://en.wikipedia.org/wiki/Process_Explorer\" rel=\"nofollow noreferrer\">Process Explorer</a> you can go to specific processes' properties and look at the TCP tab to see if they're using the port you're interested in. It is a bit of a needle and haystack thing, but maybe it'll help someone...</p>\n" }, { "answer_id": 23136177, "author": "Monis Majeed", "author_id": 3335813, "author_profile": "https://Stackoverflow.com/users/3335813", "pm_score": 5, "selected": false, "text": "<p>To get a list of all the owning process IDs associated with each connection:</p>\n\n<pre><code>netstat -ao |find /i \"listening\"\n</code></pre>\n\n<p>If want to kill any process have the ID and use this command, so that port becomes free</p>\n\n<pre><code>Taskkill /F /IM PID of a process\n</code></pre>\n" }, { "answer_id": 23718720, "author": "bcorso", "author_id": 1290264, "author_profile": "https://Stackoverflow.com/users/1290264", "pm_score": 11, "selected": false, "text": "<p>There's a native GUI for Windows:</p>\n<ul>\n<li><p>Start menu → <em>All Programs</em> → <em>Accessories</em> → <em>System Tools</em> → <em>Resource Monitor</em></p>\n</li>\n<li><p>or run <code>resmon.exe</code>,</p>\n</li>\n<li><p>or from <em>TaskManager</em> → <em>Performance</em> tab.</p>\n</li>\n</ul>\n<p><img src=\"https://i.stack.imgur.com/I2UzJ.png\" alt=\"Enter image description here\" /></p>\n" }, { "answer_id": 25463469, "author": "Pankaj Pateriya", "author_id": 1989851, "author_profile": "https://Stackoverflow.com/users/1989851", "pm_score": 6, "selected": false, "text": "<p>First we find the process id of that particular task which we need to eliminate in order to get the port free:</p>\n\n<p>Type </p>\n\n<pre><code>netstat -n -a -o\n</code></pre>\n\n<p>After executing this command in the Windows command line prompt (cmd), select the pid which I think the last column. Suppose this is 3312.</p>\n\n<p>Now type</p>\n\n<pre><code>taskkill /F /PID 3312\n</code></pre>\n\n<p>You can now cross check by typing the <code>netstat</code> command.</p>\n\n<p>NOTE: sometimes Windows doesn’t allow you to run this command directly on CMD, so first you need to go with these steps:</p>\n\n<p>From the start menu -> command prompt (right click on command prompt, and run as administrator)</p>\n" }, { "answer_id": 31126389, "author": "Josh", "author_id": 2718874, "author_profile": "https://Stackoverflow.com/users/2718874", "pm_score": 3, "selected": false, "text": "<p>I recommend <a href=\"http://www.nirsoft.net/utils/cports.html\" rel=\"noreferrer\">CurrPorts</a> from NirSoft.</p>\n\n<p>CurrPorts can filter the displayed results. <a href=\"https://technet.microsoft.com/en-us/sysinternals/tcpview.aspx\" rel=\"noreferrer\">TCPView</a> doesn't have this feature.</p>\n\n<p>Note: You can right click a process's socket connection and select \"Close Selected TCP Connections\" (You can also do this in TCPView). This often fixes connectivity issues I have with Outlook and Lync after I switch VPNs. With CurrPorts, you can also close connections from the command line with the \"/close\" parameter.</p>\n" }, { "answer_id": 35312370, "author": "ROMANIA_engineer", "author_id": 3885376, "author_profile": "https://Stackoverflow.com/users/3885376", "pm_score": 6, "selected": false, "text": "<h3>Get PID and Image Name</h3>\n\n<p>Use only one command:</p>\n\n<pre><code>for /f \"tokens=5\" %a in ('netstat -aon ^| findstr 9000') do tasklist /FI \"PID eq %a\"\n</code></pre>\n\n<p>where <code>9000</code> should be replaced by your port number.</p>\n\n<p>The <strong>output</strong> will contain something like this:</p>\n\n<pre><code>Image Name PID Session Name Session# Mem Usage\n========================= ======== ================ =========== ============\njava.exe 5312 Services 0 130,768 K\n</code></pre>\n\n<hr>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li><p>it iterates through every line from the output of the following command: </p>\n\n<pre><code>netstat -aon | findstr 9000\n</code></pre></li>\n<li><p>from every line, the PID (<code>%a</code> - the name is not important here) is extracted (PID is the <code>5</code><sup>th</sup> element in that line) and passed to the following command</p>\n\n<pre><code>tasklist /FI \"PID eq 5312\"\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>If you want to <strong>skip</strong> the <strong>header</strong> and the return of the <strong>command prompt</strong>, you can use:</p>\n\n<pre><code>echo off &amp; (for /f \"tokens=5\" %a in ('netstat -aon ^| findstr 9000') do tasklist /NH /FI \"PID eq %a\") &amp; echo on\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>java.exe 5312 Services 0 130,768 K\n</code></pre>\n" }, { "answer_id": 37519085, "author": "Nishat Lakhani", "author_id": 5715899, "author_profile": "https://Stackoverflow.com/users/5715899", "pm_score": 5, "selected": false, "text": "<p>It is very simple to get the port number from a PID in Windows.</p>\n\n<p>The following are the steps:</p>\n\n<ol>\n<li><p>Go to run &rarr; type cmd &rarr; press <kbd>Enter</kbd>.</p></li>\n<li><p>Write the following command...</p>\n\n<pre><code>netstat -aon | findstr [port number]\n</code></pre>\n\n<p>(Note: Don't include square brackets.)</p></li>\n<li><p>Press <kbd>Enter</kbd>...</p></li>\n<li><p>Then cmd will give you the detail of the service running on that port along with the PID.</p></li>\n<li><p>Open Task Manager and hit the service tab and match the PID with that of the cmd, and that's it.</p></li>\n</ol>\n" }, { "answer_id": 39146858, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 3, "selected": false, "text": "<h2>Using Windows' default shell (PowerShell) and without external applications</h2>\n<p>For those using PowerShell, try <a href=\"https://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71\" rel=\"nofollow noreferrer\"><code>Get-NetworkStatistics</code></a>:</p>\n<pre><code>&gt; Get-NetworkStatistics | where Localport -eq 8000\n\n\nComputerName : DESKTOP-JL59SC6\nProtocol : TCP\nLocalAddress : 0.0.0.0\nLocalPort : 8000\nRemoteAddress : 0.0.0.0\nRemotePort : 0\nState : LISTENING\nProcessName : node\nPID : 11552\n</code></pre>\n" }, { "answer_id": 40388051, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 5, "selected": false, "text": "<p>With PowerShell 5 on Windows 10 or Windows Server 2016, run <a href=\"https://learn.microsoft.com/en-us/powershell/module/nettcpip/get-nettcpconnection?view=win10-ps\" rel=\"noreferrer\"><code>Get-NetTCPConnection</code></a> cmdlet. I guess that it should also work on older Windows versions.</p>\n<p>The default output of <code>Get-NetTCPConnection</code> does not include Process ID for some reason and it is a bit confusing. However, you could always get it by formatting the output. The property you are looking for is <code>OwningProcess</code>.</p>\n<ul>\n<li><p>If you want to find out the ID of the process that is listening on port 443, run this command:</p>\n<pre><code> PS C:\\&gt; Get-NetTCPConnection -LocalPort 443 | Format-List\n\n LocalAddress : ::\n LocalPort : 443\n RemoteAddress : ::\n RemotePort : 0\n State : Listen\n AppliedSetting :\n OwningProcess : 4572\n CreationTime : 02.11.2016 21:55:43\n OffloadState : InHost\n</code></pre>\n</li>\n<li><p>Format the output to a table with the properties you look for:</p>\n<pre><code> PS C:\\&gt; Get-NetTCPConnection -LocalPort 443 | Format-Table -Property LocalAddress, LocalPort, State, OwningProcess\n\n LocalAddress LocalPort State OwningProcess\n ------------ --------- ----- -------------\n :: 443 Listen 4572\n 0.0.0.0 443 Listen 4572\n</code></pre>\n</li>\n<li><p>If you want to find out a name of the process, run this command:</p>\n<pre><code> PS C:\\&gt; Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess\n\n Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName\n ------- ------ ----- ----- ------ -- -- -----------\n 143 15 3448 11024 4572 0 VisualSVNServer\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 40745929, "author": "Technotronic", "author_id": 3013005, "author_profile": "https://Stackoverflow.com/users/3013005", "pm_score": 4, "selected": false, "text": "<p>Type in the command: <code>netstat -aon | findstr :DESIRED_PORT_NUMBER</code></p>\n\n<p>For example, if I want to find port 80: <code>netstat -aon | findstr :80</code></p>\n\n<p>This answer was originally posted to <a href=\"https://stackoverflow.com/questions/1960750/how-do-i-find-which-program-is-using-port-80-in-windows\">this question</a>.</p>\n" }, { "answer_id": 41839069, "author": "Zoomzoom", "author_id": 1371217, "author_profile": "https://Stackoverflow.com/users/1371217", "pm_score": 2, "selected": false, "text": "<p>For Windows, if you want to find stuff listening or connected to port 1234, execute the following at the cmd prompt: </p>\n\n<pre><code>netstat -na | find \"1234\"\n</code></pre>\n" }, { "answer_id": 41841264, "author": "Tajveer Singh Nijjar", "author_id": 2243541, "author_profile": "https://Stackoverflow.com/users/2243541", "pm_score": 4, "selected": false, "text": "<p>Just open a command shell and type (saying your port is 123456):</p>\n\n<pre><code>netstat -a -n -o | find \"123456\"\n</code></pre>\n\n<p>You will see everything you need.</p>\n\n<p>The headers are:</p>\n\n<pre><code> Proto Local Address Foreign Address State PID\n TCP 0.0.0.0:37 0.0.0.0:0 LISTENING 1111\n</code></pre>\n\n<p>This is as mentioned <a href=\"https://stackoverflow.com/questions/15952663/find-pid-of-process-that-use-a-port-on-windows\">here</a>.</p>\n" }, { "answer_id": 48004597, "author": "Jpsy", "author_id": 430742, "author_profile": "https://Stackoverflow.com/users/430742", "pm_score": 3, "selected": false, "text": "<p><strong>Using PowerShell...</strong>\n...this would be your friend (replace 8080 with your port number):</p>\n\n<pre><code> netstat -abno | Select-String -Context 0,1 -Pattern 8080\n</code></pre>\n\n<p><strong>Sample output</strong></p>\n\n<pre><code>&gt; TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 2920\n [tnslsnr.exe]\n&gt; TCP [::]:8080 [::]:0 LISTENING 2920\n [tnslsnr.exe]\n</code></pre>\n\n<p>So in this example tnslsnr.exe (OracleXE database) is listening on port 8080.</p>\n\n<p><strong>Quick explanation</strong></p>\n\n<ul>\n<li><code>Select-String</code> is used to filter the lengthy output of <code>netstat</code> for the relevant lines.</li>\n<li><code>-Pattern</code> tests each line against a regular expression.</li>\n<li><code>-Context 0,1</code> will output 0 leading lines and 1 trailing line for each pattern match.</li>\n</ul>\n" }, { "answer_id": 48414545, "author": "Ram Sharma", "author_id": 9137647, "author_profile": "https://Stackoverflow.com/users/9137647", "pm_score": 8, "selected": false, "text": "<p>The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don't really need elevated rights to get the process name!</p>\n\n<p><strong>Find the pid of the process running in the port number (e.g., 8080)</strong></p>\n\n<pre><code>netstat -ano | findStr \"8080\"\n</code></pre>\n\n<p><strong>Find the process name by pid</strong></p>\n\n<pre><code>tasklist /fi \"pid eq 2216\"\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/m16hz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/m16hz.png\" alt=\"find process by TCP/IP port\"></a></p>\n" }, { "answer_id": 50180952, "author": "deshapriya debesh", "author_id": 4257636, "author_profile": "https://Stackoverflow.com/users/4257636", "pm_score": 2, "selected": false, "text": "<p>Use the below batch script which takes a process name as an argument and gives <code>netstat</code> output for the process.</p>\n\n<pre><code>@echo off\nset procName=%1\nfor /f \"tokens=2 delims=,\" %%F in ('tasklist /nh /fi \"imagename eq %1\" /fo csv') do call :Foo %%~F\ngoto End\n\n:Foo\nset z=%1\necho netstat for : \"%procName%\" which had pid \"%1\"\necho ----------------------------------------------------------------------\n\nnetstat -ano |findstr %z%\ngoto :eof\n\n:End\n</code></pre>\n" }, { "answer_id": 52463164, "author": "Blue Clouds", "author_id": 1501191, "author_profile": "https://Stackoverflow.com/users/1501191", "pm_score": 4, "selected": false, "text": "<p>Netstat:</p>\n\n<ul>\n<li>-a displays all connection and listening ports</li>\n<li>-b displays executables</li>\n<li>-n stop resolve hostnames (numerical form)</li>\n<li><p>-o owning process</p>\n\n<pre><code>netstat -bano | findstr \"7002\"\n\nnetstat -ano &gt; ano.txt \n</code></pre></li>\n</ul>\n\n<p>The <a href=\"https://www.nirsoft.net/utils/cports.html\" rel=\"noreferrer\">Currports</a> tool helps to search and filter</p>\n" }, { "answer_id": 53159954, "author": "Michael Chourdakis", "author_id": 451321, "author_profile": "https://Stackoverflow.com/users/451321", "pm_score": 3, "selected": false, "text": "<p>Programmatically, you need stuff from <a href=\"https://learn.microsoft.com/el-gr/windows/desktop/api/iphlpapi/\" rel=\"noreferrer\">iphlpapi.h</a>, for example <a href=\"https://learn.microsoft.com/el-gr/windows/desktop/api/iphlpapi/nf-iphlpapi-gettcptable2\" rel=\"noreferrer\">GetTcpTable2</a>(). Structures like <a href=\"https://learn.microsoft.com/el-gr/windows/desktop/api/tcpmib/ns-tcpmib-_mib_tcp6row2\" rel=\"noreferrer\">MIB_TCP6ROW2</a> contain the owner PID.</p>\n" }, { "answer_id": 53774815, "author": "Talha Imam", "author_id": 5863938, "author_profile": "https://Stackoverflow.com/users/5863938", "pm_score": 5, "selected": false, "text": "<p>To find out which specific process (PID) is using which port:</p>\n\n<pre><code>netstat -anon | findstr 1234\n</code></pre>\n\n<p>Where 1234 is the PID of your process. [Go to Task Manager &rarr; Services/Processes tab to find out the PID of your application.]</p>\n" }, { "answer_id": 54504013, "author": "Angel Venchev", "author_id": 1571349, "author_profile": "https://Stackoverflow.com/users/1571349", "pm_score": 3, "selected": false, "text": "<p>A single-line solution that helps me is this one. Just substitute 3000 with your port:</p>\n\n<pre><code>$P = Get-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess; Stop-Process $P.Id\n</code></pre>\n\n<p>Edit: Changed <code>kill</code> to <code>Stop-Process</code> for more PowerShell-like language</p>\n" }, { "answer_id": 56059282, "author": "Anatole ABE", "author_id": 2022273, "author_profile": "https://Stackoverflow.com/users/2022273", "pm_score": 4, "selected": false, "text": "<ol>\n<li><p>Open the command prompt - start &rarr; <em>Run</em> &rarr; <code>cmd</code>, or start menu &rarr; <em>All Programs</em> &rarr; <em>Accessories</em> &rarr; <em>Command Prompt</em>.</p></li>\n<li><p>Type</p>\n\n<pre><code>netstat -aon | findstr '[port_number]'\n</code></pre></li>\n</ol>\n\n<p>Replace the <code>[port_number]</code> with the actual port number that you want to check and hit <kbd>Enter</kbd>.</p>\n\n<ol start=\"3\">\n<li>If the port is being used by any application, then that application’s detail will be shown. The number, which is shown at the last column of the list, is the PID (process ID) of that application. Make note of this.</li>\n<li><p>Type</p>\n\n<pre><code>tasklist | findstr '[PID]'\n</code></pre></li>\n</ol>\n\n<p>Replace the <code>[PID]</code> with the number from the above step and hit <kbd>Enter</kbd>.</p>\n\n<ol start=\"5\">\n<li>You’ll be shown the application name that is using your port number.</li>\n</ol>\n" }, { "answer_id": 58009506, "author": "lczapski", "author_id": 11733759, "author_profile": "https://Stackoverflow.com/users/11733759", "pm_score": 2, "selected": false, "text": "<p>Based on answers with <a href=\"https://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows/48202#48202\">info</a> and <a href=\"https://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows/23136177#23136177\">kill</a>, for me it is useful to combine them in <a href=\"https://stackoverflow.com/questions/17289969/how-to-split-command-output-in-windows-command-prompt/17290706#17290706\">one command</a>. And you can run this from cmd to get information about process that listen on given port (example 8080):</p>\n<pre><code>for /f &quot;tokens=3 delims=LISTENING&quot; %i in ('netstat -ano ^| findStr &quot;8080&quot; ^| findStr &quot;[&quot;') do @tasklist /nh /fi &quot;pid eq %i&quot;\n</code></pre>\n<p>Or if you want to kill it:</p>\n<pre><code>for /f &quot;tokens=3 delims=LISTENING&quot; %i in ('netstat -ano ^| findStr &quot;8080&quot; ^| findStr &quot;[&quot;') do @Taskkill /F /IM %i\n</code></pre>\n<p>You can also put those command into a bat file (they will be slightly different - replace <code>%i</code> for <code>%%i</code>):</p>\n<h3>File <code>portInfo.bat</code></h3>\n<pre><code>for /f &quot;tokens=3 delims=LISTENING&quot; %%i in (\n 'netstat -ano ^| findStr &quot;%1&quot; ^| findStr &quot;[&quot;'\n) do @tasklist /nh /fi &quot;pid eq %%i&quot;\n</code></pre>\n<h3>File <code>portKill.bat</code></h3>\n<pre><code>for /f &quot;tokens=3 delims=LISTENING&quot; %%i in (\n 'netstat -ano ^| findStr &quot;%1&quot; ^| findStr &quot;[&quot;'\n) do @Taskkill /F /IM %%i\n</code></pre>\n<p>Then you from cmd you can do this:</p>\n<p><code>portInfo.bat 8080</code></p>\n<p>or</p>\n<p><code>portKill.bat 8080</code></p>\n" }, { "answer_id": 62889072, "author": "jiz", "author_id": 4894302, "author_profile": "https://Stackoverflow.com/users/4894302", "pm_score": 3, "selected": false, "text": "<p>To find pid who using port 8000</p>\n<pre><code>netstat -aon | findstr '8000'\n</code></pre>\n<p>To Kill that Process in windows</p>\n<pre><code>taskkill /pid pid /f\n</code></pre>\n<p>where pid is the process id which you get form first command</p>\n" }, { "answer_id": 63375462, "author": "Benjamin Wen", "author_id": 5492956, "author_profile": "https://Stackoverflow.com/users/5492956", "pm_score": 4, "selected": false, "text": "<p>In case someone need an equivalent for macOS like I did, here is it:</p>\n<p><code>lsof -i tcp:8080</code></p>\n<p>After you get the <code>PID</code> of the process, you can kill it with:</p>\n<p><code>kill -9 &lt;PID&gt;</code></p>\n" }, { "answer_id": 64988942, "author": "Daniel Genezini", "author_id": 4058784, "author_profile": "https://Stackoverflow.com/users/4058784", "pm_score": 3, "selected": false, "text": "<p>You can also check the reserved ports with the command below. <a href=\"https://en.wikipedia.org/wiki/Hyper-V\" rel=\"nofollow noreferrer\">Hyper-V</a> reserve some ports, for instance.</p>\n<pre><code>netsh int ipv4 show excludedportrange protocol=tcp\n</code></pre>\n" }, { "answer_id": 66233917, "author": "David Jesus", "author_id": 5869384, "author_profile": "https://Stackoverflow.com/users/5869384", "pm_score": 5, "selected": false, "text": "<p><code>netstat -aof | findstr :8080</code> (Change 8080 for any port)</p>\n" }, { "answer_id": 71288879, "author": "Oliver Gaida", "author_id": 11000412, "author_profile": "https://Stackoverflow.com/users/11000412", "pm_score": 3, "selected": false, "text": "<h2>PowerShell</h2>\n<p>If you want to have a good overview, you can use this:</p>\n<pre><code>Get-NetTCPConnection -State Listen | Select-Object -Property *, `\n @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `\n | select ProcessName,LocalAddress,LocalPort\n</code></pre>\n<p>Then you get a table like this:</p>\n<pre><code>ProcessName LocalAddress LocalPort\n----------- ------------ ---------\nservices :: 49755\njhi_service ::1 49673\nsvchost :: 135\nservices 0.0.0.0 49755\nspoolsv 0.0.0.0 49672\n</code></pre>\n<p>For <a href=\"https://en.wikipedia.org/wiki/User_Datagram_Protocol\" rel=\"nofollow noreferrer\">UDP</a>, it is:</p>\n<pre><code>Get-NetUDPEndpoint | Select-Object -Property *, `\n @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `\n | select ProcessName,LocalAddress,LocalPort\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How do I find out which process is listening on a TCP or UDP port on Windows?
[PowerShell](https://en.wikipedia.org/wiki/PowerShell) ====================================================== TCP --- ``` Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess ``` UDP --- ``` Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess ``` [cmd](https://en.wikipedia.org/wiki/Cmd.exe) ============================================ ``` netstat -a -b ``` (Add **-n** to stop it trying to resolve hostnames, which will make it a lot faster.) Note Dane's recommendation for [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx). It looks very useful! **-a** Displays all connections and listening ports. **-b** Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. **-n** Displays addresses and port numbers in numerical form. **-o** Displays the owning process ID associated with each connection.
48,235
<p>I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base.</p> <p>Where do I start?</p> <p>What are the fundamental similarities and differences between the code which will operated under Windows and Linux?</p> <p>What skills and software do I need?</p> <hr /> <h3>Note:</h3> <p>The official website is Visual Studio oriented!<br /> Netbeans or Eclipse are my only options.<br /> I will not pay Microsoft to help an Open Source project.</p>
[ { "answer_id": 48236, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "<p>Read this article on Chrome and Open Source on Linux:</p>\n\n<p><a href=\"http://arstechnica.com/journals/linux.ars/2008/09/02/google-unveils-chrome-source-code-and-linux-port\" rel=\"noreferrer\">http://arstechnica.com/journals/linux.ars/2008/09/02/google-unveils-chrome-source-code-and-linux-port</a></p>\n\n<p>The Google V8 JavaScript Engine is also open source and available here if you want to contribute;</p>\n\n<p><a href=\"http://code.google.com/p/v8/\" rel=\"noreferrer\">http://code.google.com/p/v8/</a></p>\n\n<p>If you want to contribute on Chronium, here are the instructions:</p>\n\n<p><a href=\"http://dev.chromium.org/developers/contributing-code\" rel=\"noreferrer\">http://dev.chromium.org/developers/contributing-code</a></p>\n\n<blockquote>\n <p><a href=\"http://dev.chromium.org/Home\" rel=\"noreferrer\">Chromium</a> is an open-source browser\n project that aims to build a safer,\n faster, and more stable way for all\n Internet users to experience the web.\n This site contains design documents,\n architecture overviews, testing\n information, and more to help you\n learn to build and work with the\n Chromium source code.</p>\n</blockquote>\n\n<p>Here is how you can get started:</p>\n\n<p><a href=\"http://dev.chromium.org/developers/how-tos/getting-started\" rel=\"noreferrer\">http://dev.chromium.org/developers/how-tos/getting-started</a></p>\n\n<hr>\n\n<p>EDIT: Two more questions was added to the original question.</p>\n\n<p>Building on Linux requires the following software:</p>\n\n<ul>\n<li>Subversion >= 1.4 </li>\n<li>pkg-config >= 0.20</li>\n<li>Python >= 2.4</li>\n<li>Perl >= 5.x</li>\n<li>gcc/g++ >= 4.2</li>\n<li>bison >= 2.3</li>\n<li>flex >= 2.5.34</li>\n<li>gperf >= 3.0.3</li>\n<li>libnss3-dev >= 3.12</li>\n</ul>\n\n<p>On Ubuntu 8.04, you can fetch all of the above as follows:</p>\n\n<pre><code>$ sudo apt-get install subversion pkg-config python perl g++ bison flex gperf libnss3-dev\n</code></pre>\n\n<blockquote>\n <p><strong>Note</strong>: There is no working\n Chromium-based browser on Linux.\n Although many Chromium submodules\n build under Linux and a few unit tests\n pass, all that runs is a command-line\n \"all tests pass\" executable.</p>\n</blockquote>\n" }, { "answer_id": 692397, "author": "Paul", "author_id": 37865, "author_profile": "https://Stackoverflow.com/users/37865", "pm_score": 5, "selected": true, "text": "<p>EDIT: (2/6/10)</p>\n\n<p>A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google:</p>\n\n<p><a href=\"http://www.google.com/chrome?platform=linux\" rel=\"nofollow noreferrer\">http://www.google.com/chrome?platform=linux</a></p>\n\n<p>EDIT: (5/31/09)</p>\n\n<p>Since I answered this question, there have been more new developments in Chrome (actually \"Chromium\") for Linux: An alpha build has been released. This means it's not fully functional.</p>\n\n<p>If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list</p>\n\n<pre><code>deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main\ndeb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main\n</code></pre>\n\n<p>Then, at the command line:</p>\n\n<pre><code>aptitude update\naptitude install chromium-browser\n</code></pre>\n\n<p>Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist.</p>\n\n<p>And.... <strong>Yes</strong>, it works. I'm typing this in my freshly installed Chromium browser right now!</p>\n\n<p>The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: <a href=\"https://launchpad.net/~chromium-daily/+archive/ppa\" rel=\"nofollow noreferrer\">https://launchpad.net/~chromium-daily/+archive/ppa</a></p>\n\n<p><strong><em>The original answer:</em></strong></p>\n\n<p><a href=\"http://code.google.com/p/chromium/wiki/LinuxBuildInstructions\" rel=\"nofollow noreferrer\">Linux Build Instructions</a></p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base. Where do I start? What are the fundamental similarities and differences between the code which will operated under Windows and Linux? What skills and software do I need? --- ### Note: The official website is Visual Studio oriented! Netbeans or Eclipse are my only options. I will not pay Microsoft to help an Open Source project.
EDIT: (2/6/10) A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google: <http://www.google.com/chrome?platform=linux> EDIT: (5/31/09) Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional. If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list ``` deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main ``` Then, at the command line: ``` aptitude update aptitude install chromium-browser ``` Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist. And.... **Yes**, it works. I'm typing this in my freshly installed Chromium browser right now! The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: <https://launchpad.net/~chromium-daily/+archive/ppa> ***The original answer:*** [Linux Build Instructions](http://code.google.com/p/chromium/wiki/LinuxBuildInstructions)
48,239
<p>Is there any way to get the ID of the element that fires an event?</p> <p>I'm thinking something like:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script type="text/javascript" src="starterkit/jquery.js"&gt;&lt;/script&gt; &lt;form class="item" id="aaa"&gt; &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt; &lt;form class="item" id="bbb"&gt; &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>Except of course that the var <code>test</code> should contain the id <code>"aaa"</code>, if the event is fired from the first form, and <code>"bbb"</code>, if the event is fired from the second form.</p>
[ { "answer_id": 48242, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 6, "selected": false, "text": "<p>You can use <code>(this)</code> to reference the object that fired the function.</p>\n\n<p><code>'this'</code> is a <strong>DOM</strong> element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.</p>\n\n<p>Here is where you can learn more: <a href=\"http://remysharp.com/2007/04/12/jquerys-this-demystified/\" rel=\"noreferrer\">http://remysharp.com/2007/04/12/jquerys-this-demystified/</a></p>\n" }, { "answer_id": 48684, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 11, "selected": true, "text": "<p>In jQuery <code>event.target</code> always refers to the element that triggered the event, where <code>event</code> is the parameter passed to the function. <a href=\"http://api.jquery.com/category/events/event-object/\" rel=\"noreferrer\">http://api.jquery.com/category/events/event-object/</a></p>\n\n<pre><code>$(document).ready(function() {\n $(\"a\").click(function(event) {\n alert(event.target.id);\n });\n});\n</code></pre>\n\n<p>Note also that <code>this</code> will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as <code>$(this)</code>, e.g.:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"a\").click(function(event) {\n // this.append wouldn't work\n $(this).append(\" Clicked\");\n });\n});\n</code></pre>\n" }, { "answer_id": 3624837, "author": "Gemma", "author_id": 437705, "author_profile": "https://Stackoverflow.com/users/437705", "pm_score": 8, "selected": false, "text": "<p>For reference, try this! It works!</p>\n\n<pre><code>jQuery(\"classNameofDiv\").click(function() {\n var contentPanelId = jQuery(this).attr(\"id\");\n alert(contentPanelId);\n});\n</code></pre>\n" }, { "answer_id": 7389282, "author": "SMut", "author_id": 940734, "author_profile": "https://Stackoverflow.com/users/940734", "pm_score": 5, "selected": false, "text": "<p>I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique <code>ID</code>, which is needed for further actions, so, if the DOM is altered you need a different approach:</p>\n\n<pre><code>$(\"table\").delegate(\"tr\", \"click\", function() {\n var id=$(this).attr('id');\n alert(\"ID:\"+id); \n});\n</code></pre>\n" }, { "answer_id": 9825688, "author": "Morvael", "author_id": 1286358, "author_profile": "https://Stackoverflow.com/users/1286358", "pm_score": 4, "selected": false, "text": "<p>The source element as a jQuery object should be obtained via</p>\n\n<pre><code>var $el = $(event.target);\n</code></pre>\n\n<p>This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object\nEG.a click event on a table row, and you need the cell that was clicked</p>\n\n<pre><code>$(\"tr\").click(function(event){\n var $td = $(event.target);\n});\n</code></pre>\n" }, { "answer_id": 11562933, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 7, "selected": false, "text": "<p>For all events, not limited to just jQuery you can use</p>\n\n<pre><code>var target = event.target || event.srcElement;\nvar id = target.id\n</code></pre>\n\n<p>Where <code>event.target</code> fails it falls back on <code>event.srcElement</code> for IE.\nTo clarify the above code does not require jQuery but also works with jQuery.</p>\n" }, { "answer_id": 13211759, "author": "Darius", "author_id": 1696922, "author_profile": "https://Stackoverflow.com/users/1696922", "pm_score": 3, "selected": false, "text": "<p>You can try to use:</p>\n\n<pre><code>$('*').live('click', function() {\n console.log(this.id);\n return false;\n});\n</code></pre>\n" }, { "answer_id": 13252233, "author": "dsch", "author_id": 1803250, "author_profile": "https://Stackoverflow.com/users/1803250", "pm_score": 7, "selected": false, "text": "<p>Though it is mentioned in other posts, I wanted to spell this out:</p>\n\n<p><code>$(event.target).id</code> is undefined</p>\n\n<p><code>$(event.target)[0].id</code> gives the id attribute.</p>\n\n<p><code>event.target.id</code> also gives the id attribute.</p>\n\n<p><code>this.id</code> gives the id attribute.</p>\n\n<p>and</p>\n\n<p><code>$(this).id</code> is undefined.</p>\n\n<p>The differences, of course, is between jQuery objects and DOM objects. \"id\" is a DOM property so you have to be on the DOM element object to use it.</p>\n\n<p>(It tripped me up, so it probably tripped up someone else)</p>\n" }, { "answer_id": 16912421, "author": "vml19", "author_id": 256988, "author_profile": "https://Stackoverflow.com/users/256988", "pm_score": 2, "selected": false, "text": "<p><code>this.element.attr(\"id\")</code> works fine in IE8.</p>\n" }, { "answer_id": 19882381, "author": "Marcel Verwey", "author_id": 2603657, "author_profile": "https://Stackoverflow.com/users/2603657", "pm_score": 3, "selected": false, "text": "<p>This works on a higher <code>z-index</code> than the event parameter mentioned in above answers:</p>\n\n<pre><code>$(\"#mydiv li\").click(function(){\n\n ClickedElement = this.id;\n alert(ClickedElement);\n});\n</code></pre>\n\n<p>This way you will always get the <code>id</code> of the (in this example <code>li</code>) element. Also when clicked on a child element of the parent..</p>\n" }, { "answer_id": 21684620, "author": "Moji", "author_id": 639390, "author_profile": "https://Stackoverflow.com/users/639390", "pm_score": 2, "selected": false, "text": "<p>Both of these work,</p>\n\n<pre><code>jQuery(this).attr(\"id\");\n</code></pre>\n\n<p>and </p>\n\n<pre><code>alert(this.id);\n</code></pre>\n" }, { "answer_id": 28245626, "author": "shmuli", "author_id": 2399980, "author_profile": "https://Stackoverflow.com/users/2399980", "pm_score": 2, "selected": false, "text": "<pre><code>var buttons = document.getElementsByTagName('button');\nvar buttonsLength = buttons.length;\nfor (var i = 0; i &lt; buttonsLength; i++){\n buttons[i].addEventListener('click', clickResponse, false);\n};\nfunction clickResponse(){\n // do something based on button selection here...\n alert(this.id);\n}\n</code></pre>\n\n<p>Working JSFiddle <a href=\"http://jsfiddle.net/npvrx6sg/\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 30925343, "author": "Isochronous", "author_id": 462210, "author_profile": "https://Stackoverflow.com/users/462210", "pm_score": 3, "selected": false, "text": "<p>In the case of delegated event handlers, where you might have something like this:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li data-id=\"1\"&gt;\n &lt;span&gt;Item 1&lt;/span&gt;\n &lt;/li&gt;\n &lt;li data-id=\"2\"&gt;\n &lt;span&gt;Item 2&lt;/span&gt;\n &lt;/li&gt;\n &lt;li data-id=\"3\"&gt;\n &lt;span&gt;Item 3&lt;/span&gt;\n &lt;/li&gt;\n &lt;li data-id=\"4\"&gt;\n &lt;span&gt;Item 4&lt;/span&gt;\n &lt;/li&gt;\n &lt;li data-id=\"5\"&gt;\n &lt;span&gt;Item 5&lt;/span&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>and your JS code like so:</p>\n\n<pre><code>$(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target),\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n</code></pre>\n\n<p>You'll more than likely find that itemId is <code>undefined</code>, as the content of the LI is wrapped in a <code>&lt;span&gt;</code>, which means the <code>&lt;span&gt;</code> will probably be the event target. You can get around this with a small check, like so:</p>\n\n<pre><code>$(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n</code></pre>\n\n<p>Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):</p>\n\n<pre><code>$(document).ready(function() {\n $('ul').on('click li', function(event) {\n var $target = $(event.target),\n itemId;\n\n $target = $target.is('li') ? $target : $target.closest('li');\n itemId = $target.data('id');\n\n //do something with itemId\n });\n});\n</code></pre>\n\n<p>When using event delegation, the <code>.is()</code> method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use <code>.closest(selector)</code> to search up the DOM tree, and use <code>.find(selector)</code> (generally coupled with <code>.first()</code>, as in <code>.find(selector).first()</code>) to search down it. You don't need to use <code>.first()</code> when using <code>.closest()</code>, as it only returns the first matching ancestor element, while <code>.find()</code> returns all matching descendants.</p>\n" }, { "answer_id": 38762705, "author": "Error404", "author_id": 6304917, "author_profile": "https://Stackoverflow.com/users/6304917", "pm_score": 2, "selected": false, "text": "<p>Just use the <code>this</code> reference</p>\n\n<pre><code>$(this).attr(\"id\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(this).prop(\"id\")\n</code></pre>\n" }, { "answer_id": 39673488, "author": "Basant Rules", "author_id": 2243229, "author_profile": "https://Stackoverflow.com/users/2243229", "pm_score": 3, "selected": false, "text": "<p>Use can Use .on event</p>\n\n<pre><code> $(\"table\").on(\"tr\", \"click\", function() {\n var id=$(this).attr('id');\n alert(\"ID:\"+id); \n });\n</code></pre>\n" }, { "answer_id": 40043918, "author": "Maciej Sikora", "author_id": 4420812, "author_profile": "https://Stackoverflow.com/users/4420812", "pm_score": 5, "selected": false, "text": "<p>Element which fired event we have in <strong>event</strong> property</p>\n\n<pre><code>event.currentTarget\n</code></pre>\n\n<p>We get <strong>DOM node</strong> object on which was set event handler.</p>\n\n<hr>\n\n<p>Most nested node which started bubbling process we have in</p>\n\n<pre><code>event.target\n</code></pre>\n\n<hr>\n\n<p>Event object is always first attribute of event handler, example:</p>\n\n<pre><code>document.querySelector(\"someSelector\").addEventListener(function(event){\n\n console.log(event.target);\n console.log(event.currentTarget);\n\n});\n</code></pre>\n\n<p>More about event delegation You can read in <a href=\"http://maciejsikora.com/standard-events-vs-event-delegation/\" rel=\"noreferrer\">http://maciejsikora.com/standard-events-vs-event-delegation/</a></p>\n" }, { "answer_id": 48621503, "author": "xeon", "author_id": 5432368, "author_profile": "https://Stackoverflow.com/users/5432368", "pm_score": 1, "selected": false, "text": "<p>You can use the function to get the id and the value for the changed item(in my example, I've used a Select tag.</p>\n\n<pre><code> $('select').change(\n function() {\n var val = this.value;\n var id = jQuery(this).attr(\"id\");\n console.log(\"value changed\" + String(val)+String(id));\n }\n );\n</code></pre>\n" }, { "answer_id": 52881201, "author": "Cris", "author_id": 1978831, "author_profile": "https://Stackoverflow.com/users/1978831", "pm_score": 4, "selected": false, "text": "<p>this works with most types of elements:</p>\n\n<pre><code>$('selector').on('click',function(e){\n log(e.currentTarget.id);\n });\n</code></pre>\n" }, { "answer_id": 53251428, "author": "DAB", "author_id": 2004265, "author_profile": "https://Stackoverflow.com/users/2004265", "pm_score": 0, "selected": false, "text": "<p>I'm working with </p>\n\n<blockquote>\n <p>jQuery Autocomplete</p>\n</blockquote>\n\n<p>I tried looking for an <code>event</code> as described above, but when the request function fires it doesn't seem to be available. I used <code>this.element.attr(\"id\")</code> to get the element's ID instead, and it seems to work fine.</p>\n" }, { "answer_id": 54894197, "author": "David Dehghan", "author_id": 705945, "author_profile": "https://Stackoverflow.com/users/705945", "pm_score": 0, "selected": false, "text": "<p>In case of Angular 7.x you can get the native element and its id or properties.</p>\n\n<pre><code>myClickHandler($event) {\n this.selectedElement = &lt;Element&gt;$event.target;\n console.log(this.selectedElement.id)\n this.selectedElement.classList.remove('some-class');\n}\n</code></pre>\n\n<p>html:</p>\n\n<pre><code>&lt;div class=\"list-item\" (click)=\"myClickHandler($event)\"&gt;...&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 57583976, "author": "chings228", "author_id": 749827, "author_profile": "https://Stackoverflow.com/users/749827", "pm_score": 3, "selected": false, "text": "<pre><code>$(\".classobj\").click(function(e){\n console.log(e.currentTarget.id);\n})\n</code></pre>\n" }, { "answer_id": 62602366, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 2, "selected": false, "text": "<h1>Pure JS is simpler</h1>\n<pre><code>aaa.onclick = handler;\nbbb.onclick = handler;\n\nfunction handler() { \n var test = this.id; \n console.log(test) \n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>aaa.onclick = handler;\nbbb.onclick = handler;\n\nfunction handler() { \n var test = this.id; \n console.log(test) \n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form class=\"item\" id=\"aaa\"&gt;\n &lt;input class=\"title\"/&gt;\n&lt;/form&gt;\n&lt;form class=\"item\" id=\"bbb\"&gt;\n &lt;input class=\"title\"/&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 64854320, "author": "vr_driver", "author_id": 1190051, "author_profile": "https://Stackoverflow.com/users/1190051", "pm_score": 0, "selected": false, "text": "<p>There's plenty of ways to do this and examples already, but if you need take it a further step and need to prevent the enter key on forms, and yet still need it on a multi-line textarea, it gets more complicated. The following will solve the problem.</p>\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n $(window).keydown(function(event){\n if(event.keyCode == 13) {\n //There are 2 textarea forms that need the enter key to work.\n if((event.target.id==&quot;CommentsForOnAir&quot;) || (event.target.id==&quot;CommentsForOnline&quot;))\n {\n // Prevent the form from triggering, but allowing multi-line to still work.\n }\n else\n {\n event.preventDefault();\n return false;\n } \n }\n });\n });\n&lt;/script&gt;\n\n&lt;textarea class=&quot;form-control&quot; rows=&quot;10&quot; cols=&quot;50&quot; id=&quot;CommentsForOnline&quot; name=&quot;CommentsForOnline&quot; type=&quot;text&quot; size=&quot;60&quot; maxlength=&quot;2000&quot;&gt;&lt;/textarea&gt;\n</code></pre>\n<p>It could probably be simplified more, but you get the concept.</p>\n" }, { "answer_id": 74002779, "author": "MolyOxide", "author_id": 13019063, "author_profile": "https://Stackoverflow.com/users/13019063", "pm_score": 0, "selected": false, "text": "<p>Simply you can use either:</p>\n<pre><code>$(this).attr(&quot;id&quot;);\n</code></pre>\n<p>Or</p>\n<pre><code>$(event.target).attr(&quot;id&quot;);\n</code></pre>\n<p>But <code>$(this).attr(&quot;id&quot;)</code> will return the ID of the element to which the Event Listener is attached to.<br><br>\nWhereas when we use <code>$(event.target).attr(&quot;id&quot;)</code> this will return the ID of the element that was clicked.<br>\nFor example in a <code>&lt;div&gt;</code> if we have a <code>&lt;p&gt;</code> element then if we click on 'div' <code>$(event.target).attr(&quot;id&quot;)</code> will return the ID of <code>&lt;div&gt;</code>, if we click on 'p' then <code>$(event.target).attr(&quot;id&quot;)</code> will return ID of <code>&lt;p&gt;</code>.\n<br>\nSo use it as per your need.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
Is there any way to get the ID of the element that fires an event? I'm thinking something like: ```js $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); ``` ```html <script type="text/javascript" src="starterkit/jquery.js"></script> <form class="item" id="aaa"> <input class="title"></input> </form> <form class="item" id="bbb"> <input class="title"></input> </form> ``` Except of course that the var `test` should contain the id `"aaa"`, if the event is fired from the first form, and `"bbb"`, if the event is fired from the second form.
In jQuery `event.target` always refers to the element that triggered the event, where `event` is the parameter passed to the function. <http://api.jquery.com/category/events/event-object/> ``` $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); ``` Note also that `this` will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as `$(this)`, e.g.: ``` $(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); }); ```
48,240
<p>I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop.</p> <p>I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data.</p> <p>I believe that the way I'm doing it now is very inefficient:</p> <pre><code># routes is an array of [number, destination] that I build while iterating over the data routes.uniq.each do |route| number = route[0] destination = route[1] r = Route.find_by_number_and_destination(number, destination) if !r r = Route.new :number =&gt; number, :destination =&gt; destination r.save end # I have to check if it already exists because I can't find a way # to create a uniqueness constraint on the join table with 2 foreign keys r.stops &lt;&lt; stop unless r.stops.include? stop end </code></pre> <p>Basically, I have to do 2 things for every route I find: 1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist.</p> <p>Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?</p>
[ { "answer_id": 48529, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 1, "selected": false, "text": "<p>If I get it right, you (should) have 2 models. A Route model, and a Stop model.</p>\n\n<p>Here's how I would define these models:</p>\n\n<pre><code>class Route &lt; ActiveRecord::Base\n has_and_belongs_to_many :stops\n belongs_to :stop, :foreign_key =&gt; 'destination_id'\nend\n\nclass Stop &lt; ActiveRecorde::Base\n has_and_belongs_to_many :routes\nend\n</code></pre>\n\n<p>And here's how I would set up my tables:</p>\n\n<pre><code>create_table :routes do |t|\n t.integer :destination_id\n # Any other information you want to store about routes\nend\n\ncreate_table :stops do |t|\n # Any other information you want to store about stops\nend\n\ncreate_table :routes_stops, :primary_key =&gt; [:route_id, :stop_id] do |t|\n t.integer :route_id\n t.integer :stop_id\nend\n</code></pre>\n\n<p>Finally, here's the code I'd use:</p>\n\n<pre><code># First, find all the relevant routes, just for caching.\nRoute.find(numbers)\n\nr = Route.find(number)\nr.destination_id = destination\nr.stops &lt;&lt; stop\n</code></pre>\n\n<p>This should use only a few SQL queries.</p>\n" }, { "answer_id": 9577609, "author": "GeekOnCoffee", "author_id": 262162, "author_profile": "https://Stackoverflow.com/users/262162", "pm_score": 0, "selected": false, "text": "<p>There's likely a good way to cleanup the stops call, but this cleans it up quite a bit assuming I'm picturing properly how routes is structured. </p>\n\n<pre><code>routes.uniq.each do |number, destination|\n\n r = Route.find_or_create_by_number_and_destination(route[0], destination)\n\n r.stops &lt;&lt; stop unless r.stops.include? stop\n\nend\n</code></pre>\n" }, { "answer_id": 11144875, "author": "jacklin", "author_id": 215708, "author_profile": "https://Stackoverflow.com/users/215708", "pm_score": 1, "selected": false, "text": "<p>Try this gem:\n<a href=\"https://github.com/seamusabshere/upsert\" rel=\"nofollow\">https://github.com/seamusabshere/upsert</a></p>\n\n<p>Docs say its 80% faster than find_or_create_by</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124/" ]
I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop. I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data. I believe that the way I'm doing it now is very inefficient: ``` # routes is an array of [number, destination] that I build while iterating over the data routes.uniq.each do |route| number = route[0] destination = route[1] r = Route.find_by_number_and_destination(number, destination) if !r r = Route.new :number => number, :destination => destination r.save end # I have to check if it already exists because I can't find a way # to create a uniqueness constraint on the join table with 2 foreign keys r.stops << stop unless r.stops.include? stop end ``` Basically, I have to do 2 things for every route I find: 1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist. Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?
If I get it right, you (should) have 2 models. A Route model, and a Stop model. Here's how I would define these models: ``` class Route < ActiveRecord::Base has_and_belongs_to_many :stops belongs_to :stop, :foreign_key => 'destination_id' end class Stop < ActiveRecorde::Base has_and_belongs_to_many :routes end ``` And here's how I would set up my tables: ``` create_table :routes do |t| t.integer :destination_id # Any other information you want to store about routes end create_table :stops do |t| # Any other information you want to store about stops end create_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t| t.integer :route_id t.integer :stop_id end ``` Finally, here's the code I'd use: ``` # First, find all the relevant routes, just for caching. Route.find(numbers) r = Route.find(number) r.destination_id = destination r.stops << stop ``` This should use only a few SQL queries.
48,278
<p>I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts.</p> <p>Is there a way to make the webbrowser print the background of the displayed document too?</p> <p>Edit: Since I wanted to do this programatically, I opted for this solution:</p> <pre><code>using Microsoft.Win32; ... RegistryKey regKey = Registry.CurrentUser .OpenSubKey("Software") .OpenSubKey("Microsoft") .OpenSubKey("Internet Explorer") .OpenSubKey("Main"); //Get the current setting so that we can revert it after printjob var defaultValue = regKey.GetValue("Print_Background"); regKey.SetValue("Print_Background", "yes"); //Do the printing //Revert the registry key to the original value regKey.SetValue("Print_Background", defaultValue); </code></pre> <p>Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions.</p> <p>Thanks for all your feedback</p>
[ { "answer_id": 48292, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>By default, the browser does not print background images at all. </p>\n\n<p>In Firefox</p>\n\n<pre><code>* File &gt; Page Setup &gt; Check Off \"Print Background\"\n* File &gt; Print Preview\n</code></pre>\n\n<p>In IE</p>\n\n<pre><code>* Tools &gt; Internet Options &gt; Advanced &gt; Printing\n* Check Off \"Print Background Images and Colors\"\n</code></pre>\n\n<p>In Opera</p>\n\n<pre><code>* File &gt; Print Options &gt; Check Off \"Print Page Background\"\n* File &gt; Print Preview (You may have to scroll down/up to see it refresh)\n</code></pre>\n" }, { "answer_id": 51298, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": true, "text": "<p>If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done.</p>\n\n<p>I consider this <em>very bad</em> practice in the first place, but if you must do it then be kind.</p>\n\n<pre><code>Registry.LocalMachine\n</code></pre>\n\n<p>Also, try changing <code>LocalUser</code> instead of <code>LocalMachine</code> - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine.</p>\n" }, { "answer_id": 751459, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The corresponding HKCU key for this setting is:\nHKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Main\\Print_Background</p>\n" }, { "answer_id": 1765873, "author": "Master DJon", "author_id": 214898, "author_profile": "https://Stackoverflow.com/users/214898", "pm_score": 2, "selected": false, "text": "<p>Another registry key would be : \nHKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\Print_Background\nHKEY_LOCAL_MACHINE\\Software\\Microsoft\\Internet Explorer\\PageSetup\\Print_Background</p>\n" }, { "answer_id": 2475422, "author": "icliff", "author_id": 297132, "author_profile": "https://Stackoverflow.com/users/297132", "pm_score": 0, "selected": false, "text": "<pre><code>var sh = new ActiveXObject(\"WScript.Shell\");\nkey = \"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Internet Explorer\\\\Main\\\\Print_Background\";\nvar defaultValue = sh.RegRead(key); \nsh.RegWrite(key,\"yes\",\"REG_SZ\");\ndocument.frames['detailFrame'].focus(); \ndocument.frames['detailFrame'].print();\nsh.RegWrite(key,defaultValue,\"REG_SZ\"); \nreturn false; \n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4582/" ]
I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts. Is there a way to make the webbrowser print the background of the displayed document too? Edit: Since I wanted to do this programatically, I opted for this solution: ``` using Microsoft.Win32; ... RegistryKey regKey = Registry.CurrentUser .OpenSubKey("Software") .OpenSubKey("Microsoft") .OpenSubKey("Internet Explorer") .OpenSubKey("Main"); //Get the current setting so that we can revert it after printjob var defaultValue = regKey.GetValue("Print_Background"); regKey.SetValue("Print_Background", "yes"); //Do the printing //Revert the registry key to the original value regKey.SetValue("Print_Background", defaultValue); ``` Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions. Thanks for all your feedback
If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done. I consider this *very bad* practice in the first place, but if you must do it then be kind. ``` Registry.LocalMachine ``` Also, try changing `LocalUser` instead of `LocalMachine` - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine.
48,288
<p>I've been trying to understand <a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx" rel="nofollow noreferrer">Process.MainWindowHandle</a>.</p> <p>According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but <em>the first window associated with the process remains the main window</em>." (Emphasis added)</p> <p>But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.</p> <p>To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.</p> <p>Here's the interesting part of this test app...</p> <pre><code> IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd != oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } </code></pre> <p>You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.</p> <p><img src="https://i.stack.imgur.com/r54iB.png" alt="MainWindowHandleMystery"></p> <p>Perhaps I've misunderstood the documentation. </p> <p>Can anyone shed light?</p>
[ { "answer_id": 48301, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Actually Process.MainWindowHandle is a handle of top-most window, it's not really the \"Main Window Handle\"</p>\n" }, { "answer_id": 48318, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": true, "text": "<p>@edg,</p>\n\n<p>I guess it's an error in MSDN. You can clearly see in Relfector, that \"Main window\" check in .NET looks like:</p>\n\n<pre><code>private bool IsMainWindow(IntPtr handle)\n{\n return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) \n &amp;&amp; NativeMethods.IsWindowVisible(new HandleRef(this, handle)));\n}\n</code></pre>\n\n<p>When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
I've been trying to understand [Process.MainWindowHandle](http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx). According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but *the first window associated with the process remains the main window*." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... ``` IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd != oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } ``` You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. ![MainWindowHandleMystery](https://i.stack.imgur.com/r54iB.png) Perhaps I've misunderstood the documentation. Can anyone shed light?
@edg, I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like: ``` private bool IsMainWindow(IntPtr handle) { return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && NativeMethods.IsWindowVisible(new HandleRef(this, handle))); } ``` When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.
48,340
<p>i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract. </p> <p>here is the code below;</p> <pre><code>public void Foo() { try { DoSomething(); // throws FaultException&lt;FooFault&gt; } catch (FaultException) { throw; } catch (Exception ex) { myProject.Exception.Throw&lt;FooFault&gt;(ex); } } </code></pre> <p>in service contract;</p> <pre><code>[FaultException(typeof(FooFault))] void Foo(); </code></pre> <p>when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?</p>
[ { "answer_id": 48345, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>Take a closer look at catched exception. Was it FaultException&lt; FooFault> or FaultException ? There are 2 version of FaultException class: <a href=\"http://msdn.microsoft.com/en-us/library/ms576199.aspx\" rel=\"nofollow noreferrer\">generic</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms576199.aspx\" rel=\"nofollow noreferrer\">non-generic</a></p>\n" }, { "answer_id": 48413, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": -1, "selected": false, "text": "<p>@yapiskan,</p>\n\n<p>C# is a strong typed language Foo&lt; X> != Foo. So if you need to catch some exception, provide <em>exact</em> type in <em>catch</em> clause.</p>\n\n<p>You can learn more on exception handling reading <a href=\"http://msdn.microsoft.com/en-us/library/ms229005.aspx\" rel=\"nofollow noreferrer\">this</a> MSDN article.</p>\n" }, { "answer_id": 284215, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 1, "selected": false, "text": "<p>Actually your exception is caught but you fail to notice it since visual studio highlights the next line, not the line throwing the exception. Replace</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>with some other lines and see them in action.</p>\n" }, { "answer_id": 295188, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": -1, "selected": false, "text": "<p>The problem is that exceptions are checked in the order they are declared. Try putting the Exception catch block first and you will see that the compiler complains: other catch blocks will NEVER be evaluated. The following code is generally what .Net is doing in your case:</p>\n\n<pre><code> // Begin try\n DoSomething(); // throws FaultException&lt;FooFault&gt;\n // End try\n if (exceptionOccured)\n {\n if(exception is FaultException) // FE catch block.\n {\n throw;\n // Goto Exit\n }\n if(exception is Exception) // EX catch block\n {\n throw new FaultException&lt;FooFault&gt;();\n // Goto Exit\n }\n }\n\n // Exit\n</code></pre>\n\n<p>As you can see your FaultException never re-enters the try-catch-finally (i.e. try-catch-finally is not recursive in nature).</p>\n\n<p>Try this instead:</p>\n\n<pre><code> try\n {\n try\n {\n DoSomething(); // throws FaultException&lt;FooFault&gt;\n }\n catch (Exception ex)\n {\n if (ex is FaultException&lt;FooFault&gt;)\n throw;\n else\n myProject.Exception.Throw&lt;FooFault&gt;(ex);\n }\n }\n catch (FaultException)\n {\n throw;\n }\n</code></pre>\n\n<p>HTH.</p>\n" }, { "answer_id": 1872524, "author": "Konamiman", "author_id": 4574, "author_profile": "https://Stackoverflow.com/users/4574", "pm_score": 2, "selected": false, "text": "<p>Are you consuming the WCF service from Silverlight? If so, a special configuration is needed to make the service return a HTTP 200 code instead of 500 in case of error. The details are here: <a href=\"http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx</a></p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract. here is the code below; ``` public void Foo() { try { DoSomething(); // throws FaultException<FooFault> } catch (FaultException) { throw; } catch (Exception ex) { myProject.Exception.Throw<FooFault>(ex); } } ``` in service contract; ``` [FaultException(typeof(FooFault))] void Foo(); ``` when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?
Are you consuming the WCF service from Silverlight? If so, a special configuration is needed to make the service return a HTTP 200 code instead of 500 in case of error. The details are here: <http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx>
48,356
<p>Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:</p> <pre><code>ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. </code></pre> <p>At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?</p> <hr> <p>EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.</p> <hr> <p>EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.</p> <hr> <p>EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.</p> <p>Any help would be appreciated!</p>
[ { "answer_id": 48361, "author": "zappan", "author_id": 4723, "author_profile": "https://Stackoverflow.com/users/4723", "pm_score": 0, "selected": false, "text": "<p>you can't rely on object being garbage collected in C# (i assume you're using c#, based on tagging) if it holds resources like being bound to the network resource like in your example, or holding some other kind of stream, a file stream would be a common example.</p>\n\n<p>you have to assure to release the resources that the object is holding, so that it can be garbage collected. otherwise it won't be garbage collected, but remain living somewhere in the memory. your pseudocode example doesn't provide that you're doing the resources releasing, you just state that the object gets (should get) garbage collected.</p>\n" }, { "answer_id": 48362, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>The garbage collector doesn't guarantee you that the socket will ever be closed. For a complete example read this <a href=\"http://msdn.microsoft.com/en-us/library/fx6588te.aspx\" rel=\"nofollow noreferrer\">MSDN example</a>.</p>\n\n<p>The main point is to actually call <code>Socket.Close()</code> as soon as possible. For example, ClassA could implement <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"nofollow noreferrer\">IDisposable</a> and use it like this:</p>\n\n<pre><code>using (ClassA a = new ClassA()) \n{\n // code goes here\n}\n// 'a' is now disposed and the socket is closed\n</code></pre>\n" }, { "answer_id": 48369, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 0, "selected": false, "text": "<p>The garbage collector runs the finalizer of the object at some indeterminate time.\nYou could implement the IDisposable interface and call the Dispose() method before the object looses Scope - or let the using statement do that for you.</p>\n\n<p>see <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.idisposable.aspx</a> and <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/yh598w02.aspx</a></p>\n\n<p>edit: works fine for me</p>\n\n<pre>\nusing System;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n class ClassA : IDisposable\n {\n protected Socket s;\n public ClassA()\n {\n s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n s.Bind(new IPEndPoint(IPAddress.Any, 5678));\n }\n\n public void Dispose()\n {\n s.Close();\n }\n }\n\n static void Main(string[] args)\n {\n using(ClassA a=new ClassA()) {\n }\n using (ClassA b = new ClassA())\n {\n }\n }\n }\n}\n</pre>\n" }, { "answer_id": 48383, "author": "AlexeyMK", "author_id": 5021, "author_profile": "https://Stackoverflow.com/users/5021", "pm_score": 3, "selected": true, "text": "<p>(this is what finally got everything to work for me)</p>\n\n<p>Make sure EVERY socket that the socket in A connects to has </p>\n\n<pre><code>socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);\n</code></pre>\n\n<p>set upon being initiated. </p>\n" }, { "answer_id": 1497357, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The best solution is to retry to bind the socket a few times (2-3). On the first attempt, if it fails, i have found that it will properly (and permanently) close the original socket.</p>\n\n<p>HTH,</p>\n\n<p>_NT</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this: ``` ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. ``` At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket? --- EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem. --- EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you. --- EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket. Any help would be appreciated!
(this is what finally got everything to work for me) Make sure EVERY socket that the socket in A connects to has ``` socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true); ``` set upon being initiated.
48,426
<p>My gcc build toolchain produces a .map file. How do I display the memory map graphically?</p>
[ { "answer_id": 112078, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 6, "selected": true, "text": "<p>Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the <code>sections</code> and <code>symbols</code> lists).</p>\n\n<p>You can control the script by modifying these lines:</p>\n\n<pre><code>with open('t.map') as f:\ncolors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']\ntotal_height = 32.0\n</code></pre>\n\n<p>map2html.py</p>\n\n<pre><code>from __future__ import with_statement\nimport re\n\nclass Section:\n def __init__(self, address, size, segment, section):\n self.address = address\n self.size = size\n self.segment = segment\n self.section = section\n def __str__(self):\n return self.section+\"\"\n\nclass Symbol:\n def __init__(self, address, size, file, name):\n self.address = address\n self.size = size\n self.file = file\n self.name = name\n def __str__(self):\n return self.name\n\n#===============================\n# Load the Sections and Symbols\n#\nsections = []\nsymbols = []\n\nwith open('t.map') as f:\n in_sections = True\n for line in f:\n m = re.search('^([0-9A-Fx]+)\\s+([0-9A-Fx]+)\\s+((\\[[ 0-9]+\\])|\\w+)\\s+(.*?)\\s*$', line)\n if m:\n if in_sections:\n sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))\n else:\n symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))\n else:\n if len(sections) &gt; 0:\n in_sections = False\n\n\n#===============================\n# Gererate the HTML File\n#\n\ncolors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']\ntotal_height = 32.0\n\nsegments = set()\nfor s in sections: segments.add(s.segment)\nsegment_colors = dict()\ni = 0\nfor s in segments:\n segment_colors[s] = colors[i % len(colors)]\n i += 1\n\ntotal_size = 0\nfor s in symbols:\n total_size += s.size\n\nsections.sort(lambda a,b: a.address - b.address)\nsymbols.sort(lambda a,b: a.address - b.address)\n\ndef section_from_address(addr):\n for s in sections:\n if addr &gt;= s.address and addr &lt; (s.address + s.size):\n return s\n return None\n\nprint \"&lt;html&gt;&lt;head&gt;\"\nprint \" &lt;style&gt;a { color: black; text-decoration: none; font-family:monospace }&lt;/style&gt;\"\nprint \"&lt;body&gt;\"\nprint \"&lt;table cellspacing='1px'&gt;\"\nfor sym in symbols:\n section = section_from_address(sym.address)\n height = (total_height/total_size) * sym.size\n font_size = 1.0 if height &gt; 1.0 else height\n print \"&lt;tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'&gt;&lt;td style='overflow:hidden'&gt;\" % \\\n (segment_colors[section.segment], height, height, font_size)\n print \"&lt;a href='#%s'&gt;%s&lt;/a&gt;\" % (sym.name, sym.name)\n print \"&lt;/td&gt;&lt;/tr&gt;\"\nprint \"&lt;/table&gt;\"\nprint \"&lt;/body&gt;&lt;/html&gt;\"\n</code></pre>\n\n<p>And here's a bad rendering of the HTML it outputs:</p>\n\n<p><img src=\"https://i.imgur.com/jsGhtBn.png\" alt=\"Map\"></p>\n" }, { "answer_id": 35893722, "author": "Sredni", "author_id": 1761205, "author_profile": "https://Stackoverflow.com/users/1761205", "pm_score": 3, "selected": false, "text": "<p>I've written a C# program to display the information in a Map file along with information not usually present in the map file (like static symbols provided you can use <code>binutils</code>). The code is available <a href=\"https://github.com/govind-mukundan/MapViewer\" rel=\"nofollow noreferrer\">here</a>. In short it parses the map file and also uses <code>BINUTILS</code> (if available) to gather more information. To run it you need to download the code and run the project under visual studio, browse to the map file path and click <code>Analyze</code>.</p>\n\n<p>Note: Only works for <code>GCC/LD</code> map files</p>\n\n<p>Screenshot:\n[<img src=\"https://i.stack.imgur.com/W9uZ9.png\" alt=\"3]\"></p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
My gcc build toolchain produces a .map file. How do I display the memory map graphically?
Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the `sections` and `symbols` lists). You can control the script by modifying these lines: ``` with open('t.map') as f: colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 ``` map2html.py ``` from __future__ import with_statement import re class Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+"" class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name #=============================== # Load the Sections and Symbols # sections = [] symbols = [] with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) > 0: in_sections = False #=============================== # Gererate the HTML File # colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 segments = set() for s in sections: segments.add(s.segment) segment_colors = dict() i = 0 for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1 total_size = 0 for s in symbols: total_size += s.size sections.sort(lambda a,b: a.address - b.address) symbols.sort(lambda a,b: a.address - b.address) def section_from_address(addr): for s in sections: if addr >= s.address and addr < (s.address + s.size): return s return None print "<html><head>" print " <style>a { color: black; text-decoration: none; font-family:monospace }</style>" print "<body>" print "<table cellspacing='1px'>" for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height > 1.0 else height print "<tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'><td style='overflow:hidden'>" % \ (segment_colors[section.segment], height, height, font_size) print "<a href='#%s'>%s</a>" % (sym.name, sym.name) print "</td></tr>" print "</table>" print "</body></html>" ``` And here's a bad rendering of the HTML it outputs: ![Map](https://i.imgur.com/jsGhtBn.png)
48,432
<p>Being relatively new to the .net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? </p> <p>For a specific example of a project I'm working on : a list of unique id / name pairs are being retrieved from a remote web-service.</p> <ul> <li>this list will change infrequently (once per day), </li> <li>will be read-only from the point of view of the application where it is being used</li> <li>will be stored at the application level for all requests to access</li> </ul> <p>Given those points, I plan to store the returned values at the application level in a singleton class.</p> <p>My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id:</p> <pre><code>sugarsoap soapService = new sugarsoap(); branch_summary[] branchList = soapService.getBranches(); foreach (branch_summary aBranch in branchList) { branchNameList.Add(aBranch.id, aBranch.name); } </code></pre> <p>The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved:</p> <pre><code>public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = from b in branchList where b.id == branchId select b; return branch_summary.name; } </code></pre> <p>Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance.</p>
[ { "answer_id": 48476, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 0, "selected": false, "text": "<p>I'm not sure a singleton class is absolutely necessary, do you absolutely need global access at all times? Is the list large? </p>\n\n<p>I assume you will have a refresh method on the singleton class for when the properties need to change and also that you have some way of notifying the singleton to update when the list changes.</p>\n\n<p>Both solutions are viable. I think LINQ will populate the collection faster in the constructor (but not noticeably faster). Traditional collection based approaches are fine. Personally, I would choose the LINQ version if only because it is new tech and I like to use it. Assuming your deployment environment has .NET 3.5...</p>\n\n<p>Do you have a method on your webservice for getting branches by Id? That would be the third option if the branch info is needed infrequently.</p>\n" }, { "answer_id": 48545, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 3, "selected": true, "text": "<p>i dont think the linq you wrote would compile, it'd have to be</p>\n\n<pre><code>public string branchName (string branchId) \n{\n //branchList populated in the constructor\n branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault();\n return branch_summary == null ? null : branch_summary.name;\n}\n</code></pre>\n\n<p>note the .FirstsOrDefault()</p>\n\n<p>I'd rather use LINQ for the reason that it can be used in other places, for writing more complex filters on your data. I also think it's easier to read than NameValueCollection alternative.</p>\n\n<p>that's my $0.02</p>\n" }, { "answer_id": 1130367, "author": "Sam Harwell", "author_id": 138304, "author_profile": "https://Stackoverflow.com/users/138304", "pm_score": 1, "selected": false, "text": "<p>In general, your simple one-line for/foreach loop will be faster than using Linq. Also, Linq doesn't [always] offer significant readability improvements in this case. Here is the general rule I code by:</p>\n\n<p>If the algorithm is simple enough to write and maintain without Linq, and you don't need delayed evaluation, <em>and</em> Linq doesn't offer sufficient maintainability improvements, then don't use it. However, there are times where Linq <em>immensely</em> improves the readability and correctness of your code, as shown in two examples I posted <a href=\"http://blog.280z28.org/archives/2008/10/20/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://blog.280z28.org/archives/2008/10/24/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 12652310, "author": "SimpleVar", "author_id": 1282539, "author_profile": "https://Stackoverflow.com/users/1282539", "pm_score": 0, "selected": false, "text": "<p>Shortened and workified:</p>\n\n<pre><code>public string BranchName(string branchId) \n{\n var bs = branchList.FirstOrDefault(b =&gt; b.Id == branchId);\n\n return bs == null ? null : bs.Name;\n}\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4396/" ]
Being relatively new to the .net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? For a specific example of a project I'm working on : a list of unique id / name pairs are being retrieved from a remote web-service. * this list will change infrequently (once per day), * will be read-only from the point of view of the application where it is being used * will be stored at the application level for all requests to access Given those points, I plan to store the returned values at the application level in a singleton class. My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id: ``` sugarsoap soapService = new sugarsoap(); branch_summary[] branchList = soapService.getBranches(); foreach (branch_summary aBranch in branchList) { branchNameList.Add(aBranch.id, aBranch.name); } ``` The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved: ``` public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = from b in branchList where b.id == branchId select b; return branch_summary.name; } ``` Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance.
i dont think the linq you wrote would compile, it'd have to be ``` public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault(); return branch_summary == null ? null : branch_summary.name; } ``` note the .FirstsOrDefault() I'd rather use LINQ for the reason that it can be used in other places, for writing more complex filters on your data. I also think it's easier to read than NameValueCollection alternative. that's my $0.02
48,458
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="noreferrer">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="noreferrer">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="noreferrer">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
[ { "answer_id": 48467, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 1, "selected": false, "text": "<p>I am not entirely up to date on the latest best practices, et cetera when it comes to code layout, but when I did my first GAE application, I used something along your second option, where the code and templates are next to eachother.</p>\n\n<p>There was two reasons for this - one, it kept the code and template nearby, and secondly, I had the directory structure layout mimic that of the website - making it (for me) a bit easier too remember where everything was.</p>\n" }, { "answer_id": 67533, "author": "Jiayao Yu", "author_id": 10289, "author_profile": "https://Stackoverflow.com/users/10289", "pm_score": 3, "selected": false, "text": "<p>I think the first option is considered the best practice. And make the code folder your first package. The Rietveld project developed by Guido van Rossum is a very good model to learn from. Have a look at it: <a href=\"http://code.google.com/p/rietveld\" rel=\"nofollow noreferrer\">http://code.google.com/p/rietveld</a></p>\n\n<p>With regard to Django 1.0, I suggest you start using the Django trunk code instead of the GAE built in django port. Again, have a look at how it's done in Rietveld.</p>\n" }, { "answer_id": 70271, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 8, "selected": true, "text": "<p>First, I would suggest you have a look at \"<a href=\"http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine\" rel=\"noreferrer\">Rapid Development with Python, Django, and Google App Engine</a>\"</p>\n\n<p>GvR describes a general/standard project layout on page 10 of his <a href=\"http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine/rapid_development_with_django_gae.pdf?attredirects=0\" rel=\"noreferrer\">slide presentation</a>. </p>\n\n<p>Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty.</p>\n\n<h2>Boilerplate files</h2>\n\n<ul>\n<li>These hardly vary between projects</li>\n<li>app.yaml: direct all non-static requests to main.py </li>\n<li>main.py: initialize app and send it all requests </li>\n</ul>\n\n<h2>Project lay-out</h2>\n\n<ul>\n<li>static/*: static files; served directly by App Engine</li>\n<li>myapp/*.py: app-specific python code\n\n<ul>\n<li>views.py, models.py, tests.py, __init__.py, and more</li>\n</ul></li>\n<li>templates/*.html: templates (or myapp/templates/*.html)</li>\n</ul>\n\n<p>Here are some code examples that may help as well:</p>\n\n<h2>main.py</h2>\n\n<pre><code>import wsgiref.handlers\n\nfrom google.appengine.ext import webapp\nfrom myapp.views import *\n\napplication = webapp.WSGIApplication([\n ('/', IndexHandler),\n ('/foo', FooHandler)\n], debug=True)\n\ndef main():\n wsgiref.handlers.CGIHandler().run(application)\n</code></pre>\n\n<h2>myapp/views.py</h2>\n\n<pre><code>import os\nimport datetime\nimport logging\nimport time\n\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom models import *\n\nclass IndexHandler(webapp.RequestHandler):\n def get(self):\n date = \"foo\"\n # Do some processing \n template_values = {'data': data }\n path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html')\n self.response.out.write(template.render(path, template_values))\n\nclass FooHandler(webapp.RequestHandler):\n def get(self):\n #logging.debug(\"start of handler\")\n</code></pre>\n\n<h2>myapp/models.py</h2>\n\n<pre><code>from google.appengine.ext import db\n\nclass SampleModel(db.Model):\n</code></pre>\n\n<p>I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like:</p>\n\n<h2>Project lay-out</h2>\n\n<ul>\n<li>static/: static files; served directly by App Engine\n\n<ul>\n<li>js/*.js</li>\n<li>images/*.gif|png|jpg</li>\n<li>css/*.css</li>\n</ul></li>\n<li>myapp/: app structure\n\n<ul>\n<li>models/*.py</li>\n<li>views/*.py</li>\n<li>tests/*.py</li>\n<li>templates/*.html: templates</li>\n</ul></li>\n</ul>\n" }, { "answer_id": 153862, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 4, "selected": false, "text": "<p>My usual layout looks something like this:</p>\n\n<ul>\n<li>app.yaml</li>\n<li>index.yaml</li>\n<li>request.py - contains the basic WSGI app</li>\n<li>lib\n\n<ul>\n<li><code>__init__.py</code> - common functionality, including a request handler base class</li>\n</ul></li>\n<li>controllers - contains all the handlers. request.yaml imports these.</li>\n<li>templates\n\n<ul>\n<li>all the django templates, used by the controllers</li>\n</ul></li>\n<li>model\n\n<ul>\n<li>all the datastore model classes</li>\n</ul></li>\n<li>static\n\n<ul>\n<li>static files (css, images, etc). Mapped to /static by app.yaml</li>\n</ul></li>\n</ul>\n\n<p>I can provide examples of what my app.yaml, request.py, lib/<strong>init</strong>.py, and sample controllers look like, if this isn't clear.</p>\n" }, { "answer_id": 3105295, "author": "systempuntoout", "author_id": 130929, "author_profile": "https://Stackoverflow.com/users/130929", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"http://webpy.org/\" rel=\"nofollow noreferrer\">webpy</a> so I've adopted it as templating framework on Google App Engine.<br>\nMy package folders are typically organized like this:</p>\n\n<pre><code>app.yaml\napplication.py\nindex.yaml\n/app\n /config\n /controllers\n /db\n /lib\n /models\n /static\n /docs\n /images\n /javascripts\n /stylesheets\n test/\n utility/\n views/\n</code></pre>\n\n<p><a href=\"http://github.com/systempuntoout/stackprinter\" rel=\"nofollow noreferrer\">Here</a> is an example.</p>\n" }, { "answer_id": 12535000, "author": "sunil", "author_id": 278681, "author_profile": "https://Stackoverflow.com/users/278681", "pm_score": 4, "selected": false, "text": "<p>I implemented a google app engine boilerplate today and checked it on github. This is along the lines described by Nick Johnson above (who used to work for Google).</p>\n\n<p>Follow this link <a href=\"https://github.com/droot/gae-boilerplate\">gae-boilerplate</a></p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: * Main Level contains: + all .py files (didn't know how to make packages work) + all .html templates for main level pages * Subdirectories: + separate folders for css, images, js, etc. + folders that hold .html templates for subdirecty-type urls Example: <http://www.bowlsk.com/> maps to HomePage (default package), template at "index.html" <http://www.bowlsk.com/games/view-series.html?series=7130> maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: * Main Folder containing: appdef, indexes, main.py? + Subfolder for code. Does this have to be my first package? + Subfolder for templates. Folder heirarchy would match package heirarchy + Individual subfolders for css, images, js, etc. * Main Folder containing appdef, indexes, main.py? + Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.
First, I would suggest you have a look at "[Rapid Development with Python, Django, and Google App Engine](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine)" GvR describes a general/standard project layout on page 10 of his [slide presentation](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine/rapid_development_with_django_gae.pdf?attredirects=0). Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an \_\_init\_\_.py file. It's ok if its empty. Boilerplate files ----------------- * These hardly vary between projects * app.yaml: direct all non-static requests to main.py * main.py: initialize app and send it all requests Project lay-out --------------- * static/\*: static files; served directly by App Engine * myapp/\*.py: app-specific python code + views.py, models.py, tests.py, \_\_init\_\_.py, and more * templates/\*.html: templates (or myapp/templates/\*.html) Here are some code examples that may help as well: main.py ------- ``` import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) ``` myapp/views.py -------------- ``` import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") ``` myapp/models.py --------------- ``` from google.appengine.ext import db class SampleModel(db.Model): ``` I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like: Project lay-out --------------- * static/: static files; served directly by App Engine + js/\*.js + images/\*.gif|png|jpg + css/\*.css * myapp/: app structure + models/\*.py + views/\*.py + tests/\*.py + templates/\*.html: templates
48,470
<p>Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says:</p> <blockquote> <p>Visual Studio .NET macros</p> <p>To stop the macro from running, double-click the spinning cassette.<br> Click here to not show this balloon again.</p> </blockquote> <p>I have trouble clicking the balloon because my macro runs so quickly.</p> <p>Is this controllable by some dialog box option?</p> <p>(I found someone else asking this question on <a href="http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.ide/2005-11/msg00267.html" rel="noreferrer">some other site</a> but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)</p>
[ { "answer_id": 48478, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 2, "selected": false, "text": "<p>Okay, I found a way to make the balloon clickable, and clicking it does indeed stop it from popping up again. (On the other site I referenced in the original question the question asker claims that this is not the case. Though he was in VS2005 and I'm using VS2008.)</p>\n\n<p>Anyway, I inserted a pause line in the macro so it would run for long enough for me to click the balloon:</p>\n\n<pre><code>System.Threading.Thread.Sleep(2000)\n</code></pre>\n\n<p>It would still be nice to know if there's a dialog somewhere for turning this back on, in case I have a crazy change of heart.</p>\n" }, { "answer_id": 296494, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>This will disable the pop up:</p>\n\n<p>For Visual Studio 2008:</p>\n\n<pre>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\8.0<br>\nDWORD DontShowMacrosBalloon=6</pre>\n\n<p>For Visual Studio 2010 (the DWORD won't be there by default, use <code>New | DWORD value</code> to create it):</p>\n\n<pre>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\10.0<br>\nDWORD DontShowMacrosBalloon=6</pre>\n\n<p>Delete the same key to re-enable it.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says: > > Visual Studio .NET macros > > > To stop the macro from running, double-click the spinning cassette. > > Click here to not show this balloon again. > > > I have trouble clicking the balloon because my macro runs so quickly. Is this controllable by some dialog box option? (I found someone else asking this question on [some other site](http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.ide/2005-11/msg00267.html) but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)
This will disable the pop up: For Visual Studio 2008: ``` HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0 DWORD DontShowMacrosBalloon=6 ``` For Visual Studio 2010 (the DWORD won't be there by default, use `New | DWORD value` to create it): ``` HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0 DWORD DontShowMacrosBalloon=6 ``` Delete the same key to re-enable it.
48,474
<p>I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues.</p> <p>I just want to position overlapping images relative to one another.</p> <p>As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.</p>
[ { "answer_id": 48482, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 3, "selected": false, "text": "<p>The easy way to do it is to use background-image then just put an &lt;img&gt; in that element.</p>\n\n<p>The other way to do is using css layers. There is a ton a resources available to help you with this, just search for <a href=\"http://www.google.com/search?q=css+layers\" rel=\"noreferrer\">css layers</a>.</p>\n" }, { "answer_id": 48484, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 6, "selected": false, "text": "<p>This is a barebones look at what I've done to float one image over another.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {\n position: absolute;\n top: 25px;\n left: 25px;\n}\n.imgA1 {\n z-index: 1;\n}\n.imgB1 {\n z-index: 3;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;img class=\"imgA1\" src=\"https://via.placeholder.com/200/333333\"&gt;\n&lt;img class=\"imgB1\" src=\"https://via.placeholder.com/100\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"http://www.webmasterworld.com/css/3193750.htm\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 48530, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 5, "selected": false, "text": "<p>Here's code that may give you ideas:</p>\n\n<pre><code>&lt;style&gt;\n.containerdiv { float: left; position: relative; } \n.cornerimage { position: absolute; top: 0; right: 0; } \n&lt;/style&gt;\n\n&lt;div class=\"containerdiv\"&gt;\n &lt;img border=\"0\" src=\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\" alt=\"\"\"&gt;\n &lt;img class=\"cornerimage\" border=\"0\" src=\"http://www.gravatar.com/avatar/\" alt=\"\"&gt;\n&lt;div&gt;\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/xj14v0nj/\" rel=\"noreferrer\">JSFiddle</a></p>\n\n<p>I suspect that <a href=\"https://stackoverflow.com/questions/48474#48484\">Espo's solution</a> may be inconvenient because it requires you to position both images absolutely. You may want the first one to position itself in the flow.</p>\n\n<p>Usually, there is a natural way to do that is CSS. You put position: relative on the container element, and then absolutely position children inside it. Unfortunately, you cannot put one image inside another. That's why I needed container div. Notice that I made it a float to make it autofit to its contents. Making it display: inline-block should theoretically work as well, but browser support is poor there.</p>\n\n<p>EDIT: I deleted size attributes from the images to illustrate my point better. If you want the container image to have its default sizes and you don't know the size beforehand, you cannot use the <a href=\"https://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html#48482\">background trick</a>. If you do, it is a better way to go. </p>\n" }, { "answer_id": 48531, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>Inline style only for clarity here. Use a real CSS stylesheet.</p>\n\n<pre><code>&lt;!-- First, your background image is a DIV with a background \n image style applied, not a IMG tag. --&gt;\n&lt;div style=\"background-image:url(YourBackgroundImage);\"&gt;\n &lt;!-- Second, create a placeholder div to assist in positioning \n the other images. This is relative to the background div. --&gt;\n &lt;div style=\"position: relative; left: 0; top: 0;\"&gt;\n &lt;!-- Now you can place your IMG tags, and position them relative \n to the container we just made --&gt; \n &lt;img src=\"YourForegroundImage\" style=\"position: relative; top: 0; left: 0;\"/&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 48533, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p>@buti-oxa: Not to be pedantic, but your code is invalid. The HTML <code>width</code> and <code>height</code> attributes do not allow for units; you're likely thinking of the CSS <code>width:</code> and <code>height:</code> properties. You should also provide a content-type (<code>text/css</code>; see Espo's code) with the <code>&lt;style&gt;</code> tag.</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt; \n.containerdiv { float: left; position: relative; } \n.cornerimage { position: absolute; top: 0; right: 0; } \n&lt;/style&gt;\n\n&lt;div class=\"containerdiv\"&gt;\n &lt;img border=\"0\" src=\"http://www.gravatar.com/avatar/\" alt=\"\" width=\"100\" height=\"100\"&gt;\n &lt;img class=\"cornerimage\" border=\"0\" src=\"http://www.gravatar.com/avatar/\" alt=\"\" width=\"40\" height=\"40\"&gt;\n&lt;div&gt;\n</code></pre>\n\n<p>Leaving <code>px;</code> in the <code>width</code> and <code>height</code> attributes might cause a rendering engine to balk.</p>\n" }, { "answer_id": 1997397, "author": "rrichter", "author_id": 5038, "author_profile": "https://Stackoverflow.com/users/5038", "pm_score": 10, "selected": true, "text": "<p>Ok, after some time, here's what I landed on:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.parent {\n position: relative;\n top: 0;\n left: 0;\n}\n.image1 {\n position: relative;\n top: 0;\n left: 0;\n border: 1px red solid;\n}\n.image2 {\n position: absolute;\n top: 30px;\n left: 30px;\n border: 1px green solid;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"parent\"&gt;\n &lt;img class=\"image1\" src=\"https://via.placeholder.com/50\" /&gt;\n &lt;img class=\"image2\" src=\"https://via.placeholder.com/100\" /&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>As the simplest solution. That is:</p>\n<p>Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.</p>\n" }, { "answer_id": 8306607, "author": "Wez", "author_id": 1070683, "author_profile": "https://Stackoverflow.com/users/1070683", "pm_score": 4, "selected": false, "text": "<p>One issue I noticed that could cause errors is that in rrichter's answer, the code below:</p>\n\n<pre><code>&lt;img src=\"b.jpg\" style=\"position: absolute; top: 30; left: 70;\"/&gt;\n</code></pre>\n\n<p>should include the px units within the style eg.</p>\n\n<pre><code>&lt;img src=\"b.jpg\" style=\"position: absolute; top: 30px; left: 70px;\"/&gt;\n</code></pre>\n\n<p>Other than that, the answer worked fine. Thanks.</p>\n" }, { "answer_id": 14434582, "author": "Danield", "author_id": 703717, "author_profile": "https://Stackoverflow.com/users/703717", "pm_score": 3, "selected": false, "text": "<p>You can absolutely position <code>pseudo elements</code> relative to their parent element.</p>\n\n<p>This gives you two extra layers to play with for every element - so positioning one image on top of another becomes easy - with minimal and semantic markup (no empty divs etc).</p>\n\n<p>markup:</p>\n\n<pre><code>&lt;div class=\"overlap\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>css:</p>\n\n<pre><code>.overlap\n{\n width: 100px;\n height: 100px;\n position: relative;\n background-color: blue;\n}\n.overlap:after\n{\n content: '';\n position: absolute;\n width: 20px;\n height: 20px;\n top: 5px;\n left: 5px;\n background-color: red;\n}\n</code></pre>\n\n<p>Here's a <a href=\"http://jsfiddle.net/danield770/nFvUu/3/\" rel=\"noreferrer\"><strong>LIVE DEMO</strong></a></p>\n" }, { "answer_id": 51639228, "author": "Elkin Angulo", "author_id": 5618571, "author_profile": "https://Stackoverflow.com/users/5618571", "pm_score": 3, "selected": false, "text": "<p>It may be a little late but for this you can do:</p>\n\n<p><a href=\"https://i.stack.imgur.com/uyctb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uyctb.png\" alt=\"enter image description here\"></a></p>\n\n<p>HTML</p>\n\n<pre><code>&lt;!-- html --&gt;\n&lt;div class=\"images-wrapper\"&gt;\n &lt;img src=\"images/1\" alt=\"image 1\" /&gt;\n &lt;img src=\"images/2\" alt=\"image 2\" /&gt;\n &lt;img src=\"images/3\" alt=\"image 3\" /&gt;\n &lt;img src=\"images/4\" alt=\"image 4\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>SASS</p>\n\n<pre><code>// In _extra.scss\n$maxImagesNumber: 5;\n\n.images-wrapper {\n img {\n position: absolute;\n padding: 5px;\n border: solid black 1px;\n }\n\n @for $i from $maxImagesNumber through 1 {\n :nth-child(#{ $i }) {\n z-index: #{ $maxImagesNumber - ($i - 1) };\n left: #{ ($i - 1) * 30 }px;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 60033524, "author": "Pallavi Singh", "author_id": 12818184, "author_profile": "https://Stackoverflow.com/users/12818184", "pm_score": 0, "selected": false, "text": "<p>Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.</p>\n" }, { "answer_id": 67323791, "author": "Howdy", "author_id": 2246369, "author_profile": "https://Stackoverflow.com/users/2246369", "pm_score": 1, "selected": false, "text": "<p>Set background-size cover. Then wrap your div with another div now set max-width on parent div.</p>\n<pre><code>&lt;div style=&quot;max-width:100px&quot;&gt;\n &lt;div style=&quot;background-image:url('/image.png'); background-size: cover; height:100px; width:100px; &quot;&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 68994219, "author": "Fzum", "author_id": 7449607, "author_profile": "https://Stackoverflow.com/users/7449607", "pm_score": 2, "selected": false, "text": "<p>You could use <strong>CSS-Grid</strong>, which is a very convenient solution if you want to <strong>stack, overlap</strong> content. First you need to define your grid. Inside that grid, you &quot;tell&quot; your img-tags where to be places within that grid. If you define them to be at the same start of the grid, they will be overlapped. In the following example two images are overlapped, one is below them.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div style=\"display: grid; grid-template-columns: [first-col] 100%; grid-template-rows: [first-row] 300px\"&gt;\n &lt;img src=\"https://fakeimg.pl/300/\" style=\"grid-column-start: first-col; grid-row-start: first-row\"&gt;\n &lt;img src=\"https://fakeimg.pl/300/\" style=\"grid-column-start: first-col; grid-row-start: first-row\"&gt;\n &lt;img src=\"https://fakeimg.pl/300/\"&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can find a very good explanation of CSS-Grid <a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 72413713, "author": "John Chidi", "author_id": 13283577, "author_profile": "https://Stackoverflow.com/users/13283577", "pm_score": 1, "selected": false, "text": "<p>Here is a solution that worked for me. Assuming all the images to be stacked are inside a div container, all you need to do is to set the <strong>display</strong> property of the div to <strong>flex</strong>. Don't set any position for the first image but for every other image, set the <strong>position</strong> property to <strong>absolute</strong>. Finally, use z-index to control the layers. You can set the first image's z-index to 1, the second image's z-index to 2, and so on (In my own case, I set the z-index of every other image apart from the first image to 2). If you want to center the images, you can set the <strong>justify-content</strong> property of the div to <strong>center</strong> to align the images horizontally to the center and adjust the <strong>top</strong> property to align the images vertically to the center. The values you use for the justify-content and top properties depend on the size of your images and whether the sizes are responsive on different devices or not.\nHere's my example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {\n border: 2px solid red;\n}\n\n.img1n2 {\n display: flex; \n justify-content:center;\n}\n\n.img1 {\n z-index: 1;\n}\n\n.img2 {\n position: absolute; \n z-index: 2;\n top: 52.5%;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"img1n2\"&gt;\n &lt;img class=\"img1\" src=\"https://fakeimg.pl/400/\"&gt;\n &lt;img class=\"img2\" src=\"https://fakeimg.pl/300/\" width=\"100\"&gt;\n &lt;img class=\"img2\" src=\"https://fakeimg.pl/200/\" width=\"50\"&gt;\n &lt;img class=\"img2\" src=\"https://fakeimg.pl/50/\" width=\"30\"&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can actually stack a thousand or a million images with this method. You can play around with the CSS to suit your specific needs. Happy coding!</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5038/" ]
I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues. I just want to position overlapping images relative to one another. As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.
Ok, after some time, here's what I landed on: ```css .parent { position: relative; top: 0; left: 0; } .image1 { position: relative; top: 0; left: 0; border: 1px red solid; } .image2 { position: absolute; top: 30px; left: 30px; border: 1px green solid; } ``` ```html <div class="parent"> <img class="image1" src="https://via.placeholder.com/50" /> <img class="image2" src="https://via.placeholder.com/100" /> </div> ``` As the simplest solution. That is: Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
48,491
<p>I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run:</p> <pre><code>$ rsync --remove-source-files speed:/var/crawldir . </code></pre> <p>but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions?</p>
[ { "answer_id": 48500, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "<p>How much control do you have over the download process? If you roll your own, you can have the file being downloaded go to a temp directory or have a temporary name until it's finished downloading, and then mv it to the correct name when it's done. If you're using third party software, then you don't have as much control, but you still might be able to do the temp directory thing.</p>\n" }, { "answer_id": 48517, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>It seems to me the problem is <em>transferring</em> a file before it's complete, not that you're deleting it.</p>\n\n<p>If this is Linux, it's possible for a file to be open by process A and process B can unlink the file. There's no error, but of course A is wasting its time. Therefore, the fact that rsync deletes the source file is not a problem.</p>\n\n<p>The problem is rsync deletes the source file only after it's copied, and if it's still being written to disk you'll have a partial file.</p>\n\n<p>How about this: Mount <code>mass</code> as a remote file system (NFS would work) in <code>speed</code>. Then just web-crawl the files directly.</p>\n" }, { "answer_id": 48628, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 2, "selected": false, "text": "<p>Rsync can exclude files matching certain patters. Even if you can't modify it to make it download files to a temporary directory, maybe it has a convention of naming the files differently during download (for example: <code>foo.downloading</code> while downloading for a file named <code>foo</code>) and you can use this property to exclude files which are still being downloaded from being copied.</p>\n" }, { "answer_id": 93280, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>If you have control over the crawling process, or it has predictable output, the above solutions (storing in a tempfile until finished, then mv'ing to the completed-downloads place, or ignoring files with a '.downloading' kind of name) might work. If all of that is beyond your control, you can make sure that the file is not opened by any process by doing 'lsof $filename' and checking if there's a result. Clearly if no one has the file open, it's safe to move it over. </p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4300/" ]
I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run: ``` $ rsync --remove-source-files speed:/var/crawldir . ``` but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions?
How much control do you have over the download process? If you roll your own, you can have the file being downloaded go to a temp directory or have a temporary name until it's finished downloading, and then mv it to the correct name when it's done. If you're using third party software, then you don't have as much control, but you still might be able to do the temp directory thing.
48,497
<p>The following XHTML code is not working:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="/dojotoolkit/dijit/themes/tundra/tundra.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="/dojotoolkit/dojo/resources/dojo.css" /&gt; &lt;script type="text/javascript" src="/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true" /&gt; &lt;script type="text/javascript"&gt; dojo.require("dijit.form.ValidationTextBox"); dojo.require("dojo.parser"); &lt;/script&gt; &lt;/head&gt; &lt;body class="nihilo"&gt; &lt;input type="text" dojoType="dijit.form.ValidationTextBox" size="30" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In Firebug I get the following error message:</p> <blockquote> <p>[Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMNSHTMLElement.innerHTML]" nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame :: <a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> :: anonymous :: line 319" data: no] <a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> Line 319</p> </blockquote> <p>Any idea what is wrong?</p>
[ { "answer_id": 48552, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 0, "selected": false, "text": "<p>Well, what is dojo.js doing at line 319?</p>\n" }, { "answer_id": 48554, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 1, "selected": false, "text": "<p>Where you import dojo.js:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/dojotoolkit/dojo/dojo.js\" djConfig=\"parseOnLoad: true\"/&gt;\n</code></pre>\n\n<p>It should be:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/dojotoolkit/dojo/dojo.js\" djConfig=\"parseOnLoad:true\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Have fun with dojo, it's can do some cool stuff.</p>\n\n<p>Brian Gianforcaro</p>\n" }, { "answer_id": 48895, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 0, "selected": false, "text": "<p>Are you sure your pointing to the right path in the script tags?</p>\n\n<p>I put it up on the web, check it out.</p>\n\n<p>The left is Dojo parsed input, the right is an regular old input. \n<a href=\"http://tncrocks.com/test/stackoverflow/\" rel=\"nofollow noreferrer\">Link</a></p>\n\n<p>I'm on OS X, using firefox 3.0.1 I get no errors under firebug. </p>\n" }, { "answer_id": 49259, "author": "simon", "author_id": 4875, "author_profile": "https://Stackoverflow.com/users/4875", "pm_score": 2, "selected": false, "text": "<p>The problem seams to be the ending of the file...</p>\n\n<ul>\n<li>If I name the file <a href=\"http://www.tasix.ch/Greter/test2.html\" rel=\"nofollow noreferrer\">test2.html</a> everything works.</li>\n<li>If I name the file <a href=\"http://www.tasix.ch/Greter/test2.xhtml\" rel=\"nofollow noreferrer\">test2.xhtml</a> I get the error message.</li>\n</ul>\n\n<p>The diverence between the two seams to be the Content-Type in the response header from apache.</p>\n\n<ul>\n<li>For .html it is Content-Type text/html; charset=ISO-8859-1</li>\n<li>For .xhtml it is Content-Type application/xhtml+xml</li>\n</ul>\n" }, { "answer_id": 289725, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 0, "selected": false, "text": "<p>There are some similar tickets on the dojo trac page:</p>\n\n<p><a href=\"http://trac.dojotoolkit.org/search?q=xhtml+ns_error&amp;noquickjump=1&amp;ticket=on\" rel=\"nofollow noreferrer\">http://trac.dojotoolkit.org/search?q=xhtml+ns_error&amp;noquickjump=1&amp;ticket=on</a></p>\n\n<p>Probably you are facing a bug and you will need to fill a new ticket.</p>\n" }, { "answer_id": 319678, "author": "nsdel", "author_id": 40807, "author_profile": "https://Stackoverflow.com/users/40807", "pm_score": 1, "selected": false, "text": "<p>The problem is that innerHTML is an unofficial property that is not part of the W3C specifications, and thus may or may not work depending upon the browser, especially when the page is being rendered as a XHTML file rather than a HTML file. See <a href=\"http://domscripting.com/blog/display/35\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_in_xh.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4875/" ]
The following XHTML code is not working: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="/dojotoolkit/dijit/themes/tundra/tundra.css" /> <link rel="stylesheet" type="text/css" href="/dojotoolkit/dojo/resources/dojo.css" /> <script type="text/javascript" src="/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true" /> <script type="text/javascript"> dojo.require("dijit.form.ValidationTextBox"); dojo.require("dojo.parser"); </script> </head> <body class="nihilo"> <input type="text" dojoType="dijit.form.ValidationTextBox" size="30" /> </body> </html> ``` In Firebug I get the following error message: > > [Exception... "Component returned failure code: 0x80004003 > (NS\_ERROR\_INVALID\_POINTER) [nsIDOMNSHTMLElement.innerHTML]" nsresult: > "0x80004003 (NS\_ERROR\_INVALID\_POINTER)" location: "JS frame :: > <http://localhost:21000/dojotoolkit/dojo/dojo.js> :: anonymous :: line > 319" data: no] <http://localhost:21000/dojotoolkit/dojo/dojo.js> Line > 319 > > > Any idea what is wrong?
The problem seams to be the ending of the file... * If I name the file [test2.html](http://www.tasix.ch/Greter/test2.html) everything works. * If I name the file [test2.xhtml](http://www.tasix.ch/Greter/test2.xhtml) I get the error message. The diverence between the two seams to be the Content-Type in the response header from apache. * For .html it is Content-Type text/html; charset=ISO-8859-1 * For .xhtml it is Content-Type application/xhtml+xml
48,521
<p>I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?</p> <p>The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.</p>
[ { "answer_id": 48522, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "<p>Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.</p>\n\n<p>So to do this, just wrap your single object in an IEnumerable.</p>\n\n<p>Even this would work:</p>\n\n<pre><code>DataBindObject.DataSource = new List&lt;YourObject&gt;().Add(YourObjectInstance);\n</code></pre>\n" }, { "answer_id": 48523, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>In ASP.NET2.0 you can use the generic collections to make this single object\na list of only one object in it that you can databind to any server control\nusing the objectdatasource, e.g.</p>\n\n<pre><code>List&lt;clsScannedDriverLicense&gt; DriverLicenses = new\nList&lt;clsScannedDriverLicense&gt;();\n//this creates a generic collection for you that you can return from\n//your BLL to the ObjectDataSource\nDriverLicenses.Add(TheOneObjectThatYouHaveofType_c lsDriverLicense);\n</code></pre>\n\n<p>Then your ObjectDataSource would look like that:</p>\n\n<pre><code>&lt;asp:ObjectDataSource ID=\"odsDL\" runat=\"server\"\nSelectMethod=\"OrdersByCustomer\"\nTypeName=\"YourBLL.UtiltiesClassName\"\nDataObjectTypeName=\"clsScannedDriverLicense\"&gt;\n&lt;/asp:ObjectDataSource&gt;\n</code></pre>\n\n<p><a href=\"http://www.velocityreviews.com/forums/t122605-can-you-still-databind-to-a-single-object-in-asp-net-20.html\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 48595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I don't think you have much choice other than using an class that implements IEnumerable&lt;T&gt;. Even if the DataSource property was smart enough to take a scalar object, it would probably convert it internally to a vector.</p>\n\n<p>I would however consider using a simple array rather than a List&lt;T&gt; as this will result in fewer memory allocations. If you don't like the array syntax (and also to increase readability) you could use a helper method:</p>\n\n<p>T[] DataSourceHelper::ToVector(T scalar) {\n return new T[] { scalar };\n }</p>\n" }, { "answer_id": 2869610, "author": "Jason Kleban", "author_id": 162273, "author_profile": "https://Stackoverflow.com/users/162273", "pm_score": 1, "selected": false, "text": "<p>I'm after the same thing you are. I've posted a new question <a href=\"https://stackoverflow.com/questions/2854234/two-way-databinding-of-a-custom-templated-asp-net-control\">Two-way databinding of a custom templated asp.net control</a> that has a bit of a lead. See what you can make of it...</p>\n" }, { "answer_id": 3326610, "author": "Francisco Aquino", "author_id": 187126, "author_profile": "https://Stackoverflow.com/users/187126", "pm_score": 0, "selected": false, "text": "<p>Using this in my formView:</p>\n\n<pre><code>databoundControl.DataSource = new [] { singleObject };\ndataboundControl.DataBind();\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ? The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.
Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does. So to do this, just wrap your single object in an IEnumerable. Even this would work: ``` DataBindObject.DataSource = new List<YourObject>().Add(YourObjectInstance); ```
48,526
<p>I've been looking into different web statistics programs for my site, and one promising one is <a href="http://www.hping.org/visitors/" rel="nofollow noreferrer">Visitors</a>. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's <a href="http://us.php.net/manual/en/function.shell-exec.php" rel="nofollow noreferrer">shell_exec</a>, but my web host (<a href="https://www.nearlyfreespeech.net/" rel="nofollow noreferrer">NFSN</a>) has PHP's <a href="http://us2.php.net/features.safe-mode" rel="nofollow noreferrer">safe mode</a> on and it's giving me an error message.</p> <p>Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)</p>
[ { "answer_id": 48528, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Visitors looks like a log analyzer and report generator. Its probably best setup as a chron job to create static HTML pages once a day or so.</p>\n\n<p>If you don't have shell access to your hosting account, or some sort of control panel that lets you setup up chron jobs, you'll be out of luck.</p>\n" }, { "answer_id": 48556, "author": "Sam McAfee", "author_id": 577, "author_profile": "https://Stackoverflow.com/users/577", "pm_score": 0, "selected": false, "text": "<p>Is there any reason not to just use <a href=\"http://www.google.com/analytics/\" rel=\"nofollow noreferrer\">Google Analytics</a>? It's free, and you don't have to write it yourself. I use it, and it gives you a lot of information.</p>\n\n<p>Sorry, I know it's not a \"programming\" answer ;)</p>\n" }, { "answer_id": 48561, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 0, "selected": false, "text": "<p>I second the answer of Jonathan: this is a log analyzer, meaning that you must feed it as input the logfile of the webserver and it generates a summarization of it. Given that you are on a shared host, it is improbable that you can access to that file, and even if you would access it, it is probable that it contains then entries for <em>all</em> the websites hosted on the given machine (setting up separate logging for each VirtualHost is certainly possible with Apache, but I don't know if it is a common practice).</p>\n\n<p>One possible workaround would be for you to write out a logfile from your pages. However this is rather difficult and can have a severe performance impact (you have to serialize the writes to the logfile for one, if you don't want to get garbage from time to time). All in all, I would suggest going with an online analytics service, like Google Analytics.</p>\n" }, { "answer_id": 48568, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>As fortune would have it I do have access to the log file for my site. I've been able to generate the HTML page on the server manually - I've just been looking for a way to get it to happen automatically. All I need is to execute a shell command and get the output to display as the page.</p>\n</blockquote>\n\n<p>Sounds like a good job for an intern.</p>\n\n<p>=)</p>\n\n<p>Call your host and see if you can work out a deal for doing a shell execute.</p>\n" }, { "answer_id": 48721, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": true, "text": "<p>I managed to solve this problem on my own. I put the following lines in a file named visitors.cgi:</p>\n\n<pre><code>#!/bin/sh\n\nprintf \"Content-type: text/html\\n\\n\"\nexec visitors -A /home/logs/access_log\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
I've been looking into different web statistics programs for my site, and one promising one is [Visitors](http://www.hping.org/visitors/). Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's [shell\_exec](http://us.php.net/manual/en/function.shell-exec.php), but my web host ([NFSN](https://www.nearlyfreespeech.net/)) has PHP's [safe mode](http://us2.php.net/features.safe-mode) on and it's giving me an error message. Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)
I managed to solve this problem on my own. I put the following lines in a file named visitors.cgi: ``` #!/bin/sh printf "Content-type: text/html\n\n" exec visitors -A /home/logs/access_log ```
48,550
<p>I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;</p> <pre><code>&lt;target name="publish-artifacts-to-build"&gt; &lt;msbuild project="my-solution.sln" target="Publish"&gt; &lt;property name="Configuration" value="debug" /&gt; &lt;property name="OutDir" value="builds\" /&gt; &lt;arg line="/m:2 /tv:3.5" /&gt; &lt;/msbuild&gt; &lt;/target&gt; </code></pre> <p>and all I get is this as a response;</p> <pre><code>[msbuild] Skipping unpublishable project. </code></pre> <p>Is it possible to publish web applications via the command line in this way?</p>
[ { "answer_id": 48553, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": true, "text": "<p>The \"Publish\" target you are trying to invoke is for \"OneClick\" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. \nYou would want to use the AspNetCompiler task, rather than the MSBuild task. See <a href=\"http://msdn2.microsoft.com/en-us/library/ms164291.aspx\" rel=\"noreferrer\">http://msdn2.microsoft.com/en-us/library/ms164291.aspx</a> for more info on this task. Your \"PublishDir\" would correspond to the TargetPath property of the task. </p>\n\n<p><a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1032073&amp;SiteID=1\" rel=\"noreferrer\">Source</a></p>\n" }, { "answer_id": 6762142, "author": "Alexander Beletsky", "author_id": 386751, "author_profile": "https://Stackoverflow.com/users/386751", "pm_score": 4, "selected": false, "text": "<p>I came up with such solution, works great for me:</p>\n\n<pre><code>msbuild /t:ResolveReferences;_WPPCopyWebApplication /p:BuildingProject=true;OutDir=C:\\Temp\\buidl\\ Test.csproj\n</code></pre>\n\n<p>Secret sauce is _WPPCopyWebApplication target.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4642/" ]
I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target; ``` <target name="publish-artifacts-to-build"> <msbuild project="my-solution.sln" target="Publish"> <property name="Configuration" value="debug" /> <property name="OutDir" value="builds\" /> <arg line="/m:2 /tv:3.5" /> </msbuild> </target> ``` and all I get is this as a response; ``` [msbuild] Skipping unpublishable project. ``` Is it possible to publish web applications via the command line in this way?
The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. You would want to use the AspNetCompiler task, rather than the MSBuild task. See <http://msdn2.microsoft.com/en-us/library/ms164291.aspx> for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task. [Source](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1032073&SiteID=1)
48,555
<p>I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod_deflate and mod_gzip, so these options are out. I do have PHP 5 at my disposal, though, so I could use the gzip component of that.</p> <p>I am currently placing the following in my .htaccess file:</p> <blockquote> <p>php_value output_handler ob_gzhandler</p> </blockquote> <p>However, this only compresses the HTML and leaves out the CSS and JS.</p> <p>Is there a reliable way of transparently compressing the output of the CSS and JS without having to change every page? I have searched Google and a number of solutions are presented, but I've yet to get one to work. If anyone could suggest a solution that they know to work, that would be very gratefully received.</p> <p>Note, <strong>Method 2</strong> in <strong><a href="http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method" rel="noreferrer">The Definitive Post on Gzipping your CSS</a></strong> looks like a good solution, but I couldn't get it working. Has anyone else succeeded using this method?</p>
[ { "answer_id": 48583, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 1, "selected": false, "text": "<p>You can try your luck with <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">mod_rewrite</a>.</p>\n\n<p>Create a script that takes a local static file name as input, through e.g. <code>$_SERVER['QUERY_STRING']</code> and outputs it in compressed form. Many providers don't allow configuring <code>mod_rewrite</code> with <code>.htaccess</code> files or have it completely disabled though.</p>\n\n<p>If you haven't used <em>rewrite</em> before, I recommend a good beginner's guide, like probably <a href=\"http://www.workingwith.me.uk/articles/scripting/mod_rewrite\" rel=\"nofollow noreferrer\">this one</a>.\nThis way you can make the apache redirect all requests for a static file to a php script. style.css will be redirected to <em>compress.php?style.css</em> for instance.</p>\n\n<p>As always be <strong>extremely</strong> cautious on the input you accept or you have an <code>XSS</code> exploit on your hands!</p>\n" }, { "answer_id": 48592, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "<p>What I do:</p>\n\n<ul>\n<li>I place scripts in a <code>js</code> and stylesheets in a <code>css</code> dir, respectively.</li>\n<li><p>In the Apache configuration, I add directives like so:</p>\n\n<pre><code>&lt;Directory /data/www/path/to/some/site/js/&gt;\n AddHandler application/x-httpd-php .js\n php_value auto_prepend_file gzip-js.php\n php_flag zlib.output_compression On\n&lt;/Directory&gt;\n&lt;Directory /data/www/path/to/some/site/css/&gt;\n AddHandler application/x-httpd-php .css\n php_value auto_prepend_file gzip-css.php\n php_flag zlib.output_compression On\n&lt;/Directory&gt;\n</code></pre></li>\n<li><p>gzip-js.php in the <code>js</code> directory looks like this:</p>\n\n<pre><code>&lt;?php\n header(\"Content-type: text/javascript; charset: UTF-8\");\n?&gt;\n</code></pre></li>\n<li><p>…and gzip-cs.php in the <code>css</code> directory looks like this:</p>\n\n<pre><code>&lt;?php\n header(\"Content-type: text/css; charset: UTF-8\");\n?&gt;\n</code></pre></li>\n</ul>\n\n<p>This may not be the most elegant solution, but it most certainly is a simple one that requires few changes and works well.</p>\n" }, { "answer_id": 48761, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 1, "selected": false, "text": "<p>what ever you do, be careful about caching on the client side:</p>\n\n<p>Browsers do all sort of tricks to try and minimize the bandwith and there are many ways in the HTTP protocol to do that, all of which are dealt with by apache - if you are just serving a local file. </p>\n\n<p>If you are not, then <strong>it's your responsibility</strong>.</p>\n\n<p>Have a look at least at the ETag and the If-Modified-Since mechanics which are supported by all current browsers and seem to be the most robust way to query the server for updated content. </p>\n\n<p>A possible way to serve a CSS file to browsers using the If-Modified-Since-Header is something like this (the empty headers to turn off any non-caching headers PHP sends per default):</p>\n\n<pre><code>$p = 'path/to/css/file'\n$i = stat($p);\nif ($_SERVER['HTTP_IF_MODIFIED_SINCE']){\n $imd = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);\n if ( ($imd &gt; 0) &amp;&amp; ($imd &gt;= $i['mtime'])){\n header('HTTP/1.0 304 Not Modified');\n header('Expires:');\n header('Cache-Control:');\n header('Last-Modified: '.date('r', $i['mtime']));\n exit;\n }\n}\nheader('Last-Modified: '.date('r', $i['mtime']));\nheader('Content-Type: text/css');\nheader('Content-Length: '.filesize($p));\nheader('Cache-Control:');\nheader('Pragma:');\nheader('Expires:');\nreadfile($p);\n</code></pre>\n\n<p>The code will use the if-modified-since-header the browser sends to check if the actual file on the server has changed since the date the browser has given. If so, the file is sent, otherwise, a 304 Not Modified is returned and the browser does not have to re-download the whole content (and if it's intelligent enough, it keeps the parsed CSS around in memory too).</p>\n\n<p>There is another mechanic involving the server sending a unique ETag-Header for each piece of content. The Client will send that back using an If-None-Match header allowing the server to decide not only on the date of last modification but also on the content itself.</p>\n\n<p>This just makes the code more complicated though, so I have left it out. FF, IE and Opera (probably Safari too) all send the If-Modified-Since header when they receive content with a Last-Modified header attached, so this works fine.</p>\n\n<p>Also keep in mind that certain versions of IE (or the JScript-Runtime it uses) <em>still</em> have problems with GZIP-transferred content.</p>\n\n<p>Oh. And I know that's not part of the question, but so does Acrobat in some versions. I've had cases and cases of white screens while serving PDFs with gzip transfer encoding.</p>\n" }, { "answer_id": 55092, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 3, "selected": false, "text": "<p>Sorry about the delay - it's a busy week for me.</p>\n\n<p>Assumptions:</p>\n\n<ul>\n<li><code>.htaccess</code> is in the same file as <code>compress.php</code></li>\n<li>static files to be compressed are in <code>static</code> subdirectory</li>\n</ul>\n\n<p>I started my solution from setting the following directives in .htaccess:</p>\n\n<pre><code>RewriteEngine on\nRewriteRule ^static/.+\\.(js|ico|gif|jpg|jpeg|png|css|swf)$ compress.php [NC]\n</code></pre>\n\n<p>It's required that your provider allows you to override <code>mod_rewrite</code> options in <code>.htaccess</code> files.\nThen the compress.php file itself can look like this:</p>\n\n<pre><code>&lt;?php\n\n$basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) );\n$file = realpath( $basedir . $_SERVER[\"REQUEST_URI\"] );\n\nif( !file_exists($file) &amp;&amp; strpos($file, $basedir) === 0 ) {\n header(\"HTTP/1.0 404 Not Found\");\n print \"File does not exist.\";\n exit();\n}\n\n$components = split('\\.', basename($file));\n$extension = strtolower( array_pop($components) );\n\nswitch($extension)\n{\n case 'css':\n $mime = \"text/css\";\n break;\n default:\n $mime = \"text/plain\";\n}\n\nheader( \"Content-Type: \" . $mime );\nreadfile($file);\n</code></pre>\n\n<p>You should of course add more mime types to the switch statement. I didn't want to make the solution dependant on the pecl <code>fileinfo</code> extension or any other magical mime type detecting libraries - this is the simplest approach.</p>\n\n<p>As for securing the script - I do a translation to a real path in the file system so no hacked '../../../etc/passwd' or other shellscript file paths don't go through.</p>\n\n<p>That's the</p>\n\n<pre><code>$basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) );\n$file = realpath( $basedir . $_SERVER[\"REQUEST_URI\"] );\n</code></pre>\n\n<p>snippet. Although I'm pretty sure most of the paths that are in other hierarchy than $basedir will get handled by the Apache before they even reach the script.</p>\n\n<p>Also I check if the resulting path is inside the script's directory tree.\nAdd the headers for cache control as pilif suggested and you should have a working solution to your problem.</p>\n" }, { "answer_id": 1937300, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 1, "selected": false, "text": "<p>Instead of gzipping on the fly when users request the CSS and JavaScript files, you could gzip them ahead of time. As long as Apache serves them with the right headers, you’re golden.</p>\n\n<p>For example, on Mac OS X, gzipping a file on the command line is as easy as:</p>\n\n<pre><code>gzip -c styles.css &gt; styles-gzip.css\n</code></pre>\n\n<p>Might not be the sort of workflow that works for you though.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod\_deflate and mod\_gzip, so these options are out. I do have PHP 5 at my disposal, though, so I could use the gzip component of that. I am currently placing the following in my .htaccess file: > > php\_value output\_handler ob\_gzhandler > > > However, this only compresses the HTML and leaves out the CSS and JS. Is there a reliable way of transparently compressing the output of the CSS and JS without having to change every page? I have searched Google and a number of solutions are presented, but I've yet to get one to work. If anyone could suggest a solution that they know to work, that would be very gratefully received. Note, **Method 2** in **[The Definitive Post on Gzipping your CSS](http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method)** looks like a good solution, but I couldn't get it working. Has anyone else succeeded using this method?
Sorry about the delay - it's a busy week for me. Assumptions: * `.htaccess` is in the same file as `compress.php` * static files to be compressed are in `static` subdirectory I started my solution from setting the following directives in .htaccess: ``` RewriteEngine on RewriteRule ^static/.+\.(js|ico|gif|jpg|jpeg|png|css|swf)$ compress.php [NC] ``` It's required that your provider allows you to override `mod_rewrite` options in `.htaccess` files. Then the compress.php file itself can look like this: ``` <?php $basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) ); $file = realpath( $basedir . $_SERVER["REQUEST_URI"] ); if( !file_exists($file) && strpos($file, $basedir) === 0 ) { header("HTTP/1.0 404 Not Found"); print "File does not exist."; exit(); } $components = split('\.', basename($file)); $extension = strtolower( array_pop($components) ); switch($extension) { case 'css': $mime = "text/css"; break; default: $mime = "text/plain"; } header( "Content-Type: " . $mime ); readfile($file); ``` You should of course add more mime types to the switch statement. I didn't want to make the solution dependant on the pecl `fileinfo` extension or any other magical mime type detecting libraries - this is the simplest approach. As for securing the script - I do a translation to a real path in the file system so no hacked '../../../etc/passwd' or other shellscript file paths don't go through. That's the ``` $basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) ); $file = realpath( $basedir . $_SERVER["REQUEST_URI"] ); ``` snippet. Although I'm pretty sure most of the paths that are in other hierarchy than $basedir will get handled by the Apache before they even reach the script. Also I check if the resulting path is inside the script's directory tree. Add the headers for cache control as pilif suggested and you should have a working solution to your problem.
48,567
<p>I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.</p>
[ { "answer_id": 48571, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": true, "text": "<p>You can use the WindowsIdentity.Impersonate method to \nachieve this. This method allows code to impersonate a different Windows \nuser. Here is a link for more information on this method with a good sample:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx</a></p>\n\n<p>Complete example:</p>\n\n<pre><code>// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.\n// IMPORTANT NOTES:\n// This sample can be run only on Windows XP. The default Windows 2000 security policy\n// prevents this sample from executing properly, and changing the policy to allow\n// proper execution presents a security risk.\n// This sample requests the user to enter a password on the console screen.\n// Because the console window does not support methods allowing the password to be masked,\n// it will be visible to anyone viewing the screen.\n// The sample is intended to be executed in a .NET Framework 1.1 environment. To execute\n// this code in a 1.0 environment you will need to use a duplicate token in the call to the\n// WindowsIdentity constructor. See KB article Q319615 for more information.\n\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\nusing System.Security.Permissions;\nusing System.Windows.Forms;\n\n[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]\n[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = \"FullTrust\")]\npublic class ImpersonationDemo\n{\n [DllImport(\"advapi32.dll\", SetLastError=true, CharSet = CharSet.Unicode)]\n public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,\n int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n [DllImport(\"kernel32.dll\", CharSet=System.Runtime.InteropServices.CharSet.Auto)]\n private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,\n int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);\n\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Auto)]\n public extern static bool CloseHandle(IntPtr handle);\n\n [DllImport(\"advapi32.dll\", CharSet=CharSet.Auto, SetLastError=true)]\n public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,\n int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);\n\n // Test harness.\n // If you incorporate this code into a DLL, be sure to demand FullTrust.\n [PermissionSetAttribute(SecurityAction.Demand, Name = \"FullTrust\")]\n public static void Main(string[] args)\n {\n IntPtr tokenHandle = new IntPtr(0);\n IntPtr dupeTokenHandle = new IntPtr(0);\n try\n {\n string userName, domainName;\n // Get the user token for the specified user, domain, and password using the\n // unmanaged LogonUser method.\n // The local machine name can be used for the domain name to impersonate a user on this machine.\n Console.Write(\"Enter the name of the domain on which to log on: \");\n domainName = Console.ReadLine();\n\n Console.Write(\"Enter the login of a user on {0} that you wish to impersonate: \", domainName);\n userName = Console.ReadLine();\n\n Console.Write(\"Enter the password for {0}: \", userName);\n\n const int LOGON32_PROVIDER_DEFAULT = 0;\n //This parameter causes LogonUser to create a primary token.\n const int LOGON32_LOGON_INTERACTIVE = 2;\n\n tokenHandle = IntPtr.Zero;\n\n // Call LogonUser to obtain a handle to an access token.\n bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),\n LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,\n ref tokenHandle);\n\n Console.WriteLine(\"LogonUser called.\");\n\n if (false == returnValue)\n {\n int ret = Marshal.GetLastWin32Error();\n Console.WriteLine(\"LogonUser failed with error code : {0}\", ret);\n throw new System.ComponentModel.Win32Exception(ret);\n }\n\n Console.WriteLine(\"Did LogonUser Succeed? \" + (returnValue? \"Yes\" : \"No\"));\n Console.WriteLine(\"Value of Windows NT token: \" + tokenHandle);\n\n // Check the identity.\n Console.WriteLine(\"Before impersonation: \"\n + WindowsIdentity.GetCurrent().Name);\n // Use the token handle returned by LogonUser.\n WindowsIdentity newId = new WindowsIdentity(tokenHandle);\n WindowsImpersonationContext impersonatedUser = newId.Impersonate();\n\n // Check the identity.\n Console.WriteLine(\"After impersonation: \"\n + WindowsIdentity.GetCurrent().Name);\n\n // Stop impersonating the user.\n impersonatedUser.Undo();\n\n // Check the identity.\n Console.WriteLine(\"After Undo: \" + WindowsIdentity.GetCurrent().Name);\n\n // Free the tokens.\n if (tokenHandle != IntPtr.Zero)\n CloseHandle(tokenHandle);\n\n }\n catch(Exception ex)\n {\n Console.WriteLine(\"Exception occurred. \" + ex.Message);\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 48606, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>Impersonate will change the Thread context. If you want to change the identity and launch a separate process, you will have to use runas command.</p>\n\n<p>The .NET Developer's Guide to Windows Security by Keith Brown is an excellent read which describes all the security scenarios.\n<a href=\"http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook.HomePage\" rel=\"nofollow noreferrer\">Online version</a> is also available.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.
You can use the WindowsIdentity.Impersonate method to achieve this. This method allows code to impersonate a different Windows user. Here is a link for more information on this method with a good sample: <http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx> Complete example: ``` // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES: // This sample can be run only on Windows XP. The default Windows 2000 security policy // prevents this sample from executing properly, and changing the policy to allow // proper execution presents a security risk. // This sample requests the user to enter a password on the console screen. // Because the console window does not support methods allowing the password to be masked, // it will be visible to anyone viewing the screen. // The sample is intended to be executed in a .NET Framework 1.1 environment. To execute // this code in a 1.0 environment you will need to use a duplicate token in the call to the // WindowsIdentity constructor. See KB article Q319615 for more information. using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.Windows.Forms; [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] public class ImpersonationDemo { [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)] private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); // Test harness. // If you incorporate this code into a DLL, be sure to demand FullTrust. [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Main(string[] args) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); try { string userName, domainName; // Get the user token for the specified user, domain, and password using the // unmanaged LogonUser method. // The local machine name can be used for the domain name to impersonate a user on this machine. Console.Write("Enter the name of the domain on which to log on: "); domainName = Console.ReadLine(); Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName); userName = Console.ReadLine(); Console.Write("Enter the password for {0}: ", userName); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); Console.WriteLine("LogonUser called."); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); Console.WriteLine("LogonUser failed with error code : {0}", ret); throw new System.ComponentModel.Win32Exception(ret); } Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No")); Console.WriteLine("Value of Windows NT token: " + tokenHandle); // Check the identity. Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // Use the token handle returned by LogonUser. WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); // Check the identity. Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); // Stop impersonating the user. impersonatedUser.Undo(); // Check the identity. Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name); // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } catch(Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } } } ```
48,570
<p>I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.</p> <p>I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? </p>
[ { "answer_id": 48585, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 2, "selected": false, "text": "<p>How do you feel about using the <a href=\"http://en.wikipedia.org/wiki/Observer_Pattern\" rel=\"nofollow noreferrer\">Observer</a> pattern? If not, you can implement a true callback this way:</p>\n\n<pre><code>// This function uses a callback function. \nfunction doIt($callback) \n{ \n $data = \"this is my data\";\n $callback($data); \n} \n\n\n// This is a sample callback function for doIt(). \nfunction myCallback($data) \n{ \n print 'Data is: ' . $data . \"\\n\"; \n} \n\n\n// Call doIt() and pass our sample callback function's name. \ndoIt('myCallback'); \n</code></pre>\n\n<p>Displays: Data is: this is my data</p>\n" }, { "answer_id": 48591, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 5, "selected": true, "text": "<p>(Apart from the observer pattern) you can also use <a href=\"http://php.net/manual/function.call-user-func.php\" rel=\"nofollow noreferrer\"><code>call_user_func()</code></a> or <a href=\"http://php.net/manual/function.call-user-func-array.php\" rel=\"nofollow noreferrer\"><code>call_user_func_array()</code></a>.</p>\n\n<p>If you pass an <code>array(obj, methodname)</code> as first parameter it will invoked as <code>$obj-&gt;methodname()</code>.</p>\n\n<pre><code>&lt;?php\nclass Foo {\n public function bar($x) {\n echo $x;\n }\n}\n\nfunction xyz($cb) {\n $value = rand(1,100);\n call_user_func($cb, $value);\n}\n\n$foo = new Foo;\nxyz( array($foo, 'bar') );\n?&gt;\n</code></pre>\n" }, { "answer_id": 3158886, "author": "Benjamin", "author_id": 381220, "author_profile": "https://Stackoverflow.com/users/381220", "pm_score": 2, "selected": false, "text": "<p>I was wondering if we could use __invoke magic method to create \"kind of\" first class function and thus implement a callback</p>\n\n<p>Sound something like that, for PHP 5.3</p>\n\n<pre><code>interface Callback \n{\n public function __invoke(); \n}\n\nclass MyCallback implements Callback\n{\n private function sayHello () { echo \"Hello\"; }\n public function __invoke () { $this-&gt;sayHello(); } \n}\n\nclass MySecondCallback implements Callback\n{\n private function sayThere () { echo \"World\"; }\n public function __invoke () { $this-&gt;sayThere(); }\n}\n\nclass WhatToPrint\n{\n protected $callbacks = array();\n public function register (Callback $callback) \n {\n $this-&gt;callbacks[] = $callback;\n return $this;\n }\n public function saySomething ()\n {\n foreach ($this-&gt;callbacks as $callback) $callback(); \n }\n}\n\n$first_callback = new MyCallback;\n$second_callback = new MySecondCallback;\n$wrapper = new WhatToPrint;\n$wrapper-&gt;register($first_callback)-&gt;register($second_callback)-&gt;saySomething();\n</code></pre>\n\n<hr>\n\n<p>Will print HelloWorld</p>\n\n<p>Hope it'll help ;)</p>\n\n<p>But I'd prefer the Controller pattern with SPL for such a feature.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
(Apart from the observer pattern) you can also use [`call_user_func()`](http://php.net/manual/function.call-user-func.php) or [`call_user_func_array()`](http://php.net/manual/function.call-user-func-array.php). If you pass an `array(obj, methodname)` as first parameter it will invoked as `$obj->methodname()`. ``` <?php class Foo { public function bar($x) { echo $x; } } function xyz($cb) { $value = rand(1,100); call_user_func($cb, $value); } $foo = new Foo; xyz( array($foo, 'bar') ); ?> ```
48,578
<p>Not entirely sure what's going on here; any help would be appreciated.</p> <p>I'm trying to create a new .NET MVC web app. I was pretty sure I had it set up correctly, but I'm getting the following error:</p> <pre><code>The type 'System.Web.Mvc.ViewPage' is ambiguous: it could come from assembly 'C:\MyProject\bin\System.Web.Mvc.DLL' or from assembly 'C:\MyProject\bin\MyProject.DLL'. Please specify the assembly explicitly in the type name. </code></pre> <p>The source error it reports is as follows:</p> <pre><code>Line 1: &lt;%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %&gt; Line 2: Line 3: &lt;asp:Content ID="indexContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"&gt; </code></pre> <p>Anything stand out that I'm doing completely wrong?</p>
[ { "answer_id": 48581, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 1, "selected": false, "text": "<p>This error usually indicates a class naming conflict. You are referencing two namespaces or you created a class with the same name in another namespace that you are using. I would start by looking at what that could be.</p>\n" }, { "answer_id": 48589, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<pre><code> Inherits=\"System.Web.Mvc.ViewPage\"\n</code></pre>\n\n<p>I'd imagine that this should be pointed at your View codebehind file class, not at the base ViewPage class.</p>\n" }, { "answer_id": 48594, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "<p>Are you using a CodeBehind file, I don't see CodeBehind=\"\" attribute where you are specifying the Inherits from? Then you have to point inherits to the class name of the codebehind.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" AutoEventWireup=\"true\" CodeBehind=\"Index.aspx.cs\" Inherits=\"MvcApplication4.Views.Home.Index\" %&gt;\n</code></pre>\n\n<p>Make sure the Inherits is fully qualified. It should be the namespace followed by the class name.</p>\n" }, { "answer_id": 48597, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>I suppose you named one of your page \"ViewPage\" is that the case?</p>\n\n<p>And like @Jonathan mentioned, this smells:</p>\n\n<pre><code>Inherits=\"System.Web.Mvc.ViewPage\"\n</code></pre>\n\n<p>On my MVC application, <em>all</em> the view pages have this instead:</p>\n\n<pre><code>Inherits=\"MySite.Views.Pages.Home\"\n</code></pre>\n\n<p>Or something along the line. Your aspx page markup should have \"Inherits\" point to your code-behind class name, not the actual class that it is inheriting. The attribute name is rather misleading but its an artifact of earlier days.</p>\n" }, { "answer_id": 419280, "author": "Peter M", "author_id": 33336, "author_profile": "https://Stackoverflow.com/users/33336", "pm_score": 2, "selected": false, "text": "<p>I'm running ASP.NET MVC Beta and also encountered this error. </p>\n\n<p>It came about while I was trying to remove the code behind file for a view. I removed the \"CodeBehind\" attribute in the @Page directive and changed the \"Inherits\" attribute to point to System.Web.Mvc.ViewPage, but left the actual aspx.cs code behind file untouched in my project.</p>\n\n<p>At this point, if I tried to run my project, I got the error you mentioned. </p>\n\n<p>I resolved this error by deleting the aspx.cs (code behind) file for the view from my project.</p>\n" }, { "answer_id": 1050259, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 1, "selected": false, "text": "<p>Open up C:\\MyProject\\bin\\MyProject.DLL in Reflector and look for ViewPage to see if you've defined one by accident.</p>\n" }, { "answer_id": 7202990, "author": "Eric Herlitz", "author_id": 296568, "author_profile": "https://Stackoverflow.com/users/296568", "pm_score": 0, "selected": false, "text": "<p>No this should be a structural error message.</p>\n\n<p>Check <a href=\"http://trikks.wordpress.com/2011/08/26/the-type-is-ambiguous-it-could-come-from-assembly-or-from-assembly-please-specify-the-assembly-explicitly-in-the-type-name/\" rel=\"nofollow\">http://trikks.wordpress.com/2011/08/26/the-type-is-ambiguous-it-could-come-from-assembly-or-from-assembly-please-specify-the-assembly-explicitly-in-the-type-name/</a></p>\n" }, { "answer_id": 13310425, "author": "Paul", "author_id": 1423534, "author_profile": "https://Stackoverflow.com/users/1423534", "pm_score": 2, "selected": false, "text": "<p>Check your assembly references to <code>System.Web.Mvc</code> in <code>web.config</code>. </p>\n\n<p>Mine were explicitly specifying <code>2.0.0.0</code>, but my project referenced <code>3.0.0.0</code></p>\n" }, { "answer_id": 48819319, "author": "Ayson Baxter", "author_id": 465941, "author_profile": "https://Stackoverflow.com/users/465941", "pm_score": 0, "selected": false, "text": "<p>I had the same exact error this week.</p>\n\n<p>My Webform.aspx file had a generated designer.cs file. In this file the class was actually named \"ViewPage\". Delete the designer file, or move the class contents to the webform.aspx.cs file and my error was gone.</p>\n\n<p>Just putting it out there in case someone had this error.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1540/" ]
Not entirely sure what's going on here; any help would be appreciated. I'm trying to create a new .NET MVC web app. I was pretty sure I had it set up correctly, but I'm getting the following error: ``` The type 'System.Web.Mvc.ViewPage' is ambiguous: it could come from assembly 'C:\MyProject\bin\System.Web.Mvc.DLL' or from assembly 'C:\MyProject\bin\MyProject.DLL'. Please specify the assembly explicitly in the type name. ``` The source error it reports is as follows: ``` Line 1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> Line 2: Line 3: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> ``` Anything stand out that I'm doing completely wrong?
Are you using a CodeBehind file, I don't see CodeBehind="" attribute where you are specifying the Inherits from? Then you have to point inherits to the class name of the codebehind. Example: ``` <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication4.Views.Home.Index" %> ``` Make sure the Inherits is fully qualified. It should be the namespace followed by the class name.
48,616
<p>How do I set a property of a user control in <code>ListView</code>'s <code>LayoutTemplate</code> from the code-behind?</p> <pre><code>&lt;asp:ListView ...&gt; &lt;LayoutTemplate&gt; &lt;myprefix:MyControl id="myControl" ... /&gt; &lt;/LayoutTemplate&gt; ... &lt;/asp:ListView&gt; </code></pre> <p>I want to do this:</p> <pre><code>myControl.SomeProperty = somevalue; </code></pre> <p>Please notice that my control is not in <code>ItemTemplate</code>, it is in <code>LayoutTemplate</code>, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.</p>
[ { "answer_id": 48636, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx\" rel=\"nofollow noreferrer\">FindControl</a> method on each ListViewItem.</p>\n\n<pre><code>var control = (MyControl)Item.FindControl(\"yourControlId\");\n</code></pre>\n" }, { "answer_id": 1315742, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control.</p>\n\n<pre><code>var control = (MyControl)myListView.FindControl(\"myControlId\");\n</code></pre>\n" }, { "answer_id": 1794556, "author": "tgittos", "author_id": 218293, "author_profile": "https://Stackoverflow.com/users/218293", "pm_score": 1, "selected": false, "text": "<p>This has been answered in this Stack Overflow question:<br />\n<a href=\"https://stackoverflow.com/questions/433846/access-a-control-inside-a-the-layouttemplate-of-a-listview\"><a href=\"https://stackoverflow.com/questions/433846/access-a-control-inside-a-the-layouttemplate-of-a-listview\">Access a control inside a the LayoutTemplate of a ListView</a></a></p>\n\n<p>See the comment on the accepted answer by tanathos.</p>\n\n<p>I know this was asked over a year ago, but it's one of the first results for the search term I used to get here, so I wanted to leave the answer for anyone else who stumbled upon it.</p>\n" }, { "answer_id": 1963712, "author": "Brian Mains", "author_id": 231716, "author_profile": "https://Stackoverflow.com/users/231716", "pm_score": 0, "selected": false, "text": "<p>The layout gets created, and fires a LayoutCreated event that says the layout has been created in the system.</p>\n\n<p>Then, you can use listview.FindControl to get a reference to that control.</p>\n" }, { "answer_id": 3926198, "author": "Ben Rabidou", "author_id": 469285, "author_profile": "https://Stackoverflow.com/users/469285", "pm_score": 4, "selected": false, "text": "<pre><code>var control = (MyControl)myListView.FindControl(\"myControlId\");\n</code></pre>\n\n<p>This will work but make sure you do it after the data bind or the LayoutTemplate will not have been created thus throwing an error.</p>\n" }, { "answer_id": 52902606, "author": "Jeff", "author_id": 3128942, "author_profile": "https://Stackoverflow.com/users/3128942", "pm_score": 0, "selected": false, "text": "<p>In case you need the VB.net version, here it is:</p>\n\n<pre><code>Dim control = CType(myListView.FindControl(\"myControlId\"), MyControl)\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
How do I set a property of a user control in `ListView`'s `LayoutTemplate` from the code-behind? ``` <asp:ListView ...> <LayoutTemplate> <myprefix:MyControl id="myControl" ... /> </LayoutTemplate> ... </asp:ListView> ``` I want to do this: ``` myControl.SomeProperty = somevalue; ``` Please notice that my control is not in `ItemTemplate`, it is in `LayoutTemplate`, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.
To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control. ``` var control = (MyControl)myListView.FindControl("myControlId"); ```
48,642
<p>I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type: </p> <pre><code>:s/\(abc\)/\1\1/ </code></pre> <p>But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef": </p> <pre><code>:s/\(def\)/\1\1/ </code></pre> <p>How can I write the command in the commandline so that it does this?</p> <pre><code>:s/\(*whatever is under the commandline*\)/\1\1 </code></pre>
[ { "answer_id": 48657, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 7, "selected": true, "text": "<p><code>&lt;cword&gt;</code> is the word under the cursor (:help <code>&lt;cword&gt;</code>).</p>\n\n<p>Sorry, I should have been more complete in this answer.</p>\n\n<p>You can nmap a command to it, or this series of keystrokes for the lazy will work:</p>\n\n<pre><code>b #go to beginning of current word\nyw #yank to register\n</code></pre>\n\n<p>Then, when you are typing in your pattern you can hit <code>&lt;control-r&gt;0&lt;enter&gt;</code> which will paste in your command the contents of the 0-th register.</p>\n\n<p>You can also make a command for this like:</p>\n\n<pre><code>:nmap &lt;leader&gt;w :s/\\(&lt;c-r&gt;=expand(\"&lt;cword&gt;\")&lt;cr&gt;\\)/\n</code></pre>\n\n<p>Which will map hitting '\\' and 'w' at the same time to replace your command line with</p>\n\n<pre><code>:s/\\(&lt;currentword&gt;\\)/\n</code></pre>\n" }, { "answer_id": 76316, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You need to escape the backslashes within the mapping. You can also include the substitution string within the mapping.</p>\n\n<pre><code>:nmap &lt;leader&gt;w :s/\\\\(&lt;c-r&gt;=expand(\"&lt;cword&gt;\")&lt;cr&gt;\\\\)/\\\\1\\\\1&lt;cr&gt;\n</code></pre>\n" }, { "answer_id": 80683, "author": "bmb", "author_id": 5298, "author_profile": "https://Stackoverflow.com/users/5298", "pm_score": 1, "selected": false, "text": "<pre><code>ywPx\n</code></pre>\n\n<p>will do what you describe.</p>\n\n<pre><code>ywPxw\n</code></pre>\n\n<p>will also advance the cursor to the next word.</p>\n" }, { "answer_id": 82120, "author": "user11211", "author_id": 11211, "author_profile": "https://Stackoverflow.com/users/11211", "pm_score": 5, "selected": false, "text": "<pre><code>yiwP\n</code></pre>\n\n<p><code>yiw</code>: Yank inner word (the word under the cursor). This command also moves the cursor to the beginning of the word.</p>\n\n<p><code>P</code>: Paste before the cursor.</p>\n\n<p>You can then map the e.g.: <code>&lt; ALT &gt; - D</code> to this command:</p>\n\n<pre><code>:nmap &lt; ALT &gt;-D yiwP\n</code></pre>\n" }, { "answer_id": 82158, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 4, "selected": false, "text": "<p>Another easy way to do this is to use the <code>*</code> command.</p>\n\n<p>In regular mode, when over a word, type </p>\n\n<pre><code>*:s//\\0\\0&lt;Enter&gt;\n</code></pre>\n\n<p><code>*</code> makes the search pattern the current word (e.g. \\&lt;abc\\>). </p>\n\n<p><code>:s//</code> does a substitution using the current search pattern, and <code>\\0</code> in the replacement\nsection is the matched string.</p>\n\n<p>You can then repeat this behaviour, say over word \"def\", by either typing the same again, or by typing </p>\n\n<pre><code>*@:\n</code></pre>\n\n<p><code>@:</code> just repeats the last ex command, without a need for an &lt;Enter>, in this case the substitution.</p>\n\n<p>You can also record a quick macro to do this using the <code>q</code> command </p>\n\n<pre><code>qd*:s//\\0\\0&lt;Enter&gt;q\n</code></pre>\n\n<p>Then repeat it to your hearts content by typing</p>\n\n<pre><code>@d\n</code></pre>\n\n<p>when over a word you want to double. As this is only one character less than the prior solution, it may not be worth it to you - unless you will be doing other ex-commands between the word-doubling, which would change the behaviour of <code>@:</code></p>\n" }, { "answer_id": 628865, "author": "César Alforde", "author_id": 75950, "author_profile": "https://Stackoverflow.com/users/75950", "pm_score": 7, "selected": false, "text": "<p>While in command-line mode, <kbd>CTRL</kbd>+<kbd>R</kbd> <kbd>CTRL</kbd>+<kbd>W</kbd> will insert the word under the cursor.</p>\n\n<p>See the help for <code>c_CTRL-R</code> for a listing of all the other special registers:</p>\n\n<pre><code>:help c_CTRL-R\n</code></pre>\n" }, { "answer_id": 869112, "author": "SergioAraujo", "author_id": 2571881, "author_profile": "https://Stackoverflow.com/users/2571881", "pm_score": -1, "selected": false, "text": "<pre><code>\" count word (case sensitive)\nnmap &lt;F4&gt; :%s/\\(&lt;c-r&gt;=expand(\"&lt;cword&gt;\")&lt;cr&gt;\\)//gn&lt;cr&gt;\n</code></pre>\n" }, { "answer_id": 27369655, "author": "BBW Before Windows", "author_id": 3186686, "author_profile": "https://Stackoverflow.com/users/3186686", "pm_score": 0, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/users/11211/user11211\">user11211</a> <a href=\"https://stackoverflow.com/a/82120/1084\">has the most straightforward way</a> to duplicate the word under cursor:</p>\n\n<pre><code>yiwP\n</code></pre>\n\n<p>yank inner word (moves cursor to start of word), paste (before cursor).</p>\n\n<p>eg. straigh[t]forward ----> straightforwar[d]straightforward</p>\n\n<p>[] is cursor</p>\n\n<p>To elaborate...</p>\n\n<p>You probably want to have the cursor following your duplicated word:</p>\n\n<pre><code>yiwPea\n</code></pre>\n\n<p>straigh[t]forward ----> straightforwardstraightforward[]</p>\n\n<p>NOTE:</p>\n\n<pre><code>yiw\n</code></pre>\n\n<p>is yank inner word (without whitespace)</p>\n\n<pre><code>yaw\n</code></pre>\n\n<p>is yank all word (including trailing whitespace).</p>\n\n<pre><code>yawPea\n</code></pre>\n\n<p>is therefore duplicate word including whitespace, and position cursor.</p>\n\n<p>straigh[t]forward ----> straightforward straightforward[]</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084/" ]
I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type: ``` :s/\(abc\)/\1\1/ ``` But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef": ``` :s/\(def\)/\1\1/ ``` How can I write the command in the commandline so that it does this? ``` :s/\(*whatever is under the commandline*\)/\1\1 ```
`<cword>` is the word under the cursor (:help `<cword>`). Sorry, I should have been more complete in this answer. You can nmap a command to it, or this series of keystrokes for the lazy will work: ``` b #go to beginning of current word yw #yank to register ``` Then, when you are typing in your pattern you can hit `<control-r>0<enter>` which will paste in your command the contents of the 0-th register. You can also make a command for this like: ``` :nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/ ``` Which will map hitting '\' and 'w' at the same time to replace your command line with ``` :s/\(<currentword>\)/ ```
48,668
<p>I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?</p>
[ { "answer_id": 48672, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>When you create types for 'Use and throw' purposes. \nThis seems to have come due to LINQ. Seems to be a way to create structures with fields on the fly for a LINQ query. Returning a struct/type with specified fields only. If not for this, you'd have to declare a .Net type for each unique combination of fields you wish to retrieve.</p>\n" }, { "answer_id": 48677, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": false, "text": "<p>From LINQ in action (page 76 section 2.6.3): </p>\n\n<blockquote>\n <p>... anonymous types [are] a great tool for quick and simple temporary results. We don't need to declare classes to hold temporary results thanks to temporary types.</p>\n</blockquote>\n\n<p>basically they're useful to hold information in the local scope temporarily. Anything more requires the use of reflection and can become quite a problem. The example they give in the above-quoted book is in writing to console the id, name, and amount of memory taken up by each running process. They create an anonymous type, add it to a list (all one statement) and then use ObjectDumper to output it. Therefore the code no longer needs a separately declared class to hold the id, name and memory used but its all declared implicitly bringing the line count down to 4:</p>\n\n<pre><code>var pl = new List&lt;Object&gt;();\nforeach(var p in Process.GetProcesses())\n pl.Add(new {p.Id, p.ProcessName, Memory=p.WorkingSet64});\nObjectDumper.Write(pl);\n</code></pre>\n" }, { "answer_id": 48705, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 5, "selected": true, "text": "<p>Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding.</p>\n\n<p>I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method.</p>\n\n<p>For instance:</p>\n\n<pre><code>var query = from item in database.Items\n // ...\n select new { Id = item.Id, Name = item.Name };\n\nreturn query.ToDictionary(item =&gt; item.Id, item =&gt; item.Name);\n</code></pre>\n\n<p>Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.</p>\n" }, { "answer_id": 48706, "author": "Registered User", "author_id": 5087, "author_profile": "https://Stackoverflow.com/users/5087", "pm_score": 1, "selected": false, "text": "<p>Use them with Linq.</p>\n" }, { "answer_id": 168109, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>The most popular use of anonymous types are for specifying projections in a LINQ to SQL query. </p>\n\n<p>This query</p>\n\n<pre><code>from x in db.Table1 select new {x.Column1, Alias2=x.Column2}\n</code></pre>\n\n<p>will be converted to this SQL:</p>\n\n<pre><code>SELECT Column1, Column2 AS Alias2 FROM Table1\n</code></pre>\n\n<p>With anonymous types, you can create ad hoc projections without defining the type for it beforehand. The compiler will define the type for you.</p>\n" }, { "answer_id": 168135, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 0, "selected": false, "text": "<p>It is important to know, that LINQ doesn't force you, to use anonymous types. You can also write normal object constructions after select.</p>\n\n<pre><code>var query = from item in database.Items\n// ...\nselect new Person(item.id, item.Name)\n</code></pre>\n\n<p>This prevents you from ugly reflection programming.</p>\n" }, { "answer_id": 887762, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>@Wouter :</p>\n\n<pre><code>var query = from item in database.Items\nselect new Person\n{\nID =item.id,\nNAME= item.Name\n};\n</code></pre>\n\n<p>where ID and NAME are real property of your Person class.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method. For instance: ``` var query = from item in database.Items // ... select new { Id = item.Id, Name = item.Name }; return query.ToDictionary(item => item.Id, item => item.Name); ``` Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.
48,669
<p>I receive HTML pages from our creative team, and then use those to build aspx pages. One challenge I frequently face is getting the HTML I spit out to match theirs exactly. I almost always end up screwing up the nesting of <code>&lt;div&gt;</code>s between my page and the master pages.</p> <p>Does anyone know of a tool that will help in this situation -- something that will compare 2 pages and output the structural differences? I can't use a standard diff tool, because IDs change from what I receive from creative, text replaces <i>lorem ipsum</i>, etc.. </p>
[ { "answer_id": 48674, "author": "DrFloyd5", "author_id": 1736623, "author_profile": "https://Stackoverflow.com/users/1736623", "pm_score": 2, "selected": false, "text": "<p>If out output XML compliant HTML. Or at least translate your HTML product into XML compliancy, you at least could then XSL your output to remove the content and id tags. Apply the same transformation to their html, and then compare.</p>\n" }, { "answer_id": 48675, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>I was thinking on lines of <a href=\"http://msdn.microsoft.com/en-us/library/aa302294.aspx\" rel=\"nofollow noreferrer\">XML Diff</a> since HTML can be represented as an XML Document.\nThe challenge with HTML is that it might not be always well formed. Found one more here showing how to use <a href=\"http://msdn.microsoft.com/en-us/library/aa302295.aspx\" rel=\"nofollow noreferrer\">XMLDiff class</a>. </p>\n" }, { "answer_id": 48699, "author": "Xian", "author_id": 4642, "author_profile": "https://Stackoverflow.com/users/4642", "pm_score": 0, "selected": false, "text": "<p>winmerge is a good visual diff program</p>\n" }, { "answer_id": 49348, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">HTMLTidy</a> to convert the HTML to well-formed XML so you can use <a href=\"http://msdn.microsoft.com/en-us/library/aa302294.aspx\" rel=\"nofollow noreferrer\">XML Diff</a>, as Gulzar suggested.</p>\n\n<pre><code>tidy -asxml index.html\n</code></pre>\n" }, { "answer_id": 1593331, "author": "elhoim", "author_id": 171469, "author_profile": "https://Stackoverflow.com/users/171469", "pm_score": 1, "selected": false, "text": "<p>A copy of my own answer from <a href=\"https://stackoverflow.com/questions/31722/anyone-have-a-diff-algorithm-for-rendered-html/1593296#1593296\">here</a>.</p>\n\n<hr>\n\n<p>What about <a href=\"http://code.google.com/p/daisydiff/\" rel=\"nofollow noreferrer\">DaisyDiff</a> (<a href=\"http://code.google.com/p/daisydiff/\" rel=\"nofollow noreferrer\">Java</a> and <a href=\"http://www.mediawiki.org/wiki/Visual_Diff\" rel=\"nofollow noreferrer\">PHP</a> vesions available).</p>\n\n<p>Following features are really nice:</p>\n\n<ul>\n<li>Works with badly formed HTML that can be found \"in the wild\".</li>\n<li>The diffing is more specialized in HTML than XML tree differs. Changing part of a text node will not cause the entire node to be changed.</li>\n<li>In addition to the default visual diff, HTML source can be diffed coherently.</li>\n<li>Provides easy to understand descriptions of the changes.</li>\n<li>The default GUI allows easy browsing of the modifications through keyboard shortcuts and links. </li>\n</ul>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
I receive HTML pages from our creative team, and then use those to build aspx pages. One challenge I frequently face is getting the HTML I spit out to match theirs exactly. I almost always end up screwing up the nesting of `<div>`s between my page and the master pages. Does anyone know of a tool that will help in this situation -- something that will compare 2 pages and output the structural differences? I can't use a standard diff tool, because IDs change from what I receive from creative, text replaces *lorem ipsum*, etc..
You can use [HTMLTidy](http://tidy.sourceforge.net/) to convert the HTML to well-formed XML so you can use [XML Diff](http://msdn.microsoft.com/en-us/library/aa302294.aspx), as Gulzar suggested. ``` tidy -asxml index.html ```
48,680
<p>Say I have a <code>Textbox</code> nested within a <code>TabControl</code>. </p> <p>When the form loads, I would like to focus on that <code>Textbox</code> (by default the focus is set to the <code>TabControl</code>).</p> <p>Simply calling <code>textbox1.focus()</code> in the <code>Load</code> event of the form does not appear to work. </p> <p>I have been able to focus it by doing the following:</p> <pre><code> private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } </code></pre> <p><strong>My question is:</strong></p> <p>Is there a more elegant way to do this?</p>
[ { "answer_id": 48719, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 7, "selected": true, "text": "<p>The following is the solution:</p>\n\n<pre><code>private void frmMainLoad(object sender, EventArgs e)\n{\n ActiveControl = textBox1;\n}\n</code></pre>\n\n<p>The better question would however be why... I'm not entirely sure what the answer to that one is.</p>\n\n<p>Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.</p>\n" }, { "answer_id": 634852, "author": "Korby", "author_id": 76687, "author_profile": "https://Stackoverflow.com/users/76687", "pm_score": 4, "selected": false, "text": "<p>Try putting it in the <code>Form_Shown()</code> event. Because it's in a container, putting in the Form_Load or even the Form() constructor won't work.</p>\n" }, { "answer_id": 986845, "author": "bdwakefield", "author_id": 55053, "author_profile": "https://Stackoverflow.com/users/55053", "pm_score": 1, "selected": false, "text": "<p>You just need to add the Control.Select() for your control to this code. I have used this to set focus on controls during validation when there are errors.</p>\n\n<pre><code>private void ShowControlTab(Control ControlToShow)\n {\n if (!TabSelected)\n {\n if (ControlToShow.Parent != null)\n {\n if (ControlToShow.Parent.GetType() == typeof(TabPage))\n {\n TabPage Tab = (TabPage)ControlToShow.Parent;\n if (WOTabs.TabPages.Contains(Tab))\n {\n WOTabs.SelectedTab = Tab;\n TabSelected = true;\n return;\n }\n }\n\n ShowControlTab(ControlToShow.Parent);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 2355348, "author": "Mikhail G", "author_id": 283508, "author_profile": "https://Stackoverflow.com/users/283508", "pm_score": 2, "selected": false, "text": "<p>Try to use <code>textbox1.Select()</code> instead of <code>textbox1.Focus()</code>. This helped me few times.</p>\n" }, { "answer_id": 5487429, "author": "Reh", "author_id": 684068, "author_profile": "https://Stackoverflow.com/users/684068", "pm_score": 1, "selected": false, "text": "<p>I had a user control within another user control. textbox1.Select() worked for me but textbox1.Focus() did not work.</p>\n\n<p>You can also try setting Tabstop to false, textbox1.Focus(), TabStop true.</p>\n" }, { "answer_id": 23888913, "author": "osama9988", "author_id": 3511799, "author_profile": "https://Stackoverflow.com/users/3511799", "pm_score": 0, "selected": false, "text": "<pre><code> private void ChildForm1_Load(object sender, EventArgs e)\n {\n ActiveControl = txt_fname;\n\n }\n</code></pre>\n\n<p>i use this code it works fine on win tab control or dotnetbar supertab contrl</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
Say I have a `Textbox` nested within a `TabControl`. When the form loads, I would like to focus on that `Textbox` (by default the focus is set to the `TabControl`). Simply calling `textbox1.focus()` in the `Load` event of the form does not appear to work. I have been able to focus it by doing the following: ``` private void frmMainLoad(object sender, EventArgs e) { foreach (TabPage tab in this.tabControl1.TabPages) { this.tabControl1.SelectedTab = tab; } } ``` **My question is:** Is there a more elegant way to do this?
The following is the solution: ``` private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } ``` The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.
48,744
<h2>How do you find the phone numbers in 50,000 HTML pages?<br><br></h2> <blockquote> <h3>Jeff Attwood posted 5 Questions for programmers applying for jobs:</h3> <p>In an effort to make life simpler for phone screeners, I've put together this list of Five Essential Questions that you need to ask during an SDE screen. They won't guarantee that your candidate will be great, but they will help eliminate a huge number of candidates who are slipping through our process today.</p> <p><strong>1) Coding</strong> The candidate has to write some simple code, with correct syntax, in C, C++, or Java.</p> <p><strong>2) OO design</strong> The candidate has to define basic OO concepts, and come up with classes to model a simple problem.</p> <p><strong>3) Scripting and regexes</strong> The candidate has to describe how to find the phone numbers in 50,000 HTML pages.</p> <p><strong>4) Data structures</strong> The candidate has to demonstrate basic knowledge of the most common data structures.</p> <p><strong>5) Bits and bytes</strong> The candidate has to answer simple questions about bits, bytes, and binary numbers.</p> <p>Please understand: what I'm looking for here is a total vacuum in one of these areas. It's OK if they struggle a little and then figure it out. It's OK if they need some minor hints or prompting. I don't mind if they're rusty or slow. What you're looking for is candidates who are utterly clueless, or horribly confused, about the area in question.</p> <p><strong><a href="http://www.codinghorror.com/blog/archives/001042.html" rel="noreferrer">>>> The Entirety of Jeff´s Original Post &lt;&lt;&lt;</a></strong></p> </blockquote> <p><br> <strong>Note:</strong> Steve Yegge originally posed the Question.</p>
[ { "answer_id": 48767, "author": "Ande Turner", "author_id": 4857, "author_profile": "https://Stackoverflow.com/users/4857", "pm_score": 1, "selected": false, "text": "<h2>Perl Solution</h2>\n<p>By: &quot;MH&quot; via codinghorror,com on September 5, 2008 07:29 AM</p>\n<pre><code>#!/usr/bin/perl\nwhile (&lt;*.html&gt;) {\n my $filename = $_;\n my @data = &lt;$filename&gt;;\n\n # Loop once through with simple search\n while (@data) {\n if (/\\(?(\\d\\d\\d)\\)?[ -]?(\\d\\d\\d)-?(\\d\\d\\d\\d)/) {\n push( @files, $filename );\n next;\n }\n }\n\n # None found, strip html\n $text = &quot;&quot;;\n $text .= $_ while (@data);\n $text =~ s#&lt;[^&gt;]+&gt;##gxs;\n\n # Strip line breaks\n $text =~ s#\\n|\\r##gxs;\n\n # Check for occurrence.\n if ( $text =~ /\\(?(\\d\\d\\d)\\)?[ -]?(\\d\\d\\d)-?(\\d\\d\\d\\d)/ ) {\n push( @files, $filename );\n next;\n }\n}\n\n# Print out result\nprint join( '\\n', @files );\n</code></pre>\n" }, { "answer_id": 48788, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": "<p>Made this in Java. The regex was borrowed from <a href=\"http://forums.msdn.microsoft.com/en-US/regexp/thread/8d4846c0-4eca-427a-b34a-856c7f8695cb/\" rel=\"nofollow noreferrer\">this forum</a>.</p>\n<pre><code> final String regex = &quot;[\\\\s](\\\\({0,1}\\\\d{3}\\\\){0,1}&quot; +\n &quot;[- \\\\.]\\\\d{3}[- \\\\.]\\\\d{4})|&quot; +\n &quot;(\\\\+\\\\d{2}-\\\\d{2,4}-\\\\d{3,4}-\\\\d{3,4})&quot;;\n final Pattern phonePattern = Pattern.compile(regex);\n \n /* The result set */\n Set&lt;File&gt; files = new HashSet&lt;File&gt;();\n \n File dir = new File(&quot;/initDirPath&quot;);\n if (!dir.isDirectory()) return;\n \n for (File file : dir.listFiles()) {\n if (file.isDirectory()) continue;\n \n BufferedReader reader = new BufferedReader(new FileReader(file));\n \n String line;\n boolean found = false;\n while ((line = reader.readLine()) != null \n &amp;&amp; !found) {\n \n if (found = phonePattern.matcher(line).find()) {\n files.add(file);\n }\n }\n }\n\n for (File file : files) {\n System.out.println(file.getAbsolutePath());\n }\n</code></pre>\n<p>Performed some tests and it went ok! :)\nRemeber I'm not trying to use the best design here. Just implemented the algorithm for that.</p>\n" }, { "answer_id": 48812, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<pre><code>egrep '\\(?\\d{3}\\)?[-\\s.]?\\d{3}[-.]\\d{4}' *.html\n</code></pre>\n" }, { "answer_id": 48826, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 6, "selected": true, "text": "<pre><code>egrep \"(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})\" . -R --include='*.html'\n</code></pre>\n" }, { "answer_id": 48834, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 1, "selected": false, "text": "<p>i love doing these little problems, can't help myself.</p>\n\n<p>not sure if it was worth doing though since it's very similar to the java answer.</p>\n\n<pre><code>private readonly Regex phoneNumExp = new Regex(@\"(\\({0,1}\\d{3}\\){0,1}[- \\.]\\d{3}[- \\.]\\d{4})|(\\+\\d{2}-\\d{2,4}-\\d{3,4}-\\d{3,4})\");\n\npublic HashSet&lt;string&gt; Search(string dir)\n{\n var numbers = new HashSet&lt;string&gt;();\n\n string[] files = Directory.GetFiles(dir, \"*.html\", SearchOption.AllDirectories);\n\n foreach (string file in files)\n {\n using (var sr = new StreamReader(file))\n {\n string line;\n\n while ((line = sr.ReadLine()) != null)\n {\n var match = phoneNumExp.Match(line);\n\n if (match.Success)\n {\n numbers.Add(match.Value);\n }\n }\n }\n }\n\n return numbers;\n}\n</code></pre>\n" }, { "answer_id": 110756, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": -1, "selected": false, "text": "<p>Here's why phone interview coding questions don't work: </p>\n\n<p>phone screener: how do you find the phone numbers in 50,000 HTML pages?</p>\n\n<p>candidate: hang on one second (covers phone) hey (roommate/friend/etc who's super good at programming), how do you find the phone numbers in 50,000 HTML pages?</p>\n\n<p>Save the coding questions for early in the in-person interview, and make the interview questions more personal, i.e. \"I'd like details about the last time you solved a problem using code\". That's a question that will beg follow-ups to their details and it's a lot harder to get someone else to answer it for you without sounding weird over the phone.</p>\n" }, { "answer_id": 716989, "author": "em70", "author_id": 87079, "author_profile": "https://Stackoverflow.com/users/87079", "pm_score": 2, "selected": false, "text": "<p>Borrowing 2 things from the C# answer from sieben, here's a little F# snippet that will do the job. All it's missing is a way to call processDirectory, which is left out intentionally :)</p>\n\n<pre><code>\nopen System\nopen System.IO\nopen System.Text.RegularExpressions\n\nlet rgx = Regex(@\"(\\({0,1}\\d{3}\\){0,1}[- \\.]\\d{3}[- \\.]\\d{4})|(\\+\\d{2}-\\d{2,4}-\\d{3,4}-\\d{3,4})\", RegexOptions.Compiled)\n\nlet processFile contents = contents |> rgx.Matches |> Seq.cast |> Seq.map(fun m -> m.Value)\n\nlet processDirectory path = Directory.GetFiles(path, \"*.html\", SearchOption.AllDirectories) |> Seq.map(File.ReadAllText >> processFile) |> Seq.concat\n</code></pre>\n" }, { "answer_id": 15592111, "author": "ruralcoder", "author_id": 324308, "author_profile": "https://Stackoverflow.com/users/324308", "pm_score": 2, "selected": false, "text": "<p>Here is a improved regex pattern</p>\n\n<pre><code>\\(?\\d{3}\\)?[-\\s\\.]?\\d{3}[-\\s\\.]?\\d{4}\n</code></pre>\n\n<p>It is able to identify several number formats</p>\n\n<ol>\n<li>xxx.xxx.xxxx</li>\n<li>xxx.xxxxxxx</li>\n<li>xxx-xxx-xxx</li>\n<li>xxxxxxxxxx</li>\n<li>(xxx) xxx xxxx </li>\n<li>(xxx) xxx-xxxx</li>\n<li>(xxx)xxx-xxxx</li>\n</ol>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
How do you find the phone numbers in 50,000 HTML pages? ------------------------------------------------------- > > ### Jeff Attwood posted 5 Questions for programmers applying for jobs: > > > In an effort to make life simpler for phone screeners, I've put together > this list of Five Essential Questions > that you need to ask during an SDE > screen. They won't guarantee that your > candidate will be great, but they will > help eliminate a huge number of > candidates who are slipping through > our process today. > > > **1) Coding** The candidate has to write > some simple code, with correct syntax, > in C, C++, or Java. > > > **2) OO design** The candidate has to > define basic OO concepts, and come up > with classes to model a simple > problem. > > > **3) Scripting and regexes** The > candidate has to describe how to find > the phone numbers in 50,000 HTML > pages. > > > **4) Data structures** The candidate has > to demonstrate basic knowledge of the > most common data structures. > > > **5) Bits and bytes** The candidate has > to answer simple questions about bits, > bytes, and binary numbers. > > > Please understand: what I'm looking > for here is a total vacuum in one of > these areas. It's OK if they struggle > a little and then figure it out. It's > OK if they need some minor hints or > prompting. I don't mind if they're > rusty or slow. What you're looking for > is candidates who are utterly > clueless, or horribly confused, about > the area in question. > > > **[>>> The Entirety of Jeff´s Original Post <<<](http://www.codinghorror.com/blog/archives/001042.html)** > > > **Note:** Steve Yegge originally posed the Question.
``` egrep "(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})" . -R --include='*.html' ```
48,772
<p>I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far:</p> <pre><code>drop table exams; drop table question_bank; drop table anwser_bank; create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); </code></pre> <p>When I run the query I get this error:</p> <blockquote> <p>Msg 8139, Level 16, State 0, Line 9 Number of referencing columns in foreign key differs from number of referenced columns, table 'question_bank'.</p> </blockquote> <p>Can you spot the error?</p>
[ { "answer_id": 48778, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 9, "selected": true, "text": "<pre><code>create table question_bank\n(\n question_id uniqueidentifier primary key,\n question_exam_id uniqueidentifier not null,\n question_text varchar(1024) not null,\n question_point_value decimal,\n constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)\n);\n</code></pre>\n" }, { "answer_id": 48838, "author": "Sara Chipps", "author_id": 4140, "author_profile": "https://Stackoverflow.com/users/4140", "pm_score": 6, "selected": false, "text": "<p>You can also name your foreign key constraint by using:</p>\n\n<pre><code>CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)\n</code></pre>\n" }, { "answer_id": 48883, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 8, "selected": false, "text": "<p>And if you just want to create the constraint on its own, you can use ALTER TABLE</p>\n\n<pre><code>alter table MyTable\nadd constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)\n</code></pre>\n\n<p>I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.</p>\n" }, { "answer_id": 52341, "author": "Vitor Silva", "author_id": 1842864, "author_profile": "https://Stackoverflow.com/users/1842864", "pm_score": 3, "selected": false, "text": "<p>Like you, I don't usually create foreign keys by hand, but if for some reason I need the script to do so I usually create it using ms sql server management studio and before saving then changes, I select Table Designer | Generate Change Script</p>\n" }, { "answer_id": 6297360, "author": "Bijimon", "author_id": 51038, "author_profile": "https://Stackoverflow.com/users/51038", "pm_score": 4, "selected": false, "text": "<pre><code>create table question_bank\n(\n question_id uniqueidentifier primary key,\n question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),\n question_text varchar(1024) not null,\n question_point_value decimal\n);\n</code></pre>\n\n<p>--That will work too. Pehaps a bit more intuitive construct?</p>\n" }, { "answer_id": 24415106, "author": "Shavais", "author_id": 283102, "author_profile": "https://Stackoverflow.com/users/283102", "pm_score": 5, "selected": false, "text": "<p>I like AlexCuse's answer, but something you should pay attention to whenever you add a foreign key constraint is how you want updates to the referenced column in a row of the referenced table to be treated, and especially how you want deletes of rows in the referenced table to be treated. </p>\n\n<p>If a constraint is created like this:</p>\n\n<pre><code>alter table MyTable\nadd constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) \nreferences MyOtherTable(PKColumn)\n</code></pre>\n\n<p>.. then <strong>updates or deletes in the referenced table will blow up with an error if there is a corresponding row in the referencing table.</strong></p>\n\n<p>That might be the behaviour you want, but in my experience, it much more commonly isn't.</p>\n\n<p>If you instead create it like this:</p>\n\n<pre><code>alter table MyTable\nadd constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) \nreferences MyOtherTable(PKColumn)\non update cascade \non delete cascade\n</code></pre>\n\n<p>..then updates and deletes in the parent table will result in updates and deletes of the corresponding rows in the referencing table.</p>\n\n<p>(I'm not suggesting that the default should be changed, the default errs on the side of caution, which is good. I'm just saying it's something that a person who is creating constaints <strong><em>should always pay attention to</em></strong>.)</p>\n\n<p>This can be done, by the way, when creating a table, like this:</p>\n\n<pre><code>create table ProductCategories (\n Id int identity primary key,\n ProductId int references Products(Id)\n on update cascade on delete cascade\n CategoryId int references Categories(Id) \n on update cascade on delete cascade\n)\n</code></pre>\n" }, { "answer_id": 33299702, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>Necromancing.<br />\nActually, doing this correctly is a little bit trickier. </p>\n\n<p>You first need to check if the primary-key exists for the column you want to set your foreign key to reference to. </p>\n\n<p>In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID </p>\n\n<pre><code>-- First, chech if the table exists...\nIF 0 &lt; (\n SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE = 'BASE TABLE'\n AND TABLE_SCHEMA = 'dbo'\n AND TABLE_NAME = 'T_SYS_Language_Forms'\n)\nBEGIN\n -- Check for NULL values in the primary-key column\n IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)\n BEGIN\n ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL \n\n -- No, don't drop, FK references might already exist...\n -- Drop PK if exists \n -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name \n --DECLARE @pkDropCommand nvarchar(1000) \n --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \n --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' \n --AND TABLE_SCHEMA = 'dbo' \n --AND TABLE_NAME = 'T_SYS_Language_Forms' \n ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' \n --))\n ---- PRINT @pkDropCommand \n --EXECUTE(@pkDropCommand) \n\n -- Instead do\n -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';\n\n\n -- Check if they keys are unique (it is very possible they might not be) \n IF 1 &gt;= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)\n BEGIN\n\n -- If no Primary key for this table\n IF 0 = \n (\n SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \n WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' \n AND TABLE_SCHEMA = 'dbo' \n AND TABLE_NAME = 'T_SYS_Language_Forms' \n -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' \n )\n ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)\n ;\n\n -- Adding foreign key\n IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') \n ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); \n END -- End uniqueness check\n ELSE\n PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' \n END -- End NULL check\n ELSE\n PRINT 'FSCK, need to figure out how to update NULL value(s)...' \nEND \n</code></pre>\n" }, { "answer_id": 37452116, "author": "Abhishek Jaiswal", "author_id": 5275530, "author_profile": "https://Stackoverflow.com/users/5275530", "pm_score": 3, "selected": false, "text": "<p>To Create a foreign key on any table </p>\n\n<pre><code>ALTER TABLE [SCHEMA].[TABLENAME] ADD FOREIGN KEY (COLUMNNAME) REFERENCES [TABLENAME](COLUMNNAME)\nEXAMPLE\nALTER TABLE [dbo].[UserMaster] ADD FOREIGN KEY (City_Id) REFERENCES [dbo].[CityMaster](City_Id)\n</code></pre>\n" }, { "answer_id": 44222324, "author": "elkhayari abderrazzak", "author_id": 7840801, "author_profile": "https://Stackoverflow.com/users/7840801", "pm_score": 3, "selected": false, "text": "<p>This script is about creating tables with foreign key and I added referential integrity constraint <strong>sql-server</strong>.</p>\n\n<pre><code>create table exams\n( \n exam_id int primary key,\n exam_name varchar(50),\n);\n\ncreate table question_bank \n(\n question_id int primary key,\n question_exam_id int not null,\n question_text varchar(1024) not null,\n question_point_value decimal,\n constraint question_exam_id_fk\n foreign key references exams(exam_id)\n ON DELETE CASCADE\n);\n</code></pre>\n" }, { "answer_id": 45422537, "author": "Md Ashikul Islam", "author_id": 7801470, "author_profile": "https://Stackoverflow.com/users/7801470", "pm_score": 3, "selected": false, "text": "<p>If you want to create two table's columns into a relationship by using a query try the following:</p>\n\n<pre><code>Alter table Foreign_Key_Table_name add constraint \nForeign_Key_Table_name_Columnname_FK\nForeign Key (Column_name) references \nAnother_Table_name(Another_Table_Column_name)\n</code></pre>\n" }, { "answer_id": 57623016, "author": "Aamir Shaikh", "author_id": 6043224, "author_profile": "https://Stackoverflow.com/users/6043224", "pm_score": 2, "selected": false, "text": "<p>I always use this syntax to create the foreign key constraint between 2 tables</p>\n\n<pre><code>Alter Table ForeignKeyTable\nAdd constraint `ForeignKeyTable_ForeignKeyColumn_FK`\n`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`\n</code></pre>\n\n<p>i.e. </p>\n\n<pre><code>Alter Table tblEmployee\nAdd constraint tblEmployee_DepartmentID_FK\nforeign key (DepartmentID) references tblDepartment (ID)\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: ``` drop table exams; drop table question_bank; drop table anwser_bank; create table exams ( exam_id uniqueidentifier primary key, exam_name varchar(50), ); create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint question_exam_id foreign key references exams(exam_id) ); create table anwser_bank ( anwser_id uniqueidentifier primary key, anwser_question_id uniqueidentifier, anwser_text varchar(1024), anwser_is_correct bit ); ``` When I run the query I get this error: > > Msg 8139, Level 16, State 0, Line 9 > Number of referencing columns in > foreign key differs from number of > referenced columns, table > 'question\_bank'. > > > Can you spot the error?
``` create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id) ); ```
48,774
<p>What's the "right" way to do the following as a boolean expression?</p> <pre><code>for i in `ls $1/resources`; do if [ $i != "database.db" ] then if [ $i != "tiles" ] then if [ $i != "map.pdf" ] then if [ $i != "map.png" ] then svn export -q $1/resources/$i ../MyProject/Resources/$i ... </code></pre>
[ { "answer_id": 48787, "author": "frizz", "author_id": 1003, "author_profile": "https://Stackoverflow.com/users/1003", "pm_score": 1, "selected": false, "text": "<pre><code>for i in `ls $1/resources`; do\n if [ $i != \"database.db\" ] &amp;&amp; [ $i != \"tiles\" ] &amp;&amp; [ $i != \"map.pdf\" ] &amp;&amp; [ $i != \"map.png\" ]; then\n svn export -q $1/resources/$i ../MyProject/Resources/$i\n</code></pre>\n" }, { "answer_id": 48793, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 3, "selected": false, "text": "<p>Even shorter:</p>\n\n<pre><code>for i in `ls $1/resources`; do\n if [ $i != databse.db -a $i != titles -a $i != map.pdf ]; then\n svn export -q $1/resources/$i ../MyProject/Resources/$i\n fi\ndone;\n</code></pre>\n\n<p>The <code>-a</code> in the if expression is the equivalent of the boolean AND in shell-tests. For more see <code>man test</code></p>\n" }, { "answer_id": 64106, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 5, "selected": true, "text": "<p>The other solutions have a couple of common mistakes:\n<a href=\"http://www.pixelbeat.org/programming/shell_script_mistakes.html\" rel=\"nofollow noreferrer\">http://www.pixelbeat.org/programming/shell_script_mistakes.html</a></p>\n\n<ol>\n<li><p><code>for i in $(ls ...)</code> is redundant/problematic\njust do: <code>for i in $1/resources*; do ...</code></p></li>\n<li><p><code>[ $i != file1 -a $1 != file2 ]</code> This actually has 2 problems.</p>\n\n<p>a. The <code>$i</code> is not quoted, hence names with spaces will cause issues</p>\n\n<p>b. <code>-a</code> is inefficient if <code>stat</code>ing files as it doesn't short circuit (I know the above is not <code>stat</code>ing files).</p></li>\n</ol>\n\n<p>So instead try:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>for i in $1/resources/*; do\n if [ \"$i\" != \"database.db\" ] &amp;&amp;\n [ \"$i\" != \"tiles\" ] &amp;&amp;\n [ \"$i\" != \"map.pdf\" ] &amp;&amp;\n [ \"$i\" != \"map.png\" ]; then\n svn export -q \"$i\" \"../MyProject/Resources/$(basename $i)\"\n fi\ndone\n</code></pre>\n" }, { "answer_id": 64247, "author": "Fred Yankowski", "author_id": 7887, "author_profile": "https://Stackoverflow.com/users/7887", "pm_score": 2, "selected": false, "text": "<p>Consider using a <strong>case</strong> statement:</p>\n\n<pre><code>for i in $(ls $1/resources); do\n case $i in\n database.db|tiles|map.pdf|map.png)\n ;;\n *)\n svn export -q $1/resources/$i ../MyProject/Resources/$i;;\n esac\ndone\n</code></pre>\n" }, { "answer_id": 31630150, "author": "Evan Langlois", "author_id": 3847182, "author_profile": "https://Stackoverflow.com/users/3847182", "pm_score": 1, "selected": false, "text": "<p>For future reference, the new [[ test operator is preferred. The accepted answer is close and everything mentioned applies, but that answer will require lots of quoting and calls to multiple tests.</p>\n\n<p>The preferred method would be something like:</p>\n\n<pre><code>for i in $1/resources/*; do\n if [[ $i != \"database.db\" &amp;&amp; $i != \"tiles\" &amp;&amp;\n $i != \"map.pdf\" &amp;&amp; $i != \"map.png\" ]]; then\n svn export -q \"$i\" \"../MyProject/Resources/$(basename $i)\"\n fi\ndone\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/79/" ]
What's the "right" way to do the following as a boolean expression? ``` for i in `ls $1/resources`; do if [ $i != "database.db" ] then if [ $i != "tiles" ] then if [ $i != "map.pdf" ] then if [ $i != "map.png" ] then svn export -q $1/resources/$i ../MyProject/Resources/$i ... ```
The other solutions have a couple of common mistakes: <http://www.pixelbeat.org/programming/shell_script_mistakes.html> 1. `for i in $(ls ...)` is redundant/problematic just do: `for i in $1/resources*; do ...` 2. `[ $i != file1 -a $1 != file2 ]` This actually has 2 problems. a. The `$i` is not quoted, hence names with spaces will cause issues b. `-a` is inefficient if `stat`ing files as it doesn't short circuit (I know the above is not `stat`ing files). So instead try: ```bsh for i in $1/resources/*; do if [ "$i" != "database.db" ] && [ "$i" != "tiles" ] && [ "$i" != "map.pdf" ] && [ "$i" != "map.png" ]; then svn export -q "$i" "../MyProject/Resources/$(basename $i)" fi done ```
48,794
<p>Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?</p> <p>[EDIT] Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.</p>
[ { "answer_id": 48821, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<p>The ViewData Model property should only be used for the content that you're viewing/editing on the main section of the UI.</p>\n\n<p>Other parts of the view may need some data present in ViewData, so just add those to the dictionary.</p>\n\n<p>I'd just pass data from the dictionary like this: ViewData[\"articles\"] to the partial. (or ViewData.Get() from MvcContrib).</p>\n\n<p>You might also look at the recently implemented SubController pattern implemented in <a href=\"http://mvccontrib.org\" rel=\"nofollow noreferrer\">MvcContrib</a>.</p>\n" }, { "answer_id": 48827, "author": "Dragan Panjkov", "author_id": 481, "author_profile": "https://Stackoverflow.com/users/481", "pm_score": 0, "selected": false, "text": "<p>yes, this is correct. but let's look at this scenario:\non views that are related to articles, I'd have ViewData[\"article\"], and on views related to pages, I have ViewData[\"pages\"], but I don't have both articles and pages available all time. So, if I add:</p>\n\n<p>Html.RenderPartial(\"articlesView\", ViewData[\"articles\"])</p>\n\n<p>Html.RenderPartial(\"pagesView\", ViewData[\"pages\"])</p>\n\n<p>to my masterpage, I'll have an exception thrown on each page on which ViewDataDictionary doesn't contain both articles and pages.</p>\n\n<p>At least, that's how I see it.</p>\n" }, { "answer_id": 641339, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "<p>I had a <a href=\"https://stackoverflow.com/questions/467855/should-an-asp-net-masterpage-get-its-data-from-the-view\">similar post</a> and came up with an object model to handle it. </p>\n\n<p>I HATE the non-strongly typed views so went with this approach and it is working well.</p>\n" }, { "answer_id": 919625, "author": "user113588", "author_id": 113588, "author_profile": "https://Stackoverflow.com/users/113588", "pm_score": 2, "selected": false, "text": "<p>How about creating an HtmlHelper extension method that allows you to call a partial view result on the an action on the controller.</p>\n\n<p>Something like</p>\n\n<pre><code> public static void RenderPartialAction&lt;TController&gt;(this HtmlHelper helper, Func&lt;TController, PartialViewResult&gt; actionToRender)\n where TController : Controller, new()\n{\n var arg = new TController {ControllerContext = helper.ViewContext.Controller.ControllerContext};\n actionToRender(arg).ExecuteResult(arg.ControllerContext);\n} \n</code></pre>\n\n<p>you could then use this in your master page like</p>\n\n<pre><code>&lt;% Html.RenderPartialAction((HomeController x) =&gt; x.RenderPartial()) %&gt;\n</code></pre>\n\n<p>and in your controller the appropriate method</p>\n\n<pre><code>public PartialViewResult RenderPartial()\n{\n\n return PartialView(\"~/Path/or/View\",_homeService.GetModel())\n}\n</code></pre>\n\n<p>Well that is my 2 cents anyway</p>\n" }, { "answer_id": 1727633, "author": "Jeremy", "author_id": 52168, "author_profile": "https://Stackoverflow.com/users/52168", "pm_score": 0, "selected": false, "text": "<p>The way that I handle this is by using a BaseViewModel. All Views are strongly typed against a view model that inherits from BaseViewModel. </p>\n\n<p>The BaseViewModel class has all of the information needed by the MasterPage. So for navigation your BaseViewModel may look like this:</p>\n\n<pre><code>public class BaseViewModel\n{\n public BaseViewModel()\n {\n NavigationItems = RetrieveNavigationItemsFromModel();\n }\n public List&lt;NavItems&gt; NavigationItems {get; set;}\n}\n</code></pre>\n\n<p>In your MasterPage and PartialViews, you can cast the Model to BaseViewModel and access the NavigationsItems property.</p>\n\n<pre><code>&lt;ul&gt;\n&lt;% foreach (NavItem ni in (Model as BaseViewModel).NavigationItems) { %&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;%= ni.Url %&gt;\" alt=\"&lt;%= ni.Alt%&gt;\"&gt;&lt;%= ni.DisplayText %&gt;&lt;/a&gt;\n &lt;/li&gt;\n&lt;% } %&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 1932597, "author": "Brett Rigby", "author_id": 114805, "author_profile": "https://Stackoverflow.com/users/114805", "pm_score": 1, "selected": false, "text": "<p>I think that your solution may lie in the land of MVC 2.0 RC and beyond...</p>\n\n<p>Phil Haack posted an article on his blog: <a href=\"http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx</a></p>\n" }, { "answer_id": 2026869, "author": "Ciddan", "author_id": 68891, "author_profile": "https://Stackoverflow.com/users/68891", "pm_score": 0, "selected": false, "text": "<p>This is a very late reply, but I got to this page whilst googling - so chances are someone else will see this question (and my reply) as well.</p>\n\n<p>The way I've worked around this problem is by using a simple jQuery script to load a PartialView and execute it's controller code. Sample below.</p>\n\n<pre><code>&lt;asp:Content ID=\"indexContent\" ContentPlaceHolderID=\"MainContent\" runat=\"server\"&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function() {\n $(\"#applicationForm\").load(\"/Home/ApplicationForm\");\n });\n &lt;/script&gt;\n\n &lt;div id=\"applicationForm\" /&gt;\n\n&lt;/asp:Content&gt;\n</code></pre>\n\n<p>The big drawback to this approach is that the client has to have scripting enabled for it to work (so it's really SEO unfriendly). If that's something you can live with it works well. I only use it on an intranet site where I know that each client has JavaScript enabled and I don't have to worry about google's bots.</p>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/481/" ]
Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial? [EDIT] Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.
How about creating an HtmlHelper extension method that allows you to call a partial view result on the an action on the controller. Something like ``` public static void RenderPartialAction<TController>(this HtmlHelper helper, Func<TController, PartialViewResult> actionToRender) where TController : Controller, new() { var arg = new TController {ControllerContext = helper.ViewContext.Controller.ControllerContext}; actionToRender(arg).ExecuteResult(arg.ControllerContext); } ``` you could then use this in your master page like ``` <% Html.RenderPartialAction((HomeController x) => x.RenderPartial()) %> ``` and in your controller the appropriate method ``` public PartialViewResult RenderPartial() { return PartialView("~/Path/or/View",_homeService.GetModel()) } ``` Well that is my 2 cents anyway
48,872
<p>In <a href="https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/" rel="noreferrer">Kathleen Dollard's 2008 blog post</a>, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.</p>
[ { "answer_id": 48879, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 8, "selected": true, "text": "<p>Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):</p>\n\n<pre><code>public class SortedMap {\n private class TreeNode {\n TreeNode left;\n TreeNode right;\n }\n}\n</code></pre>\n\n<p>You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.</p>\n\n<p>If the TreeNode class was external, you would either have to make all the fields <code>public</code> or make a bunch of <code>get/set</code> methods to use it. The outside world would have another class polluting their intellisense.</p>\n" }, { "answer_id": 48892, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>If I understand Katheleen's article right, she proposes to use nested class to be able to write SomeEntity.Collection instead of EntityCollection&lt; SomeEntity>. In my opinion it's controversial way to save you some typing. I'm pretty sure that in real world application collections will have some difference in implementations, so you will need to create separate class anyway. I think that using class name to limit other class scope is not a good idea. It pollutes intellisense and strengthen dependencies between classes. Using namespaces is a standard way to control classes scope. However I find that usage of nested classes like in @hazzen comment is acceptable unless you have tons of nested classes which is a sign of bad design.</p>\n" }, { "answer_id": 48902, "author": "Chris Dail", "author_id": 5077, "author_profile": "https://Stackoverflow.com/users/5077", "pm_score": 3, "selected": false, "text": "<p>It depends on the usage. I rarely would ever use a Public nested class but use Private nested classes all of the time. A private nested class can be used for a sub-object that is intended to be used only inside the parent. An example of this would be if a HashTable class contains a private Entry object to store data internally only.</p>\n\n<p>If the class is meant to be used by the caller (externally), I generally like making it a separate standalone class.</p>\n" }, { "answer_id": 48907, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html\" rel=\"noreferrer\">From Sun's Java Tutorial:</a></p>\n\n<p>Why Use Nested Classes?\nThere are several compelling reasons for using nested classes, among them:</p>\n\n<ul>\n<li>It is a way of logically grouping classes that are only used in one place.</li>\n<li>It increases encapsulation.</li>\n<li>Nested classes can lead to more readable and maintainable code.</li>\n</ul>\n\n<p>Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such \"helper classes\" makes their package more streamlined.</p>\n\n<p><s>Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.</s> &lt;- This doesn't apply to C#'s implementation of nested classes, this only applies to Java.</p>\n\n<p>More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used. </p>\n" }, { "answer_id": 1084589, "author": "kay.one", "author_id": 98970, "author_profile": "https://Stackoverflow.com/users/98970", "pm_score": 3, "selected": false, "text": "<p>Fully Lazy and thread-safe singleton pattern</p>\n<pre><code>public sealed class Singleton\n{\n Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n return Nested.instance;\n }\n }\n \n class Nested\n {\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static Nested()\n {\n }\n\n internal static readonly Singleton instance = new Singleton();\n }\n}\n</code></pre>\n<p>source: <a href=\"https://csharpindepth.com/Articles/Singleton\" rel=\"nofollow noreferrer\">https://csharpindepth.com/Articles/Singleton</a></p>\n" }, { "answer_id": 16093091, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "<p>I often use nested classes to hide implementation detail. <a href=\"https://stackoverflow.com/a/3300140/661933\">An example from Eric Lippert's answer here:</a></p>\n\n<pre><code>abstract public class BankAccount\n{\n private BankAccount() { }\n // Now no one else can extend BankAccount because a derived class\n // must be able to call a constructor, but all the constructors are\n // private!\n private sealed class ChequingAccount : BankAccount { ... }\n public static BankAccount MakeChequingAccount() { return new ChequingAccount(); }\n private sealed class SavingsAccount : BankAccount { ... }\n}\n</code></pre>\n\n<p><strong>This pattern becomes even better with use of generics.</strong> See <a href=\"https://stackoverflow.com/questions/16082303/generic-base-class-wraps-nested-generic-class-to-reduce-type-argument-specificat\">this question</a> for two cool examples. So I end up writing</p>\n\n<pre><code>Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Id);\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>new EqualityComparer&lt;Person, int&gt;(p =&gt; p.Id);\n</code></pre>\n\n<p>Also I can have a generic list of <code>Equality&lt;Person&gt;</code> but not <code>EqualityComparer&lt;Person, int&gt;</code></p>\n\n<pre><code>var l = new List&lt;Equality&lt;Person&gt;&gt; \n { \n Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Id),\n Equality&lt;Person&gt;.CreateComparer(p =&gt; p.Name) \n }\n</code></pre>\n\n<p>where as </p>\n\n<pre><code>var l = new List&lt;EqualityComparer&lt;Person, ??&gt;&gt;&gt; \n { \n new EqualityComparer&lt;Person, int&gt;&gt;(p =&gt; p.Id),\n new EqualityComparer&lt;Person, string&gt;&gt;(p =&gt; p.Name) \n }\n</code></pre>\n\n<p>is not possible. That's the benefit of nested class inheriting from parent class.</p>\n\n<p>Another case (of the same nature - hiding implementation) is when you want to make a class's members (fields, properties etc) accessible only for a single class:</p>\n\n<pre><code>public class Outer \n{\n class Inner //private class\n {\n public int Field; //public field\n }\n\n static inner = new Inner { Field = -1 }; // Field is accessible here, but in no other class\n}\n</code></pre>\n" }, { "answer_id": 18579666, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "<p>Another use not yet mentioned for nested classes is the segregation of generic types. For example, suppose one wants to have some generic families of static classes that can take methods with various numbers of parameters, along with values for some of those parameters, and generate delegates with fewer parameters. For example, one wishes to have a static method which can take an <code>Action&lt;string, int, double&gt;</code> and yield a <code>String&lt;string, int&gt;</code> which will call the supplied action passing 3.5 as the <code>double</code>; one may also wish to have a static method which can take an an <code>Action&lt;string, int, double&gt;</code> and yield an <code>Action&lt;string&gt;</code>, passing <code>7</code> as the <code>int</code> and <code>5.3</code> as the <code>double</code>. Using generic nested classes, one can arrange to have the method invocations be something like:</p>\n\n<pre><code>MakeDelegate&lt;string,int&gt;.WithParams&lt;double&gt;(theDelegate, 3.5);\nMakeDelegate&lt;string&gt;.WithParams&lt;int,double&gt;(theDelegate, 7, 5.3);\n</code></pre>\n\n<p>or, because the latter types in each expression can be inferred even though the former ones can't:</p>\n\n<pre><code>MakeDelegate&lt;string,int&gt;.WithParams(theDelegate, 3.5);\nMakeDelegate&lt;string&gt;.WithParams(theDelegate, 7, 5.3);\n</code></pre>\n\n<p>Using the nested generic types makes it possible to tell which delegates are applicable to which parts of the overall type description.</p>\n" }, { "answer_id": 19701232, "author": "diimdeep", "author_id": 199154, "author_profile": "https://Stackoverflow.com/users/199154", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/a/16093091/199154\">nawfal</a> mentioned implementation of Abstract Factory pattern, that code can be axtended to achieve <a href=\"https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html\" rel=\"nofollow noreferrer\">Class Clusters pattern</a> which is based on Abstract Factory pattern.</p>\n" }, { "answer_id": 23323649, "author": "Rachin Goyal", "author_id": 2120933, "author_profile": "https://Stackoverflow.com/users/2120933", "pm_score": 1, "selected": false, "text": "<p>The nested classes can be used for following needs:</p>\n\n<ol>\n<li>Classification of the data</li>\n<li>When the logic of the main class is complicated and you feel like you require subordinate objects to manage the class</li>\n<li>When you that the state and existence of the class fully depends on the enclosing class</li>\n</ol>\n" }, { "answer_id": 27575449, "author": "Eric Dand", "author_id": 1159805, "author_profile": "https://Stackoverflow.com/users/1159805", "pm_score": 0, "selected": false, "text": "<p>I like to nest exceptions that are unique to a single class, ie. ones that are never thrown from any other place.</p>\n\n<p>For example:</p>\n\n<pre><code>public class MyClass\n{\n void DoStuff()\n {\n if (!someArbitraryCondition)\n {\n // This is the only class from which OhNoException is thrown\n throw new OhNoException(\n \"Oh no! Some arbitrary condition was not satisfied!\");\n }\n // Do other stuff\n }\n\n public class OhNoException : Exception\n {\n // Constructors calling base()\n }\n}\n</code></pre>\n\n<p>This helps keep your project files tidy and not full of a hundred stubby little exception classes.</p>\n" }, { "answer_id": 28959647, "author": "tm1", "author_id": 806690, "author_profile": "https://Stackoverflow.com/users/806690", "pm_score": 0, "selected": false, "text": "<p>Bear in mind that you'll need to test the nested class. If it is private, you won't be able to test it in isolation.</p>\n\n<p>You could make it internal, though, <a href=\"https://stackoverflow.com/q/1211707/806690\">in conjunction with the <code>InternalsVisibleTo</code> attribute</a>. However, this would be the same as making a private field internal only for testing purposes, which I consider bad self-documentation.</p>\n\n<p>So, you may want to only implement private nested classes involving low complexity.</p>\n" }, { "answer_id": 29379421, "author": "Tyree Jackson", "author_id": 1072184, "author_profile": "https://Stackoverflow.com/users/1072184", "pm_score": 3, "selected": false, "text": "<p>In addition to the other reasons listed above, there is one more reason that I can think of not only to use nested classes, but in fact public nested classes. For those who work with multiple generic classes that share the same generic type parameters, the ability to declare a generic namespace would be extremely useful. Unfortunately, .Net (or at least C#) does not support the idea of generic namespaces. So in order to accomplish the same goal, we can use generic classes to fulfill the same goal. Take the following example classes related to a logical entity:</p>\n\n<pre><code>public class BaseDataObject\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n where tDataObject : BaseDataObject&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataObjectList : BaseDataObjectList&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;, new()\n where tBusiness : IBaseBusiness&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataAccess : IBaseDataAccess&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n}\n\npublic class BaseDataObjectList\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n: \n CollectionBase&lt;tDataObject&gt;\n where tDataObject : BaseDataObject&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataObjectList : BaseDataObjectList&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;, new()\n where tBusiness : IBaseBusiness&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataAccess : IBaseDataAccess&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n}\n\npublic interface IBaseBusiness\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n where tDataObject : BaseDataObject&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataObjectList : BaseDataObjectList&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;, new()\n where tBusiness : IBaseBusiness&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataAccess : IBaseDataAccess&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n}\n\npublic interface IBaseDataAccess\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n where tDataObject : BaseDataObject&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataObjectList : BaseDataObjectList&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;, new()\n where tBusiness : IBaseBusiness&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n where tDataAccess : IBaseDataAccess&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n}\n</code></pre>\n\n<p>We can simplify the signatures of these classes by using a generic namespace (implemented via nested classes):</p>\n\n<pre><code>public\npartial class Entity\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n where tDataObject : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.BaseDataObject\n where tDataObjectList : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.BaseDataObjectList, new()\n where tBusiness : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.IBaseBusiness\n where tDataAccess : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.IBaseDataAccess\n{\n\n public class BaseDataObject {}\n\n public class BaseDataObjectList : CollectionBase&lt;tDataObject&gt; {}\n\n public interface IBaseBusiness {}\n\n public interface IBaseDataAccess {}\n\n}\n</code></pre>\n\n<p>Then, through the use of partial classes as suggested by Erik van Brakel in an earlier comment, you can separate the classes into separate nested files. I recommend using a Visual Studio extension like NestIn to support nesting the partial class files. This allows the \"namespace\" class files to also be used to organize the nested class files in a folder like way.</p>\n\n<p>For example:</p>\n\n<p>Entity.cs</p>\n\n<pre><code>public\npartial class Entity\n &lt;\n tDataObject, \n tDataObjectList, \n tBusiness, \n tDataAccess\n &gt;\n where tDataObject : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.BaseDataObject\n where tDataObjectList : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.BaseDataObjectList, new()\n where tBusiness : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.IBaseBusiness\n where tDataAccess : Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;.IBaseDataAccess\n{\n}\n</code></pre>\n\n<p>Entity.BaseDataObject.cs</p>\n\n<pre><code>partial class Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n\n public class BaseDataObject\n {\n\n public DataTimeOffset CreatedDateTime { get; set; }\n public Guid CreatedById { get; set; }\n public Guid Id { get; set; }\n public DataTimeOffset LastUpdateDateTime { get; set; }\n public Guid LastUpdatedById { get; set; }\n\n public\n static\n implicit operator tDataObjectList(DataObject dataObject)\n {\n var returnList = new tDataObjectList();\n returnList.Add((tDataObject) this);\n return returnList;\n }\n\n }\n\n}\n</code></pre>\n\n<p>Entity.BaseDataObjectList.cs</p>\n\n<pre><code>partial class Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n\n public class BaseDataObjectList : CollectionBase&lt;tDataObject&gt;\n {\n\n public tDataObjectList ShallowClone() \n {\n var returnList = new tDataObjectList();\n returnList.AddRange(this);\n return returnList;\n }\n\n }\n\n}\n</code></pre>\n\n<p>Entity.IBaseBusiness.cs</p>\n\n<pre><code>partial class Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n\n public interface IBaseBusiness\n {\n tDataObjectList Load();\n void Delete();\n void Save(tDataObjectList data);\n }\n\n}\n</code></pre>\n\n<p>Entity.IBaseDataAccess.cs</p>\n\n<pre><code>partial class Entity&lt;tDataObject, tDataObjectList, tBusiness, tDataAccess&gt;\n{\n\n public interface IBaseDataAccess\n {\n tDataObjectList Load();\n void Delete();\n void Save(tDataObjectList data);\n }\n\n}\n</code></pre>\n\n<p>The files in the visual studio solution explorer would then be organized as such:</p>\n\n<pre><code>Entity.cs\n+ Entity.BaseDataObject.cs\n+ Entity.BaseDataObjectList.cs\n+ Entity.IBaseBusiness.cs\n+ Entity.IBaseDataAccess.cs\n</code></pre>\n\n<p>And you would implement the generic namespace like the following:</p>\n\n<p>User.cs</p>\n\n<pre><code>public\npartial class User\n:\n Entity\n &lt;\n User.DataObject, \n User.DataObjectList, \n User.IBusiness, \n User.IDataAccess\n &gt;\n{\n}\n</code></pre>\n\n<p>User.DataObject.cs</p>\n\n<pre><code>partial class User\n{\n\n public class DataObject : BaseDataObject \n {\n public string UserName { get; set; }\n public byte[] PasswordHash { get; set; }\n public bool AccountIsEnabled { get; set; }\n }\n\n}\n</code></pre>\n\n<p>User.DataObjectList.cs</p>\n\n<pre><code>partial class User\n{\n\n public class DataObjectList : BaseDataObjectList {}\n\n}\n</code></pre>\n\n<p>User.IBusiness.cs</p>\n\n<pre><code>partial class User\n{\n\n public interface IBusiness : IBaseBusiness {}\n\n}\n</code></pre>\n\n<p>User.IDataAccess.cs</p>\n\n<pre><code>partial class User\n{\n\n public interface IDataAccess : IBaseDataAccess {}\n\n}\n</code></pre>\n\n<p>And the files would be organized in the solution explorer as follows:</p>\n\n<pre><code>User.cs\n+ User.DataObject.cs\n+ User.DataObjectList.cs\n+ User.IBusiness.cs\n+ User.IDataAccess.cs\n</code></pre>\n\n<p>The above is a simple example of using an outer class as a generic namespace. I've built \"generic namespaces\" containing 9 or more type parameters in the past. Having to keep those type parameters synchronized across the nine types that all needed to know the type parameters was tedious, especially when adding a new parameter. The use of generic namespaces makes that code far more manageable and readable.</p>\n" }, { "answer_id": 50997412, "author": "Alex Martinez", "author_id": 4698151, "author_profile": "https://Stackoverflow.com/users/4698151", "pm_score": 0, "selected": false, "text": "<p>yes for this case:</p>\n\n<pre><code>class Join_Operator\n{\n\n class Departamento\n {\n public int idDepto { get; set; }\n public string nombreDepto { get; set; }\n }\n\n class Empleado\n {\n public int idDepto { get; set; }\n public string nombreEmpleado { get; set; }\n }\n\n public void JoinTables()\n {\n List&lt;Departamento&gt; departamentos = new List&lt;Departamento&gt;();\n departamentos.Add(new Departamento { idDepto = 1, nombreDepto = \"Arquitectura\" });\n departamentos.Add(new Departamento { idDepto = 2, nombreDepto = \"Programación\" });\n\n List&lt;Empleado&gt; empleados = new List&lt;Empleado&gt;();\n empleados.Add(new Empleado { idDepto = 1, nombreEmpleado = \"John Doe.\" });\n empleados.Add(new Empleado { idDepto = 2, nombreEmpleado = \"Jim Bell\" });\n\n var joinList = (from e in empleados\n join d in departamentos on\n e.idDepto equals d.idDepto\n select new\n {\n nombreEmpleado = e.nombreEmpleado,\n nombreDepto = d.nombreDepto\n });\n foreach (var dato in joinList)\n {\n Console.WriteLine(\"{0} es empleado del departamento de {1}\", dato.nombreEmpleado, dato.nombreDepto);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 63224333, "author": "Hamid", "author_id": 9523274, "author_profile": "https://Stackoverflow.com/users/9523274", "pm_score": 0, "selected": false, "text": "<p>Base on my understanding of this concept\nwe could use this feature when classes are related to each other conceptually.\nI mean some of them are complete one Item in our business like entities that exist in the DDD world that help to an aggregate root object to complete its business logic.</p>\n<p>In order to clarify I'm going to show this via an example:</p>\n<p>Imagine that we have two classes like Order and OrderItem.\nIn order class, we are going to manage all orderItems and in OrderItem we are holding data about a single order\nfor clarification, you can see below classes:</p>\n<pre><code> class Order\n {\n private List&lt;OrderItem&gt; _orderItems = new List&lt;OrderItem&gt;();\n\n public void AddOrderItem(OrderItem line)\n {\n _orderItems.Add(line);\n }\n\n public double OrderTotal()\n {\n double total = 0;\n foreach (OrderItem item in _orderItems)\n {\n total += item.TotalPrice();\n }\n\n return total;\n }\n\n // Nested class\n public class OrderItem\n {\n public int ProductId { get; set; }\n public int Quantity { get; set; }\n public double Price { get; set; }\n public double TotalPrice() =&gt; Price * Quantity;\n }\n }\n\n class Program\n {\n\n static void Main(string[] args)\n {\n Order order = new Order();\n\n Order.OrderItem orderItem1 = new Order.OrderItem();\n orderItem1.ProductId = 1;\n orderItem1.Quantity = 5;\n orderItem1.Price = 1.99;\n order.AddOrderItem(orderItem1);\n\n Order.OrderItem orderItem2 = new Order.OrderItem();\n orderItem2.ProductId = 2;\n orderItem2.Quantity = 12;\n orderItem2.Price = 0.35;\n order.AddOrderItem(orderItem2);\n\n Console.WriteLine(order.OrderTotal());\n ReadLine();\n }\n\n\n }\n</code></pre>\n" } ]
2008/09/07
[ "https://Stackoverflow.com/questions/48872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100/" ]
In [Kathleen Dollard's 2008 blog post](https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/), she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.
Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified): ``` public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; } } ``` You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation. If the TreeNode class was external, you would either have to make all the fields `public` or make a bunch of `get/set` methods to use it. The outside world would have another class polluting their intellisense.
48,908
<p>I am a bit confused about socket programming in C.</p> <p>You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article <s><a href="http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html" rel="nofollow noreferrer">Network programming under Unix systems</a></s> to be very informative.</p> <p>What confuses me is the timing of data arriving on the socket.</p> <p>How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? </p> <p>My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?</p>
[ { "answer_id": 48910, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>When you do a read on the socket, you tell it how many maximum bytes to read, but if it doesn't have that many, it gives you however many it's got. It's up to you to design the protocol so you know whether you've got a partial packet or not. For instance, in the past when sending variable length binary data, I would put an int at the beginning that said how many bytes to expect. I'd do a read requesting a number of bytes greater than the largest possible packet in my protocol, and then I'd compare the first int against however many bytes I'd received, and either process it or try more reads until I'd gotten the full packet, depending.</p>\n" }, { "answer_id": 48912, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "<p>Sockets operate at a higher level than raw packets - it's like a file you can read/write from. Also, when you try to read from a socket, the operating system will block (put on hold) your process until it has data to fulfill the request.</p>\n" }, { "answer_id": 48929, "author": "dfjacobs", "author_id": 4848, "author_profile": "https://Stackoverflow.com/users/4848", "pm_score": 5, "selected": true, "text": "<p>Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete.</p>\n\n<p>When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes.</p>\n\n<p>Here's a typical C function for reading a set number of bytes from a socket:</p>\n\n<pre><code>/* buffer points to memory block that is bigger than the number of bytes to be read */\n/* socket is open socket that is connected to a sender */\n/* bytesToRead is the number of bytes expected from the sender */\n/* bytesRead is a pointer to a integer variable that will hold the number of bytes */\n/* actually received from the sender. */\n/* The function returns either the number of bytes read, */\n/* 0 if the socket was closed by the sender, and */\n/* -1 if an error occurred while reading from the socket */\nint readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead)\n{\n *bytesRead = 0;\n while(*bytesRead &lt; bytesToRead)\n {\n int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead);\n if(ret &lt;= 0)\n {\n /* either connection was closed or an error occurred */\n return ret;\n }\n else\n {\n *bytesRead += ret;\n }\n }\n return *bytesRead;\n}\n</code></pre>\n" }, { "answer_id": 49131, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 4, "selected": false, "text": "<p>So, the answer to your question depends a fair bit on whether you are using UDP or TCP as your transport.</p>\n\n<p>For UDP, life gets a lot simpler, in that you can call recv/recvfrom/recvmsg with the packet size you need (you'd likely send fixed-length packets from the source anyway), and make the assumption that if data is available, it's there in multiples of packet-length sizes. (I.E. You call recv* with the size of your sending side packet, and you're set.)</p>\n\n<p>For TCP, life gets a bit more interesting - for the purpose of this explanation, I will assume that you already know how to use socket(), bind(), listen() and accept() - the latter being how you get the file descriptor (FD) of your newly made connection.</p>\n\n<p>There are two ways of doing the I/O for a socket - blocking, in which you call read(fd, buf, N) and the read sits there and waits until you've read N bytes into buf - or non-blocking, in which you have to check (using select() or poll()) whether the FD is readable, and THEN do your read().</p>\n\n<p>When dealing with TCP-based connections, the OS doesn't pay attention to the packet sizes, since it's considered a continual stream of data, not seperate packet-sized chunks.</p>\n\n<p>If your application uses \"packets\" (packed or unpacked data structures that you're passing around), you ought to be able to call read() with the proper size argument, and read an entire data structure off the socket at a time. The only caveat you have to deal with, is to remember to properly byte-order any data that you're sending, in case the source and destination system are of different byte endian-ness. This applies to both UDP and TCP.</p>\n\n<p>As far as *NIX socket programming is concerned, I highly recommend W. Richard Stevens' \"Unix Network Programming, Vol. 1\" (UNPv1) and \"Advanced Programming in an Unix Environment\" (APUE). The first is a tome regarding network-based programming, regardless of the transport, and the latter is a good all-around programming book as it applies to *NIX based programming. Also, look for \"TCP/IP Illustrated\", Volumes 1 and 2.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
I am a bit confused about socket programming in C. You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article ~~[Network programming under Unix systems](http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html)~~ to be very informative. What confuses me is the timing of data arriving on the socket. How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?
Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete. When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes. Here's a typical C function for reading a set number of bytes from a socket: ``` /* buffer points to memory block that is bigger than the number of bytes to be read */ /* socket is open socket that is connected to a sender */ /* bytesToRead is the number of bytes expected from the sender */ /* bytesRead is a pointer to a integer variable that will hold the number of bytes */ /* actually received from the sender. */ /* The function returns either the number of bytes read, */ /* 0 if the socket was closed by the sender, and */ /* -1 if an error occurred while reading from the socket */ int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead) { *bytesRead = 0; while(*bytesRead < bytesToRead) { int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead); if(ret <= 0) { /* either connection was closed or an error occurred */ return ret; } else { *bytesRead += ret; } } return *bytesRead; } ```
48,916
<p>I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress.</p> <p>I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the <code>main()</code> method?). I am also missing how <code>Application.Run()</code> works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway?</p> <p>I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :) </p>
[ { "answer_id": 48944, "author": "McKenzieG1", "author_id": 3776, "author_profile": "https://Stackoverflow.com/users/3776", "pm_score": 3, "selected": false, "text": "<p>One simple way is the use something like this as main():</p>\n\n<pre><code>&lt;STAThread()&gt; Public Shared Sub Main()\n\n splash = New frmSplash\n splash.Show()\n\n ' Your startup code goes here...\n\n UpdateSplashAndLogMessage(\"Startup part 1 done...\")\n\n ' ... and more as needed...\n\n splash.Hide()\n Application.Run(myMainForm)\nEnd Sub\n</code></pre>\n\n<p>When the .NET CLR starts your application, it creates a 'main' thread and starts executing your main() on that thread. The Application.Run(myMainForm) at the end does two things:</p>\n\n<ol>\n<li>Starts the Windows 'message pump', using the thread that has been executing main() as the GUI thread.</li>\n<li>Designates your 'main form' as the 'shutdown form' for the application. If the user closes that form, then the Application.Run() terminates and control returns to your main(), where you can do any shutdown you want.</li>\n</ol>\n\n<p>There is no need to spawn a thread to take care of the splash window, and in fact this is a bad idea, because then you would have to use thread-safe techniques to update the splash contents from main().</p>\n\n<p>If you need other threads to do background operations in your application, you can spawn them from main(). Just remember to set Thread.IsBackground to True, so that they will die when the main / GUI thread terminates. Otherwise you will have to arrange to terminate all your other threads yourself, or they will keep your application alive (but with no GUI) when the main thread terminates.</p>\n" }, { "answer_id": 48946, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<p>The trick is to to create separate thread responsible for splash screen showing.<br>\nWhen you run you app .net creates main thread and loads specified (main) form. To conceal hard work you can hide main form until loading is done. </p>\n\n<p>Assuming that Form1 - is your main form and SplashForm is top level, borderles nice splash form:</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n Hide();\n bool done = false;\n ThreadPool.QueueUserWorkItem((x) =&gt;\n {\n using (var splashForm = new SplashForm())\n {\n splashForm.Show();\n while (!done)\n Application.DoEvents();\n splashForm.Close();\n }\n });\n\n Thread.Sleep(3000); // Emulate hardwork\n done = true;\n Show();\n}\n</code></pre>\n" }, { "answer_id": 48971, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 7, "selected": true, "text": "<p>Well, for a ClickOnce app that I deployed in the past, we used the <code>Microsoft.VisualBasic</code> namespace to handle the splash screen threading. You can reference and use the <code>Microsoft.VisualBasic</code> assembly from C# in .NET 2.0 and it provides a lot of nice services.</p>\n\n<ol>\n<li>Have the main form inherit from <code>Microsoft.VisualBasic.WindowsFormsApplicationBase</code></li>\n<li><p>Override the \"OnCreateSplashScreen\" method like so:</p>\n\n<pre><code>protected override void OnCreateSplashScreen()\n{\n this.SplashScreen = new SplashForm();\n this.SplashScreen.TopMost = true;\n}\n</code></pre></li>\n</ol>\n\n<p>Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading.</p>\n\n<p>This really makes things simple, and the <code>VisualBasic.WindowsFormsApplicationBase</code> is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#.</p>\n\n<p>At the end of the day, it's all IL and <code>bytecode</code> anyway, so why not use it?</p>\n" }, { "answer_id": 49031, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 3, "selected": false, "text": "<p>I think using some method like <a href=\"https://stackoverflow.com/questions/48916/multi-threaded-splash-screen-in-c#48946\">aku's</a> or <a href=\"https://stackoverflow.com/questions/48916/multi-threaded-splash-screen-in-c#48971\">Guy's</a> is the way to go, but a couple of things to take away from the specific examples:</p>\n\n<ol>\n<li><p>The basic premise would be to show your splash on a separate thread as soon as possible. That's the way I would lean, similar to what aku's illustrated, since it's the way I'm most familiar with. I was not aware of the VB function Guy mentioned. And, even thought it's a <em>VB</em> library, he is right -- it's all IL in the end. So, even if it feels <em>dirty</em> it's not all that bad! :) I think you'll want to be sure that either VB provides a separate thread for in that override or that you create one yourself -- definitely research that.</p></li>\n<li><p>Assuming you create another thread to display this splash, you will want to be careful of cross thread UI updates. I bring this up because you mentioned updating progress. Basically, to be safe, you need to call an update function (that you create) on the splash form using a delegate. You pass that delegate to the <a href=\"http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx\" rel=\"nofollow noreferrer\">Invoke</a> function on your splash screen's form object. In fact if you call the splash form directly to update progress/UI elements on it, you'll get an exception provided you are running on the .Net 2.0 CLR. As a rule of thumb, any UI element on a form must be updated by the thread that created it -- that's what Form.Invoke insures.</p></li>\n</ol>\n\n<p>Finally, I would likely opt to create the splash (if not using the VB overload) in the main method of your code. To me this is better than having the main form perform creation of the object and to be so tightly bound to it. If you take that approach, I'd suggest creating a simple interface that the splash screen implements -- something like IStartupProgressListener -- which receives start-up progress updates via a member function. This will allow you to easily swap in/out either class as needed, and nicely decouples the code. The splash form can also know when to close itself if you notify when start-up is complete.</p>\n" }, { "answer_id": 2117094, "author": "DelftRed", "author_id": 256697, "author_profile": "https://Stackoverflow.com/users/256697", "pm_score": 3, "selected": false, "text": "<p>I recommend calling <code>Activate();</code> directly after the last <code>Show();</code> in the answer provided by aku.</p>\n\n<p>Quoting MSDN: </p>\n\n<blockquote>\n <p>Activating a form brings it to the\n front if this is the active\n application, or it flashes the window\n caption if this is not the active\n application. The form must be visible\n for this method to have any effect.</p>\n</blockquote>\n\n<p>If you don't activate your main form, it may be displayed <em>behind</em> any other open windows, making it look a bit silly.</p>\n" }, { "answer_id": 2117218, "author": "K Singh", "author_id": 139406, "author_profile": "https://Stackoverflow.com/users/139406", "pm_score": 2, "selected": false, "text": "<p>I posted an article on splash screen incorporation in the application at codeproject. It is multithreaded and might be of your interest</p>\n\n<p><a href=\"http://www.codeproject.com/KB/dotnet/Yet_Another_Splash_Screen.aspx\" rel=\"noreferrer\">Yet Another Splash Screen in C#</a></p>\n" }, { "answer_id": 3296362, "author": "Jay", "author_id": 114994, "author_profile": "https://Stackoverflow.com/users/114994", "pm_score": 3, "selected": false, "text": "<p>This is an old question, but I kept coming across it when trying to find a threaded splash screen solution for WPF that could include animation.</p>\n\n<p>Here is what I ultimately pieced together:</p>\n\n<p>App.XAML:</p>\n\n<pre><code>&lt;Application Startup=\"ApplicationStart\" …\n</code></pre>\n\n<p>App.XAML.cs:</p>\n\n<pre><code>void ApplicationStart(object sender, StartupEventArgs e)\n{\n var thread = new Thread(() =&gt;\n {\n Dispatcher.CurrentDispatcher.BeginInvoke ((Action)(() =&gt; new MySplashForm().Show()));\n Dispatcher.Run();\n });\n thread.SetApartmentState(ApartmentState.STA);\n thread.IsBackground = true;\n thread.Start();\n\n // call synchronous configuration process\n // and declare/get reference to \"main form\"\n\n thread.Abort();\n\n mainForm.Show();\n mainForm.Activate();\n }\n</code></pre>\n" }, { "answer_id": 4994912, "author": "Adam Nofsinger", "author_id": 18524, "author_profile": "https://Stackoverflow.com/users/18524", "pm_score": 4, "selected": false, "text": "<p>After looking all over Google and SO for solutions, this is my favorite:\n<a href=\"http://bytes.com/topic/c-sharp/answers/277446-winform-startup-splash-screen\">http://bytes.com/topic/c-sharp/answers/277446-winform-startup-splash-screen</a></p>\n\n<p><strong>FormSplash.cs:</strong></p>\n\n<pre><code>public partial class FormSplash : Form\n{\n private static Thread _splashThread;\n private static FormSplash _splashForm;\n\n public FormSplash() {\n InitializeComponent();\n }\n\n /// &lt;summary&gt;\n /// Show the Splash Screen (Loading...)\n /// &lt;/summary&gt;\n public static void ShowSplash()\n {\n if (_splashThread == null)\n {\n // show the form in a new thread\n _splashThread = new Thread(new ThreadStart(DoShowSplash));\n _splashThread.IsBackground = true;\n _splashThread.Start();\n }\n }\n\n // called by the thread\n private static void DoShowSplash()\n {\n if (_splashForm == null)\n _splashForm = new FormSplash();\n\n // create a new message pump on this thread (started from ShowSplash)\n Application.Run(_splashForm);\n }\n\n /// &lt;summary&gt;\n /// Close the splash (Loading...) screen\n /// &lt;/summary&gt;\n public static void CloseSplash()\n {\n // need to call on the thread that launched this splash\n if (_splashForm.InvokeRequired)\n _splashForm.Invoke(new MethodInvoker(CloseSplash));\n\n else\n Application.ExitThread();\n }\n}\n</code></pre>\n\n<p><strong>Program.cs:</strong></p>\n\n<pre><code>static class Program\n{\n /// &lt;summary&gt;\n /// The main entry point for the application.\n /// &lt;/summary&gt;\n [STAThread]\n static void Main(string[] args)\n {\n // splash screen, which is terminated in FormMain\n FormSplash.ShowSplash();\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n // this is probably where your heavy lifting is:\n Application.Run(new FormMain());\n }\n}\n</code></pre>\n\n<p><strong>FormMain.cs</strong></p>\n\n<pre><code> ...\n\n public FormMain()\n {\n InitializeComponent(); \n\n // bunch of database access, form loading, etc\n // this is where you could do the heavy lifting of \"loading\" the app\n PullDataFromDatabase();\n DoLoadingWork(); \n\n // ready to go, now close the splash\n FormSplash.CloseSplash();\n }\n</code></pre>\n\n<p>I had issues with the <code>Microsoft.VisualBasic</code> solution -- Worked find on XP, but on Windows 2003 Terminal Server, the main application form would show up (after the splash screen) in the background, and the taskbar would blink. And bringing a window to foreground/focus in code is a whole other can of worms you can Google/SO for.</p>\n" }, { "answer_id": 6744070, "author": "Reabetswe Molefe", "author_id": 851539, "author_profile": "https://Stackoverflow.com/users/851539", "pm_score": 2, "selected": false, "text": "<pre><code>private void MainForm_Load(object sender, EventArgs e)\n{\n FormSplash splash = new FormSplash();\n splash.Show();\n splash.Update();\n System.Threading.Thread.Sleep(3000);\n splash.Hide();\n}\n</code></pre>\n\n<p>I got this from the Internet somewhere but cannot seem to find it again. Simple but yet effective.</p>\n" }, { "answer_id": 8234046, "author": "Patratacus", "author_id": 179037, "author_profile": "https://Stackoverflow.com/users/179037", "pm_score": 2, "selected": false, "text": "<p>I like Aku's answer a lot, but the code is for C# 3.0 and up since it uses a lambda function. For people needing to use the code in C# 2.0, here's the code using anonymous delegate instead of the lambda function. You need a topmost winform called <code>formSplash</code> with <code>FormBorderStyle = None</code>. The <code>TopMost = True</code> parameter of the form is important because the splash screen might look like it appears then disappears quickly if it's not topmost. I also choose <code>StartPosition=CenterScreen</code> so it looks like what a professional app would do with a splash screen. If you want an even cooler effect, you can use the <code>TrasparencyKey</code> property to make an irregular shaped splash screen.</p>\n\n<pre><code>private void formMain_Load(object sender, EventArgs e)\n {\n\n Hide();\n bool done = false;\n ThreadPool.QueueUserWorkItem(delegate\n {\n using (formSplash splashForm = new formSplash())\n {\n splashForm.Show();\n while (!done)\n Application.DoEvents();\n splashForm.Close();\n }\n }, null);\n\n Thread.Sleep(2000);\n done = true;\n Show();\n }\n</code></pre>\n" }, { "answer_id": 18376592, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 2, "selected": false, "text": "<p>I disagree with the other answers recommending <code>WindowsFormsApplicationBase</code>. In my experience, it can slow your app. To be precise, while it runs your form's constructor in parallel with the splash screen, it postpone your form's Shown event.</p>\n\n<p>Consider an app (without splashs screen) with a constructor that takes 1 second and a event handler on Shown that takes 2 seconds. This app is usable after 3 seconds.</p>\n\n<p>But suppose you install a splash screen using <code>WindowsFormsApplicationBase</code>. You might think <code>MinimumSplashScreenDisplayTime</code> of 3 seconds is sensible and won't slow your app. But, try it, your app will now take 5 seconds to load.</p>\n\n<hr>\n\n<pre><code>class App : WindowsFormsApplicationBase\n{\n protected override void OnCreateSplashScreen()\n {\n this.MinimumSplashScreenDisplayTime = 3000; // milliseconds\n this.SplashScreen = new Splash();\n }\n\n protected override void OnCreateMainForm()\n {\n this.MainForm = new Form1();\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public Form1()\n{\n InitializeComponent();\n Shown += Form1_Shown;\n Thread.Sleep(TimeSpan.FromSeconds(1));\n}\n\nvoid Form1_Shown(object sender, EventArgs e)\n{\n Thread.Sleep(TimeSpan.FromSeconds(2));\n Program.watch.Stop();\n this.textBox1.Text = Program.watch.ElapsedMilliseconds.ToString();\n}\n</code></pre>\n\n<hr>\n\n<p>Conclusion: don't use <code>WindowsFormsApplicationBase</code> if your app has a handler on the Slown event. You can write better code that runs the splash in parallel to both the constructor and the Shown event.</p>\n" }, { "answer_id": 46033441, "author": "Do-do-new", "author_id": 3535036, "author_profile": "https://Stackoverflow.com/users/3535036", "pm_score": 0, "selected": false, "text": "<p>Actually mutlithreading here is not necessary.</p>\n\n<p>Let your business logic generate an event whenever you want to update splash screen. </p>\n\n<p>Then let your form update the splash screen accordingly in the method hooked to eventhandler.</p>\n\n<p>To differentiate updates you can either fire different events or provide data in a class inherited from EventArgs.</p>\n\n<p>This way you can have nice changing splash screen without any multithreading headache.</p>\n\n<p>Actually with this you can even support, for example, gif image on a splash form. In order for it to work, call Application.DoEvents() in your handler:</p>\n\n<pre><code>private void SomethingChanged(object sender, MyEventArgs e)\n{\n formSplash.Update(e);\n Application.DoEvents(); //this will update any animation\n}\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246/" ]
I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress. I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the `main()` method?). I am also missing how `Application.Run()` works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway? I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :)
Well, for a ClickOnce app that I deployed in the past, we used the `Microsoft.VisualBasic` namespace to handle the splash screen threading. You can reference and use the `Microsoft.VisualBasic` assembly from C# in .NET 2.0 and it provides a lot of nice services. 1. Have the main form inherit from `Microsoft.VisualBasic.WindowsFormsApplicationBase` 2. Override the "OnCreateSplashScreen" method like so: ``` protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashForm(); this.SplashScreen.TopMost = true; } ``` Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading. This really makes things simple, and the `VisualBasic.WindowsFormsApplicationBase` is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#. At the end of the day, it's all IL and `bytecode` anyway, so why not use it?
48,919
<p>What is the JavaScript to scroll to the top when a button/link/etc. is clicked?</p>
[ { "answer_id": 48925, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;a href=\"javascript:scroll(0, 0)\"&gt;Top&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 48939, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 2, "selected": false, "text": "<p>If you had an anchor link at the top of the page, you could do it with anchors too.</p>\n\n<pre><code>&lt;a name=\"top\"&gt;&lt;/a&gt;\n&lt;a href='#top\"&gt;top&lt;/a&gt;\n</code></pre>\n\n<p>It'll work in browser's with Javascript disabled, but changes the url. :( It also lets you jump to anywhere the name anchor is set.</p>\n" }, { "answer_id": 68626, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<p>actually, this works by itself, no need to define it.</p>\n\n<pre><code>&lt;a href=\"#top\"&gt;top&lt;/a&gt;\n</code></pre>\n\n<p>This is a \"magic\" hashname value that does not need to be defined in browsers.</p>\n\n<p>Just like this will \"reload\" the page.</p>\n\n<pre><code>&lt;a href=\"/\"&gt;reload&lt;/a&gt;\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
What is the JavaScript to scroll to the top when a button/link/etc. is clicked?
``` <a href="javascript:scroll(0, 0)">Top</a> ```
48,931
<p>I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions.</p> <p>I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour.</p> <p>I think these can be stored using the <code>jQuery.data()</code> function:</p> <pre><code>//save old hover behavior (somehow) $('#foo').data('oldhoverin',???) $('#foo').data('oldhoverout',???); //set new hover behavior $('#foo').hover(newhoverin,newhoverout); </code></pre> <p>Do stuff with new hover behaviour...</p> <pre><code>//restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); </code></pre> <p>But how do I get the currently registered hover functions from jQuery?</p> <p>Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"</p>
[ { "answer_id": 49042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this is what you mean, but you can bind custom events and then trigger them.</p>\n\n<p><a href=\"http://docs.jquery.com/Events/bind\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/bind</a></p>\n\n<p>So add your hover event, script the functionality you need for that hover, then trigger your custom event.</p>\n" }, { "answer_id": 49126, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<p>Not sure if this will work, but you can try this:</p>\n\n<pre><code>\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;Jquery - Get, change and restore hover handlers&lt;/title&gt;\n &lt;script src=\"jquery.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n function setHover(obj, mouseenter, mouseleave) {\n obj.data(\"_mouseenter\", mouseenter);\n obj.data(\"_mouseleave\", mouseleave);\n obj.hover(obj.data(\"_mouseenter\"), obj.data(\"_mouseleave\"));\n }\n function removeHover(obj) {\n obj.unbind(\"mouseenter\", obj.data(\"_mouseenter\"));\n obj.unbind(\"mouseleave\", obj.data(\"_mouseleave\"));\n obj.data(\"_mouseenter\", undefined);\n obj.data(\"_mouseleave\", undefined);\n }\n $(document).ready(function() {\n var test = $(\"#test\");\n setHover(test, function(e) {\n alert(\"original \" + e.type);\n }, function(e) {\n alert(\"original \" + e.type);\n });\n var saved_mouseenter = test.data(\"_mouseenter\");\n var saved_mouseleave = test.data(\"_mouseleave\");\n removeHover(test);\n setHover(test, function() {\n alert(\"zip\");\n }, function() {\n alert('zam');\n });\n removeHover(test);\n setHover(test, saved_mouseenter, saved_mouseleave);\n });\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;p&gt;&lt;a id=\"test\" href=\"\"&gt;test&lt;/a&gt;&lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>If not, maybe it'll give you some ideas.</p>\n" }, { "answer_id": 49434, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 3, "selected": true, "text": "<p>Calling an event <code>bind</code> method (such as <code>hover</code>) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events.</p>\n\n<p>You can add your own events, and then remove them without affecting any other events then use Event namespacing: <a href=\"http://docs.jquery.com/Events_(Guide)#Namespacing_events\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events_(Guide)#Namespacing_events</a></p>\n" }, { "answer_id": 49700, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 0, "selected": false, "text": "<p>Maybe it would be easier to just hide the old element and create a clone with your event handlers attached? Then just swap back in the old element when you're done..</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5114/" ]
I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions. I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour. I think these can be stored using the `jQuery.data()` function: ``` //save old hover behavior (somehow) $('#foo').data('oldhoverin',???) $('#foo').data('oldhoverout',???); //set new hover behavior $('#foo').hover(newhoverin,newhoverout); ``` Do stuff with new hover behaviour... ``` //restore old hover behaviour $('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout')); ``` But how do I get the currently registered hover functions from jQuery? Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"
Calling an event `bind` method (such as `hover`) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events. You can add your own events, and then remove them without affecting any other events then use Event namespacing: <http://docs.jquery.com/Events_(Guide)#Namespacing_events>
48,933
<p>Does anybody know of a way to list up the "loaded plugins" in <strong>Vim</strong>? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status.</p>
[ { "answer_id": 48952, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 10, "selected": true, "text": "<p>Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following <a href=\"http://rayninfo.co.uk/vimtips.html\" rel=\"noreferrer\">VIM Tips</a> site: </p>\n\n<pre><code>\" where was an option set \n:scriptnames : list all plugins, _vimrcs loaded (super) \n:verbose set history? : reveals value of history and where set \n:function : list functions \n:func SearchCompl : List particular function\n</code></pre>\n" }, { "answer_id": 6706782, "author": "Mohammed", "author_id": 846425, "author_profile": "https://Stackoverflow.com/users/846425", "pm_score": 6, "selected": false, "text": "<p>The problem with <code>:scriptnames</code>, <code>:commands</code>, <code>:functions</code>, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.</p>\n\n<p>To get around this, I wrote <a href=\"https://github.com/mbadran/headlights\" rel=\"noreferrer\">Headlights</a>, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.</p>\n" }, { "answer_id": 33961194, "author": "Matt Florence", "author_id": 76289, "author_profile": "https://Stackoverflow.com/users/76289", "pm_score": 5, "selected": false, "text": "<p>If you use <a href=\"https://github.com/VundleVim/Vundle.vim\">Vundle</a>, <code>:PluginList</code>.</p>\n" }, { "answer_id": 39443529, "author": "akashbw", "author_id": 5123544, "author_profile": "https://Stackoverflow.com/users/5123544", "pm_score": 5, "selected": false, "text": "<pre><code>:set runtimepath?\n</code></pre>\n\n<p>This lists the path of all plugins loaded when a file is opened with Vim.</p>\n" }, { "answer_id": 54680934, "author": "penkwin", "author_id": 3550086, "author_profile": "https://Stackoverflow.com/users/3550086", "pm_score": 4, "selected": false, "text": "<p>:help local-additions</p>\n\n<p>Lists local plugins added.</p>\n" }, { "answer_id": 64393657, "author": "aris", "author_id": 2628879, "author_profile": "https://Stackoverflow.com/users/2628879", "pm_score": 3, "selected": false, "text": "<p>If you use <a href=\"https://github.com/junegunn/vim-plug\" rel=\"noreferrer\">vim-plug</a> (Plug), &quot;\nA minimalist Vim plugin manager.&quot;:</p>\n<pre><code>:PlugStatus\n</code></pre>\n<p>That will not only list your plugins but check their status.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4037/" ]
Does anybody know of a way to list up the "loaded plugins" in **Vim**? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status.
Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following [VIM Tips](http://rayninfo.co.uk/vimtips.html) site: ``` " where was an option set :scriptnames : list all plugins, _vimrcs loaded (super) :verbose set history? : reveals value of history and where set :function : list functions :func SearchCompl : List particular function ```
48,934
<p>I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:</p> <pre><code>procedure TForm1.CalculateGP(..) const Price : money = 0; begin ... Price := 1.0; ... end; </code></pre> <p>So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, <strong>why</strong>? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?</p>
[ { "answer_id": 48938, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 6, "selected": true, "text": "<p>You need to turn assignable typed constants on.\n\nProject -> Options -> Compiler -> Assignable typed Constants</p>\n\n<p>Also you can add <code>{$J+}</code> or <code>{$WRITEABLECONST ON}</code> to the pas file, which is probably better, since it'll work even if you move the file to another project.</p>\n" }, { "answer_id": 49060, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 5, "selected": false, "text": "<p>Type-inferred constants can only be scalar values - i.e. things like integers, doubles, etc. For these kinds of constants, the compiler does indeed replace the constant's symbol with the constant's value whenever it meets them in expressions.</p>\n\n<p>Typed constants, on the other hand, can be structured values - arrays and records. These guys need actual storage in the executable - i.e. they need to have storage allocated for them such that, when the OS loads the executable, the value of the typed constant is physically contained at some location in memory.</p>\n\n<p>To explain why, historically, typed constants in early Delphi and its predecessor, Turbo Pascal, are writable (and thus essentially initialized global variables), we need to go back to the days of DOS.</p>\n\n<p>DOS runs in real-mode, in x86 terms. This means that programs have direct access to physical memory without any <a href=\"http://en.wikipedia.org/wiki/Memory_management_unit\" rel=\"noreferrer\">MMU</a> doing virtual-physical mappings. When programs have direct access to memory, no memory protection is in effect. In other words, if there is memory at any given address, it is both readable and writable in real-mode.</p>\n\n<p>So, in a Turbo Pascal program for DOS with a typed constant, whose value is allocated at an address in memory at runtime, that typed constant will be writable. There is no hardware MMU getting in the way and preventing the program from writing to it. Similarly, because Pascal has no notion of 'const'ness that C++ has, there is nothing in the type system to stop you. A lot of people took advantage of this, since Turbo Pascal and Delphi did not at that time have initialized global variables as a feature.</p>\n\n<p>Moving on to Windows, there is a layer between memory addresses and physical addresses: the memory management unit. This chip takes the page index (a shifted mask) of the memory address you're trying to access, and looks up the attributes of this page in its <a href=\"http://en.wikipedia.org/wiki/Page_table\" rel=\"noreferrer\">page table</a>. These attributes include readable, writable, and for modern x86 chips, non-executable flags. With this support, it's possible to mark sections of the .EXE or .DLL with attributes such that when the Windows loader loads the executable image into memory, it assigns appropriate page attributes for memory pages that map to disk pages within these sections.</p>\n\n<p>When the 32-bit Windows version of the Delphi compiler came around, it thus made sense to make const-like things <strong>really</strong> const, as the OS also has this feature.</p>\n" }, { "answer_id": 68314, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": false, "text": "<ol>\n<li><p>Why: Because in previous versions of Delphi the typed constants were assignable by default to preserve compatibility with older versions where they were always writable (Delphi 1 up to early Pascal).<br>\nThe default has now been changed to make constants really constant…</p></li>\n<li><p>Compiler switch: {$J+} or {$J-} {$WRITEABLECONST ON} or {$WRITEABLECONST OFF}<br>\nOr in the project options for the compiler: check assignable typed Constants </p></li>\n<li>How it works: If the compiler can compute the value at compile time, it replaces the const by its value everywhere in the code, otherwise it holds a pointer to a memory area holding the value, which can be made writeable or not. </li>\n<li>see 3.</li>\n</ol>\n" }, { "answer_id": 100061, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 2, "selected": false, "text": "<p>Like Barry said, people took advantage of consts; One of the ways this was used, was for keeping track of singleton instances.\nIf you look at a classic singleton implementation, you would see this :</p>\n\n<pre><code> // Example implementation of the Singleton pattern.\n TSingleton = class(TObject)\n protected\n constructor CreateInstance; virtual;\n class function AccessInstance(Request: Integer): TSingleton;\n public\n constructor Create; virtual;\n destructor Destroy; override;\n class function Instance: TSingleton;\n class procedure ReleaseInstance;\n end;\n\nconstructor TSingleton.Create;\nbegin\n inherited Create;\n\n raise Exception.CreateFmt('Access class %s through Instance only', [ClassName]);\nend;\n\nconstructor TSingleton.CreateInstance;\nbegin\n inherited Create;\n\n // Do whatever you would normally place in Create, here.\nend;\n\ndestructor TSingleton.Destroy;\nbegin\n // Do normal destruction here\n\n if AccessInstance(0) = Self then\n AccessInstance(2);\n\n inherited Destroy;\nend;\n\n{$WRITEABLECONST ON}\nclass function TSingleton.AccessInstance(Request: Integer): TSingleton;\nconst\n FInstance: TSingleton = nil;\nbegin\n case Request of\n 0 : ;\n 1 : if not Assigned(FInstance) then\n FInstance := CreateInstance;\n 2 : FInstance := nil;\n else\n raise Exception.CreateFmt('Illegal request %d in AccessInstance', [Request]);\n end;\n Result := FInstance;\nend;\n{$IFNDEF WRITEABLECONST_ON}\n {$WRITEABLECONST OFF}\n{$ENDIF}\n\nclass function TSingleton.Instance: TSingleton;\nbegin\n Result := AccessInstance(1);\nend;\n\nclass procedure TSingleton.ReleaseInstance;\nbegin\n AccessInstance(0).Free;\nend;\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this: ``` procedure TForm1.CalculateGP(..) const Price : money = 0; begin ... Price := 1.0; ... end; ``` So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, **why**? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?
You need to turn assignable typed constants on. Project -> Options -> Compiler -> Assignable typed Constants Also you can add `{$J+}` or `{$WRITEABLECONST ON}` to the pas file, which is probably better, since it'll work even if you move the file to another project.
48,935
<p>I'm building an application in C# using WPF. How can I bind to some keys?</p> <p>Also, how can I bind to the <a href="http://en.wikipedia.org/wiki/Windows_key" rel="noreferrer">Windows key</a>?</p>
[ { "answer_id": 48942, "author": "John Virgolino", "author_id": 4246, "author_profile": "https://Stackoverflow.com/users/4246", "pm_score": 1, "selected": false, "text": "<p>I'm not sure about WPF, but this may help. I used the solution described in <em><a href=\"http://www.pinvoke.net/default.aspx/user32/RegisterHotKey.html\" rel=\"nofollow noreferrer\">RegisterHotKey (user32)</a></em> (modified to my needs of course) for a C# Windows Forms application to assign a CTRL-KEY combination within Windows to bring up a C# form, and it worked beautifully (even on Windows Vista). I hope it helps and good luck!</p>\n" }, { "answer_id": 49102, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 0, "selected": false, "text": "<p><code>RegisterHotKey()</code> suggested by John could work - the only catch is that it requires an HWND (using <code>PresentationSource.FromVisual()</code>, and casting the result to an HwndSource). </p>\n\n<p>However, you'll also need to respond to the <code>WM_HOTKEY</code> message - I'm not sure if there is a way to get access to the WndProc of a WPF window or not (which can be done for Windows Forms windows).</p>\n" }, { "answer_id": 49171, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "<p>I'm not sure of what you mean by &quot;global&quot; here, but here it goes (I'm assuming you mean a command at the application level, for example, <em>Save All</em> that can be triggered from anywhere by <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd>.)</p>\n<p>You find the global <code>UIElement</code> of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to &quot;bubbling&quot; of WPF events, events at child elements will bubble all the way up to the root of the control tree.</p>\n<p>Now, first you need</p>\n<ol>\n<li>to bind the Key-Combo with a Command using an <code>InputBinding</code> like this</li>\n<li>you can then hookup the command to your handler (e.g. code that gets called by <code>SaveAll</code>) via a <code>CommandBinding</code>.</li>\n</ol>\n<p>For the <kbd>Windows</kbd> Key, you use the right <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx\" rel=\"nofollow noreferrer\">Key</a> enumerated member, <strong><code>Key.LWin</code></strong> or <strong><code>Key.RWin</code></strong></p>\n<pre><code>public WindowMain()\n{\n InitializeComponent();\n\n // Bind Key\n var ib = new InputBinding(\n MyAppCommands.SaveAll,\n new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));\n this.InputBindings.Add(ib);\n\n // Bind handler\n var cb = new CommandBinding( MyAppCommands.SaveAll);\n cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );\n\n this.CommandBindings.Add (cb );\n}\n\nprivate void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)\n{\n // Do the Save All thing here.\n}\n</code></pre>\n" }, { "answer_id": 1960122, "author": "jgraves", "author_id": 204961, "author_profile": "https://Stackoverflow.com/users/204961", "pm_score": 4, "selected": false, "text": "<p>If you're going to mix Win32 and WPF, here's how I did it:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Windows.Interop;\nusing System.Windows.Media;\nusing System.Threading;\nusing System.Windows;\nusing System.Windows.Input;\n\nnamespace GlobalKeyboardHook\n{\n public class KeyboardHandler : IDisposable\n {\n\n public const int WM_HOTKEY = 0x0312;\n public const int VIRTUALKEYCODE_FOR_CAPS_LOCK = 0x14;\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);\n\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool UnregisterHotKey(IntPtr hWnd, int id);\n\n private readonly Window _mainWindow;\n WindowInteropHelper _host;\n\n public KeyboardHandler(Window mainWindow)\n {\n _mainWindow = mainWindow;\n _host = new WindowInteropHelper(_mainWindow);\n\n SetupHotKey(_host.Handle);\n ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;\n }\n\n void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)\n {\n if (msg.message == WM_HOTKEY)\n {\n //Handle hot key kere\n }\n }\n\n private void SetupHotKey(IntPtr handle)\n {\n RegisterHotKey(handle, GetType().GetHashCode(), 0, VIRTUALKEYCODE_FOR_CAPS_LOCK);\n }\n\n public void Dispose()\n {\n UnregisterHotKey(_host.Handle, GetType().GetHashCode());\n }\n }\n}\n</code></pre>\n\n<p>You can get the virtual-key code for the hotkey you want to register here: <a href=\"http://msdn.microsoft.com/en-us/library/ms927178.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms927178.aspx</a></p>\n\n<p>There may be a better way, but this is what I've got so far.</p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 2643355, "author": "Mattias Wikström", "author_id": 317213, "author_profile": "https://Stackoverflow.com/users/317213", "pm_score": 1, "selected": false, "text": "<p>Although RegisterHotKey is sometimes precisely what you want, in most cases you probably do not want to use system-wide hotkeys. I ended up using code like the following:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Windows;\nusing System.Windows.Interop;\n\nnamespace WpfApp\n{\n public partial class MainWindow : Window\n {\n const int WM_KEYUP = 0x0101;\n\n const int VK_RETURN = 0x0D;\n const int VK_LEFT = 0x25; \n \n public MainWindow()\n {\n this.InitializeComponent();\n\n ComponentDispatcher.ThreadPreprocessMessage += \n ComponentDispatcher_ThreadPreprocessMessage;\n }\n\n void ComponentDispatcher_ThreadPreprocessMessage(\n ref MSG msg, ref bool handled)\n {\n if (msg.message == WM_KEYUP)\n {\n if ((int)msg.wParam == VK_RETURN)\n MessageBox.Show(&quot;RETURN was pressed&quot;);\n \n if ((int)msg.wParam == VK_LEFT)\n MessageBox.Show(&quot;LEFT was pressed&quot;);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 9330358, "author": "Eric Ouellet", "author_id": 452845, "author_profile": "https://Stackoverflow.com/users/452845", "pm_score": 6, "selected": false, "text": "<p>This is a full working solution, hope it helps...</p>\n\n<p>Usage:</p>\n\n<pre><code>_hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Win, OnHotKeyHandler);\n</code></pre>\n\n<p>...</p>\n\n<pre><code>private void OnHotKeyHandler(HotKey hotKey)\n{\n SystemHelper.SetScreenSaverRunning();\n}\n</code></pre>\n\n<p>Class:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Mime;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Input;\nusing System.Windows.Interop;\n\nnamespace UnManaged\n{\n public class HotKey : IDisposable\n {\n private static Dictionary&lt;int, HotKey&gt; _dictHotKeyToCalBackProc;\n\n [DllImport(\"user32.dll\")]\n private static extern bool RegisterHotKey(IntPtr hWnd, int id, UInt32 fsModifiers, UInt32 vlc);\n\n [DllImport(\"user32.dll\")]\n private static extern bool UnregisterHotKey(IntPtr hWnd, int id);\n\n public const int WmHotKey = 0x0312;\n\n private bool _disposed = false;\n\n public Key Key { get; private set; }\n public KeyModifier KeyModifiers { get; private set; }\n public Action&lt;HotKey&gt; Action { get; private set; }\n public int Id { get; set; }\n\n // ******************************************************************\n public HotKey(Key k, KeyModifier keyModifiers, Action&lt;HotKey&gt; action, bool register = true)\n {\n Key = k;\n KeyModifiers = keyModifiers;\n Action = action;\n if (register)\n {\n Register();\n }\n }\n\n // ******************************************************************\n public bool Register()\n {\n int virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key);\n Id = virtualKeyCode + ((int)KeyModifiers * 0x10000);\n bool result = RegisterHotKey(IntPtr.Zero, Id, (UInt32)KeyModifiers, (UInt32)virtualKeyCode);\n\n if (_dictHotKeyToCalBackProc == null)\n {\n _dictHotKeyToCalBackProc = new Dictionary&lt;int, HotKey&gt;();\n ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage);\n }\n\n _dictHotKeyToCalBackProc.Add(Id, this);\n\n Debug.Print(result.ToString() + \", \" + Id + \", \" + virtualKeyCode);\n return result;\n }\n\n // ******************************************************************\n public void Unregister()\n {\n HotKey hotKey;\n if (_dictHotKeyToCalBackProc.TryGetValue(Id, out hotKey))\n {\n UnregisterHotKey(IntPtr.Zero, Id);\n }\n }\n\n // ******************************************************************\n private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled)\n {\n if (!handled)\n {\n if (msg.message == WmHotKey)\n {\n HotKey hotKey;\n\n if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey))\n {\n if (hotKey.Action != null)\n {\n hotKey.Action.Invoke(hotKey);\n }\n handled = true;\n }\n }\n }\n }\n\n // ******************************************************************\n // Implement IDisposable.\n // Do not make this method virtual.\n // A derived class should not be able to override this method.\n public void Dispose()\n {\n Dispose(true);\n // This object will be cleaned up by the Dispose method.\n // Therefore, you should call GC.SupressFinalize to\n // take this object off the finalization queue\n // and prevent finalization code for this object\n // from executing a second time.\n GC.SuppressFinalize(this);\n }\n\n // ******************************************************************\n // Dispose(bool disposing) executes in two distinct scenarios.\n // If disposing equals true, the method has been called directly\n // or indirectly by a user's code. Managed and unmanaged resources\n // can be _disposed.\n // If disposing equals false, the method has been called by the\n // runtime from inside the finalizer and you should not reference\n // other objects. Only unmanaged resources can be _disposed.\n protected virtual void Dispose(bool disposing)\n {\n // Check to see if Dispose has already been called.\n if (!this._disposed)\n {\n // If disposing equals true, dispose all managed\n // and unmanaged resources.\n if (disposing)\n {\n // Dispose managed resources.\n Unregister();\n }\n\n // Note disposing has been done.\n _disposed = true;\n }\n }\n }\n\n // ******************************************************************\n [Flags]\n public enum KeyModifier\n {\n None = 0x0000,\n Alt = 0x0001,\n Ctrl = 0x0002,\n NoRepeat = 0x4000,\n Shift = 0x0004,\n Win = 0x0008\n }\n\n // ******************************************************************\n}\n</code></pre>\n" }, { "answer_id": 11032209, "author": "Gorgsenegger", "author_id": 412036, "author_profile": "https://Stackoverflow.com/users/412036", "pm_score": 1, "selected": false, "text": "<p>I've found the <a href=\"http://www.codeproject.com/Tips/274003/Global-Hotkeys-in-WPF#\" rel=\"nofollow\">Global Hotkeys in WPF</a> project on codeproject.com which does the job for me. It's relatively recent, does not need a reference to System.Windows.Forms and works \"globally\" in terms of reacting to the hotkey being pressed even if \"your\" application is not the active window.</p>\n" }, { "answer_id": 12676910, "author": "Louis Kottmann", "author_id": 677014, "author_profile": "https://Stackoverflow.com/users/677014", "pm_score": 4, "selected": false, "text": "<p>Registering OS level shortcuts is hardly ever a good thing: users don't want you to mess with their OS.<br></p>\n\n<p>That said, there is a much simpler and user friendly way of doing this in WPF, if you're ok with the hotkey working within the application only (i.e as long as your WPF app has the focus):</p>\n\n<p>In App.xaml.cs :</p>\n\n<pre><code>protected override void OnStartup(StartupEventArgs e)\n{\n EventManager.RegisterClassHandler(typeof(Window), Window.PreviewKeyUpEvent, new KeyEventHandler(OnWindowKeyUp));\n}\n\nprivate void OnWindowKeyUp(object source, KeyEventArgs e))\n{\n //Do whatever you like with e.Key and Keyboard.Modifiers\n}\n</code></pre>\n\n<p>It's that simple</p>\n" }, { "answer_id": 15646002, "author": "Mario", "author_id": 1357191, "author_profile": "https://Stackoverflow.com/users/1357191", "pm_score": 1, "selected": false, "text": "<p>Baboon's solution works best because you may have multiple windows. I did tweak it so it uses the PreviewKeyDownEvent instead of the PreviewKeyUpEvent in order to handle repetition in keystrokes.</p>\n\n<p>I would advise against OS-level registration unless you are writing something like a snipping tool or an audio recording app as it will let you access functionality when the window is not focused.</p>\n" }, { "answer_id": 33797344, "author": "BornToCode", "author_id": 1057791, "author_profile": "https://Stackoverflow.com/users/1057791", "pm_score": 2, "selected": false, "text": "<p>This is similar to the answers already given, but I find it a bit cleaner:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\nnamespace GlobalHotkeyExampleForm\n{\n public partial class ExampleForm : Form\n {\n [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);\n [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n private static extern bool UnregisterHotKey(IntPtr hWnd, int id);\n\n enum KeyModifier\n {\n None = 0,\n Alt = 1,\n Control = 2,\n Shift = 4,\n WinKey = 8\n }\n\n public ExampleForm()\n {\n InitializeComponent();\n\n int id = 0; // The id of the hotkey. \n RegisterHotKey(this.Handle, id, (int)KeyModifier.Shift, Keys.A.GetHashCode()); // Register Shift + A as global hotkey. \n }\n\n protected override void WndProc(ref Message m)\n {\n base.WndProc(ref m);\n\n if (m.Msg == 0x0312)\n {\n /* Note that the three lines below are not needed if you only want to register one hotkey.\n * The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */\n\n Keys key = (Keys)(((int)m.LParam &gt;&gt; 16) &amp; 0xFFFF); // The key of the hotkey that was pressed.\n KeyModifier modifier = (KeyModifier)((int)m.LParam &amp; 0xFFFF); // The modifier of the hotkey that was pressed.\n int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.\n\n\n MessageBox.Show(\"Hotkey has been pressed!\");\n // do something\n }\n }\n\n private void ExampleForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.\n }\n }\n}\n</code></pre>\n\n<p>I've found it on <a href=\"http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/\" rel=\"nofollow\">fluxbytes.com</a>.</p>\n" }, { "answer_id": 63843177, "author": "Anthony Nguyen", "author_id": 12848112, "author_profile": "https://Stackoverflow.com/users/12848112", "pm_score": 2, "selected": false, "text": "<p>With the NHotKey package, you can make your hotkey global:</p>\n<ul>\n<li><a href=\"https://github.com/thomaslevesque/NHotkey\" rel=\"nofollow noreferrer\">https://github.com/thomaslevesque/NHotkey</a></li>\n<li><a href=\"https://thomaslevesque.com/2014/02/05/wpf-declare-global-hotkeys-in-xaml-with-nhotkey/\" rel=\"nofollow noreferrer\">https://thomaslevesque.com/2014/02/05/wpf-declare-global-hotkeys-in-xaml-with-nhotkey/</a> (use web.archive.org if the link is broken)</li>\n</ul>\n<p>In short, for XAML, all you need to do is to replace</p>\n<pre><code>&lt;KeyBinding Gesture=&quot;Ctrl+Alt+Add&quot; Command=&quot;{Binding IncrementCommand}&quot; /&gt;\n</code></pre>\n<p>by</p>\n<pre><code>&lt;KeyBinding Gesture=&quot;Ctrl+Alt+Add&quot; Command=&quot;{Binding IncrementCommand}&quot;\n HotkeyManager.RegisterGlobalHotkey=&quot;True&quot; /&gt;\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146637/" ]
I'm building an application in C# using WPF. How can I bind to some keys? Also, how can I bind to the [Windows key](http://en.wikipedia.org/wiki/Windows_key)?
I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, *Save All* that can be triggered from anywhere by `Ctrl` + `Shift` + `S`.) You find the global `UIElement` of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree. Now, first you need 1. to bind the Key-Combo with a Command using an `InputBinding` like this 2. you can then hookup the command to your handler (e.g. code that gets called by `SaveAll`) via a `CommandBinding`. For the `Windows` Key, you use the right [Key](http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx) enumerated member, **`Key.LWin`** or **`Key.RWin`** ``` public WindowMain() { InitializeComponent(); // Bind Key var ib = new InputBinding( MyAppCommands.SaveAll, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control)); this.InputBindings.Add(ib); // Bind handler var cb = new CommandBinding( MyAppCommands.SaveAll); cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing ); this.CommandBindings.Add (cb ); } private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e) { // Do the Save All thing here. } ```
48,947
<p>How are callbacks written in PHP?</p>
[ { "answer_id": 48948, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 5, "selected": false, "text": "<p>Implementation of a callback is done like so</p>\n\n<pre><code>// This function uses a callback function. \nfunction doIt($callback) \n{ \n $data = \"this is my data\";\n $callback($data); \n} \n\n\n// This is a sample callback function for doIt(). \nfunction myCallback($data) \n{ \n print 'Data is: ' . $data . \"\\n\"; \n} \n\n\n// Call doIt() and pass our sample callback function's name. \ndoIt('myCallback');\n</code></pre>\n\n<p>Displays: Data is: this is my data</p>\n" }, { "answer_id": 49034, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 3, "selected": false, "text": "<p>One nifty trick that I've recently found is to use PHP's <a href=\"http://ca.php.net/create_function\" rel=\"noreferrer\"><code>create_function()</code></a> to create an anonymous/lambda function for one-shot use. It's useful for PHP functions like <code>array_map()</code>, <code>preg_replace_callback()</code>, or <code>usort()</code> that use callbacks for custom processing. It looks pretty much like it does an <code>eval()</code> under the covers, but it's still a nice functional-style way to use PHP.</p>\n" }, { "answer_id": 49570, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>I cringe every time I use <code>create_function()</code> in php. </p>\n\n<p>Parameters are a coma separated string, the whole function body in a string... Argh... I think they could not have made it uglier even if they tried.</p>\n\n<p>Unfortunately, it is the only choice when creating a named function is not worth the trouble.</p>\n" }, { "answer_id": 49581, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 3, "selected": false, "text": "<p>well... with 5.3 on the horizon, all will be better, because with 5.3, we'll get closures and with them anonymous functions</p>\n\n<p><a href=\"http://wiki.php.net/rfc/closures\" rel=\"noreferrer\">http://wiki.php.net/rfc/closures</a></p>\n" }, { "answer_id": 50515, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 3, "selected": false, "text": "<p>You will want to verify whatever your calling is valid. For example, in the case of a specific function, you will want to check and see if the function exists:</p>\n\n<pre><code>function doIt($callback) {\n if(function_exists($callback)) {\n $callback();\n } else {\n // some error handling\n }\n}\n</code></pre>\n" }, { "answer_id": 50596, "author": "Steve Clay", "author_id": 3779, "author_profile": "https://Stackoverflow.com/users/3779", "pm_score": 8, "selected": true, "text": "<p>The manual uses the terms \"callback\" and \"callable\" interchangeably, however, \"callback\" traditionally refers to a string or array value that acts like a <a href=\"http://en.wikipedia.org/wiki/Function_pointer\" rel=\"noreferrer\">function pointer</a>, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:</p>\n\n<pre><code>$cb1 = 'someGlobalFunction';\n$cb2 = ['ClassName', 'someStaticMethod'];\n$cb3 = [$object, 'somePublicMethod'];\n\n// this syntax is callable since PHP 5.2.3 but a string containing it\n// cannot be called directly\n$cb2 = 'ClassName::someStaticMethod';\n$cb2(); // fatal error\n\n// legacy syntax for PHP 4\n$cb3 = array(&amp;$object, 'somePublicMethod');\n</code></pre>\n\n<p>This is a safe way to use callable values in general:</p>\n\n<pre><code>if (is_callable($cb2)) {\n // Autoloading will be invoked to load the class \"ClassName\" if it's not\n // yet defined, and PHP will check that the class has a method\n // \"someStaticMethod\". Note that is_callable() will NOT verify that the\n // method can safely be executed in static context.\n\n $returnValue = call_user_func($cb2, $arg1, $arg2);\n}\n</code></pre>\n\n<p>Modern PHP versions allow the first three formats above to be invoked directly as <code>$cb()</code>. <code>call_user_func</code> and <code>call_user_func_array</code> support all the above.</p>\n\n<p>See: <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"noreferrer\">http://php.net/manual/en/language.types.callable.php</a></p>\n\n<p>Notes/Caveats: </p>\n\n<ol>\n<li>If the function/class is namespaced, the string must contain the fully-qualified name. E.g. <code>['Vendor\\Package\\Foo', 'method']</code></li>\n<li><code>call_user_func</code> does not support passing non-objects by reference, so you can either use <code>call_user_func_array</code> or, in later PHP versions, save the callback to a var and use the direct syntax: <code>$cb()</code>;</li>\n<li>Objects with an <a href=\"http://us2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke\" rel=\"noreferrer\"><code>__invoke()</code></a> method (including anonymous functions) fall under the category \"callable\" and can be used the same way, but I personally don't associate these with the legacy \"callback\" term.</li>\n<li>The legacy <code>create_function()</code> creates a global function and returns its name. It's a wrapper for <code>eval()</code> and anonymous functions should be used instead.</li>\n</ol>\n" }, { "answer_id": 1272403, "author": "goliatone", "author_id": 125083, "author_profile": "https://Stackoverflow.com/users/125083", "pm_score": 3, "selected": false, "text": "<p><code>create_function</code> did not work for me inside a class. I had to use <code>call_user_func</code>.</p>\n\n<pre><code>&lt;?php\n\nclass Dispatcher {\n //Added explicit callback declaration.\n var $callback;\n\n public function Dispatcher( $callback ){\n $this-&gt;callback = $callback;\n }\n\n public function asynchronous_method(){\n //do asynch stuff, like fwrite...then, fire callback.\n if ( isset( $this-&gt;callback ) ) {\n if (function_exists( $this-&gt;callback )) call_user_func( $this-&gt;callback, \"File done!\" );\n }\n }\n\n}\n</code></pre>\n\n<p>Then, to use:</p>\n\n<pre><code>&lt;?php \ninclude_once('Dispatcher.php');\n$d = new Dispatcher( 'do_callback' );\n$d-&gt;asynchronous_method();\n\nfunction do_callback( $data ){\n print 'Data is: ' . $data . \"\\n\";\n}\n?&gt;\n</code></pre>\n\n<p>[Edit]\nAdded a missing parenthesis. \nAlso, added the callback declaration, I prefer it that way.</p>\n" }, { "answer_id": 2523807, "author": "Bart van Heukelom", "author_id": 85821, "author_profile": "https://Stackoverflow.com/users/85821", "pm_score": 6, "selected": false, "text": "<p>With PHP 5.3, you can now do this:</p>\n\n<pre><code>function doIt($callback) { $callback(); }\n\ndoIt(function() {\n // this will be done\n});\n</code></pre>\n\n<p>Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.</p>\n" }, { "answer_id": 11657728, "author": "Kendall Hopkins", "author_id": 188044, "author_profile": "https://Stackoverflow.com/users/188044", "pm_score": 2, "selected": false, "text": "<p>For those who don't care about breaking compatibility with PHP <code>&lt; 5.4</code>, I'd suggest using type hinting to make a cleaner implementation.</p>\n\n<pre><code>function call_with_hello_and_append_world( callable $callback )\n{\n // No need to check $closure because of the type hint\n return $callback( \"hello\" ).\"world\";\n}\n\nfunction append_space( $string )\n{\n return $string.\" \";\n}\n\n$output1 = call_with_hello_and_append_world( function( $string ) { return $string.\" \"; } );\nvar_dump( $output1 ); // string(11) \"hello world\"\n\n$output2 = call_with_hello_and_append_world( \"append_space\" );\nvar_dump( $output2 ); // string(11) \"hello world\"\n\n$old_lambda = create_function( '$string', 'return $string.\" \";' );\n$output3 = call_with_hello_and_append_world( $old_lambda );\nvar_dump( $output3 ); // string(11) \"hello world\"\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
How are callbacks written in PHP?
The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a [function pointer](http://en.wikipedia.org/wiki/Function_pointer), referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are: ``` $cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod']; // this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error // legacy syntax for PHP 4 $cb3 = array(&$object, 'somePublicMethod'); ``` This is a safe way to use callable values in general: ``` if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context. $returnValue = call_user_func($cb2, $arg1, $arg2); } ``` Modern PHP versions allow the first three formats above to be invoked directly as `$cb()`. `call_user_func` and `call_user_func_array` support all the above. See: <http://php.net/manual/en/language.types.callable.php> Notes/Caveats: 1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. `['Vendor\Package\Foo', 'method']` 2. `call_user_func` does not support passing non-objects by reference, so you can either use `call_user_func_array` or, in later PHP versions, save the callback to a var and use the direct syntax: `$cb()`; 3. Objects with an [`__invoke()`](http://us2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke) method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term. 4. The legacy `create_function()` creates a global function and returns its name. It's a wrapper for `eval()` and anonymous functions should be used instead.
48,984
<p>We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?</p>
[ { "answer_id": 49136, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 5, "selected": true, "text": "<p>Here's the code we found to work:</p>\n\n<pre><code>IE browser = new IE(....);\nbrowser.Button(\"SlowPageLoadingButton\").ClickNoWait();\nLink continueLink = browser.Link(Find.ByText(\"linktext\"));\ncontinueLink.WaitUntilExists();\ncontinueLink.Click();\n</code></pre>\n" }, { "answer_id": 176204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You should be able to leave out the call to WaitUntilExists() since WatiN does this internally when you call a method or property on an element (like the link.Click() in you rexample).</p>\n\n<p>HTH,\nJeroen van Menen\nLead dev WatiN</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?
Here's the code we found to work: ``` IE browser = new IE(....); browser.Button("SlowPageLoadingButton").ClickNoWait(); Link continueLink = browser.Link(Find.ByText("linktext")); continueLink.WaitUntilExists(); continueLink.Click(); ```
48,993
<p>I am wondering if anyone has any experience using a JQuery plugin that converts a html </p> <pre><code>&lt;select&gt; &lt;option&gt; Blah &lt;/option&gt; &lt;/select&gt; </code></pre> <p>combo box into something (probably a div) where selecting an item acts the same as clicking a link.</p> <p>I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.</p> <p>Your advice, experience and recommendations are appreciated.</p>
[ { "answer_id": 49027, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p>This bit of javascript in the 'select':</p>\n\n<pre><code>onchange=\"if(this.options[this.selectedIndex].value!=''){this.form.submit()}\"\n</code></pre>\n\n<p>It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.</p>\n" }, { "answer_id": 49419, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<p>I'm not sure where you want to link to when you click the Div, but given something like this perhaps would work:</p>\n\n<pre><code>&lt;select id=\"mySelect\"&gt;\n &lt;option value=\"1\"&gt;Option 1&lt;/option&gt;\n &lt;option value=\"2\"&gt;Option 2&lt;/options&gt;\n&lt;/select&gt;\n&lt;div id=\"myDiv\"/&gt;\n</code></pre>\n\n<p>and the following JQuery creates a list of <code>&lt;div&gt;</code> elements, a goes to a URL based on the value of the option:</p>\n\n<pre><code>$(\"#mySelect option\").each(function() {\n $(\"&lt;div&gt;\" + $(this).text() + \"&lt;/div&gt;\").appendTo($(\"#myDiv\")).bind(\"click\", $(this).val(), function(event) {\n location.href = \"goto.php?id=\" + event.data;\n });\n});\n$(\"#mySelect\").remove();\n</code></pre>\n\n<p>Does this do what you want?</p>\n" }, { "answer_id": 49454, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 4, "selected": true, "text": "<p>The simple solution is to use</p>\n\n<pre><code>$(\"#mySelect\").change(function() {\n document.location = this.value;\n});\n</code></pre>\n\n<p>This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option.</p>\n" }, { "answer_id": 431268, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you're going to have a lot of select boxes that you want to allow to use as redirects, without having to define them independently, try something similar to: </p>\n\n<pre><code>$(\"[id*='COMMON_NAME']\").change(function() {\n document.location = this.value;\n});\n</code></pre>\n\n<p>And have your select boxes be named accordingly:</p>\n\n<pre><code>&lt;select id=\"COMMON_NAME_001\"&gt;...&lt;/select&gt;\n&lt;select id=\"COMMON_NAME_002\"&gt;...&lt;/select&gt;\n</code></pre>\n\n<p>This creates a onchange event for all IDs containing \"COMMON_NAME\" to do a redirect of the <code>&lt;option&gt;</code> value.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/48993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I am wondering if anyone has any experience using a JQuery plugin that converts a html ``` <select> <option> Blah </option> </select> ``` combo box into something (probably a div) where selecting an item acts the same as clicking a link. I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack. Your advice, experience and recommendations are appreciated.
The simple solution is to use ``` $("#mySelect").change(function() { document.location = this.value; }); ``` This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option.
49,035
<p>Given a declaration like this:</p> <pre><code>class A { public: void Foo() const; }; </code></pre> <p>What does it mean?</p> <p>Google turns up this:</p> <blockquote> <p>Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.</p> </blockquote> <p>But I find that somewhat confusing; can anyone out there put it in better terms?</p> <p>Thanks. </p>
[ { "answer_id": 49036, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 1, "selected": false, "text": "<p>that will cause the method to not be able to alter any member variables of the object</p>\n" }, { "answer_id": 49039, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>Functions with <code>const</code> qualifier are not allowed to modify any member variables. For example:</p>\n\n<pre><code>class A\n{\n int x;\n mutable int y;\n\n void f() const\n {\n x = 1; // error\n y = 1; // ok because y is mutable\n }\n};\n</code></pre>\n" }, { "answer_id": 49044, "author": "dfjacobs", "author_id": 4848, "author_profile": "https://Stackoverflow.com/users/4848", "pm_score": 2, "selected": false, "text": "<p>C++ objects can be declared to be const:</p>\n\n<pre><code>const A obj = new A();\n</code></pre>\n\n<p>When an object is const, the only member functions that can be called on that object are functions declared to be const. Making an object const can be interpreted as making the object readonly. A const object cannot be changed, i.e. no data members of the object can be changed. Declaring a member function const means that the function is not allowed to make any changes to the data members of the object.</p>\n" }, { "answer_id": 49056, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 5, "selected": true, "text": "<p>Consider a variation of your class <code>A</code>.</p>\n\n<pre><code>class A {\npublic:\n void Foo() const;\n void Moo();\n\nprivate:\n int m_nState; // Could add mutable keyword if desired\n int GetState() const { return m_nState; }\n void SetState(int val) { m_nState = val; }\n};\n\nconst A *A1 = new A();\nA *A2 = new A();\n\nA1-&gt;Foo(); // OK\nA2-&gt;Foo(); // OK\n\nA1-&gt;Moo(); // Error - Not allowed to call non-const function on const object instance\nA2-&gt;Moo(); // OK\n</code></pre>\n\n<p>The <code>const</code> keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of <code>A</code>. Thus you are unable to call non-<code>const</code> functions within <code>A::Foo</code> nor change the value of member variables.</p>\n\n<p>To illustrate, <em>Foo()</em> may not invoke <code>A::SetState</code> as it is declared non-<code>const</code>, <code>A::GetState</code> however is ok because it is explicitly declared <code>const</code>. The member <code>m_nState</code> may not be changed either unless declared with the keyword <code>mutable</code>.</p>\n\n<p>One example of this usage of <code>const</code> is for 'getter' functions to obtain the value of member variables.</p>\n\n<blockquote>\n <p>@1800 Information: I forgot about mutable!</p>\n</blockquote>\n\n<p>The <code>mutable</code> keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.</p>\n" }, { "answer_id": 49076, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": false, "text": "<p>This is not an answer, just a side comment. It is <strong>highly</strong> recommended to declare variables and constants <code>const</code> as much as possible. </p>\n\n<ol>\n<li>This communicates your intent to users of your class (even/especially yourself).</li>\n<li>The compiler will keep you honest to those intentions. -- i.e., it's like compiler checked documentation.</li>\n<li>By definition, this prevents state changes you weren't expecting and can, possibly, allow you to make reasonable assumptions while in your methods.</li>\n<li><code>const</code> has a funny way of propagating through your code. Thus, it's a really good idea to start using <code>const</code> as early and as often as possible. Deciding to start <code>const</code>-ifying your code late in the game can be painful (easy, but annoying).</li>\n</ol>\n\n<p>If you're using a language with static, compile time checks it's a great idea to make as much use of them as possible... it's just another kind of testing really.</p>\n" }, { "answer_id": 58843, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 2, "selected": false, "text": "<p>Two suggested best practices from experience:</p>\n\n<p>(1) <strong>Declare const functions whenever possible</strong>. At first, I found this to be just extra work, but then I started passing my objects to functions with signatures like f(const Object&amp; o), and suddenly the compiler barfed on a line in f such as o.GetAValue(), because I hadn't marked GetAValue as a const function. This can surprise you especially when you subclass something and don't mark your version of the virtual methods as const - in that case the compile could fail on some function you've never heard of before that was written for the base class.</p>\n\n<p>(2) <strong>Avoid mutable variables</strong> when it's practical. A tempting trap can be to allow read operations to alter state, such as if you're building a \"smart\" object that does lazy or asynchronous i/o operations. If you can manage this with only one small mutable variable (like a bool), then, in my experience, this makes sense. However, if you find yourself marking every member variable as mutable in order to keep some operations const, you're defeating the purpose of the const keyword. What can go wrong is that a function which thinks it's not altering your class (since it only calls const methods) my invoke a bug in your code, and it could take a lot of effort to even realize this bug is in your class, since the other coder (rightly) assumes your data is const because he or she is only calling const methods.</p>\n" }, { "answer_id": 60123, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>const has a funny way of propagating through your code. Thus, it's a really good idea to start using const as early and as often as possible. Deciding to start const-ifying your code late in the game can be painful (easy, but annoying).</p>\n</blockquote>\n\n<p>Additionally, you will easily run into problems if methods that should be const aren't! This will creep through the code as well, and make it worse and worse.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
Given a declaration like this: ``` class A { public: void Foo() const; }; ``` What does it mean? Google turns up this: > > Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message. > > > But I find that somewhat confusing; can anyone out there put it in better terms? Thanks.
Consider a variation of your class `A`. ``` class A { public: void Foo() const; void Moo(); private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; } }; const A *A1 = new A(); A *A2 = new A(); A1->Foo(); // OK A2->Foo(); // OK A1->Moo(); // Error - Not allowed to call non-const function on const object instance A2->Moo(); // OK ``` The `const` keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of `A`. Thus you are unable to call non-`const` functions within `A::Foo` nor change the value of member variables. To illustrate, *Foo()* may not invoke `A::SetState` as it is declared non-`const`, `A::GetState` however is ok because it is explicitly declared `const`. The member `m_nState` may not be changed either unless declared with the keyword `mutable`. One example of this usage of `const` is for 'getter' functions to obtain the value of member variables. > > @1800 Information: I forgot about mutable! > > > The `mutable` keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.
49,046
<p>Why does <code>n</code> not equal to <code>8</code> in the following function?</p> <pre><code>void foo(char cvalue[8]) { int n = sizeof (cvalue); } </code></pre> <p>But <code>n</code> <em>does</em> equal to <code>8</code> in this version of the function:</p> <pre><code>void bar() { char cvalue[8]; int n = sizeof (cvalue); } </code></pre>
[ { "answer_id": 49055, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": 7, "selected": true, "text": "<p>Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.</p>\n\n<pre><code>// These all do the same thing\nvoid foo(char cvalue[8])\nvoid foo(char cvalue[])\nvoid foo(char *cvalue)\n</code></pre>\n" }, { "answer_id": 49061, "author": "dagorym", "author_id": 171, "author_profile": "https://Stackoverflow.com/users/171", "pm_score": 1, "selected": false, "text": "<p>In the first example, cvalue as passed parameter is in really just a pointer to a character array and when you take the <code>sizeof()</code> of it, you get the size of the pointer. In the second case, where you've declared it as a local variable, you get the size of the the entire array.</p>\n" }, { "answer_id": 49129, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "<p>The size of the parameter on 32-bit systems will be 4 and on 64-bit systems compiled with -m64 will be 8. This is because arrays are passed as pointers in functions. The pointer is merely a memory address.</p>\n" }, { "answer_id": 49656, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 4, "selected": false, "text": "<p>C and C++ arrays are not first class objects; you cannot pass arrays to functions, they always decay to pointers.</p>\n\n<p>You can, however, pass pointers and references to arrays. This prevents the array bounds from decaying. So this is legal:</p>\n\n<pre><code>template&lt;typename T, size_t N&gt;\nvoid foo(const T(&amp;arr)[N])\n{\n int n = sizeof(arr);\n}\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5065/" ]
Why does `n` not equal to `8` in the following function? ``` void foo(char cvalue[8]) { int n = sizeof (cvalue); } ``` But `n` *does* equal to `8` in this version of the function: ``` void bar() { char cvalue[8]; int n = sizeof (cvalue); } ```
Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want. ``` // These all do the same thing void foo(char cvalue[8]) void foo(char cvalue[]) void foo(char *cvalue) ```
49,098
<p>So I have a function that looks something like this:</p> <pre><code>float function(){ float x = SomeValue; return x / SomeOtherValue; } </code></pre> <p>At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:</p> <pre><code>float function(){ float x = SomeValue; cout &lt;&lt; x; return x / SomeOtherValue; } </code></pre> <p>and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing?</p> <p>(If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)</p>
[ { "answer_id": 49120, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 2, "selected": false, "text": "<p>Printing a value to cout should not change the value of the paramter in any way at all.</p>\n\n<p>However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function.</p>\n\n<p>Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.</p>\n" }, { "answer_id": 49121, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 0, "selected": false, "text": "<p>I dont think the cout has any effect on the variable, the problem would have to be somewhere else.</p>\n" }, { "answer_id": 49130, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "<p>Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. </p>\n\n<p>This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register).</p>\n\n<p>When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.</p>\n\n<p>See the MSDN documentation on VC++ <a href=\"http://msdn.microsoft.com/en-us/library/e7s85ffb(VS.80).aspx\" rel=\"noreferrer\">floating point switches</a>. You could try compiling with /fp:strict and seeing what happens.</p>\n" }, { "answer_id": 50068, "author": "David Joyner", "author_id": 1146, "author_profile": "https://Stackoverflow.com/users/1146", "pm_score": 2, "selected": false, "text": "<p>As an aside, it's always a good idea to declare immutable variables using <code>const</code>:</p>\n\n<pre><code>float function(){\n const float x = SomeValue;\n cout &lt;&lt; x;\n return x / SomeOtherValue;\n}\n</code></pre>\n\n<p>Among other things this will prevent you from unintentionally passing your variables to functions that may modify them via non-<code>const</code> references.</p>\n" }, { "answer_id": 3607991, "author": "Joe", "author_id": 435796, "author_profile": "https://Stackoverflow.com/users/435796", "pm_score": 1, "selected": false, "text": "<p>cout causes a reference to the variable, which often will cause the compiler to force it to spill it to the stack.</p>\n\n<p>Because it is a float, this likely causes its value to be truncated from the double or long double representation it would normally have.</p>\n\n<p>Calling any function (non-inlined) that takes a pointer or reference to x should end up causing the same behavior, but if the compiler later gets smarter and learns to inline it, you'll be equally screwed :)</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
So I have a function that looks something like this: ``` float function(){ float x = SomeValue; return x / SomeOtherValue; } ``` At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: ``` float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue; } ``` and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)
Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ [floating point switches](http://msdn.microsoft.com/en-us/library/e7s85ffb(VS.80).aspx). You could try compiling with /fp:strict and seeing what happens.
49,107
<p>Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? </p> <p>For example, is there a clean way to implement <em>swap( intA, intB )</em> in Actionscript?</p>
[ { "answer_id": 49109, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": -1, "selected": false, "text": "<p>If ActionScript works like Javascript,</p>\n\n<pre><code>[a,b] = [b,a]\n</code></pre>\n" }, { "answer_id": 50755, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 4, "selected": true, "text": "<p>I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object:</p>\n\n<pre><code>function swapAB(aValuesContainer:Object):void\n{\n if (!(aValuesContainer.hasOwnProperty(\"a\") &amp;&amp; aValuesContainer.hasOwnProperty(\"b\")))\n throw new ArgumentError(\"aValuesContainer must have properties a and b\");\n\n var tempValue:int = aValuesContainer[\"a\"];\n aValuesContainer[\"a\"] = aValuesContainer[\"b\"];\n aValuesContainer[\"b\"] = tempValue;\n}\nvar ints:Object = {a:13, b:25};\nswapAB(ints);\n</code></pre>\n" }, { "answer_id": 50990, "author": "imaginaryboy", "author_id": 2508, "author_profile": "https://Stackoverflow.com/users/2508", "pm_score": 2, "selected": false, "text": "<p>I suppose an alternative would be somewhere defining this sort of thing ...</p>\n\n<pre><code>public class Reference {\n public var value:*;\n}\n</code></pre>\n\n<p>Then use functions that take some number of Reference arguments to act as \"pointers\" if you're really just looking for \"out\" parameters and either initialize them on the way in or not and your swap would become:</p>\n\n<pre><code>function swap(Reference a, Reference b) {\n var tmp:* = a.value;\n a.value = b.value;\n b.value = tmp;\n}\n</code></pre>\n\n<p>And you could always go nuts and define specific IntReference, StringReference, etc.</p>\n" }, { "answer_id": 50992, "author": "Andres", "author_id": 1815, "author_profile": "https://Stackoverflow.com/users/1815", "pm_score": 2, "selected": false, "text": "<p>You could also use a wrapper instead of int:</p>\n\n<pre><code>public class Integer\n{\n public var value:int;\n\n public function Integer(value:int)\n {\n this.value = value;\n }\n}\n</code></pre>\n\n<p>Of course, this would be more useful if you could use operator overloading...</p>\n" }, { "answer_id": 51315, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>This is nitpicking, but <code>int</code>, <code>String</code>, <code>Number</code> and the others <em>are</em> passed by reference, it's just that they are immutable. Of course, the effect is the same as if they were passed by value.</p>\n" }, { "answer_id": 657222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It is annoying. But if you use different idioms than in e.g. C#, you can get reasonable-quality results. If you need to pass a lot of parameters back and forth, pass in an object filled with the needed data, and change the object's parameters when you return. The Object class is for just this sort of thing.</p>\n\n<p>If you just need to return a bunch of data, return an Object. This is more in keeping with the ECMAScript style than pass-by-ref semantics.</p>\n" }, { "answer_id": 1313114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Destructuring assignment (e.g. [a,b] = [b,a]) isn't defined in the ECMA-262 3 specification, and it's not implemented in JavaScript 1.5, which is the version equivalent to the JScript implementation in IE. I've seen this syntax in the AS4 specifications preview though, and I believe it's part of JavaScript 1.7.</p>\n" }, { "answer_id": 2434629, "author": "acgeek", "author_id": 292536, "author_profile": "https://Stackoverflow.com/users/292536", "pm_score": 2, "selected": false, "text": "<p>Just look at some Java code. Java has had the convention that reference types are passed by reference and primitive types are passed by value since it's inception. It's a very good model in many ways.</p>\n\n<p>But talking about swap, the best and easiest way to do a swap in Java/AS3 is with the following three lines:</p>\n\n<pre>\nvar temp:int = array[i];\narray[j] = array[i];\narray[i] = temp;\n</pre>\n\n<p>Theres not really any reason to use a function to do a simple swap, when you can do it faster with just 3 lines.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4969/" ]
Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? For example, is there a clean way to implement *swap( intA, intB )* in Actionscript?
I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object: ``` function swapAB(aValuesContainer:Object):void { if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b"))) throw new ArgumentError("aValuesContainer must have properties a and b"); var tempValue:int = aValuesContainer["a"]; aValuesContainer["a"] = aValuesContainer["b"]; aValuesContainer["b"] = tempValue; } var ints:Object = {a:13, b:25}; swapAB(ints); ```
49,110
<p>I'm looking for the basic loop like:</p> <pre><code>for(int i = 0; i &lt; MAX; i++) { doSomething(i); } </code></pre> <p>but for Bash.</p>
[ { "answer_id": 49111, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 8, "selected": true, "text": "<p>From <a href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html\" rel=\"noreferrer\">this site</a>:</p>\n\n<pre><code>for i in $(seq 1 10);\ndo\n echo $i\ndone\n</code></pre>\n" }, { "answer_id": 49114, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 6, "selected": false, "text": "<pre><code>for ((i = 0 ; i &lt; max ; i++ )); do echo \"$i\"; done\n</code></pre>\n" }, { "answer_id": 49115, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "<p>Try the Bash built-in help:</p>\n<pre class=\"lang-none prettyprint-override\"><code>help for\n</code></pre>\n<h3>Output</h3>\n<pre class=\"lang-none prettyprint-override\"><code>for: for NAME [in WORDS ... ;] do COMMANDS; done\n The `for' loop executes a sequence of commands for each member in a\n list of items. If `in WORDS ...;' is not present, then `in &quot;$@&quot;' is\n assumed. For each element in WORDS, NAME is set to that element, and\n the COMMANDS are executed.\n\nfor ((: for (( exp1; exp2; exp3 )); do COMMANDS; done\n Equivalent to\n (( EXP1 ))\n while (( EXP2 )); do\n COMMANDS\n (( EXP3 ))\n done\n EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is\n omitted, it behaves as if it evaluates to 1.\n</code></pre>\n" }, { "answer_id": 49125, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 5, "selected": false, "text": "<p>The Bash <code>for</code> consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.</p>\n<p>So, if you have a limited list of words, just put them in the following syntax:</p>\n<pre><code>for w in word1 word2 word3\ndo\n doSomething($w)\ndone\n</code></pre>\n<p>Probably you want to iterate along some numbers, so you can use the <code>seq</code> command to generate a list of numbers for you: (from 1 to 100 for example)</p>\n<pre><code>seq 1 100\n</code></pre>\n<p>and use it in the <em>for</em> loop:</p>\n<pre><code>for n in $(seq 1 100)\ndo\n doSomething($n)\ndone\n</code></pre>\n<p>Note the <code>$(...)</code> syntax. It's a Bash behaviour, and it allows you to pass the output from one command (in our case from <code>seq</code>) to another (the <code>for</code>).</p>\n<p>This is really useful when you have to iterate over all directories in some path, for example:</p>\n<pre><code>for d in $(find $somepath -type d)\ndo\n doSomething($d)\ndone\n</code></pre>\n<p>The possibilities are infinite to generate the lists.</p>\n" }, { "answer_id": 49180, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I use variations of this all the time to process files...</p>\n\n<blockquote>\n <p>for files in *.log; do echo \"Do stuff with: $files\"; echo \"Do more stuff with: $files\"; done;</p>\n</blockquote>\n\n<p>If processing lists of files is what you're interested in, look into the <strong>-execdir</strong> option for <strong>files</strong>.</p>\n" }, { "answer_id": 77973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you're interested only in Bash, the &quot;for(( ... ))&quot; solution presented above is the best, but if you want something <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a> SH compliant that will work on all Unices, you'll have to use &quot;expr&quot; and &quot;while&quot;, and that's because &quot;(())&quot; or &quot;seq&quot; or &quot;i=i+1&quot; are not that portable among various shells.</p>\n" }, { "answer_id": 143376, "author": "terson", "author_id": 22974, "author_profile": "https://Stackoverflow.com/users/22974", "pm_score": 2, "selected": false, "text": "<p>I commonly like to use a slight variant on the standard <em>for</em> loop. I often use this to run a command on a series of remote hosts. I take advantage of Bash's brace expansion to create for loops that allow me to create non-numerical <em>for</em> loops.</p>\n<p>Example:</p>\n<p>I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:</p>\n<pre><code>% for host in {frontend{1..5},backend{1..3}}.mycompany.com\n do ssh $host &quot;echo -n $host; uptime&quot;\n done\n</code></pre>\n<p>I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z, etc.). However, the double period syntax is a new feature of Bash 3.0; earlier versions will not support this.</p>\n" }, { "answer_id": 3307917, "author": "David Gardner", "author_id": 86080, "author_profile": "https://Stackoverflow.com/users/86080", "pm_score": 5, "selected": false, "text": "<p>Bash <em>3.0+</em> can use this syntax:</p>\n<pre><code>for i in {1..10} ; do ... ; done\n</code></pre>\n<p>...which avoids spawning an external program to expand the sequence (such as <code>seq 1 10</code>).</p>\n<p>Of course, this has the same problem as the <code>for(())</code> solution, being tied to Bash and even a particular version (if this matters to you).</p>\n" }, { "answer_id": 14098446, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 3, "selected": false, "text": "<pre><code>#! /bin/bash\n\nfunction do_something {\n echo value=${1}\n}\n\nMAX=4\nfor (( i=0; i&lt;MAX; i++ )) ; {\n do_something ${i}\n}\n</code></pre>\n\n<hr>\n\n<p>Here's an example that can also work in older shells, while still being efficient for large counts:</p>\n\n<pre><code>Z=$(date) awk 'BEGIN { for ( i=0; i&lt;4; i++ ) { print i,\"hello\",ENVIRON[\"Z\"]; } }'\n</code></pre>\n\n<p>But good luck doing useful things inside of <code>awk</code>: <a href=\"https://stackoverflow.com/q/19075671/86967\">How do I use shell variables in an awk script?</a></p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535/" ]
I'm looking for the basic loop like: ``` for(int i = 0; i < MAX; i++) { doSomething(i); } ``` but for Bash.
From [this site](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html): ``` for i in $(seq 1 10); do echo $i done ```
49,147
<p>I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.</p> <p>I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in</p> <pre><code>MessageBox("Hello, World!"); </code></pre> <p>I received the following error:</p> <p>MessageBox is a 'type' but used as a 'variable'</p> <p>Fair enough, it seems in C# MessageBox is an Object. I tried the following</p> <pre><code>MessageBox a = new MessageBox("Hello, World!"); </code></pre> <p>I received the following error: MessageBox does not contain a constructor that takes '1' arguments</p> <p>Now I am stumped. Please help.</p>
[ { "answer_id": 49151, "author": "moobaa", "author_id": 3569, "author_profile": "https://Stackoverflow.com/users/3569", "pm_score": 5, "selected": false, "text": "<p>Code summary:</p>\n\n<pre><code>using System.Windows.Forms;\n\n...\n\nMessageBox.Show( \"hello world\" );\n</code></pre>\n\n<p>Also (<a href=\"https://stackoverflow.com/a/6639482/1582588\">as per this other stack post</a>): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select <code>System.Windows.Forms</code> on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.</p>\n" }, { "answer_id": 49152, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": false, "text": "<p>It is a static function on the MessageBox class, the simple way to do this is using</p>\n\n<pre><code>MessageBox.Show(\"my message\");\n</code></pre>\n\n<p>in the System.Windows.Forms class. You can find more on the msdn page for this <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.show.aspx\" rel=\"noreferrer\">here</a> . Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert(\"my message\"); or confirm(\"my question\"); functions.</p>\n" }, { "answer_id": 49153, "author": "Merus", "author_id": 5133, "author_profile": "https://Stackoverflow.com/users/5133", "pm_score": 7, "selected": true, "text": "<p>MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like</p>\n\n<pre><code>if (MessageBox.Show(\"Do you want to continue?\", \"Question\", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {\n //some interesting behaviour here\n}\n</code></pre>\n\n<p>which I guess is a bit unwieldy but it gets the job done.</p>\n\n<p>See <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult</a> for additional enum options you can use here.</p>\n" }, { "answer_id": 10829863, "author": "William Fitzmaurice", "author_id": 1427875, "author_profile": "https://Stackoverflow.com/users/1427875", "pm_score": 0, "selected": false, "text": "<p>In the <code>System.Windows.Forms</code> class, you can find more on the <a href=\"http://www.msdn.com/\" rel=\"nofollow\">MSDN</a> page for this here. Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript <code>alert(\"my message\");</code> or <code>confirm(\"my question\");</code> functions.</p>\n" }, { "answer_id": 18951433, "author": "user2680314", "author_id": 2680314, "author_profile": "https://Stackoverflow.com/users/2680314", "pm_score": 0, "selected": false, "text": "<p>This is some of the things you can put into a message box. Enjoy <br />\n<code>MessageBox.Show(\"Enter the text for the message box\",<br />\n \"Enter the name of the message box\",<br />\n (Enter the button names e.g. MessageBoxButtons.YesNo),<br />\n (Enter the icon e.g. MessageBoxIcon.Question),<br />\n (Enter the default button e.g. MessageBoxDefaultButton.Button1)</code><br />\nMore information can be found <a href=\"http://msdn.microsoft.com/en-us/library/ww6cfk80.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-1\" rel=\"nofollow\">here</a> </p>\n" }, { "answer_id": 21935165, "author": "Sagar Dev Timilsina", "author_id": 3335710, "author_profile": "https://Stackoverflow.com/users/3335710", "pm_score": 3, "selected": false, "text": "<p>Try below code:</p>\n\n<pre><code>MessageBox.Show(\"Test Information Message\", \"Caption\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n</code></pre>\n" }, { "answer_id": 28933652, "author": "KeithJ", "author_id": 3470547, "author_profile": "https://Stackoverflow.com/users/3470547", "pm_score": 0, "selected": false, "text": "<p>I got the same error <strong>'System.Windows.Forms.MessageBox' is a 'type' but is used like a 'variable'</strong>, even if using:</p>\n\n<pre><code>MessageBox.Show(\"Hello, World!\");\n</code></pre>\n\n<p>I guess my initial attempts with invalid syntax caused some kind of bug and I ended up fixing it by adding a space between \"MessageBox.Show\" and the brackets ():</p>\n\n<pre><code>MessageBox.Show (\"Hello, World!\");\n</code></pre>\n\n<p>Now using the original syntax without the extra space works again:</p>\n\n<pre><code>MessageBox.Show(\"Hello, World!\");\n</code></pre>\n" }, { "answer_id": 50077660, "author": "MicroDOS", "author_id": 9714192, "author_profile": "https://Stackoverflow.com/users/9714192", "pm_score": 1, "selected": false, "text": "<p>Also you can use a <code>MessageBox</code> with <code>OKCancel</code> options, but it requires many codes.\nThe <code>if</code> block is for <code>OK</code>, the <code>else</code> block is for <code>Cancel</code>. Here is the code:</p>\n\n<pre><code>if (MessageBox.Show(\"Are you sure you want to do this?\", \"Question\", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)\n{\n MessageBox.Show(\"You pressed OK!\");\n}\nelse\n{\n MessageBox.Show(\"You pressed Cancel!\");\n}\n</code></pre>\n\n<p>You can also use a <code>MessageBox</code> with <code>YesNo</code> options:</p>\n\n<pre><code>if (MessageBox.Show(\"Are you sure want to doing this?\", \"Question\", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)\n{\n MessageBox.Show(\"You are pressed Yes!\");\n}\nelse\n{\n MessageBox.Show(\"You are pressed No!\");\n}\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition. I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in ``` MessageBox("Hello, World!"); ``` I received the following error: MessageBox is a 'type' but used as a 'variable' Fair enough, it seems in C# MessageBox is an Object. I tried the following ``` MessageBox a = new MessageBox("Hello, World!"); ``` I received the following error: MessageBox does not contain a constructor that takes '1' arguments Now I am stumped. Please help.
MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like ``` if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) { //some interesting behaviour here } ``` which I guess is a bit unwieldy but it gets the job done. See <https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult> for additional enum options you can use here.
49,158
<p>I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. </p> <p>Is there a way I can use GreaseMonkey to log me into this site automatically?</p> <p>Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit</p>
[ { "answer_id": 49188, "author": "Garo Yeriazarian", "author_id": 2655, "author_profile": "https://Stackoverflow.com/users/2655", "pm_score": 1, "selected": false, "text": "<p>Why don't you use Firefox (I assume you're using Firefox) to remember your credentials using the Password Manager?</p>\n\n<p>I found this link: <a href=\"http://www.peej.co.uk/articles/http-auth-with-html-forms.html\" rel=\"nofollow noreferrer\">HTTP Authentication with HTML Forms</a>. Looks like you can use javascript to do HTTP authentication. I don't think you can have Greasemonkey interrupt when you are first navigating to a URL though. You might have to setup some sort of launching point that you can use to have greasemonkey automatically redirect + login. For example, you can have the local page that takes the destination URL in the query string, have Greasemonkey automatically do the authenticate + redirect. The only problem is that you'll have to wrap the site bookmarks with your launching page for the bookmarks you use as entry points.</p>\n" }, { "answer_id": 49736, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 2, "selected": false, "text": "<p>HTTP authentication information is sent on every request, not just to log in. The browser will cache the login information for the session after you log in the first time. So, you don't really save anything by trying to check if you are already logged in.</p>\n\n<p>You could also forget about greasemonkey altogether and just give your login into on the url like so:</p>\n\n<pre><code>http://username:password@host/\n</code></pre>\n\n<p>Of course, saving this in a bookmark may be a security risk, but not more-so than saving your password in the browser.</p>\n" }, { "answer_id": 55744, "author": "jklp", "author_id": 3847, "author_profile": "https://Stackoverflow.com/users/3847", "pm_score": 4, "selected": true, "text": "<p>It is possible to log in using HTTP authentication by setting the \"Authorization\" HTTP header, with the value of this header set to the string \"basic username:password\", but with the \"username:password\" portion of the string Base 64 encoded. </p>\n\n<p><a href=\"http://frontier.userland.com/stories/storyReader$2159\" rel=\"nofollow noreferrer\">http://frontier.userland.com/stories/storyReader$2159</a></p>\n\n<p>A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM_xmlhttpRequest </p>\n\n<p><a href=\"http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html\" rel=\"nofollow noreferrer\">http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html</a></p>\n\n<p>So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following</p>\n\n<p><a href=\"http://www.webtoolkit.info/javascript-base64.html\" rel=\"nofollow noreferrer\">http://www.webtoolkit.info/javascript-base64.html</a></p>\n\n<pre><code>var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML;\nif (loggedInText != \"logged in as jklp\") {\n var username = 'jklp';\n var password = 'jklpPass';\n var base64string = Base64.encode(username + \":\" + password);\n\n GM_xmlhttpRequest({\n method: 'GET',\n url: 'http://foo.com/trac/login',\n headers: {\n 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',\n 'Accept': 'application/atom+xml,application/xml,text/xml',\n 'Authorization':'Basic ' + base64string,\n }\n });\n}\n</code></pre>\n\n<p>So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in. </p>\n" }, { "answer_id": 2070220, "author": "Marcin", "author_id": 251368, "author_profile": "https://Stackoverflow.com/users/251368", "pm_score": 0, "selected": false, "text": "<p>\"<a href=\"http://username:password@host/\" rel=\"nofollow noreferrer\">http://username:password@host/</a>\" doesn't work on IE, FireFox works ok.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3847/" ]
I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. Is there a way I can use GreaseMonkey to log me into this site automatically? Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit
It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded. <http://frontier.userland.com/stories/storyReader$2159> A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM\_xmlhttpRequest <http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html> So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following <http://www.webtoolkit.info/javascript-base64.html> ``` var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML; if (loggedInText != "logged in as jklp") { var username = 'jklp'; var password = 'jklpPass'; var base64string = Base64.encode(username + ":" + password); GM_xmlhttpRequest({ method: 'GET', url: 'http://foo.com/trac/login', headers: { 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3', 'Accept': 'application/atom+xml,application/xml,text/xml', 'Authorization':'Basic ' + base64string, } }); } ``` So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in.
49,166
<p>I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:</p> <pre><code>try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } </code></pre> <p>Now, I have two problems:</p> <ul> <li><p>I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?</p></li> <li><p>This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.</p></li> </ul> <p>Any help with either would be great.</p>
[ { "answer_id": 49176, "author": "Garo Yeriazarian", "author_id": 2655, "author_profile": "https://Stackoverflow.com/users/2655", "pm_score": 1, "selected": false, "text": "<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (<a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx\" rel=\"nofollow noreferrer\">linky</a>) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.</p>\n" }, { "answer_id": 49177, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 1, "selected": false, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/z9f66s0a.aspx\" rel=\"nofollow noreferrer\">MSDN</a>, UnauthorizedAccessException is <strong>not thrown</strong> by OpenSubKey. So I think it's not needed.</p>\n" }, { "answer_id": 49186, "author": "Merus", "author_id": 5133, "author_profile": "https://Stackoverflow.com/users/5133", "pm_score": 1, "selected": true, "text": "<p>John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey.</p>\n\n<p>We're a little wary about changing the security context on the computer - I've found a reference <a href=\"http://vbcity.com/forums/topic.asp?tid=43510\" rel=\"nofollow noreferrer\">here</a> about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead.</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key: ``` try { remoteKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.LocalMachine, addr.Value).OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); return 1; } catch (IOException e) { IOException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 2; } catch (UnauthorizedAccessException e) { UnauthorizedAccessException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 3; } catch (System.Security.SecurityException e) { System.Security.SecurityException myexception = e; //Console.WriteLine("{0}: {1}: {2}", // e.GetType().Name, e.Message, addr.Value); return 4; } ``` Now, I have two problems: * I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas? * This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI. Any help with either would be great.
John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey. We're a little wary about changing the security context on the computer - I've found a reference [here](http://vbcity.com/forums/topic.asp?tid=43510) about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead.
49,194
<p>I have an action like this:</p> <pre><code>public class News : System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } </code></pre> <p>With a route like this:</p> <pre><code>routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", new { controller = "News", action = "Archive" } ); </code></pre> <p>The URL that I am on is:</p> <pre><code>News.mvc/Archive/2008 </code></pre> <p>I have a form on this page like this:</p> <pre><code>&lt;form&gt; &lt;select name="year"&gt; &lt;option value="2007"&gt;2007&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form.</p> <p>This requires the form 'action' attribute to be "News.mvc/Archive".</p> <p>However, if I declare a form like this:</p> <pre><code>&lt;form method="get" action="&lt;%=Url.RouteUrl("News-Archive")%&gt;"&gt; </code></pre> <p>it renders as:</p> <pre><code>&lt;form method="get" action="/News.mvc/Archive/2008"&gt; </code></pre> <p>Can someone please let me know what I'm missing?</p>
[ { "answer_id": 49197, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 3, "selected": true, "text": "<p>You have a couple problems, I think.</p>\n\n<p>First, your route doesn't have a default value for \"year\", so the URL \"/News.mvc/Archive\" is actually not valid for routing purposes.</p>\n\n<p>Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having \"?year=2007\" on the end of them. This is just how GET-method forms are designed to work in HTML.</p>\n\n<p>So you need to come to some conclusion about what's important.</p>\n\n<ul>\n<li>If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL).</li>\n<li>If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the \"int year\" parameter on your action, since form values will also populate action method parameters.</li>\n</ul>\n" }, { "answer_id": 49206, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p>I think I've worked out why - the route includes {year} so the generated routes always will too..</p>\n\n<p>If anyone can confirm this?</p>\n" }, { "answer_id": 49223, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p><strong>Solution</strong></p>\n\n<p>Okay here is the solution, (thanks to Brad for leading me there).</p>\n\n<p>1) Require default value in route:</p>\n\n<pre><code>routes.MapRoute(\n \"News-Archive\", \n \"News.mvc/Archive/{year}\", \n new { controller = \"News\", action = \"Archive\", year = 0 }\n );\n</code></pre>\n\n<p>2) Add a redirect to parse GET parameters as though they are URL segments.</p>\n\n<pre><code>public ActionResult Archive(int year)\n{\n if (!String.IsNullOrEmpty(Request[\"year\"]))\n {\n return RedirectToAction(\"Archive\", new { year = Request[\"year\"] });\n }\n}\n</code></pre>\n\n<p>3) Make sure you have your redirect code for Request params <em>before</em> any code for redirecting \"default\" year entries. i.e.</p>\n\n<pre><code>public ActionResult Archive(int year)\n{\n if (!String.IsNullOrEmpty(Request[\"year\"]))\n {\n return RedirectToAction(\"Archive\", new { year = Request[\"year\"] });\n }\n if (year == 0)\n {\n /* ... */\n }\n /* ... */\n}\n</code></pre>\n\n<p>3) Explicitly specify the default value for year in the Url.RouteUrl() call:</p>\n\n<pre><code>Url.RouteUrl(\"News-Archive\", new { year = 0 })\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I have an action like this: ``` public class News : System.Web.Mvc.Controller { public ActionResult Archive(int year) { / *** / } } ``` With a route like this: ``` routes.MapRoute( "News-Archive", "News.mvc/Archive/{year}", new { controller = "News", action = "Archive" } ); ``` The URL that I am on is: ``` News.mvc/Archive/2008 ``` I have a form on this page like this: ``` <form> <select name="year"> <option value="2007">2007</option> </select> </form> ``` Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form. This requires the form 'action' attribute to be "News.mvc/Archive". However, if I declare a form like this: ``` <form method="get" action="<%=Url.RouteUrl("News-Archive")%>"> ``` it renders as: ``` <form method="get" action="/News.mvc/Archive/2008"> ``` Can someone please let me know what I'm missing?
You have a couple problems, I think. First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes. Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML. So you need to come to some conclusion about what's important. * If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL). * If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters.
49,211
<p>I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the <a href="http://www.phdcc.com/cryptorc4.htm" rel="nofollow noreferrer">exponent of one trick</a> to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format.</p> <p>The question is how can we use this in our .NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the <a href="http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx" rel="nofollow noreferrer">Microsoft Enhanced Cryptographic Provider</a> is 168 bits (3 keys of 56 bits). However, the .NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the .NET framework is for parity?</p> <p>Anyway, we need to read the key portion out of the blob and somehow be able to use that in our .NET application. Currently we are not getting the expected results when attempting to use the key in .NET. The decryption is failing miserably. Any help would be greatly appreciated. </p> <h2>Update:</h2> <p>I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others.</p>
[ { "answer_id": 49232, "author": "Nic Strong", "author_id": 2281, "author_profile": "https://Stackoverflow.com/users/2281", "pm_score": 1, "selected": false, "text": "<p>Ok, forget the last answer I can't read :) You are working with 3Des keys not RSA keys.</p>\n\n<p>I worked on a bunch of code to share keys between .NET, CryptoAPI and openssl. Found a lot of good example code here for doing the key conversions: </p>\n\n<p><a href=\"http://www.jensign.com/JavaScience/cryptoutils/index.html\" rel=\"nofollow noreferrer\">http://www.jensign.com/JavaScience/cryptoutils/index.html</a></p>\n\n<p>There is some 3des stuff in some of those examples, but it was related to openssl -> .NET iirc.</p>\n\n<p>I also just looked back over the RSA key code and one thing I notice I am doing is using Array.Reverse() on all the key parts of the RSA key (D,DP,DQ,InverseQ,Modulus,P,Q) i guess to convert endian. I remember that being non-obvious when first tackling the problem.</p>\n\n<p>Hope some of that helps. Good luck.</p>\n" }, { "answer_id": 345696, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 4, "selected": true, "text": "<h2>Intro</h2>\n\n<p>I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere.</p>\n\n<h2>Prerequisites</h2>\n\n<p>In order for a lot of this to make sense it's necessary to read the <a href=\"http://www.phdcc.com/cryptorc4.htm\" rel=\"nofollow noreferrer\"><em>exponent of one trick</em></a>, which allows you to export a session key out to a blob (a well known byte structure). One can then do what they wish with this byte stream, but it holds the all important key.</p>\n\n<h2>MSDN Documentation is Confusing</h2>\n\n<p>In this particular example, I'm using the <a href=\"http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx\" rel=\"nofollow noreferrer\">Microsoft Enhanced Cryptographic Provider</a>, with the Triple DES (<a href=\"http://msdn.microsoft.com/en-us/library/aa382020(VS.85).aspx\" rel=\"nofollow noreferrer\">CALG_3DES</a>) algorithm. The first thing that threw me for a loop was the fact that the key length is listed at 168 bits, with a block length of 64 bits. How can the key length be 168? Three keys of 56 bits? What happens to the other byte? </p>\n\n<p>So with that information I started to read elsewhere how the last byte is really parity and for whatever reason CryptoAPI strips that off. Is that really the case? Seems kind of crazy that they would do that, but OK.</p>\n\n<h2>Consumption of Key in .NET</h2>\n\n<p>Using the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider(VS.80).aspx\" rel=\"nofollow noreferrer\">TripleDESCryptoServiceProvider</a>, I noticed the remarks in the docs indicated that:</p>\n\n<blockquote>\n <p>This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.</p>\n</blockquote>\n\n<p>So if CryptoAPI has key lengths of 168, how will I get that into .NET which supports only supports multiples of 64? Therefore, the .NET side of the API takes parity into account, where the CryptoAPI does not. As one could imagine... <em>confused was I</em>.</p>\n\n<p>So with all of this, I'm trying to figure out how to reconstruct the key on the .NET side with the proper parity information. Doable, but not very fun... let's just leave it at that. Once I got all of this in place, everything ended up failing with a CAPITAL <strong>F</strong>. </p>\n\n<p>Still with me? Good, because I just fell off my horse again.</p>\n\n<h2>Light Bulbs and Fireworks</h2>\n\n<p>Low and behold, as I'm scraping MSDN for every last bit of information I find a conflicting piece in the Win32 <a href=\"http://msdn.microsoft.com/en-us/library/aa379931(VS.85).aspx\" rel=\"nofollow noreferrer\">CryptExportKey</a> function. Low and behold I find this piece of invaluble information:</p>\n\n<blockquote>\n <p>For any of the DES key permutations that use a PLAINTEXTKEYBLOB, only the full key size, including parity bit, may be exported. The following key sizes are supported.</p>\n \n <p>Algorithm Supported key size </p>\n \n <p>CALG_DES 64 bits </p>\n \n <p>CALG_3DES_112 128 bits </p>\n \n <p>CALG_3DES 192 bits </p>\n</blockquote>\n\n<p>So it does export a key that is a multiple of 64 bits! Woohoo! Now to fix the code on the .NET side.</p>\n\n<h2>.NET Import Code Tweak</h2>\n\n<p>The byte order is important to keep in mind when importing a byte stream that contains a key that was exported as a blob from the CryptoAPI. The two API's do not use the same byte order, therefore, as <a href=\"https://stackoverflow.com/questions/49211/how-can-i-use-a-key-blob-generated-from-win32-cryptoapi-in-my-net-application#49232\">@nic-strong</a> indicates, reversing the byte array is essential before actually trying to use the key. Other than that, things work as expected. Simply solved:</p>\n\n<pre><code>Array.Reverse( keyByteArray );\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>I hope this helps somebody out there. I spent way too much time trying to track this down. Leave any comments if you have further questions and I can attempt to help fill in any details. </p>\n\n<p>Happy Crypto!</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the [exponent of one trick](http://www.phdcc.com/cryptorc4.htm) to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format. The question is how can we use this in our .NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the [Microsoft Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx) is 168 bits (3 keys of 56 bits). However, the .NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the .NET framework is for parity? Anyway, we need to read the key portion out of the blob and somehow be able to use that in our .NET application. Currently we are not getting the expected results when attempting to use the key in .NET. The decryption is failing miserably. Any help would be greatly appreciated. Update: ------- I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others.
Intro ----- I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere. Prerequisites ------------- In order for a lot of this to make sense it's necessary to read the [*exponent of one trick*](http://www.phdcc.com/cryptorc4.htm), which allows you to export a session key out to a blob (a well known byte structure). One can then do what they wish with this byte stream, but it holds the all important key. MSDN Documentation is Confusing ------------------------------- In this particular example, I'm using the [Microsoft Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx), with the Triple DES ([CALG\_3DES](http://msdn.microsoft.com/en-us/library/aa382020(VS.85).aspx)) algorithm. The first thing that threw me for a loop was the fact that the key length is listed at 168 bits, with a block length of 64 bits. How can the key length be 168? Three keys of 56 bits? What happens to the other byte? So with that information I started to read elsewhere how the last byte is really parity and for whatever reason CryptoAPI strips that off. Is that really the case? Seems kind of crazy that they would do that, but OK. Consumption of Key in .NET -------------------------- Using the [TripleDESCryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider(VS.80).aspx), I noticed the remarks in the docs indicated that: > > This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits. > > > So if CryptoAPI has key lengths of 168, how will I get that into .NET which supports only supports multiples of 64? Therefore, the .NET side of the API takes parity into account, where the CryptoAPI does not. As one could imagine... *confused was I*. So with all of this, I'm trying to figure out how to reconstruct the key on the .NET side with the proper parity information. Doable, but not very fun... let's just leave it at that. Once I got all of this in place, everything ended up failing with a CAPITAL **F**. Still with me? Good, because I just fell off my horse again. Light Bulbs and Fireworks ------------------------- Low and behold, as I'm scraping MSDN for every last bit of information I find a conflicting piece in the Win32 [CryptExportKey](http://msdn.microsoft.com/en-us/library/aa379931(VS.85).aspx) function. Low and behold I find this piece of invaluble information: > > For any of the DES key permutations that use a PLAINTEXTKEYBLOB, only the full key size, including parity bit, may be exported. The following key sizes are supported. > > > Algorithm Supported key size > > > CALG\_DES 64 bits > > > CALG\_3DES\_112 128 bits > > > CALG\_3DES 192 bits > > > So it does export a key that is a multiple of 64 bits! Woohoo! Now to fix the code on the .NET side. .NET Import Code Tweak ---------------------- The byte order is important to keep in mind when importing a byte stream that contains a key that was exported as a blob from the CryptoAPI. The two API's do not use the same byte order, therefore, as [@nic-strong](https://stackoverflow.com/questions/49211/how-can-i-use-a-key-blob-generated-from-win32-cryptoapi-in-my-net-application#49232) indicates, reversing the byte array is essential before actually trying to use the key. Other than that, things work as expected. Simply solved: ``` Array.Reverse( keyByteArray ); ``` Conclusion ---------- I hope this helps somebody out there. I spent way too much time trying to track this down. Leave any comments if you have further questions and I can attempt to help fill in any details. Happy Crypto!
49,214
<p>I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:</p> <pre><code>List&lt;int&gt; iList = new List&lt;int&gt;(); for (int i = 1; i &lt;= x; i++) { iList.Add(i); } </code></pre> <p>This seems dumb, surely there's a more elegant way to do this, something like the <a href="http://au2.php.net/manual/en/function.range.php" rel="noreferrer">PHP range method</a></p>
[ { "answer_id": 49216, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<p>LINQ to the rescue:</p>\n\n<pre><code>// Adding value to existing list\nvar list = new List&lt;int&gt;();\nlist.AddRange(Enumerable.Range(1, x));\n\n// Creating new list\nvar list = Enumerable.Range(1, x).ToList();\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336752.aspx#range\" rel=\"noreferrer\">Generation Operators</a> on <a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx\" rel=\"noreferrer\">LINQ 101</a></p>\n" }, { "answer_id": 49218, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 8, "selected": true, "text": "<p>If you're using .Net 3.5, <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx\" rel=\"noreferrer\">Enumerable.Range</a> is what you need.</p>\n\n<blockquote>\n <p>Generates a sequence of integral\n numbers within a specified range.</p>\n</blockquote>\n" }, { "answer_id": 49342, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 4, "selected": false, "text": "<p>I'm one of many who has <a href=\"http://blog.functionalfun.net/2008/04/project-euler-problem-4.html\" rel=\"noreferrer\">blogged</a> about a ruby-esque <em>To</em> extension method that you can write if you're using C#3.0:</p>\n\n<p><pre><code>\npublic static class IntegerExtensions\n{\n public static IEnumerable&lt;int&gt; To(this int first, int last)\n {\n for (int i = first; i &lt;= last; i++)<br>\n { \n yield return i;\n } \n }\n}\n</pre></code></p>\n\n<p>Then you can create your list of integers like this</p>\n\n<p><pre><code>List&lt;int&gt; = first.To(last).ToList();</pre></code> </p>\n\n<p>or\n<pre><code>List&lt;int&gt; = 1.To(x).ToList();</pre></code></p>\n" }, { "answer_id": 36462316, "author": "Gaspare Bonventre", "author_id": 3976189, "author_profile": "https://Stackoverflow.com/users/3976189", "pm_score": 1, "selected": false, "text": "<p>Here is a short method that returns a List of integers.</p>\n\n<pre><code> public static List&lt;int&gt; MakeSequence(int startingValue, int sequenceLength)\n {\n return Enumerable.Range(startingValue, sequenceLength).ToList&lt;int&gt;();\n }\n</code></pre>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously: ``` List<int> iList = new List<int>(); for (int i = 1; i <= x; i++) { iList.Add(i); } ``` This seems dumb, surely there's a more elegant way to do this, something like the [PHP range method](http://au2.php.net/manual/en/function.range.php)
If you're using .Net 3.5, [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx) is what you need. > > Generates a sequence of integral > numbers within a specified range. > > >
49,252
<p>For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:</p> <p><code>Object.variable_name= 'new value'</code> </p> <p>However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:</p> <p><code>Object.send('variable.name=', 'new value')</code></p> <p>However, I am wondering is there a way to escape the period so that I can use</p> <p><code>Object.variable.name= 'new value'</code></p>
[ { "answer_id": 49255, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": 4, "selected": true, "text": "<p>Don't do it!</p>\n\n<p>Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:</p>\n\n<pre><code>attr_writer :bar\nattr_reader :baz\nattr_accessor :foo\n</code></pre>\n\n<p>Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.</p>\n\n<pre><code>class SillySetter\n def initialize path=nil\n @path = path\n end\n\n def method_missing name,value=nil\n new_path = @path ? \"#{@path}.#{name}\" : name\n if name.to_s[-1] == ?=\n puts \"setting #{new_path} #{value}\"\n else\n return self.class.new(path=new_path)\n end\n end\nend\n\ns = SillySetter.new\ns.foo = 5 # -&gt; setting foo= 5\ns.foo.bar.baz = 4 # -&gt; setting foo.bar.baz= 4\n</code></pre>\n\n<p>I didn't want to encourage ruby sillyness, but I just couldn't help myself!</p>\n" }, { "answer_id": 49575, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "<p>If there's no hope of changing the canonical names, you could alias the getters and setters manually:</p>\n\n<pre><code>def variable_name\n send 'variable.name'\nend\n\ndef variable_name=(value)\n send 'variable.name=', value\nend\n</code></pre>\n" }, { "answer_id": 103920, "author": "fatgeekuk", "author_id": 17518, "author_profile": "https://Stackoverflow.com/users/17518", "pm_score": 1, "selected": false, "text": "<p>The only reason I can think of to do this, is if you really REALLY hate the person who is going to be maintaining this code after you.</p>\n\n<p>And I don't mean 'he ran over my dog' hatred. </p>\n\n<p>I mean real steaming pulsing vein in temple hatred.</p>\n\n<p>So, in short, don't. :-)</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
For a project I am working on in ruby I am overriding the method\_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object: `Object.variable_name= 'new value'` However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround: `Object.send('variable.name=', 'new value')` However, I am wondering is there a way to escape the period so that I can use `Object.variable.name= 'new value'`
Don't do it! Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros: ``` attr_writer :bar attr_reader :baz attr_accessor :foo ``` Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go. ``` class SillySetter def initialize path=nil @path = path end def method_missing name,value=nil new_path = @path ? "#{@path}.#{name}" : name if name.to_s[-1] == ?= puts "setting #{new_path} #{value}" else return self.class.new(path=new_path) end end end s = SillySetter.new s.foo = 5 # -> setting foo= 5 s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4 ``` I didn't want to encourage ruby sillyness, but I just couldn't help myself!
49,258
<p>I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I <em>don't</em> want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.</p>
[ { "answer_id": 49255, "author": "Nick Retallack", "author_id": 2653, "author_profile": "https://Stackoverflow.com/users/2653", "pm_score": 4, "selected": true, "text": "<p>Don't do it!</p>\n\n<p>Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:</p>\n\n<pre><code>attr_writer :bar\nattr_reader :baz\nattr_accessor :foo\n</code></pre>\n\n<p>Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.</p>\n\n<pre><code>class SillySetter\n def initialize path=nil\n @path = path\n end\n\n def method_missing name,value=nil\n new_path = @path ? \"#{@path}.#{name}\" : name\n if name.to_s[-1] == ?=\n puts \"setting #{new_path} #{value}\"\n else\n return self.class.new(path=new_path)\n end\n end\nend\n\ns = SillySetter.new\ns.foo = 5 # -&gt; setting foo= 5\ns.foo.bar.baz = 4 # -&gt; setting foo.bar.baz= 4\n</code></pre>\n\n<p>I didn't want to encourage ruby sillyness, but I just couldn't help myself!</p>\n" }, { "answer_id": 49575, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "<p>If there's no hope of changing the canonical names, you could alias the getters and setters manually:</p>\n\n<pre><code>def variable_name\n send 'variable.name'\nend\n\ndef variable_name=(value)\n send 'variable.name=', value\nend\n</code></pre>\n" }, { "answer_id": 103920, "author": "fatgeekuk", "author_id": 17518, "author_profile": "https://Stackoverflow.com/users/17518", "pm_score": 1, "selected": false, "text": "<p>The only reason I can think of to do this, is if you really REALLY hate the person who is going to be maintaining this code after you.</p>\n\n<p>And I don't mean 'he ran over my dog' hatred. </p>\n\n<p>I mean real steaming pulsing vein in temple hatred.</p>\n\n<p>So, in short, don't. :-)</p>\n" } ]
2008/09/08
[ "https://Stackoverflow.com/questions/49258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3955/" ]
I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I *don't* want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.
Don't do it! Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros: ``` attr_writer :bar attr_reader :baz attr_accessor :foo ``` Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go. ``` class SillySetter def initialize path=nil @path = path end def method_missing name,value=nil new_path = @path ? "#{@path}.#{name}" : name if name.to_s[-1] == ?= puts "setting #{new_path} #{value}" else return self.class.new(path=new_path) end end end s = SillySetter.new s.foo = 5 # -> setting foo= 5 s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4 ``` I didn't want to encourage ruby sillyness, but I just couldn't help myself!