qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
161,056
<p>Is there a CSS editor which automatically expands one-line declarations as multi-line declarations on focus ? To clarify my thought, see example below:</p> <p>Original CSS:</p> <pre><code>div#main { color: orange; margin: 1em 0; border: 1px solid black; } </code></pre> <p>But when focusing on it, editor automatically expands it to:</p> <pre><code>div#main { color: orange; margin: 1em 0; border: 1px solid black; } </code></pre> <p>And when it looses focus, editor again it automatically compresses it to one-line declaration.</p> <p>Thanks.</p>
[ { "answer_id": 161079, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "<p>Sorry. I don't know of any IDEs that explicitly do that.</p>\n\n<p>But, there are quite a few external options:</p>\n\n<ul>\n<li><a href=\"http://csstidy.sourceforge.net/\" rel=\"nofollow noreferrer\">CSSTidy</a> (download)</li>\n<li><a href=\"http://www.cleancss.com/\" rel=\"nofollow noreferrer\">Clean CSS</a> (in-browser)</li>\n<li><a href=\"http://floele.flyspray.org/csstidy//css_optimiser.php\" rel=\"nofollow noreferrer\">CSS Optimiser</a> (in-browser)</li>\n<li><a href=\"http://www.google.com/search?q=css+(tidy+OR+beautify)\" rel=\"nofollow noreferrer\">others...</a> (Google Search)</li>\n</ul>\n" }, { "answer_id": 161149, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 1, "selected": false, "text": "<p>I've not heard of one. If you're on a Mac I can definitely recommend <a href=\"http://macrabbit.com/cssedit/\" rel=\"nofollow noreferrer\">CSSEdit</a>. It does auto-formatting very nicely, amoungst other things.</p>\n\n<p>EDIT: I originally said \"though as the comment says it's a great idea\" but, thinking about it, is that what you really want? I can see that it would be good to have expansion/contraction onClick (in which case <a href=\"http://macromates.com/\" rel=\"nofollow noreferrer\">TextMate</a> - again Mac - though CSS suport isn't as good as CSSEdit), but onFocus?</p>\n" }, { "answer_id": 161198, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>da5id, I actually don't care about implementation details (onclick or onhover, though onclick seems better when you say it ;), I'm just curious if there are any editors which supports this kind of feature in any way.</p>\n\n<p>PS. I'm not on Mac but Windows.</p>\n" }, { "answer_id": 161795, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": false, "text": "<p>If you are using Visual Studio you should be able to do a close approximation of this:</p>\n\n<ol>\n<li>You can change how CSS is formatted\nvia the Tools -> Options menu.</li>\n<li>Check 'Show all settings' if it is unchecked.</li>\n<li>Go to Text Editor -> CSS -> Format and pick the semi-expanded option</li>\n<li>Ok you changes.</li>\n<li>Then <kbd>ctrl+A</kbd>, <kbd>ctrl+K</kbd>, <kbd>ctrl+D</kbd> should re-format your document</li>\n<li>When you are finished editing just go back to the options and pick the compact CSS format then <kbd>ctrl+A</kbd>,<kbd>ctrl+K</kbd>,<kbd>ctrl+D</kbd> to re-format again.</li>\n</ol>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 161904, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Its not exactly what you want but try the windows port of textmate <a href=\"http://www.e-texteditor.com/\" rel=\"nofollow noreferrer\">E Text Editor</a>, for on click folding of css rules, auto formating and most other textmate functionality.</p>\n" }, { "answer_id": 162432, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>You can do that with the scripting language of your favorite editor.</p>\n\n<p>For example in SciTE:</p>\n\n<pre><code>function ExpandContractCSS()\n local ext = string.lower(props[\"FileExt\"])\n if ext ~= \"css\" then return end\n local line = GetCurrentLine()\n local newForm\n if string.find(line, \"}\") then\n -- On one line\n newForm = string.gsub(line, \"; *\", \";\\r\\n \")\n newForm = string.gsub(newForm, \"{ *\", \"{\\r\\n \")\n newForm = string.gsub(newForm, \" *}\", \"}\")\n else\n -- To contract\n -- Well, just use Ctrl+Z!\n -- Maybe not, code to come if interest\n end\n if newForm ~= nil then\n ReplaceCurrentLine(newForm)\n end\nend\n</code></pre>\n\n<p>GetCurrentLine and ReplaceCurrentLine are just convenience functions from my collection, I can give them (and do the contraction part) if you are interested.</p>\n" }, { "answer_id": 165941, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 0, "selected": false, "text": "<p>It's a good question. I'd love to see this in a CSS editor. <a href=\"http://www.newsgator.com/Individuals/TopStyle/Default.aspx\" rel=\"nofollow noreferrer\">TopStyle</a> does this, but it isn't automatic; you have you use a hotkey.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a CSS editor which automatically expands one-line declarations as multi-line declarations on focus ? To clarify my thought, see example below: Original CSS: ``` div#main { color: orange; margin: 1em 0; border: 1px solid black; } ``` But when focusing on it, editor automatically expands it to: ``` div#main { color: orange; margin: 1em 0; border: 1px solid black; } ``` And when it looses focus, editor again it automatically compresses it to one-line declaration. Thanks.
If you are using Visual Studio you should be able to do a close approximation of this: 1. You can change how CSS is formatted via the Tools -> Options menu. 2. Check 'Show all settings' if it is unchecked. 3. Go to Text Editor -> CSS -> Format and pick the semi-expanded option 4. Ok you changes. 5. Then `ctrl+A`, `ctrl+K`, `ctrl+D` should re-format your document 6. When you are finished editing just go back to the options and pick the compact CSS format then `ctrl+A`,`ctrl+K`,`ctrl+D` to re-format again. Hope this helps.
161,064
<p>I'm running autoconf and configure sets SHELL to '/bin/sh'. This creates huge problems. How to force SHELL to be '/bin/bash' for autoconf?</p> <p>I'm trying to get this running on osx, it's working on linux. Linux is using SHELL=/bin/bash. osx defaults to /bin/sh.</p>
[ { "answer_id": 161070, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": -1, "selected": false, "text": "<p><code>ln -f /bin/bash /bin/sh</code></p>\n\n<p>:-P (No, it's not a serious answer. Please don't hose your system by doing it!)</p>\n" }, { "answer_id": 161071, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 0, "selected": false, "text": "<p>Where is SHELL being set to that? What is being run with /bin/sh when you want /bin/bash?</p>\n\n<p>configure scripts are meant to run anywhere, even on the horribly broken and non-Bash shells that exist in the wild.</p>\n\n<p><strong>Edit</strong>: What exactly is the problem?</p>\n\n<p><strong>Another edit</strong>: Perhaps you'd like the script to re-execute itself, something like this. It's probably buggy:</p>\n\n<pre><code>if test \"$SHELL\" = \"/bin/sh\" &amp;&amp; test -x /bin/bash; then\n exec /bin/bash -c \"$0\" \"$@\"\nfi\n</code></pre>\n" }, { "answer_id": 161128, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "<p>I have similar problems on Solaris with GCC - and I use the 'standard' technique:</p>\n\n<pre><code>CONFIG_SHELL=/bin/bash ./configure ...\n</code></pre>\n\n<p>(Or, actually, I use /bin/ksh, but setting the CONFIG_SHELL env var allows you to tell autoconf scripts which shell to use.)</p>\n\n<p>I checked the configure script for git and gd (they happened to be extracted) to check that this wasn't a GCC peculiar env var.</p>\n" }, { "answer_id": 1148485, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 3, "selected": false, "text": "<p>What are the \"huge problems\"? autoconf works very hard to generate a configure script that works with a very large percentage of shells. If you have an example of a construct that autoconf is writing that is not portable, please report it to the autoconf mailing list. On the other hand, if the problems you are experiencing are a result of your own shell code in configure.ac not being portable (eg, you're using bashisms) then the solution is to either stop using non-portable code or require the user to explicitly set SHELL or CONFIG_SHELL at configure time.</p>\n\n<p>It sounds like the problem you are experiencing is in the environment of the user running configure. On Linux, your user has SHELL set to /bin/bash, but on OS X it is set to /bin/sh. The configure script generated by autoconf does some initial tests of the shell it is running under and does attempt to re-exec itself using a different shell if the provided shell lacks certain features. However, if you are introducing non-portable shell code in configure.ac, then you are violating one of the main philosophy's of autoconf -- namely that configure scripts should be portable. If you truly want to use bashisms in your shell code, then you are requiring your user to pass SHELL=/bin/bash as an argument to the configure script. This is not a bug in autoconf, but would be considered by many to be a bug in your project's build.</p>\n" }, { "answer_id": 9611812, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 2, "selected": false, "text": "<p>Autoconf is supposed to solve portability problems by generating a script which can run \"anywhere\". That's why it generates bizarre code like:</p>\n\n<pre><code>if test X$foo = X ; then ... # check if foo is empty\n</code></pre>\n\n<p>rather than:</p>\n\n<pre><code>if [ \"$x\" = \"\" ] ; then ...\n</code></pre>\n\n<p>That kind of crufty code probably once allowed these scripts to run on some ancient Ultrix system or whatever.</p>\n\n<p>An configure script not running because of shell differences is like coming to a Formula-1 race with 10 liters of gas, and three spare tires.</p>\n\n<p>If you're developing a configure script with Autoconf, and it is sensitive to whether the shell is Bash or the OSX shell, you are doing something wrong, or the Autoconf people broke something. If it's from you, fix whatever shell pieces you are adding to the script by making them portable.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
I'm running autoconf and configure sets SHELL to '/bin/sh'. This creates huge problems. How to force SHELL to be '/bin/bash' for autoconf? I'm trying to get this running on osx, it's working on linux. Linux is using SHELL=/bin/bash. osx defaults to /bin/sh.
I have similar problems on Solaris with GCC - and I use the 'standard' technique: ``` CONFIG_SHELL=/bin/bash ./configure ... ``` (Or, actually, I use /bin/ksh, but setting the CONFIG\_SHELL env var allows you to tell autoconf scripts which shell to use.) I checked the configure script for git and gd (they happened to be extracted) to check that this wasn't a GCC peculiar env var.
161,084
<p>I was just wondering if anyone knew of a good way that I could parse the file at the bottom of the post.</p> <p>I have a database setup with the correct tables for each section eg Refferal Table,Caller Table,Location Table. Each table has the same columns that are show in the file below</p> <p>I would really like something that is fairly genetic so if the file layout changes it won't mess me around to much. At the moment I am just reading the file in a line at a time and just using a case statement to check which section i'm in. </p> <p>Is anyone able to help me with this?</p> <p>PS. I am using VB but C# or anything else will be fine, also the x's in the document are just personal info I have blanked</p> <p>Thanks, Nathan</p> <p>File:---></p> <pre><code>DIAL BEFORE YOU DIG Call 1100, Fax 1300 652 077 PO Box 7710 MELBOURNE, VIC 8004 Utilities are requested to respond within 2 working days and reference the Sequence number. [REFFERAL DETAILS] FROM= Dial Before You Dig - Web TO= Technical Services UTILITY ID= xxxxxx COMPANY= {Company Name} ENQUIRY DATE= 02/10/2008 13:53 COMMENCEMENT DATE= 06/10/2008 SEQUENCE NO= xxxxxxxxx PLANNING= No [CALLER DETAILS] CUSTOMER ID= 403552 CONTACT NAME= {Name of Contact} CONTACT HOURS= 0 COMPANY= Underground Utility Locating ADDRESS= {Address} SUBURB= {Suburb} STATE= {State} POSTCODE= 4350 TELEPHONE= xxxxxxxxxx MOBILE= xxxxxxxxxx FAX TYPE= Private FAX NUMBER= xxxxxxxxxx PUBLIC ADDRESS= xxxxxxxxxx PUBLIC TELEPHONE= EMAIL ADDRESS= {Email Address} [LOCATION DETAILS] ADDRESS= {Location Address} SUBURB= {Location Suburb} STATE= xxx POSTCODE= xxx DEPOSITED PLAN NO= 0 SECTION &amp; HUNDRED NO= 0 PROPERTY PHONE NO= SIDE OF STREET= B INTERSECTION= xxxxxx DISTANCE= 0-200m B ACTIVITY CODE= 15 ACTIVITY DESCRIPTION= xxxxxxxxxxxxxxxxxx MAP TYPE= StateGrid MAP REF= Q851_63 MAP PAGE= MAP GRID 1= MAP GRID 2= MAP GRID 3= MAP GRID 4= MAP GRID 5= GPS X COORD= GPS Y COORD= PRIVATE/ROAD/BOTH= B TRAFFIC AFFECTED= No NOTIFICATION NO= 3082321 MESSAGE= entire intersection of Allora-Clifton rd , Hillside rd and merivale st MOCSMESSAGE= Digsafe generated referral Notice: Please DO NOT REPLY TO THIS EMAIL as it has been automatically generated and replies are not monitored. Should you wish to advise Dial Before You Dig of any issues with this enquiry, please Call 1100 (See attached file: 3082321_LLGDA94.GML) </code></pre>
[ { "answer_id": 161092, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=parse+.ini+vb+.net&amp;ie=UTF-8&amp;oe=UTF-8\" rel=\"nofollow noreferrer\">Google has the answers</a>, once you know that the file-format is called '.ini'</p>\n\n<p><strong>Edit:</strong> That is, it's an .ini plus some extra leading/trailing gunk.</p>\n" }, { "answer_id": 161095, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 2, "selected": false, "text": "<p>You could read each line of the file sequentially. Each line is essentially a name value pair. Place each value in a map (hash table) keyed by name. Use a map for each section. When done parsing the file you'll have maps containing all the name value pairs. Iterate over each map and populate your database tables.</p>\n" }, { "answer_id": 161152, "author": "pbh101", "author_id": 1266, "author_profile": "https://Stackoverflow.com/users/1266", "pm_score": 2, "selected": false, "text": "<p>I would head to Python for any type of string parsing like this. I'm not sure how much of this information you want to retain, but I would perhaps use Python's <code>split()</code> function to split on <code>=</code> to get rid of the equals sign, then strip the whitespace out of the second piece of the pie.</p>\n\n<p>First, I would mask out the header/footer info I know I don't need, then do something akin to the following:</p>\n\n<p>Let's take a chunk and save it in <code>test1.txt</code>:</p>\n\n<pre>\nADDRESS= {Location Address}\nSUBURB= {Location Suburb}\nSTATE= xxx\nPOSTCODE= xxx\nDEPOSITED PLAN NO= 0\nSECTION & HUNDRED NO= 0\nPROPERTY PHONE NO=\n</pre>\n\n<p>Here's a small python snippet:</p>\n\n<pre>\n>>> f = open(\"test1.txt\", \"r\")\n>>> l = f.readlines()\n>>> l = [line.split('=') for line in l]\n>>> for line in l:\n print line\n\n['ADDRESS', '{Location Address}']\n['SUBURB', '{Location Suburb}']\n['STATE', 'xxx']\n['POSTCODE', 'xxx']\n['DEPOSITED PLAN NO', '0']\n['SECTION & HUNDRED NO', '0']\n['PROPERTY PHONE NO', '']\n</pre>\n\n<p>This would essentially give you a [Column, Value] tuple you could use to insert the data into your database (after escaping all strings, etc etc, SQL Injection warning).</p>\n\n<p>This is assuming the email input and your DB will have the same column names, but if they didn't, it'd be fairly trivial to set up a column mapping using a dictionary. On the flip side, if the email and columns are in sync, you don't need to know the names of the columns to get the parsing down.</p>\n\n<p>You could iterate through the pseudo-dictionary and print out each key-value pair in the right spot in your parameterized sql string.</p>\n\n<p>Hope this helps!</p>\n\n<p>Edit: While this is in Python, C#/VB.net should have the same/similar abilities.</p>\n" }, { "answer_id": 224550, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 1, "selected": false, "text": "<pre><code>Using f As StreamReader = File.OpenText(\"sample.txt\")\n Dim g As String = \"undefined\"\n Do\n Dim s As String = f.ReadLine\n If s Is Nothing Then Exit Do\n s = s.Replace(Chr(9), \" \")\n If s.StartsWith(\"[\") And s.EndsWith(\"]\") Then\n g = s.Substring(\"[\".Length, s.Length - \"[]\".Length)\n Else\n Dim ss() As String = s.Split(New Char() {\"=\"c}, 2)\n If ss.Length = 2 Then\n Console.WriteLine(\"{0}.{1}={2}\", g, Trim(ss(0)), Trim(ss(1)))\n End If\n End If\n Loop\nEnd Using\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
I was just wondering if anyone knew of a good way that I could parse the file at the bottom of the post. I have a database setup with the correct tables for each section eg Refferal Table,Caller Table,Location Table. Each table has the same columns that are show in the file below I would really like something that is fairly genetic so if the file layout changes it won't mess me around to much. At the moment I am just reading the file in a line at a time and just using a case statement to check which section i'm in. Is anyone able to help me with this? PS. I am using VB but C# or anything else will be fine, also the x's in the document are just personal info I have blanked Thanks, Nathan File:---> ``` DIAL BEFORE YOU DIG Call 1100, Fax 1300 652 077 PO Box 7710 MELBOURNE, VIC 8004 Utilities are requested to respond within 2 working days and reference the Sequence number. [REFFERAL DETAILS] FROM= Dial Before You Dig - Web TO= Technical Services UTILITY ID= xxxxxx COMPANY= {Company Name} ENQUIRY DATE= 02/10/2008 13:53 COMMENCEMENT DATE= 06/10/2008 SEQUENCE NO= xxxxxxxxx PLANNING= No [CALLER DETAILS] CUSTOMER ID= 403552 CONTACT NAME= {Name of Contact} CONTACT HOURS= 0 COMPANY= Underground Utility Locating ADDRESS= {Address} SUBURB= {Suburb} STATE= {State} POSTCODE= 4350 TELEPHONE= xxxxxxxxxx MOBILE= xxxxxxxxxx FAX TYPE= Private FAX NUMBER= xxxxxxxxxx PUBLIC ADDRESS= xxxxxxxxxx PUBLIC TELEPHONE= EMAIL ADDRESS= {Email Address} [LOCATION DETAILS] ADDRESS= {Location Address} SUBURB= {Location Suburb} STATE= xxx POSTCODE= xxx DEPOSITED PLAN NO= 0 SECTION & HUNDRED NO= 0 PROPERTY PHONE NO= SIDE OF STREET= B INTERSECTION= xxxxxx DISTANCE= 0-200m B ACTIVITY CODE= 15 ACTIVITY DESCRIPTION= xxxxxxxxxxxxxxxxxx MAP TYPE= StateGrid MAP REF= Q851_63 MAP PAGE= MAP GRID 1= MAP GRID 2= MAP GRID 3= MAP GRID 4= MAP GRID 5= GPS X COORD= GPS Y COORD= PRIVATE/ROAD/BOTH= B TRAFFIC AFFECTED= No NOTIFICATION NO= 3082321 MESSAGE= entire intersection of Allora-Clifton rd , Hillside rd and merivale st MOCSMESSAGE= Digsafe generated referral Notice: Please DO NOT REPLY TO THIS EMAIL as it has been automatically generated and replies are not monitored. Should you wish to advise Dial Before You Dig of any issues with this enquiry, please Call 1100 (See attached file: 3082321_LLGDA94.GML) ```
[Google has the answers](http://www.google.com/search?client=safari&rls=en-us&q=parse+.ini+vb+.net&ie=UTF-8&oe=UTF-8), once you know that the file-format is called '.ini' **Edit:** That is, it's an .ini plus some extra leading/trailing gunk.
161,093
<p>I have a table that looks like that:</p> <p><img src="https://i.stack.imgur.com/R0TIr.jpg" alt="alt text"></p> <p>The rows are sorted by CLNDR_DATE DESC.</p> <p>I need to find a CLNDR_DATE that corresponds to the highlighted row, in other words:<br> Find the topmost group of rows WHERE EFFECTIVE_DATE IS NOT NULL, and return the CLNR_DATE of a last row of that group.</p> <p>Normally I would open a cursor and cycle from top to bottom until I find a NULL in EFFECTIVE_DATE. Then I would know that the date I am looking for is CLNDR_DATE, obtained at the previous step.</p> <p>However, I wonder if the same can be achieved with a single SQL?</p>
[ { "answer_id": 161105, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": true, "text": "<p>Warning: Not a DBA by any means. ;)</p>\n\n<p>But, a quick, untested stab at it:</p>\n\n<pre><code>SELECT min(CLNDR_DATE) FROM [TABLE]\nWHERE (EFFECTIVE_DATE IS NOT NULL)\n AND (CLNDR_DATE &gt; (\n SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL\n ))\n</code></pre>\n\n<p>Assuming you want the <strong>first</strong> CLNDR_DATE <strong>with</strong> EFFECTIVE_DATE after the <strong>last without</strong>.</p>\n\n<p>If you want the <strong>first with</strong> after the <strong>first without</strong>, change the subquery to use min() instead of max().</p>\n" }, { "answer_id": 161109, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>The first result from this recordset is what you're looking for. Depending on your Database, you may be able to only return this row by using LIMIT, or TOP</p>\n\n<pre><code>SELECT CLNDR_DATE \nFROM TABLE\nWHERE CLNDR_DATE &gt; (SELECT MAX(CLNDR_DATE)\n FROM TABLE \n WHERE EFFECTIVE_DATE IS NOT NULL)\nORDER BY CLNDR_DATE\n</code></pre>\n" }, { "answer_id": 161119, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>When you are in Oracle environment you can use analytical functions (<a href=\"http://www.orafaq.com/node/55\" rel=\"nofollow noreferrer\">http://www.orafaq.com/node/55</a>), which are very powerful tools to do kind of queries you asking for.</p>\n\n<p>Using standard SQL I think it is impossible, but maybe some SQL gurus will show up some nice solution.</p>\n" }, { "answer_id": 161150, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 1, "selected": false, "text": "<p>Using Oracle's analytic function (untested)</p>\n\n<pre><code>select *\nfrom\n(\n select \n clndr_date, \n effective_date, \n lag(clndr_date, 1, null) over (order by clndr_date desc) prev_clndr_date\n from table\n)\nwhere effective_date is null\n</code></pre>\n\n<p>The <code>lag(clndr_date, 1, null) over (order by clndr_date desc)</code> returns the previous clndr_date, or use null if this is the first row.</p>\n\n<p>(edit: fixed order)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10557/" ]
I have a table that looks like that: ![alt text](https://i.stack.imgur.com/R0TIr.jpg) The rows are sorted by CLNDR\_DATE DESC. I need to find a CLNDR\_DATE that corresponds to the highlighted row, in other words: Find the topmost group of rows WHERE EFFECTIVE\_DATE IS NOT NULL, and return the CLNR\_DATE of a last row of that group. Normally I would open a cursor and cycle from top to bottom until I find a NULL in EFFECTIVE\_DATE. Then I would know that the date I am looking for is CLNDR\_DATE, obtained at the previous step. However, I wonder if the same can be achieved with a single SQL?
Warning: Not a DBA by any means. ;) But, a quick, untested stab at it: ``` SELECT min(CLNDR_DATE) FROM [TABLE] WHERE (EFFECTIVE_DATE IS NOT NULL) AND (CLNDR_DATE > ( SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL )) ``` Assuming you want the **first** CLNDR\_DATE **with** EFFECTIVE\_DATE after the **last without**. If you want the **first with** after the **first without**, change the subquery to use min() instead of max().
161,108
<p>I've been developing web applications for a while and i am quite comfortable with mySql, in fact as many do i use some form of SQL almost every day. I like the syntax and a have zero problems writing queries or optimizing my tables. I have enjoyed this mysql <a href="http://www.tmtm.org/en/mysql/ruby/" rel="nofollow noreferrer">api</a>.</p> <p>The thing that has been bugging me is Ruby on Rails uses ActiveRecord and migrates everything so you use functions to query the database. I suppose the idea being you "never have to look at SQL again". Maybe this isn't KISS (keep it simple stupid) but is the ActiveRecord interface really best? If so why? </p> <p>Is development without having to ever write a SQL statement healthy? What if you ever have to look something up that isn't already defined as a rails function? I know they have a function that allows me to do a custom query. I guess really i want to know what people think the advantages are of using ActiveRecord over mySQL and if anyone feels like me that maybe this would be for the rails community what the calculator was to the math community and some people might forget how to do long division.</p>
[ { "answer_id": 161135, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 1, "selected": false, "text": "<p>The idea here is that by putting your DB logic inside your Active Records, you're dealing with SQL code in one place, rather than spread all over your application. This makes it easier for the various layers of your application to follow the Single Responsibility Principle (that an object should have only one reason to change).</p>\n\n<p>Here's <a href=\"http://www.devshed.com/c/a/PHP/The-Active-Record-Pattern/\" rel=\"nofollow noreferrer\">an article on the Active Record pattern</a>.</p>\n" }, { "answer_id": 161246, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 0, "selected": false, "text": "<p>Avoiding SQL helps you when you decide to change the database scheme. The abstraction is also necessary for all kinds of things, like validation. I doesn't mean you don't get to write SQL: you can always do that if you feel the need for it. But you don't have to write a 5 line query where all you need is user.save. It's the rails philosophy to avoid unnecessary code. </p>\n" }, { "answer_id": 162267, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>You're right that hiding the SQL behind ActiveRecord's layer means people might forget to check the generated SQL. I've been bitten by this myself: missing indexes, inefficient queries, etc.</p>\n\n<p>What ActiveRecord allows is making the easy things easy:</p>\n\n<pre><code>Post.find(1)\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>SELECT * FROM posts WHERE posts.id = 1\n</code></pre>\n\n<p>You, the developer, have less to type, and thus have less chances for error.</p>\n\n<p>Validation is another thing that ActiveRecord makes easy. You have to do it anyway, so why not have an easy way to do it? With the repetitive, boring, parts abstracted out?</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n validates_presence_of :title\n validates_length_of :title, :maximum =&gt; 80\nend\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>if params[:post][:title].blank? then\n # complain\nelsif params[:post][:title].length &gt; 80 then\n # complain again\nend\n</code></pre>\n\n<p>Again, easy to specify, easy to validate. Want more validation? A single line to add to an ActiveRecord model. Convoluted code with multiple conditions is always harder to debug and test. Why not make it easy on you?</p>\n\n<p>The final thing I really like about ActiveRecord instead of SQL are callbacks. Callbacks can be emulated with SQL triggers (which are only available in MySQL 5.0 or above), while ActiveRecord has had callbacks since way back then (I started on 0.13).</p>\n\n<p>To summarize:</p>\n\n<ul>\n<li>ActiveRecord makes the easy things easy;</li>\n<li>ActiveRecord removes the boring, repetitive parts;</li>\n<li>ActiveRecord does not prevent you from <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001302\" rel=\"nofollow noreferrer\">writing your own SQL</a> (usually for performance reasons), and finally;</li>\n<li>ActiveRecord is fully portable accross most database engines, while SQL itself is not (sometimes).</li>\n</ul>\n\n<p>I know in your case you are talking specifically about MySQL, but still. Having the option is nice.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18159/" ]
I've been developing web applications for a while and i am quite comfortable with mySql, in fact as many do i use some form of SQL almost every day. I like the syntax and a have zero problems writing queries or optimizing my tables. I have enjoyed this mysql [api](http://www.tmtm.org/en/mysql/ruby/). The thing that has been bugging me is Ruby on Rails uses ActiveRecord and migrates everything so you use functions to query the database. I suppose the idea being you "never have to look at SQL again". Maybe this isn't KISS (keep it simple stupid) but is the ActiveRecord interface really best? If so why? Is development without having to ever write a SQL statement healthy? What if you ever have to look something up that isn't already defined as a rails function? I know they have a function that allows me to do a custom query. I guess really i want to know what people think the advantages are of using ActiveRecord over mySQL and if anyone feels like me that maybe this would be for the rails community what the calculator was to the math community and some people might forget how to do long division.
You're right that hiding the SQL behind ActiveRecord's layer means people might forget to check the generated SQL. I've been bitten by this myself: missing indexes, inefficient queries, etc. What ActiveRecord allows is making the easy things easy: ``` Post.find(1) ``` vs ``` SELECT * FROM posts WHERE posts.id = 1 ``` You, the developer, have less to type, and thus have less chances for error. Validation is another thing that ActiveRecord makes easy. You have to do it anyway, so why not have an easy way to do it? With the repetitive, boring, parts abstracted out? ``` class Post < ActiveRecord::Base validates_presence_of :title validates_length_of :title, :maximum => 80 end ``` vs ``` if params[:post][:title].blank? then # complain elsif params[:post][:title].length > 80 then # complain again end ``` Again, easy to specify, easy to validate. Want more validation? A single line to add to an ActiveRecord model. Convoluted code with multiple conditions is always harder to debug and test. Why not make it easy on you? The final thing I really like about ActiveRecord instead of SQL are callbacks. Callbacks can be emulated with SQL triggers (which are only available in MySQL 5.0 or above), while ActiveRecord has had callbacks since way back then (I started on 0.13). To summarize: * ActiveRecord makes the easy things easy; * ActiveRecord removes the boring, repetitive parts; * ActiveRecord does not prevent you from [writing your own SQL](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001302) (usually for performance reasons), and finally; * ActiveRecord is fully portable accross most database engines, while SQL itself is not (sometimes). I know in your case you are talking specifically about MySQL, but still. Having the option is nice.
161,127
<p>We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour).</p> <p>ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it.</p> <p>Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want?</p> <p>Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?</p>
[ { "answer_id": 161232, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 1, "selected": false, "text": "<p>Is your ItemsControl/ListBox databound? </p>\n\n<p>I'm just thinking you could make the Background Brush of each item bound to a property from the source data, or pass the property through a converter. Something like: </p>\n\n<pre><code> &lt;ItemsControl DataContext=\"{Binding Source={StaticResource Things}}\" ItemsSource=\"{Binding}\" Margin=\"0\"&gt;\n &lt;ItemsControl.Resources&gt;\n &lt;local:SelectedConverter x:Key=\"conv\"/&gt;\n &lt;/ItemsControl.Resources&gt;\n &lt;ItemsControl.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;local:Control Background=\"{Binding Path=IsSelected, Converter={StaticResource conv}}\"/&gt;\n &lt;/ItemsPanelTemplate&gt;\n &lt;/ItemsControl.ItemsPanel&gt;\n</code></pre>\n" }, { "answer_id": 161366, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": true, "text": "<p>One option is to set <code>ListBoxItem.IsEnabled</code> to <code>false</code>:</p>\n\n<pre><code>&lt;ListBox x:Name=\"_listBox\"&gt;\n &lt;ListBox.ItemContainerStyle&gt;\n &lt;Style TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"IsEnabled\" Value=\"False\"/&gt;\n &lt;/Style&gt;\n &lt;/ListBox.ItemContainerStyle&gt;\n&lt;/ListBox&gt;\n</code></pre>\n\n<p>This ensures that the items are not selectable, but they may not render how you like. To fix this, you can play around with triggers and/or templates. For example:</p>\n\n<pre><code>&lt;ListBox x:Name=\"_listBox\"&gt;\n &lt;ListBox.ItemContainerStyle&gt;\n &lt;Style TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"IsEnabled\" Value=\"False\"/&gt;\n &lt;Style.Triggers&gt;\n &lt;Trigger Property=\"IsEnabled\" Value=\"False\"&gt;\n &lt;Setter Property=\"Foreground\" Value=\"Red\" /&gt;\n &lt;/Trigger&gt;\n &lt;/Style.Triggers&gt;\n &lt;/Style&gt;\n &lt;/ListBox.ItemContainerStyle&gt;\n&lt;/ListBox&gt;\n</code></pre>\n" }, { "answer_id": 4939276, "author": "Jim", "author_id": 608909, "author_profile": "https://Stackoverflow.com/users/608909", "pm_score": 2, "selected": false, "text": "<p>I had the same issue. I resolved it by leaving the IsEnabled set to true and handling the PreviewMouseDown event of the ListBox. In the handler set e.Handled to true in the case you don't want it to be edited. </p>\n\n<pre><code> private void lstSMTs_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)\n {\n e.Handled = !editRights;\n }\n</code></pre>\n" }, { "answer_id": 69809258, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 2, "selected": false, "text": "<p>The magical incantation that will do the trick is:</p>\n<pre><code>&lt;ListBox IsHitTestVisible=&quot;False&quot;&gt;\n</code></pre>\n<p>Unfortunately, this will also prevent any scrollbars from working.</p>\n<p>The fix to that is to put the listbox inside a scrollviewer:</p>\n<pre><code>&lt;ScrollViewer&gt;\n &lt;ListBox IsHitTestVisible=&quot;False&quot;&gt;\n &lt;/ListBox&gt;\n&lt;/ScrollViewer&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour). ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it. Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want? Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?
One option is to set `ListBoxItem.IsEnabled` to `false`: ``` <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> </Style> </ListBox.ItemContainerStyle> </ListBox> ``` This ensures that the items are not selectable, but they may not render how you like. To fix this, you can play around with triggers and/or templates. For example: ``` <ListBox x:Name="_listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsEnabled" Value="False"/> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="Red" /> </Trigger> </Style.Triggers> </Style> </ListBox.ItemContainerStyle> </ListBox> ```
161,166
<p>Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?)</p> <p>Anyways I want to write:</p> <pre><code>myIter = mySet.erase(myIter); </code></pre> <p>But GCC doesn't like it... So Is it safe to write this instead?</p> <pre><code>mySet.erase(myIter++); </code></pre> <p>Edit: And yes I'm checking against mySet.end();</p>
[ { "answer_id": 161239, "author": "Camille", "author_id": 16990, "author_profile": "https://Stackoverflow.com/users/16990", "pm_score": 4, "selected": true, "text": "<p>There is no problem with </p>\n\n<pre><code>mySet.erase(myIter++);\n</code></pre>\n\n<p>The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method.</p>\n\n<p><strong>For Greg and Mark</strong>: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.</p>\n" }, { "answer_id": 161254, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 2, "selected": false, "text": "<p>First, reread the standard and you'll see that the prototype of the set::erase method is:</p>\n\n<pre><code>void erase(iterator position);\n</code></pre>\n\n<p>However, the associative containers in the STL are \"stable\", as erasing an element do not affect the iterators on the other elements. This means that the following line is valid:</p>\n\n<pre><code>iterator to_erase = myIter++;\nmySet.erase(to_erase);\n// Now myIter is still on the next element\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?) Anyways I want to write: ``` myIter = mySet.erase(myIter); ``` But GCC doesn't like it... So Is it safe to write this instead? ``` mySet.erase(myIter++); ``` Edit: And yes I'm checking against mySet.end();
There is no problem with ``` mySet.erase(myIter++); ``` The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method. **For Greg and Mark**: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.
161,176
<p>I am working on an ASP site hosted using SUN One (used to be called Chillisoft) server. I am having trouble loading in an XML file, the code I am using is below</p> <pre><code>dim directory set directory = Server.CreateObject("MSXML2.DOMDocument") if(directory.load(Server.MapPath("directory.xml"))) then Response.Write("Loaded") else Response.Write("NotLoaded") If directory.parseError.errorCode Then Response.Write( "Parse error" ) end if end if </code></pre> <p>My asp page and directory.xml are both in the same folder "/public_html/".</p> <p>I think the problem might have something to do with the mappath not finding the file, but no errors are returned so not sure what to do.</p> <p>Thanks</p>
[ { "answer_id": 161245, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 1, "selected": false, "text": "<p>I don't know much about Sun One but I do know it has a Bean that emulates MSXML.</p>\n\n<p>Oridinarily, you would use:-</p>\n\n<pre><code>Set directory = Server.CreateObject(\"MSXML2.DOMDocument\")\ndirectory.async = false\ndirectory.load(Server.MapPath(\"directory.xml\")\n</code></pre>\n\n<p>Otherwise load returns immeadiately whilst the xml is loaded asynchronously.</p>\n\n<p>It can't see how the code you have posted would not return something without error.</p>\n\n<p>First diagnositic I would is:-</p>\n\n<pre><code>Response.Write(Server.MapPath(\"directory.xml\"))\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>Dim direcotory\nSet directory = Server.CreateObject(\"MSXML.DOMDocument\")\nResponse.Write(Not (directory Is Nothing))\n</code></pre>\n" }, { "answer_id": 168450, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 0, "selected": false, "text": "<p>The load likely returns false because it hasn't fully loaded the document yet. You need to find a way to set async to false. If the Sun One is emulating MSXML2.DOMDocument well then async should accept false but you could try -<code>1</code> or <code>Response.Write(directory.async)</code> to get an idea of what it is originally set to.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am working on an ASP site hosted using SUN One (used to be called Chillisoft) server. I am having trouble loading in an XML file, the code I am using is below ``` dim directory set directory = Server.CreateObject("MSXML2.DOMDocument") if(directory.load(Server.MapPath("directory.xml"))) then Response.Write("Loaded") else Response.Write("NotLoaded") If directory.parseError.errorCode Then Response.Write( "Parse error" ) end if end if ``` My asp page and directory.xml are both in the same folder "/public\_html/". I think the problem might have something to do with the mappath not finding the file, but no errors are returned so not sure what to do. Thanks
I don't know much about Sun One but I do know it has a Bean that emulates MSXML. Oridinarily, you would use:- ``` Set directory = Server.CreateObject("MSXML2.DOMDocument") directory.async = false directory.load(Server.MapPath("directory.xml") ``` Otherwise load returns immeadiately whilst the xml is loaded asynchronously. It can't see how the code you have posted would not return something without error. First diagnositic I would is:- ``` Response.Write(Server.MapPath("directory.xml")) ``` and then ``` Dim direcotory Set directory = Server.CreateObject("MSXML.DOMDocument") Response.Write(Not (directory Is Nothing)) ```
161,177
<p>Does C++ support '<a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html" rel="noreferrer"><strong>finally</strong></a>' blocks?</p> <p>What is the <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer"><strong>RAII idiom</strong></a>?</p> <p>What is the difference between C++'s RAII idiom and <a href="http://www.c-sharpcorner.com/uploadfile/dipalchoksi/usingstatement11092005065819am/usingstatement.aspx" rel="noreferrer"><strong>C#'s 'using' statement</strong></a>?</p>
[ { "answer_id": 161179, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 8, "selected": false, "text": "<p>No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: \"Resource Acquisition Is Initialization\" -- a <em>poor name</em><sup><strong>†</strong></sup> for a really useful concept. </p>\n\n<p>The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is <a href=\"http://www.stroustrup.com/bs_faq2.html#finally\" rel=\"noreferrer\"><strong>Bjarne Stroustrup's explanation</strong></a> of the topic.</p>\n\n<p>A common use for RAII is locking a mutex:</p>\n\n<pre><code>// A class with implements RAII\nclass lock\n{\n mutex &amp;m_;\n\npublic:\n lock(mutex &amp;m)\n : m_(m)\n {\n m.acquire();\n }\n ~lock()\n {\n m_.release();\n }\n};\n\n// A class which uses 'mutex' and 'lock' objects\nclass foo\n{\n mutex mutex_; // mutex for locking 'foo' object\npublic:\n void bar()\n {\n lock scopeLock(mutex_); // lock object.\n\n foobar(); // an operation which may throw an exception\n\n // scopeLock will be destructed even if an exception\n // occurs, which will release the mutex and allow\n // other functions to lock the object and run.\n }\n};\n</code></pre>\n\n<p>RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to <em>Mike B</em> for pointing this out.)</p>\n\n<p>For those familliar with C# or VB.NET, you may recognize that RAII is similar to <a href=\"https://web.archive.org/web/20091023110911/http://geocities.com/Jeff_Louie/deterministic_destructors.htm\" rel=\"noreferrer\"><strong>.NET deterministic destruction using IDisposable and 'using' statements</strong></a>. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.</p>\n\n<p>&nbsp;</p>\n\n<p>† Some people believe that \"Destruction is Resource Relinquishment\" is a more accurate name for the RAII idiom.</p>\n" }, { "answer_id": 161203, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 3, "selected": false, "text": "<p>FWIW, Microsoft Visual C++ does support try,finally and it has historically been used in MFC apps as a method of catching serious exceptions that would otherwise result in a crash. For example;</p>\n\n<pre><code>int CMyApp::Run() \n{\n __try\n {\n int i = CWinApp::Run();\n m_Exitok = MAGIC_EXIT_NO;\n return i;\n }\n __finally\n {\n if (m_Exitok != MAGIC_EXIT_NO)\n FaultHandler();\n }\n}\n</code></pre>\n\n<p>I've used this in the past to do things like save backups of open files prior to exit. Certain JIT debugging settings will break this mechanism though.</p>\n" }, { "answer_id": 161207, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "<p>Beyond making clean up easy with stack-based objects, RAII is also useful because the same 'automatic' clean up occurs when the object is a member of another class. When the owning class is destructed, the resource managed by the RAII class gets cleaned up because the dtor for that class gets called as a result.</p>\n\n<p>This means that when you reach RAII nirvana and all members in a class use RAII (like smart pointers), you can get away with a very simple (maybe even default) dtor for the owner class since it doesn't need to manually manage its member resource lifetimes.</p>\n" }, { "answer_id": 161247, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": false, "text": "<p>In C++ the finally is <b>NOT</b> required because of RAII.<br></p>\n\n<p>RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.</p>\n\n<p>Also IMO the code looks neater (see below).</p>\n\n<p>Example:</p>\n\n<p>A database object. To make sure the DB connection is used it must be opened and closed. By using RAII this can be done in the constructor/destructor.</p>\n\n<h3>C++ Like RAII</h3>\n\n<pre><code>void someFunc()\n{\n DB db(\"DBDesciptionString\");\n // Use the db object.\n\n} // db goes out of scope and destructor closes the connection.\n // This happens even in the presence of exceptions.\n</code></pre>\n\n<p>The use of RAII makes using a DB object correctly very easy. The DB object will correctly close itself by the use of a destructor no matter how we try and abuse it.</p>\n\n<h3>Java Like Finally</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>void someFunc()\n{\n DB db = new DB(\"DBDesciptionString\");\n try\n {\n // Use the db object.\n }\n finally\n {\n // Can not rely on finaliser.\n // So we must explicitly close the connection.\n try\n {\n db.close();\n }\n catch(Throwable e)\n {\n /* Ignore */\n // Make sure not to throw exception if one is already propagating.\n }\n }\n}\n</code></pre>\n\n<p>When using finally the correct use of the object is delegated to the user of the object. <b>i.e.</b> It is the responsibility of the object user to correctly to explicitly close the DB connection. Now you could argue that this can be done in the finaliser, but resources may have limited availability or other constraints and thus you generally do want to control the release of the object and not rely on the non deterministic behavior of the garbage collector.</p>\n\n<p>Also this is a simple example.<br>\nWhen you have multiple resources that need to be released the code can get complicated.</p>\n\n<p>A more detailed analysis can be found here: <a href=\"http://accu.org/index.php/journals/236\" rel=\"noreferrer\">http://accu.org/index.php/journals/236</a></p>\n" }, { "answer_id": 2701414, "author": "Unhandled exception", "author_id": 324539, "author_profile": "https://Stackoverflow.com/users/324539", "pm_score": -1, "selected": false, "text": "<pre><code>try\n{\n ...\n goto finally;\n}\ncatch(...)\n{\n ...\n goto finally;\n}\nfinally:\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 2958622, "author": "Mephane", "author_id": 356532, "author_profile": "https://Stackoverflow.com/users/356532", "pm_score": 3, "selected": false, "text": "<p>Sorry for digging up such an old thread, but there is a major error in the following reasoning:</p>\n\n<blockquote>\n <p>RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.</p>\n</blockquote>\n\n<p>More often than not, you have to deal with dynamically allocated objects, dynamic numbers of objects etc. Within the try-block, some code might create many objects (how many is determined at runtime) and store pointers to them in a list. Now, this is not an exotic scenario, but very common. In this case, you'd want to write stuff like</p>\n\n<pre><code>void DoStuff(vector&lt;string&gt; input)\n{\n list&lt;Foo*&gt; myList;\n\n try\n { \n for (int i = 0; i &lt; input.size(); ++i)\n {\n Foo* tmp = new Foo(input[i]);\n if (!tmp)\n throw;\n\n myList.push_back(tmp);\n }\n\n DoSomeStuff(myList);\n }\n finally\n {\n while (!myList.empty())\n {\n delete myList.back();\n myList.pop_back();\n }\n }\n}\n</code></pre>\n\n<p>Of course the list itself will be destroyed when going out of scope, but that wouldn't clean up the temporary objects you have created.</p>\n\n<p>Instead, you have to go the ugly route:</p>\n\n<pre><code>void DoStuff(vector&lt;string&gt; input)\n{\n list&lt;Foo*&gt; myList;\n\n try\n { \n for (int i = 0; i &lt; input.size(); ++i)\n {\n Foo* tmp = new Foo(input[i]);\n if (!tmp)\n throw;\n\n myList.push_back(tmp);\n }\n\n DoSomeStuff(myList);\n }\n catch(...)\n {\n }\n\n while (!myList.empty())\n {\n delete myList.back();\n myList.pop_back();\n }\n}\n</code></pre>\n\n<p>Also: why is it that even managed lanuages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?</p>\n\n<p>Hint: there's more you can do with \"finally\" than just memory deallocation.</p>\n" }, { "answer_id": 3759829, "author": "Philip Couling", "author_id": 453851, "author_profile": "https://Stackoverflow.com/users/453851", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>why is it that even managed languages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?</p>\n</blockquote>\n\n<p>Actually, languages based on Garbage collectors need \"finally\" more. A garbage collector does not destroy your objects in a timely manner, so it can not be relied upon to clean up non-memory related issues correctly.</p>\n\n<p>In terms of dynamically-allocated data, many would argue that you should be using smart-pointers.</p>\n\n<p>However...</p>\n\n<blockquote>\n <p>RAII moves the responsibility of exception safety from the user of the object to the designer</p>\n</blockquote>\n\n<p>Sadly this is its own downfall. Old C programming habits die hard. When you're using a library written in C or a very C style, RAII won't have been used. Short of re-writing the entire API front-end, that's just what you have to work with. <strong>Then</strong> the lack of \"finally\" really bites.</p>\n" }, { "answer_id": 23962251, "author": "bcmpinc", "author_id": 558366, "author_profile": "https://Stackoverflow.com/users/558366", "pm_score": 2, "selected": false, "text": "<p>Not really, but you can emulate them to some extend, for example:</p>\n\n<pre><code>int * array = new int[10000000];\ntry {\n // Some code that can throw exceptions\n // ...\n throw std::exception();\n // ...\n} catch (...) {\n // The finally-block (if an exception is thrown)\n delete[] array;\n // re-throw the exception.\n throw; \n}\n// The finally-block (if no exception was thrown)\ndelete[] array;\n</code></pre>\n\n<p>Note that the finally-block might itself throw an exception before the original exception is re-thrown, thereby discarding the original exception. This is the exact same behavior as in a Java finally-block. Also, you cannot use <code>return</code> inside the try&amp;catch blocks.</p>\n" }, { "answer_id": 24663837, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 1, "selected": false, "text": "<p>As many people have stated, the solution is to use C++11 features to avoid finally blocks. One of the features is <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow\"><code>unique_ptr</code></a>.</p>\n\n<p>Here is Mephane's answer written using RAII patterns.</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;memory&gt;\n#include &lt;list&gt;\nusing namespace std;\n\nclass Foo\n{\n ...\n};\n\nvoid DoStuff(vector&lt;string&gt; input)\n{\n list&lt;unique_ptr&lt;Foo&gt; &gt; myList;\n\n for (int i = 0; i &lt; input.size(); ++i)\n {\n myList.push_back(unique_ptr&lt;Foo&gt;(new Foo(input[i])));\n }\n\n DoSomeStuff(myList);\n}\n</code></pre>\n\n<p>Some more introduction to using unique_ptr with C++ Standard Library containers is <a href=\"http://eli.thegreenplace.net/2012/06/20/c11-using-unique_ptr-with-standard-library-containers/\" rel=\"nofollow\">here</a></p>\n" }, { "answer_id": 25510879, "author": "Paolo.Bolzoni", "author_id": 1876111, "author_profile": "https://Stackoverflow.com/users/1876111", "pm_score": 6, "selected": false, "text": "<p>RAII is usually better, but you can have easily the <strong>finally</strong> semantics in C++. Using a tiny amount of code.</p>\n<p>Besides, the C++ <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-utilities\" rel=\"noreferrer\">Core Guidelines give finally.</a></p>\n<p>Here is a link to the <a href=\"https://github.com/Microsoft/GSL\" rel=\"noreferrer\">GSL Microsoft implementation</a> and a link to the <a href=\"https://github.com/martinmoene/gsl-lite\" rel=\"noreferrer\">Martin Moene implementation</a></p>\n<p>Bjarne Stroustrup multiple times said that everything that is in the GSL it meant to go in the standard eventually. So it should be a future-proof way to use <strong>finally</strong>.</p>\n<p>You can easily implement yourself if you want though, continue reading.</p>\n<p>In C++11 RAII and lambdas allows to make a general finally:</p>\n<pre><code>namespace detail { //adapt to your &quot;private&quot; namespace\ntemplate &lt;typename F&gt;\nstruct FinalAction {\n FinalAction(F f) : clean_{f} {}\n ~FinalAction() { if(enabled_) clean_(); }\n void disable() { enabled_ = false; };\n private:\n F clean_;\n bool enabled_{true}; }; }\n\ntemplate &lt;typename F&gt;\ndetail::FinalAction&lt;F&gt; finally(F f) {\n return detail::FinalAction&lt;F&gt;(f); }\n</code></pre>\n<p>example of use:</p>\n<pre><code>#include &lt;iostream&gt;\nint main() {\n int* a = new int;\n auto delete_a = finally([a] { delete a; std::cout &lt;&lt; &quot;leaving the block, deleting a!\\n&quot;; });\n std::cout &lt;&lt; &quot;doing something ...\\n&quot;; }\n</code></pre>\n<p>the output will be:</p>\n<pre><code>doing something...\nleaving the block, deleting a!\n</code></pre>\n<p>Personally I used this few times to ensure to close POSIX file descriptor in a C++ program.</p>\n<p>Having a real class that manage resources and so avoids any kind of leaks is usually better, but this <strong>finally</strong> is useful in the cases where making a class sounds like an overkill.</p>\n<p>Besides, I like it better than other languages <strong>finally</strong> because if used naturally you write the closing code nearby the opening code (in my example the <strong>new</strong> and <strong>delete</strong>) and destruction follows construction in LIFO order as usual in C++. The only downside is that you get an auto variable you don't really use and the lambda syntax make it a little noisy (in my example in the fourth line only the word <strong>finally</strong> and the {}-block on the right are meaningful, the rest is essentially noise).</p>\n<p>Another example:</p>\n<pre><code> [...]\n auto precision = std::cout.precision();\n auto set_precision_back = finally( [precision, &amp;std::cout]() { std::cout &lt;&lt; std::setprecision(precision); } );\n std::cout &lt;&lt; std::setprecision(3);\n</code></pre>\n<p>The <strong>disable</strong> member is useful if the <strong>finally</strong> has to be called only in case of failure. For example, you have to copy an object in three different containers, you can setup the <strong>finally</strong> to undo each copy and disable after all copies are successful. Doing so, if the destruction cannot throw, you ensure the strong guarantee.</p>\n<p><strong>disable</strong> example:</p>\n<pre><code>//strong guarantee\nvoid copy_to_all(BIGobj const&amp; a) {\n first_.push_back(a);\n auto undo_first_push = finally([first_&amp;] { first_.pop_back(); });\n\n second_.push_back(a);\n auto undo_second_push = finally([second_&amp;] { second_.pop_back(); });\n\n third_.push_back(a);\n //no necessary, put just to make easier to add containers in the future\n auto undo_third_push = finally([third_&amp;] { third_.pop_back(); });\n\n undo_first_push.disable();\n undo_second_push.disable();\n undo_third_push.disable(); }\n</code></pre>\n<p>If you cannot use C++11 you can still have <em>finally</em>, but the code becomes a bit more long winded. Just define a struct with only a constructor and destructor, the constructor take references to anything needed and the destructor does the actions you need. This is basically what the lambda does, done manually.</p>\n<pre><code>#include &lt;iostream&gt;\nint main() {\n int* a = new int;\n\n struct Delete_a_t {\n Delete_a_t(int* p) : p_(p) {}\n ~Delete_a_t() { delete p_; std::cout &lt;&lt; &quot;leaving the block, deleting a!\\n&quot;; }\n int* p_;\n } delete_a(a);\n\n std::cout &lt;&lt; &quot;doing something ...\\n&quot;; }\n</code></pre>\n<p>Hopefully you can use C++11, this code is more to show how the &quot;C++ does not support finally&quot; has been nonsense since the very first weeks of C++, it was possible to write this kind of code even before C++ got its name.</p>\n" }, { "answer_id": 32349333, "author": "jave.web", "author_id": 1835470, "author_profile": "https://Stackoverflow.com/users/1835470", "pm_score": 0, "selected": false, "text": "<p><strong>EDITED</strong></p>\n<p><strong>If you are not breaking/continuing/returning</strong> etc., you could just add a catch to any unknown exception and put the always code behind it. That is also when you <strong>don't need</strong> the exception to be re-thrown.</p>\n<pre><code>try{\n // something that might throw exception\n} catch( ... ){\n // what to do with uknown exception\n}\n\n//final code to be called always,\n//don't forget that it might throw some exception too\ndoSomeCleanUp(); \n</code></pre>\n<h3>So what's the problem?</h3>\n<p>Normally finally in other programming languages usually runs <strong>no matter what</strong>(usually meaning regardless of any return, break, continue, ...) <strong>except</strong> for some sort of system <code>exit()</code> - which differes a lot per programming language - e.g. PHP and Java just exit in that moment, but Python executes finally anyways and then exits.</p>\n<p>But the code I've described above doesn't work that way\n<br>=&gt; following code outputs <strong>ONLY</strong> <code>something wrong!</code>:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nstd::string test() {\n try{\n // something that might throw exception\n throw &quot;exceptiooon!&quot;;\n\n return &quot;fine&quot;;\n } catch( ... ){\n return &quot;something wrong!&quot;;\n }\n \n return &quot;finally&quot;;\n}\n\nint main(void) {\n \n std::cout &lt;&lt; test();\n \n \n return 0;\n}\n</code></pre>\n" }, { "answer_id": 34010851, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 3, "selected": false, "text": "<p>I have a use case where I think <code>finally</code> <em>should</em> be a perfectly acceptable part of the C++11 language, as I think it is easier to read from a flow point of view. My use case is a consumer/producer chain of threads, where a sentinel <code>nullptr</code> is sent at the end of the run to shut down all threads.</p>\n\n<p>If C++ supported it, you would want your code to look like this:</p>\n\n<pre><code> extern Queue downstream, upstream;\n\n int Example()\n {\n try\n {\n while(!ExitRequested())\n {\n X* x = upstream.pop();\n if (!x) break;\n x-&gt;doSomething();\n downstream.push(x);\n } \n }\n finally { \n downstream.push(nullptr);\n }\n }\n</code></pre>\n\n<p>I think this is more logical that putting your finally declaration at the start of the loop, since it occurs after the loop has exited... but that is wishful thinking because we can't do it in C++. Note that the queue <code>downstream</code> is connected to another thread, so you can't put in the sentinel <code>push(nullptr)</code> in the destructor of <code>downstream</code> because it can't be destroyed at this point... it needs to stay alive until the other thread receives the <code>nullptr</code>.</p>\n\n<p>So here is how to use a RAII class with lambda to do the same:</p>\n\n<pre><code> class Finally\n {\n public:\n\n Finally(std::function&lt;void(void)&gt; callback) : callback_(callback)\n {\n }\n ~Finally()\n {\n callback_();\n }\n std::function&lt;void(void)&gt; callback_;\n };\n</code></pre>\n\n<p>and here is how you use it:</p>\n\n<pre><code> extern Queue downstream, upstream;\n\n int Example()\n {\n Finally atEnd([](){ \n downstream.push(nullptr);\n });\n while(!ExitRequested())\n {\n X* x = upstream.pop();\n if (!x) break;\n x-&gt;doSomething();\n downstream.push(x);\n }\n }\n</code></pre>\n" }, { "answer_id": 38701485, "author": "Fabio A.", "author_id": 566849, "author_profile": "https://Stackoverflow.com/users/566849", "pm_score": 2, "selected": false, "text": "<p>I came up with a <code>finally</code> macro that can be used <strong>almost like</strong>¹ the <code>finally</code> keyword in Java; it makes use of <code>std::exception_ptr</code> and friends, lambda functions and <code>std::promise</code>, so it requires <code>C++11</code> or above; it also makes use of the <a href=\"https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Statement-Exprs.html\" rel=\"nofollow noreferrer\">compound statement expression</a> GCC extension, which is also supported by clang.</p>\n\n<p><strong>WARNING</strong>: an <a href=\"/revisions/38701485/2\">earlier version</a> of this answer used a different implementation of the concept with many more limitations. </p>\n\n<p>First, let's define a helper class.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;future&gt;\n\ntemplate &lt;typename Fun&gt;\nclass FinallyHelper {\n template &lt;typename T&gt; struct TypeWrapper {};\n using Return = typename std::result_of&lt;Fun()&gt;::type;\n\npublic: \n FinallyHelper(Fun body) {\n try {\n execute(TypeWrapper&lt;Return&gt;(), body);\n }\n catch(...) {\n m_promise.set_exception(std::current_exception());\n }\n }\n\n Return get() {\n return m_promise.get_future().get();\n }\n\nprivate:\n template &lt;typename T&gt;\n void execute(T, Fun body) {\n m_promise.set_value(body());\n }\n\n void execute(TypeWrapper&lt;void&gt;, Fun body) {\n body();\n }\n\n std::promise&lt;Return&gt; m_promise;\n};\n\ntemplate &lt;typename Fun&gt;\nFinallyHelper&lt;Fun&gt; make_finally_helper(Fun body) {\n return FinallyHelper&lt;Fun&gt;(body);\n}\n</code></pre>\n\n<p>Then there's the actual macro.\n</p>\n\n<pre><code>#define try_with_finally for(auto __finally_helper = make_finally_helper([&amp;] { try \n#define finally }); \\\n true; \\\n ({return __finally_helper.get();})) \\\n/***/\n</code></pre>\n\n<p>It can be used like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void test() {\n try_with_finally {\n raise_exception();\n } \n\n catch(const my_exception1&amp;) {\n /*...*/\n }\n\n catch(const my_exception2&amp;) {\n /*...*/\n }\n\n finally {\n clean_it_all_up();\n } \n}\n</code></pre>\n\n<p>The use of <code>std::promise</code> makes it very easy to implement, but it probably also introduces quite a bit of unneeded overhead which could be avoided by reimplementing only the needed functionalities from <code>std::promise</code>.</p>\n\n<hr>\n\n<p>¹ <strong>CAVEAT:</strong> there are a few things that don't work quite like the java version of <code>finally</code>. Off the top of my head:</p>\n\n<ol>\n<li>it's not possible to break from an outer loop with the <code>break</code> statement from within the <code>try</code> and <code>catch()</code>'s blocks, since they live within a lambda function;</li>\n<li>there must be at least one <code>catch()</code> block after the <code>try</code>: it's a C++ requirement; </li>\n<li>if the function has a return value other than void but there's no return within the <code>try</code> and <code>catch()'s</code> blocks, compilation will fail because the <code>finally</code> macro will expand to code that will want to return a <code>void</code>. This could be, err, a<em>void</em>ed by having a <code>finally_noreturn</code> macro of sorts.</li>\n</ol>\n\n<p>All in all, I don't know if I'd ever use this stuff myself, but it was fun playing with it. :)</p>\n" }, { "answer_id": 47574378, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 4, "selected": false, "text": "<p>Another \"finally\" block emulation using C++11 lambda functions</p>\n\n<pre><code>template &lt;typename TCode, typename TFinallyCode&gt;\ninline void with_finally(const TCode &amp;code, const TFinallyCode &amp;finally_code)\n{\n try\n {\n code();\n }\n catch (...)\n {\n try\n {\n finally_code();\n }\n catch (...) // Maybe stupid check that finally_code mustn't throw.\n {\n std::terminate();\n }\n throw;\n }\n finally_code();\n}\n</code></pre>\n\n<p>Let's hope the compiler will optimize the code above.</p>\n\n<p>Now we can write code like this:</p>\n\n<pre><code>with_finally(\n [&amp;]()\n {\n try\n {\n // Doing some stuff that may throw an exception\n }\n catch (const exception1 &amp;)\n {\n // Handling first class of exceptions\n }\n catch (const exception2 &amp;)\n {\n // Handling another class of exceptions\n }\n // Some classes of exceptions can be still unhandled\n },\n [&amp;]() // finally\n {\n // This code will be executed in all three cases:\n // 1) exception was not thrown at all\n // 2) exception was handled by one of the \"catch\" blocks above\n // 3) exception was not handled by any of the \"catch\" block above\n }\n);\n</code></pre>\n\n<p>If you wish you can wrap this idiom into \"try - finally\" macros:</p>\n\n<pre><code>// Please never throw exception below. It is needed to avoid a compilation error\n// in the case when we use \"begin_try ... finally\" without any \"catch\" block.\nclass never_thrown_exception {};\n\n#define begin_try with_finally([&amp;](){ try\n#define finally catch(never_thrown_exception){throw;} },[&amp;]()\n#define end_try ) // sorry for \"pascalish\" style :(\n</code></pre>\n\n<p>Now \"finally\" block is available in C++11:</p>\n\n<pre><code>begin_try\n{\n // A code that may throw\n}\ncatch (const some_exception &amp;)\n{\n // Handling some exceptions\n}\nfinally\n{\n // A code that is always executed\n}\nend_try; // Sorry again for this ugly thing\n</code></pre>\n\n<p>Personally I don't like the \"macro\" version of \"finally\" idiom and would prefer to use pure \"with_finally\" function even though a syntax is more bulky in that case.</p>\n\n<p>You can test the code above here: <a href=\"http://coliru.stacked-crooked.com/a/1d88f64cb27b3813\" rel=\"noreferrer\">http://coliru.stacked-crooked.com/a/1d88f64cb27b3813</a></p>\n\n<p><strong>PS</strong></p>\n\n<p>If you need a <em>finally</em> block in your code, then <a href=\"https://stackoverflow.com/q/10270328/5447906\">scoped guards</a> or <a href=\"https://stackoverflow.com/a/48842771/5447906\">ON_FINALLY/ON_EXCEPTION</a> macros will probably better fit your needs.</p>\n\n<p>Here is short example of usage ON_FINALLY/ON_EXCEPTION:</p>\n\n<pre><code>void function(std::vector&lt;const char*&gt; &amp;vector)\n{\n int *arr1 = (int*)malloc(800*sizeof(int));\n if (!arr1) { throw \"cannot malloc arr1\"; }\n ON_FINALLY({ free(arr1); });\n\n int *arr2 = (int*)malloc(900*sizeof(int));\n if (!arr2) { throw \"cannot malloc arr2\"; }\n ON_FINALLY({ free(arr2); });\n\n vector.push_back(\"good\");\n ON_EXCEPTION({ vector.pop_back(); });\n\n ...\n</code></pre>\n" }, { "answer_id": 51738786, "author": "tobi_s", "author_id": 8680401, "author_profile": "https://Stackoverflow.com/users/8680401", "pm_score": 3, "selected": false, "text": "<p>As pointed out in the other answers, C++ can support <code>finally</code>-like functionality. The implementation of this functionality that is probably closest to being part of the standard language is the one accompanying the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"nofollow noreferrer\">C++ Core Guidelines</a>, a set of best practices for using C++ edited by Bjarne Stoustrup and Herb Sutter. An <a href=\"https://github.com/Microsoft/GSL/blob/master/include/gsl/gsl_util#L75\" rel=\"nofollow noreferrer\">implementation of <code>finally</code></a> is part of the <a href=\"https://github.com/Microsoft/GSL\" rel=\"nofollow noreferrer\">Guidelines Support Library</a> (GSL). Throughout the Guidelines, use of <code>finally</code> is recommended when dealing with old-style interfaces, and it also has a guideline of its own, titled <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e19-use-a-final_action-object-to-express-cleanup-if-no-suitable-resource-handle-is-available\" rel=\"nofollow noreferrer\">Use a final_action object to express cleanup if no suitable resource handle is available</a>.</p>\n\n<p>So, not only does C++ support <code>finally</code>, it is actually recommended to use it in a lot of common use-cases.</p>\n\n<p>An example use of the GSL implementation would look like:</p>\n\n<pre><code>#include &lt;gsl/gsl_util.h&gt;\n\nvoid example()\n{\n int handle = get_some_resource();\n auto handle_clean = gsl::finally([&amp;handle] { clean_that_resource(handle); });\n\n // Do a lot of stuff, return early and throw exceptions.\n // clean_that_resource will always get called.\n}\n</code></pre>\n\n<p>The GSL implementation and usage is very similar to the one in <a href=\"https://stackoverflow.com/a/25510879/8680401\">Paolo.Bolzoni's answer</a>. One difference is that the object created by <code>gsl::finally()</code> lacks the <code>disable()</code> call. If you need that functionality (say, to return the resource once it's assembled and no exceptions are bound to happen), you might prefer Paolo's implementation. Otherwise, using GSL is as close to using standardized features as you will get.</p>\n" }, { "answer_id": 53839815, "author": "Dean Roddey", "author_id": 8256857, "author_profile": "https://Stackoverflow.com/users/8256857", "pm_score": 1, "selected": false, "text": "<p>I also think that RIIA is not a fully useful replacement for exception handling and having a finally. BTW, I also think RIIA is a bad name all around. I call these types of classes 'janitors' and use them a LOT. 95% of the time they are neither initializing nor acquiring resources, they are applying some change on a scoped basis, or taking something already set up and making sure it's destroyed. This being the official pattern name obsessed internet I get abused for even suggesting my name might be better.</p>\n\n<p>I just don't think it's reasonable to require that that every complicated setup of some ad hoc list of things has to have a class written to contain it in order to avoid complications when cleaning it all back up in the face of needing to catch multiple exception types if something goes wrong in the process. This would lead to lots of ad hoc classes that just wouldn't be necessary otherwise.</p>\n\n<p>Yes it's fine for classes that are designed to manage a particular resource, or generic ones that are designed to handle a set of similar resources. But, even if all of the things involved have such wrappers, the coordination of cleanup may not just be a simple in reverse order invocation of destructors.</p>\n\n<p>I think it makes perfect sense for C++ to have a finally. I mean, jeez, so many bits and bobs have been glued onto it over the last decades that it seems odd folks would suddenly become conservative over something like finally which could be quite useful and probably nothing near as complicated as some other things that have been added (though that's just a guess on my part.)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
Does C++ support '[**finally**](http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html)' blocks? What is the [**RAII idiom**](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization)? What is the difference between C++'s RAII idiom and [**C#'s 'using' statement**](http://www.c-sharpcorner.com/uploadfile/dipalchoksi/usingstatement11092005065819am/usingstatement.aspx)?
No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a *poor name***†** for a really useful concept. The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is [**Bjarne Stroustrup's explanation**](http://www.stroustrup.com/bs_faq2.html#finally) of the topic. A common use for RAII is locking a mutex: ``` // A class with implements RAII class lock { mutex &m_; public: lock(mutex &m) : m_(m) { m.acquire(); } ~lock() { m_.release(); } }; // A class which uses 'mutex' and 'lock' objects class foo { mutex mutex_; // mutex for locking 'foo' object public: void bar() { lock scopeLock(mutex_); // lock object. foobar(); // an operation which may throw an exception // scopeLock will be destructed even if an exception // occurs, which will release the mutex and allow // other functions to lock the object and run. } }; ``` RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to *Mike B* for pointing this out.) For those familliar with C# or VB.NET, you may recognize that RAII is similar to [**.NET deterministic destruction using IDisposable and 'using' statements**](https://web.archive.org/web/20091023110911/http://geocities.com/Jeff_Louie/deterministic_destructors.htm). Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles. † Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.
161,222
<p>I've been using maven2 and hudson for a while to do my continuous integration, but I find that Eclipse and Maven do not play well together. Sure there's a plugin, but it's cranky to mash the maven project into something that eclipse likes and the build times and unit test are too long. I'm considering switching back to a pure eclipse project with no ant and no maven involved. With the infinitest plugin and possible the JavaRebel agent, it would give me a very fast build-deploy-test cycle. However I'd still like to have automatic and testing as well, so:</p> <p>How do I use continuous integration with an Eclipse project?</p> <p>Is there a command line way to do it? </p> <p>Is there a build server that already supports it natively?</p>
[ { "answer_id": 161476, "author": "Valters Vingolds", "author_id": 885, "author_profile": "https://Stackoverflow.com/users/885", "pm_score": 2, "selected": false, "text": "<p>Yeah, Eclipse Maven2 plugin is crap for now. But I would suggest for you to hang in there, there is a lot of benefit to using Maven2, so it actually balances out.</p>\n\n<p>What we do, is that we use Eclipse to develop and only use Maven to manage dependencies. Everything else is done by running \"mvn\" on command line. We keep tests in their own integration test projects (...-itest) and have continuous integration server to do build in 2 phases, first build the actual code, and second pass build and runs the -itest projects. (First pass (pure build) usually is very quick, and the integration tests build (with running of tests) usually takes quite a while.)</p>\n\n<p>Here's command line to make mvn run tests:\n<code>mvn -o verify -Ditest</code></p>\n\n<p>Of course you need to define 'itest' profile in your parent pom:\nSay, like this:</p>\n\n<pre><code>&lt;profiles&gt;\n &lt;profile&gt;\n &lt;id&gt;integration-test&lt;/id&gt;\n &lt;activation&gt;\n &lt;property&gt;\n &lt;name&gt;itest&lt;/name&gt;\n &lt;/property&gt;\n &lt;/activation&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;itest&lt;/id&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;configuration&gt;\n &lt;testSourceDirectory&gt;src/main&lt;/testSourceDirectory&gt;\n &lt;testClassesDirectory&gt;target/classes&lt;/testClassesDirectory&gt;\n &lt;forkMode&gt;once&lt;/forkMode&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n &lt;/profile&gt;\n&lt;/profiles&gt;\n</code></pre>\n" }, { "answer_id": 184698, "author": "Ian McLaird", "author_id": 18796, "author_profile": "https://Stackoverflow.com/users/18796", "pm_score": 0, "selected": false, "text": "<p>I've had fair success using Eclipse + Ant with CruiseControl. If you want automation, you're probably going to need more than just pure Eclipse.</p>\n\n<p>CruiseControl can automatically check out a copy of your project from source control, build it, run tests, and then update a web application with the results. It was pretty slick last I used it, but that was a long time ago now.</p>\n" }, { "answer_id": 229724, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 3, "selected": true, "text": "<p>I managed find a good solution. I simply got infinitest (can be installed from the Eclipse marketplace) to work when using maven and eclipse</p>\n\n<p>In Eclipse->Project Properties->Java Build Path->Source uncheck the box called: \"Allow output\nfolders for source folders\"</p>\n\n<p>That will enable your project to have more than one output path and Eclipse will then start reporting the test-classes as being part of the class path. Infinitest now finds it and starts running tests!</p>\n\n<p>All I did was use the official Maven Eclipse plugin and add this to my POM</p>\n\n<pre><code>&lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;junit&lt;/groupId&gt;\n &lt;artifactId&gt;junit&lt;/artifactId&gt;\n &lt;version&gt;4.5&lt;/version&gt;\n &lt;!-- &lt;scope&gt;provided&lt;/scope&gt; --&gt;\n &lt;/dependency&gt;\n\n &lt;dependency&gt;\n &lt;groupId&gt;org.infinitest&lt;/groupId&gt;\n &lt;artifactId&gt;infinitest&lt;/artifactId&gt;\n &lt;scope&gt;test&lt;/scope&gt;\n &lt;version&gt;4.0&lt;/version&gt;\n &lt;/dependency&gt;\n\n&lt;/dependencies&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17554/" ]
I've been using maven2 and hudson for a while to do my continuous integration, but I find that Eclipse and Maven do not play well together. Sure there's a plugin, but it's cranky to mash the maven project into something that eclipse likes and the build times and unit test are too long. I'm considering switching back to a pure eclipse project with no ant and no maven involved. With the infinitest plugin and possible the JavaRebel agent, it would give me a very fast build-deploy-test cycle. However I'd still like to have automatic and testing as well, so: How do I use continuous integration with an Eclipse project? Is there a command line way to do it? Is there a build server that already supports it natively?
I managed find a good solution. I simply got infinitest (can be installed from the Eclipse marketplace) to work when using maven and eclipse In Eclipse->Project Properties->Java Build Path->Source uncheck the box called: "Allow output folders for source folders" That will enable your project to have more than one output path and Eclipse will then start reporting the test-classes as being part of the class path. Infinitest now finds it and starts running tests! All I did was use the official Maven Eclipse plugin and add this to my POM ``` <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <!-- <scope>provided</scope> --> </dependency> <dependency> <groupId>org.infinitest</groupId> <artifactId>infinitest</artifactId> <scope>test</scope> <version>4.0</version> </dependency> </dependencies> ```
161,238
<p>As I understand it, the command to ignore the <em>content</em> of a directory using SVN is this:</p> <pre><code>svn propset svn:ignore "*" tmp/ </code></pre> <p>This should set the ignore property on the content of the <code>tmp</code> directory, right? In other words, the wildcard is set to be the ignore value on the tmp directory. Trouble is, here's what is happening on my Windows box:</p> <pre><code>&gt; svn propset svn:ignore "*" ./tmp property 'svn:ignore' set on 'app' property 'svn:ignore' set on 'config' property 'svn:ignore' set on 'db' property 'svn:ignore' set on 'doc' property 'svn:ignore' set on 'lib' property 'svn:ignore' set on 'log' property 'svn:ignore' set on 'nbproject' property 'svn:ignore' set on 'public' [etc...] </code></pre> <p>That's not right. Am I doing something wrong (or perhaps going insane), or is my svn on Windows broken?</p> <p><strong>Some notes:</strong></p> <ul> <li>The machine is running Windows Vista SP1</li> <li>Setting this property via Tortoise works perfectly.</li> <li>I'm using the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">Collabnet binaries for Windows</a>:</li> </ul> <blockquote> <p><code>> svn --version<br /> svn, version 1.5.2 (r32768)<br /> compiled Aug 28 2008, 19:05:34</code></p> </blockquote> <hr> <p><strong><em>Update:</em></strong> I've have just tried this on a Windows XP machine and it works as expected. So either this is a Vista specific issue, or there is a problem with my Vista configuration. Is anyone else able to reproduce this problem on Vista? I have just spotted that Vista isn't listed as one of the supported platforms on the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">CollabNet downloads page</a>.</p>
[ { "answer_id": 161250, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 0, "selected": false, "text": "<p>Try it without the trailing slash. Also, the tmp directory itself has to be added to the repository.</p>\n" }, { "answer_id": 161338, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": true, "text": "<p>The command <strong><em>should</em></strong> be working as you expect.</p>\n\n<p>The <code>*</code> is getting globbed, which it shouldn't be doing. So, you're running:<br>\n<code>svn propset svn:ignore [value] app config db doc lib log nbproject public ... tmp</code><br>\n(since app was the first folder affected, I'm guessing there's another folder before it).</p>\n\n<p>2 things you can try:</p>\n\n<ol>\n<li>Specify a list file: <code>svn propset svn:ignore tmp -F .svnignore</code></li>\n<li>Just specify the path: <code>svn propset svn:ignore tmp</code>. This should open your default text editor (if configured) to allow you to write and save the list.</li>\n</ol>\n\n<hr>\n\n<p><strong>Reply to comment</strong></p>\n\n<p>Since you're now attempting to correct the setting, <code>propedit</code> and <code>propdel</code> would work fine -- especially if you have other changes within the directory.</p>\n\n<p>But, if you don't have any other changes to worry about (check <code>svn st</code>), it'll be faster using <code>svn revert -R</code> and <code>svn propset</code>.</p>\n" }, { "answer_id": 161357, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 2, "selected": false, "text": "<p>This doesn't answer your svn question, but why are you trying to ignore all the contents of a directory? It seems to me that if you want a temporary directory at some point in the build, you should make the directory as part of the build instead of it being there from the repo.</p>\n\n<p>Are you trying to ignore it because it's already there and you can't delete it?</p>\n\n<p>Anyway, from my unix command line, this worked for me to ignore untracked file in a diretory called tmp</p>\n\n<pre>\n$ svn --version\nsvn, version 1.5.1 (r32289)\n compiled Aug 28 2008, 10:00:12\n\n$ svn propset svn:ignore '*' tmp\n</pre>\n\n<p>Is Windows horking your quoting?</p>\n" }, { "answer_id": 161380, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>It sounds to me like the svn.exe binary compiled for windows is doing built-in globbing, which is something that it wouldn't normally do on a unix build because the unix shell is expected to do globbing while constructing the command line. I would consider that unexpected behaviour, especially since you can't seem to work around the globbing.</p>\n\n<p>As others have pointed out, you can supply the <code>*</code> using the <code>-F</code> option or interactively in a text editor.</p>\n\n<p>However, I think you may not be going about this in the easiest way. For ignoring an entire subdirectory, I would do something like this:</p>\n\n<pre><code>svn propset svn:ignore tmp .\n</code></pre>\n\n<p>This sets the <code>svn:ignore</code> property on <code>.</code> (the current directory, the parent of <code>tmp/</code>) that tells it to ignore the <code>tmp</code> subdirectory and everything underneath it.</p>\n" }, { "answer_id": 161387, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Which version of subversion are you using?</p>\n\n<p>I tried 1.5.2 on Windows, and it only changed the property on the tmp directory:</p>\n\n<pre><code>[C:\\Temp\\temp] :svn propset svn:ignore \"*\" tmp/\nproperty 'svn:ignore' set on 'tmp'\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>[C:\\Temp\\temp] :svn proplist *\nsvn: Skipping argument: '.svn' ends in a reserved name\nProperties on 'tmp':\n svn:ignore\n</code></pre>\n" }, { "answer_id": 162162, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 3, "selected": false, "text": "<p>It looks like Microsoft, in their infinite wisdom, have <a href=\"https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1917798&amp;SiteID=1\" rel=\"noreferrer\">changed the behavior of wildcard expansion in Windows Vista</a>:</p>\n\n<p>So instead of an escaped wildcard being passed in, it gets expanded:</p>\n\n<blockquote>\n <p>Under Win 95, 98, 2000, XP, the application runs as expected: it does wildcard expansion when parameters are like «*.txt» and it does NOT when parameters are like «\"*.txt\"». Under Windows Vista, wildcard expansion takes place always, or, said otherwise, double quotation marks DOES NOT suppress it.</p>\n</blockquote>\n\n<p>There is further discussion on this issue on the <strong><a href=\"http://subversion.open.collab.net/ds/viewMessage.do?dsForumId=4&amp;viewType=browseAll&amp;dsMessageId=115201#messagefocus\" rel=\"noreferrer\">Collabnet forum</a></strong>.</p>\n" }, { "answer_id": 435168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's reasonable to use a GUI SVN client (unless you're a masochist!). If you're on Windows TortoiseSVN should be you first port of call. Right click on the file you want to ignore then click \"TortoiseSVN -> Properties\". In the properties dialog you can ignore the entire directory by clicking on the drop down arrow for \"Name\" and selecting \"svn:ignore\". Then in the values box just type \"*\" for all. This is all without the quotes of course.</p>\n" }, { "answer_id": 2638621, "author": "Alexander Klimetschek", "author_id": 2709, "author_profile": "https://Stackoverflow.com/users/2709", "pm_score": 1, "selected": false, "text": "<p>For a one-liner to use in shell scripts using the \"-F\" alternative, simply try this:</p>\n\n<pre><code>echo \"*\" &gt; .svnignore &amp;&amp; svn propset svn:ignore &lt;path&gt; -F .svnignore &amp;&amp; rm .svnignore\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
As I understand it, the command to ignore the *content* of a directory using SVN is this: ``` svn propset svn:ignore "*" tmp/ ``` This should set the ignore property on the content of the `tmp` directory, right? In other words, the wildcard is set to be the ignore value on the tmp directory. Trouble is, here's what is happening on my Windows box: ``` > svn propset svn:ignore "*" ./tmp property 'svn:ignore' set on 'app' property 'svn:ignore' set on 'config' property 'svn:ignore' set on 'db' property 'svn:ignore' set on 'doc' property 'svn:ignore' set on 'lib' property 'svn:ignore' set on 'log' property 'svn:ignore' set on 'nbproject' property 'svn:ignore' set on 'public' [etc...] ``` That's not right. Am I doing something wrong (or perhaps going insane), or is my svn on Windows broken? **Some notes:** * The machine is running Windows Vista SP1 * Setting this property via Tortoise works perfectly. * I'm using the [Collabnet binaries for Windows](http://www.collab.net/downloads/subversion/): > > `> svn --version > > svn, version 1.5.2 (r32768) > > compiled Aug 28 2008, 19:05:34` > > > --- ***Update:*** I've have just tried this on a Windows XP machine and it works as expected. So either this is a Vista specific issue, or there is a problem with my Vista configuration. Is anyone else able to reproduce this problem on Vista? I have just spotted that Vista isn't listed as one of the supported platforms on the [CollabNet downloads page](http://www.collab.net/downloads/subversion/).
The command ***should*** be working as you expect. The `*` is getting globbed, which it shouldn't be doing. So, you're running: `svn propset svn:ignore [value] app config db doc lib log nbproject public ... tmp` (since app was the first folder affected, I'm guessing there's another folder before it). 2 things you can try: 1. Specify a list file: `svn propset svn:ignore tmp -F .svnignore` 2. Just specify the path: `svn propset svn:ignore tmp`. This should open your default text editor (if configured) to allow you to write and save the list. --- **Reply to comment** Since you're now attempting to correct the setting, `propedit` and `propdel` would work fine -- especially if you have other changes within the directory. But, if you don't have any other changes to worry about (check `svn st`), it'll be faster using `svn revert -R` and `svn propset`.
161,252
<p>I'm trying to run some commands in paralel, in background, using bash. Here's what I'm trying to do:</p> <pre><code>forloop { //this part is actually written in perl //call command sequence print `touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;`; } </code></pre> <p>The part between backticks (``) spawns a new shell and executes the commands in succession. The thing is, control to the original program returns only after the last command has been executed. I would like to execute the whole statement in background (I'm not expecting any output/return values) and I would like the loop to continue running.</p> <p>The calling program (the one that has the loop) would not end until all the spawned shells finish.</p> <p>I could use threads in perl to spawn different threads which call different shells, but it seems an overkill...</p> <p>Can I start a shell, give it a set of commands and tell it to go to the background?</p>
[ { "answer_id": 161284, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 4, "selected": false, "text": "<pre><code>for command in $commands\ndo\n \"$command\" &amp;\ndone\nwait\n</code></pre>\n\n<p>The ampersand at the end of the command runs it in the background, and the <code>wait</code> waits until the background task is completed.</p>\n" }, { "answer_id": 161291, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 1, "selected": false, "text": "<p>Try to put commands in curly braces with &amp;s, like this:</p>\n\n<pre><code>{command1 &amp; ; command2 &amp; ; command3 &amp; ; }\n</code></pre>\n\n<p>This does not create a sub-shell, but executes the group of commands in the background. </p>\n\n<p>HTH</p>\n" }, { "answer_id": 161333, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 6, "selected": true, "text": "<p>I haven't tested this but how about</p>\n\n<pre><code>print `(touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;) &amp;`;\n</code></pre>\n\n<p>The parentheses mean execute in a subshell but that shouldn't hurt.</p>\n" }, { "answer_id": 161383, "author": "Mad_Ady", "author_id": 23780, "author_profile": "https://Stackoverflow.com/users/23780", "pm_score": 4, "selected": false, "text": "<p>Thanks Hugh, that did it:</p>\n\n<pre><code>adrianp@frost:~$ (echo \"started\"; sleep 15; echo \"stopped\")\nstarted\nstopped\nadrianp@frost:~$ (echo \"started\"; sleep 15; echo \"stopped\") &amp;\nstarted\n[1] 7101\nadrianp@frost:~$ stopped\n\n[1]+ Done ( echo \"started\"; sleep 15; echo \"stopped\" )\nadrianp@frost:~$ \n</code></pre>\n\n<p>The other ideas don't work because they start each command in the background, and not the command sequence (which is important in my case!).</p>\n\n<p>Thank you again!</p>\n" }, { "answer_id": 169022, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "<p>I don't know why nobody replied with the proper solution:</p>\n\n<pre><code>my @children;\nfor (...) {\n ...\n my $child = fork;\n exec \"touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;\" if $child == 0;\n push @children, $child;\n}\n# and if you want to wait for them to finish,\nwaitpid($_) for @children;\n</code></pre>\n\n<p>This causes Perl to spawn children to run each command, and allows you to wait for all the children to complete before proceeding.</p>\n\n<p>By the way,</p>\n\n<pre><code>print `some command`\n</code></pre>\n\n<p>and</p>\n\n<pre><code>system \"some command\"\n</code></pre>\n\n<p>output the same contents to stdout, but the first has a higher overhead, as Perl has to capture all of \"<code>some command</code>\"'s output</p>\n" }, { "answer_id": 1683256, "author": "NVRAM", "author_id": 57582, "author_profile": "https://Stackoverflow.com/users/57582", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/161252/bash-start-multiple-chained-commands-in-background/161284#161284\">GavinCattell</a> got the closest (for bash, IMO), but as Mad_Ady pointed out, it would not handle the \"lock\" files. This should: </p>\n\n<p>If there are other jobs pending, the <strong>wait</strong> will wait for those, too. If you need to wait for <em>only</em> the copies, you can accumulate those PIDs and wait for only those. If not, you could delete the 3 lines with \"pids\" but it's more general.</p>\n\n<p>In addition, I added checking to avoid the copy altogether:</p>\n\n<pre><code>pids=\nfor file in bigfile*\ndo\n # Skip if file is not newer...\n targ=/destination/$(basename \"${file}\")\n [ \"$targ\" -nt \"$file\" ] &amp;&amp; continue\n\n # Use a lock file: \".fileN.lock\" for each \"bigfileN\"\n lock=\".${file##*/big}.lock\"\n ( touch $lock; cp \"$file\" \"$targ\"; rm $lock ) &amp;\n pids=\"$pids $!\"\ndone\nwait $pids\n</code></pre>\n\n<p>Incidentally, it looks like you're copying new files to an FTP repository (or similar). If so, you <em>could</em> consider a copy/rename strategy instead of the lock files (but that's another topic).</p>\n" }, { "answer_id": 12404603, "author": "Eliseo Carrasco", "author_id": 1668355, "author_profile": "https://Stackoverflow.com/users/1668355", "pm_score": 2, "selected": false, "text": "<p>Run the command by using an at job:</p>\n\n<pre><code># date\n# jue sep 13 12:43:21 CEST 2012\n# at 12:45\nwarning: commands will be executed using /bin/sh\nat&gt; command1\nat&gt; command2\nat&gt; ...\nat&gt; CTRL-d\nat&gt; &lt;EOT&gt;\njob 20 at Thu Sep 13 12:45:00 2012\n</code></pre>\n\n<p>The result will be sent to your account by mail.</p>\n" }, { "answer_id": 14536754, "author": "slm", "author_id": 33204, "author_profile": "https://Stackoverflow.com/users/33204", "pm_score": 2, "selected": false, "text": "<p>The facility in bash that you're looking for is called <code>Compound Commands</code>. See the man page for more info:</p>\n\n<blockquote>\n <p>Compound Commands\n A compound command is one of the following:</p>\n\n<pre><code> (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and\n builtin commands that affect the shell's environment do not remain in effect after the command completes. The\n return status is the exit status of list.\n\n { list; }\n list is simply executed in the current shell environment. list must be terminated with a newline or semicolon.\n This is known as a group command. The return status is the exit status of list. Note that unlike the metacharac‐\n ters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized.\n Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharac‐\n ter.\n</code></pre>\n</blockquote>\n\n<p>There are others, but these are probably the 2 most common types. The first, the parens, will run a list of command in series in a subshell, while the second, the curly braces, will a list of commands in series in the current shell.</p>\n\n<h3>parens</h3>\n\n<pre><code>% ( date; sleep 5; date; )\nSat Jan 26 06:52:46 EST 2013\nSat Jan 26 06:52:51 EST 2013\n</code></pre>\n\n<h3>curly braces</h3>\n\n<pre><code>% { date; sleep 5; date; }\nSat Jan 26 06:52:13 EST 2013\nSat Jan 26 06:52:18 EST 2013\n</code></pre>\n" }, { "answer_id": 19029366, "author": "lechup", "author_id": 479931, "author_profile": "https://Stackoverflow.com/users/479931", "pm_score": 5, "selected": false, "text": "<p>Another way is to use the following syntax:</p>\n\n<pre><code>{ command1; command2; command3; } &amp;\nwait\n</code></pre>\n\n<p>Note that the <code>&amp;</code> goes at the end of the command group, not after each command. The semicolon after the final command is necessary, as are the space after the first bracket and before the final bracket. The <code>wait</code> at the end ensures that the parent process is not killed before the spawned child process (the command group) ends.</p>\n\n<p>You can also do fancy stuff like redirecting <code>stderr</code> and <code>stdout</code>:</p>\n\n<pre><code>{ command1; command2; command3; } 2&gt;&amp;2 1&gt;&amp;1 &amp;\n</code></pre>\n\n<p>Your example would look like:</p>\n\n<pre><code>forloop() {\n { touch .file1.lock; cp bigfile1 /destination; rm .file1.lock; } &amp;\n}\n# ... do some other concurrent stuff\nwait # wait for childs to end\n</code></pre>\n" }, { "answer_id": 22948867, "author": "RAKK", "author_id": 2796088, "author_profile": "https://Stackoverflow.com/users/2796088", "pm_score": 2, "selected": false, "text": "<p>I stumbled upon this thread here and decided to put together a code snippet to spawn chained statements as background jobs. I tested this on BASH for Linux, KSH for IBM AIX and Busybox's ASH for Android, so I think it's safe to say it works on <em>any</em> Bourne-like shell.</p>\n\n<pre><code>processes=0;\nfor X in `seq 0 10`; do\n let processes+=1;\n { { echo Job $processes; sleep 3; echo End of job $processes; } &amp; };\n if [[ $processes -eq 5 ]]; then\n wait;\n processes=0;\n fi;\ndone;\n</code></pre>\n\n<p>This code runs a number of background jobs up to a certain limit of concurrent jobs. You can use this, for example, to recompress a lot of gzipped files with <code>xz</code> without having a huge bunch of <code>xz</code> processes eat your entire memory and make your computer throw up: in this case, you use <code>*</code> as the <code>for</code>'s list and the batch job would be <code>gzip -cd \"$X\" | xz -9c &gt; \"${X%.gz}.xz\"</code>.</p>\n" }, { "answer_id": 26588961, "author": "Anastasios Andronidis", "author_id": 1067688, "author_profile": "https://Stackoverflow.com/users/1067688", "pm_score": 0, "selected": false, "text": "<p>Just in case that someone is still interested, you can do it without calling a subshell like this:</p>\n\n<pre><code>print `touch .file1.lock &amp;&amp; cp bigfile1 /destination &amp;&amp; rm .file1.lock &amp;`;\n</code></pre>\n" }, { "answer_id": 26685801, "author": "Nikolas Britton", "author_id": 4204519, "author_profile": "https://Stackoverflow.com/users/4204519", "pm_score": 1, "selected": false, "text": "<p>Forking in a for loop:</p>\n\n<p><code>for i in x; do ((a; b; c;)&amp;); done</code></p>\n\n<p>Example:</p>\n\n<p><code>for i in 500 300 100; do ((printf \"Start $i: \"; date; dd if=/dev/zero of=testfile_$i bs=1m count=$i 2&gt;/dev/null; printf \"End $i: \"; date;)&amp;) &amp;&amp; sleep 1; done</code></p>\n" }, { "answer_id": 26687080, "author": "Kannan Mohan", "author_id": 1198887, "author_profile": "https://Stackoverflow.com/users/1198887", "pm_score": 0, "selected": false, "text": "<p>You can use GNU <code>parallel</code> command to run jobs in parallel. It is more safe are faster. </p>\n\n<p>My guess is that you are trying to copy multiple large files from source to destination. And for that you can do that in parallel with below statement.</p>\n\n<pre><code>$ ls *|parallel -kj0 --eta 'cp {} /tmp/destination'\n</code></pre>\n\n<p>As we have used <code>-j0</code> option, all the files will be copied in parallel. In case if you need to reduce the number of parallel process then you can use <code>-j&lt;n&gt;</code> where <code>&lt;n&gt;</code> is the number of parallel process to be executed.</p>\n\n<p>Parallel will also collect the output of the process and report it in a sequential manner (with <code>-k</code> option) which other job control mechanism cannot do.</p>\n\n<p><code>--eta</code> option will give you a details statistics of the process that is going on. So we can know how may of the process have been completed and how long will it take to get finished.</p>\n" }, { "answer_id": 40691679, "author": "Radu Simionescu", "author_id": 517450, "author_profile": "https://Stackoverflow.com/users/517450", "pm_score": 2, "selected": false, "text": "<p>run the commands in a subshell:</p>\n\n<pre><code>(command1 ; command2 ; command3) &amp;\n</code></pre>\n" }, { "answer_id": 56963954, "author": "Rounak Datta", "author_id": 8303407, "author_profile": "https://Stackoverflow.com/users/8303407", "pm_score": 0, "selected": false, "text": "<p>You can pass parameters to a command group (having sequential commands) and run them in background.</p>\n\n<pre><code>for hrNum in {00..11};\ndo\n oneHour=$((10#$hrNum + 0))\n secondHour=$((10#$hrNum + 12))\n { echo \"$oneHour\"; echo \"$secondHour\"; } &amp;\n wait\ndone\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23780/" ]
I'm trying to run some commands in paralel, in background, using bash. Here's what I'm trying to do: ``` forloop { //this part is actually written in perl //call command sequence print `touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;`; } ``` The part between backticks (``) spawns a new shell and executes the commands in succession. The thing is, control to the original program returns only after the last command has been executed. I would like to execute the whole statement in background (I'm not expecting any output/return values) and I would like the loop to continue running. The calling program (the one that has the loop) would not end until all the spawned shells finish. I could use threads in perl to spawn different threads which call different shells, but it seems an overkill... Can I start a shell, give it a set of commands and tell it to go to the background?
I haven't tested this but how about ``` print `(touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;) &`; ``` The parentheses mean execute in a subshell but that shouldn't hurt.
161,348
<p>Given the following:</p> <pre><code>#light //any function returning bool * 'a let foo = let x = ref 10 fun () -&gt; x := !x - 1 if !x &lt;&gt; 0 then (true, x) else (false, x) while let (c,x) = foo() in c do print_any x;//can't access x, but would be convinent. //this is how I want it to work, without all the typing let rec loop f = match f() with | (true, x) -&gt; print_any x loop f | (false, _) -&gt; () loop foo </code></pre> <p>How should I go about solving this? Or should I just go through the hassle to convert "foo" to a sequence expression?</p>
[ { "answer_id": 161344, "author": "MrValdez", "author_id": 1599, "author_profile": "https://Stackoverflow.com/users/1599", "pm_score": 4, "selected": true, "text": "<p>I found a library in google code: <a href=\"http://code.google.com/p/php-email-address-validation/\" rel=\"noreferrer\">http://code.google.com/p/php-email-address-validation/</a></p>\n\n<p>Are there any others?</p>\n" }, { "answer_id": 161362, "author": "Chris", "author_id": 4742, "author_profile": "https://Stackoverflow.com/users/4742", "pm_score": 4, "selected": false, "text": "<p>Have you looked at <a href=\"http://us2.php.net/manual/en/function.filter-var.php\" rel=\"noreferrer\">PHP's filter_ functions</a>? They're not perfect, but they do a fairly decent job in my experience. </p>\n\n<p>Example usage (returns boolean):</p>\n\n<p><code>filter_var($someEmail, FILTER_VALIDATE_EMAIL);</code></p>\n" }, { "answer_id": 161582, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "<p>AFAIK, the only good way to validate an e-mail is to to send an e-mail and see if user goes back to the site using a link in this e-mail. That's what lot of sites do.</p>\n\n<p>As you point out with the link to the well known mammoth regex, validating all forms of e-mail address is hard, near to impossible. It is so easy to do it wrong, even for trivial style e-mails (I found too many sites rejecting caps in e-mail addresses! And most old regexes reject TLDs of more than 4 letters!).</p>\n\n<p>AFAIK, \"Jean-Luc B. O'Grady\"@example.com and e=m.c^2@[82.128.45.117] are both valid addresses... While [email protected] is likely to be invalid.</p>\n\n<p>So somehow, I would just check that we have something, a unique @, something else, and go with it: it would catch most user errors (like empty field or user name instead of e-mail address).<br>\nIf user wants to give a fake address, it would just give something random looking correct ([email protected] or [email protected]). And no validator will catch typos ([email protected] instead of [email protected]).</p>\n\n<p>If one really want to validate e-mails against full RFC, I would advise to use regexes to split around @, then check separately local name and domain name. Separate case of local name starting with \" from other cases, etc. Separate case of domain name starting with [ from other cases, etc. Split problem in smaller specific domains, and use regexes only on a well defined, simpler cases.<br>\nThis advice can be applied to lot of regex uses, of course...</p>\n" }, { "answer_id": 161742, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.email_address\" rel=\"nofollow noreferrer\">Zend_Validate</a> includes an email validator.</p>\n\n<p>There are plenty of regular expressions around for validating - everything from very basic to very advanced.\nYou really should pick something that matches the importance of a valid email in your application.</p>\n" }, { "answer_id": 161909, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 0, "selected": false, "text": "<p>I'd recommend to look at the source code of Zend_Validate_EmailAddress [<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/EmailAddress.php\" rel=\"nofollow noreferrer\">source</a>].</p>\n<p>Once you have your dependencies fixed, you can simply do the following:</p>\n<pre><code>$mail_validator = new Zend_Validate_EmailAddress();\n$mail_validator-&gt;isValid($address); // returns true or false\n</code></pre>\n<p>The best would be to get the full Zend Library into your project via <code>svn external</code> and point the include path to it...</p>\n<p>But you can just download the necessary files (<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/EmailAddress.php\" rel=\"nofollow noreferrer\">1</a>,<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Abstract.php\" rel=\"nofollow noreferrer\">2</a>,<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Ip.php\" rel=\"nofollow noreferrer\">3</a>,<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Interface.php\" rel=\"nofollow noreferrer\">4</a>,<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Hostname.php\" rel=\"nofollow noreferrer\">5</a>,<a href=\"http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Loader.php\" rel=\"nofollow noreferrer\">6</a>), and include them all (remove the <em>require_once</em> calls).</p>\n" }, { "answer_id": 167739, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.iamcal.com/\" rel=\"nofollow noreferrer\">Cal Henderson</a> (of Flickr) wrote an <a href=\"http://www.iamcal.com/publish/articles/php/parsing_email\" rel=\"nofollow noreferrer\">RFC822 compliant email address matcher</a>, with an explanation of the RFC and code utilizing the RFC to match email addresses. I've been using it for quite some time now with no complaints.</p>\n\n<blockquote>\n <p>RFC822 (published in 1982) defines,\n amongst other things, the format for\n internet text message (email)\n addresses. You can find the RFC's by\n googling - there's many many copies of\n them online. They're a little terse\n and weirdly formatted, but with a\n little effort we can seewhat they're\n getting at.</p>\n</blockquote>\n\n<p>... Update ...</p>\n\n<p>As <a href=\"https://stackoverflow.com/users/10311/porges\">Porges</a> pointed out in the comments, the library on the link is outdated, but that page has a link to an <a href=\"http://code.iamcal.com/php/rfc822/\" rel=\"nofollow noreferrer\">updated version</a>.</p>\n" }, { "answer_id": 532965, "author": "Dominic Sayers", "author_id": 63349, "author_profile": "https://Stackoverflow.com/users/63349", "pm_score": 3, "selected": false, "text": "<p>[UPDATED] I've collated everything I know about email address validation here: <a href=\"http://isemail.info\" rel=\"nofollow noreferrer\">http://isemail.info</a>, which now not only validates but also diagnoses problems with email addresses. I agree with many of the comments here that validation is only part of the answer; see my essay at <a href=\"http://isemail.info\" rel=\"nofollow noreferrer\">http://isemail.info/about</a>.</p>\n\n<p>I've now collated test cases from Cal Henderson, Dave Child, Phil Haack, Doug Lovell and RFC 3696. 158 test addresses in all.</p>\n\n<p>I ran all these tests against all the validators I could find. The comparison is here: <a href=\"http://www.dominicsayers.com/isemail\" rel=\"nofollow noreferrer\">http://www.dominicsayers.com/isemail</a></p>\n\n<p>I'll try to keep this page up-to-date as people enhance their validators. Thanks to Cal, Dave and Phil for their help and co-operation in compiling these tests and constructive criticism of <a href=\"http://code.google.com/p/isemail/source/browse/trunk/is_email.php\" rel=\"nofollow noreferrer\">my own validator</a>.</p>\n\n<p>People should be aware of the <a href=\"http://www.rfc-editor.org/errata_search.php?rfc=3696\" rel=\"nofollow noreferrer\">errata against RFC 3696</a> in particular. Three of the canonical examples are in fact invalid addresses. And the maximum length of an address is 254 or 256 characters, <strong>not</strong> 320.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21182/" ]
Given the following: ``` #light //any function returning bool * 'a let foo = let x = ref 10 fun () -> x := !x - 1 if !x <> 0 then (true, x) else (false, x) while let (c,x) = foo() in c do print_any x;//can't access x, but would be convinent. //this is how I want it to work, without all the typing let rec loop f = match f() with | (true, x) -> print_any x loop f | (false, _) -> () loop foo ``` How should I go about solving this? Or should I just go through the hassle to convert "foo" to a sequence expression?
I found a library in google code: <http://code.google.com/p/php-email-address-validation/> Are there any others?
161,388
<p>I'm using @media print in my external css file to hide menus etc. However while printing the little triangle of a dropdownlist still shows. Is there a css setting available to hide it as well and only print the selected item?</p>
[ { "answer_id": 161414, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 1, "selected": false, "text": "<p>No, there isn't. Besides, every browser displays its dropdowns in its own way, some use system widgets, some have their own. In Safari, for example, no matter what styling you remove, it still has a box (well, sort of) around the whole of it.\nIf you don't want to change your HTML code, perhaps a bit of javascript might do it - get the selected value and exchange the dropdown for a paragraph.</p>\n" }, { "answer_id": 161468, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>I would tentatively say you cannot, because it is a monolithic component: you cannot change it in the same way you cannot change the look of scrollbars, for example.</p>\n\n<p>I didn't chose my example at random: of course, in some browsers (IE at least), you can change the latter. But using some browser-specific CSS, which isn't very practical, unless you are targeting captive intranet application...</p>\n\n<p>Too bad, it is indeed a good idea to hide this part.</p>\n\n<p>[Update] There might be a way, although semantically-wise it is a bit ugly... Whatever. </p>\n\n<pre><code>&lt;select name=\"Snakes\" style=\"width: 200px;\"&gt;\n &lt;option value=\"A\"&gt;Anaconda&lt;/option&gt;\n &lt;option value=\"B\"&gt;Boa&lt;/option&gt;\n &lt;option value=\"C\"&gt;Cobra&lt;/option&gt;\n &lt;option selected=\"\" value=\"P\"&gt;Python&lt;/option&gt;\n &lt;option value=\"V\"&gt;Viper&lt;/option&gt;\n&lt;/select&gt;\n&lt;!-- Put this style in a class, of course --&gt;\n&lt;div style=\"background-color: white; \n min-width: 20px; max-width: 20px; position: relative; \n right: -180px; top: -19px;\"&gt;&amp;Nbsp;&lt;/div&gt;\n</code></pre>\n\n<p>Of course, the div must be hidden in screen media and get the above style in print media.<br>\nWorks decently in FF3, Opera 9.5 and even IE7 (not IE6) on WinXP. Alas, I fear the above hack is system dependent and might be broken in other browsers.</p>\n\n<p>PS.: I wrote Nbsp because syntax highlighting hides it otherwise... :-P</p>\n" }, { "answer_id": 166810, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 1, "selected": false, "text": "<p>As most people have said, the rendering style of form widgets is left pretty much up to the browser. You can style them a bit, but fundamental changes to them are unreliable at best.</p>\n\n<p>As another commenter mentioned, you'd be best using a bit of javascript to achieve this effect. I've given a bit of jQuery that will do this. It's not ideal though - it relies on the user clicking the \"Print this page\" links, and not using the browser's own Print functions.</p>\n\n<p>For the following markup:</p>\n\n<pre><code> &lt;p&gt;&lt;a class=\"print\" href=\"#\"&gt;print this&lt;/a&gt;&lt;/p&gt;\n &lt;form action=\"/my/action/\" method=\"POST\"&gt;\n &lt;select id=\"mySelect\"&gt;\n &lt;option value=\"1\"&gt;An Option&lt;/option&gt;\n &lt;option value=\"2\" selected=\"selected\"&gt;Another Option&lt;/option&gt;\n &lt;/select&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>This jQuery will append a paragraph containing the content of the currently selected item from the drop-down, and hide the form element before printing the page.</p>\n\n<pre><code> $(document).ready(function() {\n $('a.print').click(function() {\n var selected = $('#mySelect option:selected').text();\n $('#mySelect').after('&lt;p class=\"replacement\"&gt;' + selected + '&lt;/p&gt;');\n $('#mySelect').hide();\n window.print();\n });\n });\n</code></pre>\n" }, { "answer_id": 279363, "author": "Jacob Adams", "author_id": 32518, "author_profile": "https://Stackoverflow.com/users/32518", "pm_score": 0, "selected": false, "text": "<p>This worked for me in IE6. I didn't try other browsers</p>\n\n<p><a href=\"http://weblogs.asp.net/bleroy/archive/2005/08/09/how-to-put-a-div-over-a-select-in-ie.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/bleroy/archive/2005/08/09/how-to-put-a-div-over-a-select-in-ie.aspx</a></p>\n" }, { "answer_id": 10607347, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 3, "selected": false, "text": "<p>This works in Chrome and Firefox (others may work also)</p>\n\n<pre><code>-moz-appearance: none;\n-webkit-appearance: none;\nappearance: none;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using @media print in my external css file to hide menus etc. However while printing the little triangle of a dropdownlist still shows. Is there a css setting available to hide it as well and only print the selected item?
This works in Chrome and Firefox (others may work also) ``` -moz-appearance: none; -webkit-appearance: none; appearance: none; ```
161,398
<p>I'm possibly just stupid, but I'm trying to find a user in Active Directory from C#, using the Login name ("domain\user").</p> <p>My "Skeleton" AD Search Functionality looks like this usually:</p> <pre><code>de = new DirectoryEntry(string.Format("LDAP://{0}", ADSearchBase), null, null, AuthenticationTypes.Secure); ds = new DirectorySearcher(de); ds.SearchScope = SearchScope.Subtree; ds.PropertiesToLoad.Add("directReports"); ds.PageSize = 10; ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2); SearchResult sr = ds.FindOne(); </code></pre> <p>Now, that works if I have the full DN of the user (ADSearchBase usually points to the "Our Users" OU in Active Directory), but I simply have no idea how to look for a user based on the "domain\user" syntax.</p> <p>Any Pointers?</p>
[ { "answer_id": 161719, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": true, "text": "<p>You need to set a filter (DirectorySearcher.Filter) something like:</p>\n\n<p>\"(&amp;(objectCategory=person)(objectClass=user)(sAMAccountName={0}))\"</p>\n\n<p>Note that you only specify the username (without the domain) for the property sAMAccountName. To search for domain\\user, first locate the naming context for the required domain, then search there for sAMAccountName. </p>\n\n<p>By the way, when building LDAP query strings using String.Format, you should generally be careful to escape any special characters. It probably isn't necessary for an account name, but could be if you're searching by other properties such as the user's first (givenName property) or last (sn property) name. I have a utility method EscapeFilterLiteral to do this: you build your string like this:</p>\n\n<pre><code>String.Format(\"(&amp;(objectCategory=person)(objectClass=user)(sn={0}))\", \n EscapeFilterLiteral(lastName, false)); \n</code></pre>\n\n<p>where EscapeFilterLiteral is implemented as follows:</p>\n\n<pre><code>public static string EscapeFilterLiteral(string literal, bool escapeWildcards)\n{\n if (literal == null) throw new ArgumentNullException(\"literal\");\n\n literal = literal.Replace(\"\\\\\", \"\\\\5c\");\n literal = literal.Replace(\"(\", \"\\\\28\");\n literal = literal.Replace(\")\", \"\\\\29\");\n literal = literal.Replace(\"\\0\", \"\\\\00\");\n literal = literal.Replace(\"/\", \"\\\\2f\");\n if (escapeWildcards) literal = literal.Replace(\"*\", \"\\\\2a\");\n return literal;\n}\n</code></pre>\n\n<p>This implementation allows you treat the * character as part of the literal (escapeWildcard = true) or as a wildcard character (escapeWildcard = false).</p>\n\n<p>UPDATE: This is nothing to do with your question, but the example you posted does not call Dispose on the disposable objects it uses. Like all disposable objects these objects (DirectoryEntry, DirectorySearcher, SearchResultCollection) should always be disposed, normally with the using statement. See <a href=\"https://stackoverflow.com/questions/90652/can-i-get-more-than-1000-records-from-a-directorysearcher-in-aspnet#90668\">this post</a> for more info.</p>\n" }, { "answer_id": 161900, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p>Thanks. I figured that i can get the Domain (at least in my AD) through specifying \"LDAP://{0}.somedomain.com/DC={0},DC=somedomain,DC=com\", replacing {0} with the domain, which works in our my environment at least.</p>\n\n<p>One question though: sAMAccountName seems depreciated: <a href=\"http://msdn.microsoft.com/en-us/library/ms679635%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">The logon name used to support clients and servers running older versions of the operating system, such as Windows NT 4.0, Windows 95, Windows 98, and LAN Manager. This attribute must be less than 20 characters to support older clients.</a></p>\n\n<p>Is this still the best approach to it? Or is there a more \"modern\" field to query? (Windows 2003 Active Directory, Windows XP or 2003 Clients, .net 3.0)</p>\n\n<p><strong>Edit:</strong> Thanks again. Our structure is a bit complicated: we have a big \"domain.com\" forest, with several domains for regional offices. Essentially: The Login is \"something\\username\", the full domain us something.domain.com and the mail is [email protected] (without the something), but the principal name is [email protected]. I will manually \"translate\" something\\username to [email protected], as this seems to be the most robust way. Especially since I want to keep the Auto-Discovery feature in.</p>\n" }, { "answer_id": 18216100, "author": "Kevin M", "author_id": 1838481, "author_profile": "https://Stackoverflow.com/users/1838481", "pm_score": -1, "selected": false, "text": "<p>Logon Name(Pre-Windows 2000)</p>\n\n<pre><code>\"(&amp;(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=John))\"\n</code></pre>\n\n<p>Logon Name(Windows 2000 and above)</p>\n\n<pre><code>\"(&amp;(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userPrincipalName=John))\"\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I'm possibly just stupid, but I'm trying to find a user in Active Directory from C#, using the Login name ("domain\user"). My "Skeleton" AD Search Functionality looks like this usually: ``` de = new DirectoryEntry(string.Format("LDAP://{0}", ADSearchBase), null, null, AuthenticationTypes.Secure); ds = new DirectorySearcher(de); ds.SearchScope = SearchScope.Subtree; ds.PropertiesToLoad.Add("directReports"); ds.PageSize = 10; ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2); SearchResult sr = ds.FindOne(); ``` Now, that works if I have the full DN of the user (ADSearchBase usually points to the "Our Users" OU in Active Directory), but I simply have no idea how to look for a user based on the "domain\user" syntax. Any Pointers?
You need to set a filter (DirectorySearcher.Filter) something like: "(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))" Note that you only specify the username (without the domain) for the property sAMAccountName. To search for domain\user, first locate the naming context for the required domain, then search there for sAMAccountName. By the way, when building LDAP query strings using String.Format, you should generally be careful to escape any special characters. It probably isn't necessary for an account name, but could be if you're searching by other properties such as the user's first (givenName property) or last (sn property) name. I have a utility method EscapeFilterLiteral to do this: you build your string like this: ``` String.Format("(&(objectCategory=person)(objectClass=user)(sn={0}))", EscapeFilterLiteral(lastName, false)); ``` where EscapeFilterLiteral is implemented as follows: ``` public static string EscapeFilterLiteral(string literal, bool escapeWildcards) { if (literal == null) throw new ArgumentNullException("literal"); literal = literal.Replace("\\", "\\5c"); literal = literal.Replace("(", "\\28"); literal = literal.Replace(")", "\\29"); literal = literal.Replace("\0", "\\00"); literal = literal.Replace("/", "\\2f"); if (escapeWildcards) literal = literal.Replace("*", "\\2a"); return literal; } ``` This implementation allows you treat the \* character as part of the literal (escapeWildcard = true) or as a wildcard character (escapeWildcard = false). UPDATE: This is nothing to do with your question, but the example you posted does not call Dispose on the disposable objects it uses. Like all disposable objects these objects (DirectoryEntry, DirectorySearcher, SearchResultCollection) should always be disposed, normally with the using statement. See [this post](https://stackoverflow.com/questions/90652/can-i-get-more-than-1000-records-from-a-directorysearcher-in-aspnet#90668) for more info.
161,399
<p>I have a control where I have to check in which page I am, so I can set a certain variable accordingly.</p> <pre><code>string pageName = this.Page.ToString(); switch (pageName) { case "ASP.foo_bar_aspx": doSomething(); break; default: doSomethingElse(); break; } </code></pre> <p>this works fine locally and on some developmentservers, however when I put it live, It stopped working because I don't get <code>ASP.foo_bar_aspx</code> but <code>_ASP.foo_bar_aspx</code> (notice the underscore in the live version) Why does it act that way, Can I set it somehow?</p>
[ { "answer_id": 161409, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>That seems like a really dodgy way of getting the current request. Have you tried using <code>HttpContext.Current.Request.FilePath</code> or another <code>HttpContext.Current.Request...</code> variable instead?</p>\n" }, { "answer_id": 161411, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>You cant rely on auto generated names. Use types instead, eg:</p>\n\n<pre><code>if (Page is FooBar) { ... }\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15981/" ]
I have a control where I have to check in which page I am, so I can set a certain variable accordingly. ``` string pageName = this.Page.ToString(); switch (pageName) { case "ASP.foo_bar_aspx": doSomething(); break; default: doSomethingElse(); break; } ``` this works fine locally and on some developmentservers, however when I put it live, It stopped working because I don't get `ASP.foo_bar_aspx` but `_ASP.foo_bar_aspx` (notice the underscore in the live version) Why does it act that way, Can I set it somehow?
You cant rely on auto generated names. Use types instead, eg: ``` if (Page is FooBar) { ... } ```
161,404
<p>I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A. </p> <p>My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow.</p> <pre><code>SELECT valueC FROM C INNER JOIN ( SELECT DISTINCT lookupC FROM B INNER JOIN ( SELECT DISTINCT lookupB FROM A ) A2 ON B.id = A2.lookupB ) B2 ON C.id = B2.lookupC </code></pre> <p>EDIT: The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this:</p> <pre><code>SELECT DISTINCT valueC FROM C INNER JOIN B on C.id = B.lookupB INNER JOIN A on B.id = A.lookupB </code></pre> <p>This is very, very slow (magnitudes times slower than the nested SELECT I do above.</p>
[ { "answer_id": 161423, "author": "kristian", "author_id": 20377, "author_profile": "https://Stackoverflow.com/users/20377", "pm_score": 1, "selected": false, "text": "<p>Is this what you mean?</p>\n\n<pre><code>SELECT DISTINCT C.valueC\nFROM \nC\nINNER JOIN B ON C.id = B.lookupC\nINNER JOIN A ON B.id = A.lookupB\n</code></pre>\n" }, { "answer_id": 161428, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": false, "text": "<p>I believe your <strong>1:m</strong> relationships should already implicitly create DISTINCT JOINs.</p>\n\n<p>But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.</p>\n\n<pre><code>SELECT DISTINCT a.valueA, c.valueC\nFROM C\n INNER JOIN B ON B.lookupC = C.id\n INNER JOIN A ON A.lookupB = B.id\nORDER BY a.valueA, c.valueC\n</code></pre>\n" }, { "answer_id": 161429, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT DISTINCT C.valueC \nFROM C \n LEFT JOIN B ON C.id = B.lookupC\n LEFT JOIN A ON B.id = A.lookupB\nWHERE C.id IS NOT NULL\n</code></pre>\n\n<p>I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.</p>\n\n<hr>\n\n<p><strong>EDIT</strong>: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets. </p>\n\n<p>There is no distinct join construct you could use so just stay with what you already have :)</p>\n" }, { "answer_id": 162312, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 5, "selected": true, "text": "<p>I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.</p>\n\n<p>The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.</p>\n\n<p>What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2973/" ]
I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A. My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow. ``` SELECT valueC FROM C INNER JOIN ( SELECT DISTINCT lookupC FROM B INNER JOIN ( SELECT DISTINCT lookupB FROM A ) A2 ON B.id = A2.lookupB ) B2 ON C.id = B2.lookupC ``` EDIT: The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this: ``` SELECT DISTINCT valueC FROM C INNER JOIN B on C.id = B.lookupB INNER JOIN A on B.id = A.lookupB ``` This is very, very slow (magnitudes times slower than the nested SELECT I do above.
I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows. The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware. What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.
161,427
<p>I'm trying to understand how hibernate query cache really works. What I see now is that Hibernate does not update its second-level cache automatically when I insert new entities into the database (although I'm using only Hibernate calls). The only way I have found to make it work was to manually clean the cache after inserting new entities.</p> <p>Here is the more concrete example. I have a persistent entity called Container which can have many Items. I wanted to have all the items cached:</p> <pre> @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) class Item { // rest of the code ... } class Container { @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)<br> public List getItems() { ... } // rest of the code ... } </pre> <p>The problem which I have noticed is that when I:</p> <p>1) read some Containers from the db into memory (together with the corresponding items)</p> <pre><code> String hql = "from Container c left join fetch c.items where c.type = 1"; List&lt;Item&gt; list = hibernateTemplate.find(hql); </code></pre> <p>2) insert new Item for a chosen Container</p> <pre><code> hibernateTemplate.save(item) </code></pre> <p>3) repeat the first step<br> then in the 3rd step I cannot see the item I have inserted in the second step. I see them only if I clean the cache manually after inserting new items:</p> <pre><code> sessionFactory.evictCollection("Container.items", updatedContainerId) </code></pre> <p>My gut feeling tells me that Hibernate should do such a cache invalidation automatically. Has anyone seen it working? Am I doing something wrong or is it just not supported?</p> <p>Thanks in advance for the answer. Greetings Tom</p>
[ { "answer_id": 166517, "author": "bernardn", "author_id": 21548, "author_profile": "https://Stackoverflow.com/users/21548", "pm_score": 1, "selected": false, "text": "<p>Hibernate stores data from queries by using a key composed of the query (or query name) and the value of the specified parameters. I guess it can not easily know what cache to invalidate when you modify data.</p>\n\n<p>To solve this problem you should simply call <a href=\"http://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html#evictQueries(java.lang.String)\" rel=\"nofollow noreferrer\">SessionFactory.evictQueries</a>.</p>\n" }, { "answer_id": 1108148, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": false, "text": "<p>You might find my blog on query cache workings to be helpful in understanding what the query cache does and why it might not work the way you think it works:</p>\n\n<ul>\n<li><a href=\"http://tech.puredanger.com/2009/07/10/hibernate-query-cache/\" rel=\"noreferrer\">http://tech.puredanger.com/2009/07/10/hibernate-query-cache/</a></li>\n</ul>\n" }, { "answer_id": 10884915, "author": "Nikita Koksharov", "author_id": 764206, "author_profile": "https://Stackoverflow.com/users/764206", "pm_score": -1, "selected": false, "text": "<p>Yes, query cache auto invalidation is absent for native SQL-queries. For HQL-queries it just CLEARS ALL CACHES if any of tables participated in query have INSERT/UPDATE/DELETE for any object.</p>\n\n<p>So you may try <a href=\"https://github.com/mrniko/hibernate-dsc\" rel=\"nofollow\">Hibernate Dynamic SQL Cache</a> project, it aims to resolve this issue by automatically updating SQL query caches without invalidation.</p>\n\n<p>P.S. \"Bill the Lizard\" thanks for understaing :)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to understand how hibernate query cache really works. What I see now is that Hibernate does not update its second-level cache automatically when I insert new entities into the database (although I'm using only Hibernate calls). The only way I have found to make it work was to manually clean the cache after inserting new entities. Here is the more concrete example. I have a persistent entity called Container which can have many Items. I wanted to have all the items cached: ``` @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) class Item { // rest of the code ... } class Container { @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public List getItems() { ... } // rest of the code ... } ``` The problem which I have noticed is that when I: 1) read some Containers from the db into memory (together with the corresponding items) ``` String hql = "from Container c left join fetch c.items where c.type = 1"; List<Item> list = hibernateTemplate.find(hql); ``` 2) insert new Item for a chosen Container ``` hibernateTemplate.save(item) ``` 3) repeat the first step then in the 3rd step I cannot see the item I have inserted in the second step. I see them only if I clean the cache manually after inserting new items: ``` sessionFactory.evictCollection("Container.items", updatedContainerId) ``` My gut feeling tells me that Hibernate should do such a cache invalidation automatically. Has anyone seen it working? Am I doing something wrong or is it just not supported? Thanks in advance for the answer. Greetings Tom
You might find my blog on query cache workings to be helpful in understanding what the query cache does and why it might not work the way you think it works: * <http://tech.puredanger.com/2009/07/10/hibernate-query-cache/>
161,432
<p>Imagine the following type:</p> <pre><code>public struct Account { public int Id; public double Amount; } </code></pre> <p>What is the best algorithm to synchronize two <code>IList&lt;Account&gt;</code> in C# 2.0 ? (No linq) ?</p> <p>The first list (L1) is the reference list, the second (L2) is the one to synchronize according to the first:</p> <ul> <li>All accounts in L2 that are no longer present in L1 must be deleted from L2</li> <li>All accounts in L2 that still exist in L1 must be updated (amount attribute)</li> <li>All accounts that are in L1 but not yet in L2 must be added to L2</li> </ul> <p>The Id identifies accounts. It's no too hard to find a naive and working algorithm, but I would like to know if there is a smart solution to handle this scenario without ruining readability and perfs.</p> <p><strong>EDIT</strong> :</p> <ul> <li>Account type doesn't matter, is could be a class, has properties, equality members, etc.</li> <li>L1 and L2 are not sorted</li> <li>L2 items could not be replaced by L1 items, they must be updated (field by field, property by property)</li> </ul>
[ { "answer_id": 161441, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>For a start I'd get rid of the mutable struct. Mutable value types are a fundamentally bad thing. (As are public fields, IMO.)</p>\n\n<p>It's probably worth building a Dictionary so you can easily compare the contents of the two lists. Once you've got that easy way of checking for presence/absence, the rest should be straightforward.</p>\n\n<p>To be honest though, it sounds like you basically want L2 to be a complete copy of L1... clear L2 and just call AddRange? Or is the point that you also want to take other actions while you're changing L2?</p>\n" }, { "answer_id": 161445, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "<p>In addition to Jon Skeet's comment make your Account struct a class and override the Equals() and GetHashCode() method to get nice equality checking.</p>\n" }, { "answer_id": 161458, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>L2 = L1.clone()?</p>\n\n<p>... but I would guess you forgot to mention something.</p>\n" }, { "answer_id": 161535, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 2, "selected": false, "text": "<p>If your two lists are sorted, then you can simply walk through them in tandem. This is an O(m+n) operation. The following code could help:</p>\n\n<pre><code>class Program\n{\n static void Main()\n {\n List&lt;string&gt; left = new List&lt;string&gt; { \"Alice\", \"Charles\", \"Derek\" };\n List&lt;string&gt; right = new List&lt;string&gt; { \"Bob\", \"Charles\", \"Ernie\" };\n\n EnumerableExtensions.CompareSortedCollections(left, right, StringComparer.CurrentCultureIgnoreCase,\n s =&gt; Console.WriteLine(\"Left: \" + s), s =&gt; Console.WriteLine(\"Right: \" + s), (x,y) =&gt; Console.WriteLine(\"Both: \" + x + y));\n }\n}\n\nstatic class EnumerableExtensions\n{\n public static void CompareSortedCollections&lt;T&gt;(IEnumerable&lt;T&gt; source, IEnumerable&lt;T&gt; destination, IComparer&lt;T&gt; comparer, Action&lt;T&gt; onLeftOnly, Action&lt;T&gt; onRightOnly, Action&lt;T, T&gt; onBoth)\n {\n EnumerableIterator&lt;T&gt; sourceIterator = new EnumerableIterator&lt;T&gt;(source);\n EnumerableIterator&lt;T&gt; destinationIterator = new EnumerableIterator&lt;T&gt;(destination);\n\n while (sourceIterator.HasCurrent &amp;&amp; destinationIterator.HasCurrent)\n {\n // While LHS &lt; RHS, the items in LHS aren't in RHS\n while (sourceIterator.HasCurrent &amp;&amp; (comparer.Compare(sourceIterator.Current, destinationIterator.Current) &lt; 0))\n {\n onLeftOnly(sourceIterator.Current);\n sourceIterator.MoveNext();\n }\n\n // While RHS &lt; LHS, the items in RHS aren't in LHS\n while (sourceIterator.HasCurrent &amp;&amp; destinationIterator.HasCurrent &amp;&amp; (comparer.Compare(sourceIterator.Current, destinationIterator.Current) &gt; 0))\n {\n onRightOnly(destinationIterator.Current);\n destinationIterator.MoveNext();\n }\n\n // While LHS==RHS, the items are in both\n while (sourceIterator.HasCurrent &amp;&amp; destinationIterator.HasCurrent &amp;&amp; (comparer.Compare(sourceIterator.Current, destinationIterator.Current) == 0))\n {\n onBoth(sourceIterator.Current, destinationIterator.Current);\n sourceIterator.MoveNext();\n destinationIterator.MoveNext();\n }\n }\n\n // Mop up.\n while (sourceIterator.HasCurrent)\n {\n onLeftOnly(sourceIterator.Current);\n sourceIterator.MoveNext();\n }\n\n while (destinationIterator.HasCurrent)\n {\n onRightOnly(destinationIterator.Current);\n destinationIterator.MoveNext();\n }\n }\n}\n\ninternal class EnumerableIterator&lt;T&gt;\n{\n private readonly IEnumerator&lt;T&gt; _enumerator;\n\n public EnumerableIterator(IEnumerable&lt;T&gt; enumerable)\n {\n _enumerator = enumerable.GetEnumerator();\n MoveNext();\n }\n\n public bool HasCurrent { get; private set; }\n\n public T Current\n {\n get { return _enumerator.Current; }\n }\n\n public void MoveNext()\n {\n HasCurrent = _enumerator.MoveNext();\n }\n}\n</code></pre>\n\n<p>You'll have to be careful about modifying the collections while iterating over them, though.</p>\n\n<p>If they're not sorted, then comparing every element in one with every element in the other is O(mn), which gets painful really quickly.</p>\n\n<p>If you can bear to copy the key values from each collection into a Dictionary or similar (i.e. a collection with acceptable performance when asked \"is X present?\"), then you could come up with something reasonable.</p>\n" }, { "answer_id": 2977697, "author": "rboarman", "author_id": 131818, "author_profile": "https://Stackoverflow.com/users/131818", "pm_score": 0, "selected": false, "text": "<p>I know this is an old post but you should check out AutoMapper. It will do exactly what you want in a very flexible and configurable way.</p>\n\n<p><a href=\"http://automapper.codeplex.com/\" rel=\"nofollow noreferrer\">AutoMapper</a></p>\n" }, { "answer_id": 54690709, "author": "Mateus Wolkmer", "author_id": 9629238, "author_profile": "https://Stackoverflow.com/users/9629238", "pm_score": 1, "selected": false, "text": "<p>I had the same problem, and my best solution was the following (adapted to your case), having both lists loaded:</p>\n\n<ol>\n<li>For each <em>Account</em> in L1, verify if it exists in L2:\n\n<ul>\n<li>If found, update all values from L1's <em>Account</em> based on L2's. Then, delete the <em>Account</em> from L2.</li>\n<li>If not found, mark L1's <em>Account</em> as deleted, or delete it from the list, it depends on how your database is structured.</li>\n</ul></li>\n<li>For each <em>Account</em> left in L2, add it into L1.</li>\n</ol>\n\n<p>I recommend implementing the <code>IEquatable&lt;&gt;</code> interface in your <em>Account</em> class (or just override the <code>Equals()</code> method) so it always compares IDs on methods that require comparison between objects:</p>\n\n<pre><code>public struct Account : IEquatable&lt;Account&gt;\n{\n public int Id;\n public double Amount;\n\n public bool Equals(Account other)\n {\n if (other == null) return false;\n return (this.Id.Equals(other.Id));\n }\n}\n</code></pre>\n\n<p>The sync algorithm would be something like this (make sure both lists are initialized so no errors occurr):</p>\n\n<pre><code>L1.ForEach (L1Account =&gt;\n{\n var L2Account = L2.Find(a =&gt; a.Id == L1Account.id);\n // If found, update values\n if (L2Account != null)\n {\n L1Account.Amount = L2Account.Amount;\n L2.Remove(L2Account);\n }\n // If not found, remove it\n else\n {\n L1.Remove(L1Account);\n }\n}\n// Add any remaining L2 Account to L1\nL1.AddRange(L2);\n</code></pre>\n" }, { "answer_id": 65855217, "author": "Teneko", "author_id": 2788957, "author_profile": "https://Stackoverflow.com/users/2788957", "pm_score": 0, "selected": false, "text": "<h2>Introduction</h2>\n<p>I have implemented two algorithms, one for sorted and one for sequential collections. Both support null values and duplicates, and work in the same way:</p>\n<p>They yield return <code>CollectionModification&lt;LeftItemType,RightItemType&gt;</code>s which is similar to <code>CollectionChangedEventArgs&lt;T&gt;</code> (<a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.rtc.signaling.collectionchangedeventargs-1?view=ucma-api\" rel=\"nofollow noreferrer\">reference</a>) which can be used in return to <strong>synchronize</strong> a collection.</p>\n<p>Regarding yield return:</p>\n<blockquote>\n<p>When using one or the other algorithm where your left items (the reference collection) is compared to right items, you can apply each yield returned <code>CollectionModification</code> as soon as they are yield returned , but this can result in a &quot;collection was modified&quot;-exception (for example when using <code>List&lt;T&gt;.GetEnumerator</code>). To prevent this, both algorithms have the ability implemented to use an indexable collection as reference collection that is about to be mutated. You only have to wrap the reference collection with <code>YieldIteratorInfluencedReadOnlyList&lt;ItemType&gt;</code> (abstract) by using the extensions methods in <a href=\"https://github.com/teroneko/Teronis.DotNet/blob/76cd5f50576d99f6927f522eaf33ec651135e1a1/src/NetStandard/Collections/Algorithms/src/Modifications/YieldIteratorInfluencedReadOnlyListExtensions.cs\" rel=\"nofollow noreferrer\">YieldIteratorInfluencedReadOnlyListExtensions</a>. :)</p>\n</blockquote>\n<h3>SortedCollectionModifications</h3>\n<p>The first algorithm works for ascended or descended ordered lists and uses <code>IComparer&lt;T&gt;</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// The algorithm creates modifications that can transform one collection into another collection.\n/// The collection modifications may be used to transform &lt;paramref name=&quot;leftItems&quot;/&gt;.\n/// Assumes &lt;paramref name=&quot;leftItems&quot;/&gt; and &lt;paramref name=&quot;rightItems&quot;/&gt; to be sorted by that order you specify by &lt;paramref name=&quot;collectionOrder&quot;/&gt;.\n/// Duplications are allowed but take into account that duplications are yielded as they are appearing.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=&quot;LeftItemType&quot;&gt;The type of left items.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;RightItemType&quot;&gt;The type of right items.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;ComparablePartType&quot;&gt;The type of the comparable part of left item and right item.&lt;/typeparam&gt;\n/// &lt;param name=&quot;leftItems&quot;&gt;The collection you want to have transformed.&lt;/param&gt;\n/// &lt;param name=&quot;getComparablePartOfLeftItem&quot;&gt;The part of left item that is comparable with part of right item.&lt;/param&gt;\n/// &lt;param name=&quot;rightItems&quot;&gt;The collection in which &lt;paramref name=&quot;leftItems&quot;/&gt; could be transformed.&lt;/param&gt;\n/// &lt;param name=&quot;getComparablePartOfRightItem&quot;&gt;The part of right item that is comparable with part of left item.&lt;/param&gt;\n/// &lt;param name=&quot;collectionOrder&quot;&gt;the presumed order of items to be used to determine &lt;see cref=&quot;IComparer{T}.Compare(T, T)&quot;/&gt; argument assignment.&lt;/param&gt;\n/// &lt;param name=&quot;comparer&quot;&gt;The comparer to be used to compare comparable parts of left and right item.&lt;/param&gt;\n/// &lt;param name=&quot;yieldCapabilities&quot;&gt;The yieldCapabilities that regulates how &lt;paramref name=&quot;leftItems&quot;/&gt; and &lt;paramref name=&quot;rightItems&quot;/&gt; are synchronized.&lt;/param&gt;\n/// &lt;returns&gt;The collection modifications.&lt;/returns&gt;\n/// &lt;exception cref=&quot;ArgumentNullException&quot;&gt;Thrown when non-nullable arguments are null.&lt;/exception&gt;\npublic static IEnumerable&lt;CollectionModification&lt;LeftItemType, RightItemType&gt;&gt; YieldCollectionModifications&lt;LeftItemType, RightItemType, ComparablePartType&gt;(\n IEnumerable&lt;LeftItemType&gt; leftItems,\n Func&lt;LeftItemType, ComparablePartType&gt; getComparablePartOfLeftItem,\n IEnumerable&lt;RightItemType&gt; rightItems,\n Func&lt;RightItemType, ComparablePartType&gt; getComparablePartOfRightItem,\n SortedCollectionOrder collectionOrder,\n IComparer&lt;ComparablePartType&gt; comparer,\n CollectionModificationsYieldCapabilities yieldCapabilities)\n</code></pre>\n<p>Python algorithm inspiration taken from: <a href=\"https://cstheory.stackexchange.com/a/20121/61134\">Efficient synchronization of two instances of an ordered list</a>.</p>\n<h3>EqualityTrailingCollectionModifications</h3>\n<p>The second algorithm works for any order and uses <code>IEqualityComparer&lt;T&gt;</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// The algorithm creates modifications that can transform one collection into another collection.\n/// The collection modifications may be used to transform &lt;paramref name=&quot;leftItems&quot;/&gt;.\n/// The more the collection is synchronized in an orderly way, the more efficient the algorithm is.\n/// Duplications are allowed but take into account that duplications are yielded as they are appearing.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=&quot;LeftItemType&quot;&gt;The type of left items.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;RightItemType&quot;&gt;The type of right items.&lt;/typeparam&gt;\n/// &lt;typeparam name=&quot;ComparablePartType&quot;&gt;The type of the comparable part of left item and right item.&lt;/typeparam&gt;\n/// &lt;param name=&quot;leftItems&quot;&gt;The collection you want to have transformed.&lt;/param&gt;\n/// &lt;param name=&quot;getComparablePartOfLeftItem&quot;&gt;The part of left item that is comparable with part of right item.&lt;/param&gt;\n/// &lt;param name=&quot;rightItems&quot;&gt;The collection in which &lt;paramref name=&quot;leftItems&quot;/&gt; could be transformed.&lt;/param&gt;\n/// &lt;param name=&quot;getComparablePartOfRightItem&quot;&gt;The part of right item that is comparable with part of left item.&lt;/param&gt;\n/// &lt;param name=&quot;equalityComparer&quot;&gt;The equality comparer to be used to compare comparable parts.&lt;/param&gt;\n/// &lt;param name=&quot;yieldCapabilities&quot;&gt;The yield capabilities, e.g. only insert or only remove.&lt;/param&gt;\n/// &lt;returns&gt;The collection modifications.&lt;/returns&gt;\n/// &lt;exception cref=&quot;ArgumentNullException&quot;&gt;Thrown when non-nullable arguments are null.&lt;/exception&gt;\npublic static IEnumerable&lt;CollectionModification&lt;LeftItemType, RightItemType&gt;&gt; YieldCollectionModifications&lt;LeftItemType, RightItemType, ComparablePartType&gt;(\n IEnumerable&lt;LeftItemType&gt; leftItems,\n Func&lt;LeftItemType, ComparablePartType&gt; getComparablePartOfLeftItem,\n IEnumerable&lt;RightItemType&gt; rightItems,\n Func&lt;RightItemType, ComparablePartType&gt; getComparablePartOfRightItem,\n IEqualityComparer&lt;ComparablePartType&gt;? equalityComparer,\n CollectionModificationsYieldCapabilities yieldCapabilities)\n where ComparablePartType : notnull\n</code></pre>\n<h2>Requirements</h2>\n<p>One of the following frameworks is required</p>\n<ul>\n<li>.NET-Standard 2.0</li>\n<li>.NET Core 3.1</li>\n<li>.NET 5.0</li>\n</ul>\n<p>Both algorithms are created with custom implemented types (<code>IndexDirectory</code>, <code>NullableKeyDictionary</code>, <code>LinkedBucketList</code> to name a few), so I can not simply copy paste the code here, so I would like to reference you to my following packages:</p>\n<ul>\n<li><a href=\"https://www.nuget.org/packages/Teronis.NetStandard.Core/0.1.8-alpha.65\" rel=\"nofollow noreferrer\">Teronis.NetStandard.Core</a>: Transitively used by the packages below</li>\n<li><a href=\"https://www.nuget.org/packages/Teronis.NetStandard.Collections/0.1.8-alpha.65\" rel=\"nofollow noreferrer\">Teronis.NetStandard.Collections</a>: Contains a few custom collection types. Transitively used by the packages below</li>\n<li><a href=\"https://www.nuget.org/packages/Teronis.NetStandard.Collections.Synchronization/0.1.8-alpha.65\" rel=\"nofollow noreferrer\">Teronis.NetStandard.Collections.Algorithms</a>: Contains the algorithms</li>\n<li><a href=\"https://www.nuget.org/packages/Teronis.NetStandard.Collections.Algorithms/0.1.8-alpha.65\" rel=\"nofollow noreferrer\">Teronis.NetStandard.Collections.Synchronization</a>: Contains the collections synchroniaztion classes</li>\n</ul>\n<h2>Implementation</h2>\n<h3>Anitcipated classes</h3>\n<p><strong>Account</strong>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Account\n{\n public Account(int id) =&gt;\n Id = id;\n\n public int Id { get; }\n public double Amount { get; }\n}\n\n</code></pre>\n<p>And the following collection item equality comparer class:</p>\n<p><strong>AccountEqualityComparer</strong>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class AccountEqualityComparer : EqualityComparer&lt;Account&gt;\n{\n public new static AccountEqualityComparer Default = new AccountEqualityComparer();\n\n public override bool Equals([AllowNull] Account x, [AllowNull] Account y) =&gt;\n ReferenceEquals(x, y) || (!(x is null &amp;&amp; y is null) &amp;&amp; x.Id.Equals(y.Id));\n\n public override int GetHashCode([DisallowNull] Account obj) =&gt;\n obj.Id;\n}\n</code></pre>\n<h3>&quot;My&quot; classes</h3>\n<p><strong>AccountCollectionViewModel</strong>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using Teronis.Collections.Algorithms.Modifications;\nusing Teronis.Collections.Synchronization;\nusing Teronis.Collections.Synchronization.Extensions;\nusing Teronis.Reflection;\n\npublic class AccountCollectionViewModel : SyncingCollectionViewModel&lt;Account, Account&gt;\n{\n public AccountCollectionViewModel()\n : base(CollectionSynchronizationMethod.Sequential(AccountEqualityComparer.Default))\n {\n // In case of SyncingCollectionViewModel, we have to pass a synchronization method.\n //\n // Sequential means any order\n //\n }\n\n protected override Account CreateSubItem(Account superItem) =&gt;\n superItem;\n\n protected override void ApplyCollectionItemReplace(in ApplyingCollectionModificationBundle modificationBundle)\n {\n foreach (var (oldItem, newItem) in modificationBundle.OldSuperItemsNewSuperItemsModification.YieldTuplesForOldItemNewItemReplace())\n {\n // Implementation detail: update left public property values by right public property values.\n TeronisReflectionUtils.UpdateEntityVariables(oldItem, newItem);\n }\n }\n}\n\n</code></pre>\n<p><strong>Program</strong>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Diagnostics;\nusing System.Linq;\n\nclass Program\n{\n static void Main()\n {\n // Arrange\n var collection = new AccountCollectionViewModel();\n\n var initialData = new Account[] {\n new Account(5) { Amount = 0 },\n new Account(7) { Amount = 0 },\n new Account(3) { Amount = 0 }\n };\n\n var newData = new Account[] {\n new Account(5) { Amount = 10 }, \n /* Account by ID 7 got removed .. */ \n /* but account by ID 8 is new. */ \n new Account(8) { Amount = 10 },\n new Account(3) { Amount = 10 }\n };\n\n // Act\n collection.SynchronizeCollection(initialData);\n\n // Assert\n Debug.Assert(collection.SubItems.ElementAt(1).Id == 7, &quot;The account at index 1 has not the ID 7.&quot;);\n Debug.Assert(collection.SubItems.All(x =&gt; x.Amount == 0), &quot;Not all accounts have an amount of 0.&quot;);\n\n // Act\n collection.SynchronizeCollection(newData);\n\n // Assert\n Debug.Assert(collection.SubItems.ElementAt(1).Id == 8, &quot;The account at index 1 has not the ID 8.&quot;);\n Debug.Assert(collection.SubItems.All(x =&gt; x.Amount == 10), &quot;Not all accounts have an amount of 10.&quot;);\n\n ;\n }\n}\n</code></pre>\n<p>You can see that I use <a href=\"https://github.com/teroneko/Teronis.DotNet/blob/76cd5f50576d99f6927f522eaf33ec651135e1a1/src/NetStandard/Collections/Synchronization/src/SyncingCollectionViewModel.cs\" rel=\"nofollow noreferrer\">SyncingCollectionViewModel</a>, a very &quot;heavy&quot; type. That's because I have not finished the lightweight <a href=\"https://github.com/teroneko/Teronis.DotNet/blob/76cd5f50576d99f6927f522eaf33ec651135e1a1/src/NetStandard/Collections/Synchronization/src/SynchronizableCollection.cs\" rel=\"nofollow noreferrer\">SynchronizableCollection</a> implementation yet (virtual methods for add, remove, replace and so on are missing).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
Imagine the following type: ``` public struct Account { public int Id; public double Amount; } ``` What is the best algorithm to synchronize two `IList<Account>` in C# 2.0 ? (No linq) ? The first list (L1) is the reference list, the second (L2) is the one to synchronize according to the first: * All accounts in L2 that are no longer present in L1 must be deleted from L2 * All accounts in L2 that still exist in L1 must be updated (amount attribute) * All accounts that are in L1 but not yet in L2 must be added to L2 The Id identifies accounts. It's no too hard to find a naive and working algorithm, but I would like to know if there is a smart solution to handle this scenario without ruining readability and perfs. **EDIT** : * Account type doesn't matter, is could be a class, has properties, equality members, etc. * L1 and L2 are not sorted * L2 items could not be replaced by L1 items, they must be updated (field by field, property by property)
For a start I'd get rid of the mutable struct. Mutable value types are a fundamentally bad thing. (As are public fields, IMO.) It's probably worth building a Dictionary so you can easily compare the contents of the two lists. Once you've got that easy way of checking for presence/absence, the rest should be straightforward. To be honest though, it sounds like you basically want L2 to be a complete copy of L1... clear L2 and just call AddRange? Or is the point that you also want to take other actions while you're changing L2?
161,443
<p>In Kohana/CodeIgniter, I can have a URL in this form:</p> <pre><code>http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ... </code></pre> <p>And then read the parameters in my controller as follows:</p> <pre><code>class MyController { public function method_name($param_A, $param_B, $param_C ...) { // ... code } } </code></pre> <p>How do you achieve this in the Zend Framework?</p>
[ { "answer_id": 161636, "author": "Andrew Taylor", "author_id": 1776, "author_profile": "https://Stackoverflow.com/users/1776", "pm_score": 4, "selected": false, "text": "<p>Take a look at the Zend_Controller_Router classes:</p>\n\n<p><a href=\"http://framework.zend.com/manual/en/zend.controller.router.html\" rel=\"noreferrer\">http://framework.zend.com/manual/en/zend.controller.router.html</a></p>\n\n<p>These will allow you to define a Zend_Controller_Router_Route which maps to your URL in the way that you need.</p>\n\n<p>An example of having 4 static params for the Index action of the Index controller is:</p>\n\n<pre><code>$router = new Zend_Controller_Router_Rewrite();\n\n$router-&gt;addRoute(\n 'index',\n new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' =&gt; 'index', 'action' =&gt; 'index'))\n);\n\n$frontController-&gt;setRouter($router);\n</code></pre>\n\n<p>This is added to your bootstrap after you've defined your front controller.</p>\n\n<p>Once in your action, you can then use:</p>\n\n<pre><code>$this-&gt;_request-&gt;getParam('param1');\n</code></pre>\n\n<p>Inside your action method to access the values.</p>\n\n<p>Andrew</p>\n" }, { "answer_id": 184852, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 4, "selected": true, "text": "<p><strong>Update (04/13/2016):</strong>\nThe link in my answer below moved and has been fixed. However, just in case it disappears again -- here are a few alternatives that provide some in depth information on this technique, as well as use the original article as reference material:</p>\n\n<ul>\n<li><a href=\"http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/\" rel=\"nofollow noreferrer\">Zend Framework Controller Actions with Function Parameters</a></li>\n<li><a href=\"http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/\" rel=\"nofollow noreferrer\">Zend_Controller actions that accept parameters?</a></li>\n</ul>\n\n<hr>\n\n<p>@<a href=\"https://stackoverflow.com/questions/161443/url-segment-to-action-method-parameter-in-zend-framework#161636\">Andrew Taylor</a>'s response is the proper Zend Framework way of handling URL parameters. However, if you would like to have the URL parameters in your controller's action (as in your example) - check out <a href=\"http://devzone.zend.com/1138/actions-now-with-parameters/\" rel=\"nofollow noreferrer\">this tutorial on Zend DevZone</a>.</p>\n" }, { "answer_id": 1041892, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 1, "selected": false, "text": "<p>Originally posted here <a href=\"http://cslai.coolsilon.com/2009/03/28/extending-zend-framework/\" rel=\"nofollow noreferrer\">http://cslai.coolsilon.com/2009/03/28/extending-zend-framework/</a></p>\n\n<p>My current solution is as follows:</p>\n\n<pre><code>abstract class Coolsilon_Controller_Base \n extends Zend_Controller_Action { \n\n public function dispatch($actionName) { \n $parameters = array(); \n\n foreach($this-&gt;_parametersMeta($actionName) as $paramMeta) { \n $parameters = array_merge( \n $parameters, \n $this-&gt;_parameter($paramMeta, $this-&gt;_getAllParams()) \n ); \n } \n\n call_user_func_array(array(&amp;$this, $actionName), $parameters); \n } \n\n private function _actionReference($className, $actionName) { \n return new ReflectionMethod( \n $className, $actionName \n ); \n } \n\n private function _classReference() { \n return new ReflectionObject($this); \n } \n\n private function _constructParameter($paramMeta, $parameters) { \n return array_key_exists($paramMeta-&gt;getName(), $parameters) ? \n array($paramMeta-&gt;getName() =&gt; $parameters[$paramMeta-&gt;getName()]) : \n array($paramMeta-&gt;getName() =&gt; $paramMeta-&gt;getDefaultValue()); \n } \n\n private function _parameter($paramMeta, $parameters) { \n return $this-&gt;_parameterIsValid($paramMeta, $parameters) ? \n $this-&gt;_constructParameter($paramMeta, $parameters) : \n $this-&gt;_throwParameterNotFoundException($paramMeta, $parameters); \n } \n\n private function _parameterIsValid($paramMeta, $parameters) { \n return $paramMeta-&gt;isOptional() === FALSE \n &amp;&amp; empty($parameters[$paramMeta-&gt;getName()]) === FALSE; \n } \n\n private function _parametersMeta($actionName) { \n return $this-&gt;_actionReference( \n $this-&gt;_classReference()-&gt;getName(), \n $actionName \n ) \n -&gt;getParameters(); \n } \n\n private function _throwParameterNotFoundException($paramMeta, $parameters) { \n throw new Exception(”Parameter: {$paramMeta-&gt;getName()} Cannot be empty”); \n } \n} \n</code></pre>\n" }, { "answer_id": 1981544, "author": "Andy", "author_id": 114770, "author_profile": "https://Stackoverflow.com/users/114770", "pm_score": 2, "selected": false, "text": "<p>For a simpler method that allows for more complex configurations, try <a href=\"http://sourcecodebean.com/archives/friendly-urls-and-the-zend-router/31\" rel=\"nofollow noreferrer\">this post</a>. In summary:</p>\n\n<p>Create <code>application/configs/routes.ini</code></p>\n\n<pre><code>routes.popular.route = popular/:type/:page/:sortOrder\nroutes.popular.defaults.controller = popular\nroutes.popular.defaults.action = index\nroutes.popular.defaults.type = images\nroutes.popular.defaults.sortOrder = alltime\nroutes.popular.defaults.page = 1\nroutes.popular.reqs.type = \\w+\nroutes.popular.reqs.page = \\d+\nroutes.popular.reqs.sortOrder = \\w+\n</code></pre>\n\n<p>Add to <code>bootstrap.php</code></p>\n\n<pre><code>// create $frontController if not already initialised\n$frontController = Zend_Controller_Front::getInstance(); \n\n$config = new Zend_Config_Ini(APPLICATION_PATH . ‘/config/routes.ini’);\n$router = $frontController-&gt;getRouter();\n$router-&gt;addConfig($config,‘routes’);\n</code></pre>\n" }, { "answer_id": 6776614, "author": "Victor", "author_id": 509235, "author_profile": "https://Stackoverflow.com/users/509235", "pm_score": 2, "selected": false, "text": "<p>I have extended <code>Zend_Controller_Action</code> with my controller class and made the following changes:</p>\n\n<p>In <code>dispatch($action)</code> method replaced </p>\n\n<p><code>$this-&gt;$action();</code></p>\n\n<p>with</p>\n\n<p><code>call_user_func_array(array($this,$action), $this-&gt;getUrlParametersByPosition());</code></p>\n\n<p>And added the following method</p>\n\n<pre><code>/**\n * Returns array of url parts after controller and action\n */\nprotected function getUrlParametersByPosition()\n{\n $request = $this-&gt;getRequest();\n $path = $request-&gt;getPathInfo();\n $path = explode('/', trim($path, '/'));\n if(@$path[0]== $request-&gt;getControllerName())\n {\n unset($path[0]);\n }\n if(@$path[1] == $request-&gt;getActionName())\n {\n unset($path[1]);\n }\n return $path;\n}\n</code></pre>\n\n<p>Now for a URL like <code>/mycontroller/myaction/123/321</code></p>\n\n<p>in my action I will get all the params following controller and action</p>\n\n<pre><code>public function editAction($param1 = null, $param2 = null)\n{\n // $param1 = 123\n // $param2 = 321\n}\n</code></pre>\n\n<p>Extra parameters in URL won't cause any error as you can send more params to method then defined. You can get all of them by <code>func_get_args()</code>\nAnd you can still use <code>getParam()</code> in a usual way.\nYour URL may not contain action name using default one. </p>\n\n<p>Actually my URL does not contain parameter names. Only their values. (Exactly as it was in the question) \nAnd you have to define routes to specify parameters positions in URL to follow the concepts of framework and to be able to build URLs using Zend methods. \nBut if you always know the position of your parameter in URL you can easily get it like this. </p>\n\n<p>That is not as sophisticated as using reflection methods but I guess provides less overhead. </p>\n\n<p>Dispatch method now looks like this:</p>\n\n<pre><code>/**\n * Dispatch the requested action\n *\n * @param string $action Method name of action\n * @return void\n */\npublic function dispatch($action)\n{\n // Notify helpers of action preDispatch state\n $this-&gt;_helper-&gt;notifyPreDispatch();\n\n $this-&gt;preDispatch();\n if ($this-&gt;getRequest()-&gt;isDispatched()) {\n if (null === $this-&gt;_classMethods) {\n $this-&gt;_classMethods = get_class_methods($this);\n }\n\n // preDispatch() didn't change the action, so we can continue\n if ($this-&gt;getInvokeArg('useCaseSensitiveActions') || in_array($action, $this-&gt;_classMethods)) {\n if ($this-&gt;getInvokeArg('useCaseSensitiveActions')) {\n trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this \"feature\"');\n }\n //$this-&gt;$action();\n call_user_func_array(array($this,$action), $this-&gt;getUrlParametersByPosition()); \n } else {\n $this-&gt;__call($action, array());\n }\n $this-&gt;postDispatch();\n }\n\n // whats actually important here is that this action controller is\n // shutting down, regardless of dispatching; notify the helpers of this\n // state\n $this-&gt;_helper-&gt;notifyPostDispatch();\n} \n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742/" ]
In Kohana/CodeIgniter, I can have a URL in this form: ``` http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ... ``` And then read the parameters in my controller as follows: ``` class MyController { public function method_name($param_A, $param_B, $param_C ...) { // ... code } } ``` How do you achieve this in the Zend Framework?
**Update (04/13/2016):** The link in my answer below moved and has been fixed. However, just in case it disappears again -- here are a few alternatives that provide some in depth information on this technique, as well as use the original article as reference material: * [Zend Framework Controller Actions with Function Parameters](http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/) * [Zend\_Controller actions that accept parameters?](http://codeutopia.net/blog/2009/03/16/zend_controller-actions-that-accept-parameters/) --- @[Andrew Taylor](https://stackoverflow.com/questions/161443/url-segment-to-action-method-parameter-in-zend-framework#161636)'s response is the proper Zend Framework way of handling URL parameters. However, if you would like to have the URL parameters in your controller's action (as in your example) - check out [this tutorial on Zend DevZone](http://devzone.zend.com/1138/actions-now-with-parameters/).
161,462
<p>I'm using <code>org.w3c</code> <code>XML API</code> to open an existing <code>XML</code> file. I'm removing some nodes , and I'm adding others instead.</p> <p>The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the <code>XML</code> file is valid , it is very hard for a human to examine it.</p> <p>Is there anyway to add indentation , or at least a newline after each node?</p>
[ { "answer_id": 161478, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "<p>I'm assuming that you're using a <a href=\"http://java.sun.com/javase/6/docs/api/javax/xml/transform/Transformer.html\" rel=\"noreferrer\"><code>Transformer</code></a> to do the actual writing (to a <a href=\"http://java.sun.com/javase/6/docs/api/javax/xml/transform/stream/StreamResult.html\" rel=\"noreferrer\"><code>StreamResult</code></a>). In which case, do this before you call <code>transform</code>:</p>\n\n<pre><code>transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\ntransformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n</code></pre>\n" }, { "answer_id": 294987, "author": "mlo55", "author_id": 32993, "author_profile": "https://Stackoverflow.com/users/32993", "pm_score": 1, "selected": false, "text": "<p>There are a few good examples of \"pretty printing\" in the following thread</p>\n\n<p><a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java\">how to pretty print xml from Java</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java#260314\">Link to my effort at a solution</a></p>\n" }, { "answer_id": 10412619, "author": "Thilina", "author_id": 1369861, "author_profile": "https://Stackoverflow.com/users/1369861", "pm_score": 4, "selected": false, "text": "<pre><code>transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\ntransformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n</code></pre>\n\n<p>source\n<a href=\"https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java\">How to pretty print XML from Java?</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
I'm using `org.w3c` `XML API` to open an existing `XML` file. I'm removing some nodes , and I'm adding others instead. The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the `XML` file is valid , it is very hard for a human to examine it. Is there anyway to add indentation , or at least a newline after each node?
I'm assuming that you're using a [`Transformer`](http://java.sun.com/javase/6/docs/api/javax/xml/transform/Transformer.html) to do the actual writing (to a [`StreamResult`](http://java.sun.com/javase/6/docs/api/javax/xml/transform/stream/StreamResult.html)). In which case, do this before you call `transform`: ``` transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); ```
161,474
<p>My basic question is, in .NET, how do I clone WebControls?</p> <p>I would like to build a custom tag, which can produce multiple copies of its children. Ultimately I intend to build a tag similar to in JSP/Struts.</p> <p>But the first hurdle I have is the ability to duplicate/clone the contents of a control.</p> <p>Consider this rather contrived example;</p> <pre><code>&lt;custom:duplicate count="2"&gt; &lt;div&gt; &lt;p&gt;Some html&lt;/p&gt; &lt;asp:TextBox id="tb1" runat="server" /&gt; &lt;/div&gt; &lt;/custom:duplicate&gt; </code></pre> <p>The HTML markup which is output would be something like,</p> <pre><code>&lt;div&gt; &lt;p&gt;Some html&lt;/p&gt; &lt;input type="text" id="tb1" /&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;Some html&lt;/p&gt; &lt;input type="text" id="tb1" /&gt; &lt;/div&gt; </code></pre> <p><em>Note: I know i have the id duplicated, I can come up with a solution to that later!</em></p> <p>So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control.</p> <p>In this example I have said 'count=2' so what the control should do is output/render its children twice.</p> <p>What I would hope to do is write some "OnInit" code which does something like:</p> <pre><code>List&lt;WebControl&gt; clones; for(int i=1; i&lt;count; i++) { foreach(WebControl c in Controls) { WebControl clone = c.Clone(); clones.Add(clone); } } Controls.AddRange(clones); </code></pre> <p>However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way.</p> <p>Any ideas how I can clone WebControls?</p>
[ { "answer_id": 161526, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 0, "selected": false, "text": "<p>The way to do this in ASP.NET is using templates. There are samples in MSDN for this, just look for templated controls / ITemplate.</p>\n" }, { "answer_id": 161754, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "<p>What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all.</p>\n" }, { "answer_id": 1372034, "author": "Juri", "author_id": 50109, "author_profile": "https://Stackoverflow.com/users/50109", "pm_score": 1, "selected": false, "text": "<p>Just as a reference for others which really want to clone a <strong>custom server control</strong>.</p>\n\n<pre><code>public class MyCustomServerCtrl\n{\n\n ...\n\n public MyCustomServerCtrl Clone()\n {\n return MemberwiseClone() as MyCustomServerCtrl;\n }\n\n}\n</code></pre>\n\n<p>But note: this is needed very rarely and if so, most probably just when you're having some really specific logic. It should be avoided when possible. Generally it should be enough to use existing controls like Repeater, ListView etc..</p>\n" }, { "answer_id": 2777807, "author": "Ananda", "author_id": 334004, "author_profile": "https://Stackoverflow.com/users/334004", "pm_score": 0, "selected": false, "text": "<p>The WebControl.CopyBaseAttributes method copies the AccessKey, Enabled, ToolTip, TabIndex, and Attributes properties from the specified Web server control to the Web server control that this method is called from. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.copybaseattributes(VS.90).aspx\" rel=\"nofollow noreferrer\">MSDN Documentation</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24232/" ]
My basic question is, in .NET, how do I clone WebControls? I would like to build a custom tag, which can produce multiple copies of its children. Ultimately I intend to build a tag similar to in JSP/Struts. But the first hurdle I have is the ability to duplicate/clone the contents of a control. Consider this rather contrived example; ``` <custom:duplicate count="2"> <div> <p>Some html</p> <asp:TextBox id="tb1" runat="server" /> </div> </custom:duplicate> ``` The HTML markup which is output would be something like, ``` <div> <p>Some html</p> <input type="text" id="tb1" /> </div> <div> <p>Some html</p> <input type="text" id="tb1" /> </div> ``` *Note: I know i have the id duplicated, I can come up with a solution to that later!* So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control. In this example I have said 'count=2' so what the control should do is output/render its children twice. What I would hope to do is write some "OnInit" code which does something like: ``` List<WebControl> clones; for(int i=1; i<count; i++) { foreach(WebControl c in Controls) { WebControl clone = c.Clone(); clones.Add(clone); } } Controls.AddRange(clones); ``` However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way. Any ideas how I can clone WebControls?
What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all.
161,477
<p>Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:</p> <pre><code>class GenericClass&lt;T&gt; { public event EventHandler&lt;EventData&gt; MyEvent; public class EventData : EventArgs { /* snip */ } // ... snip } </code></pre> <p>Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:</p> <pre><code>GenericClass&lt;int&gt; gcInt = new GenericClass&lt;int&gt;; gcInt.MyEvent += new EventHandler&lt;GenericClass&lt;int&gt;.EventData&gt;(gcInt_MyEvent); // ... private void gcInt_MyEvent(object sender, GenericClass&lt;int&gt;.EventData e) { throw new NotImplementedException(); } </code></pre> <p>Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...</p> <p>Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.</p>
[ { "answer_id": 161484, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 10, "selected": true, "text": "<p>No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.</p>\n\n<pre><code>using CustomerList = System.Collections.Generic.List&lt;Customer&gt;;\n</code></pre>\n\n<p>but that will only impact that source file. In C and C++, my experience is that <code>typedef</code> is usually used within .h files which are included widely - so a single <code>typedef</code> can be used over a whole project. That ability does not exist in C#, because there's no <code>#include</code> functionality in C# that would allow you to include the <code>using</code> directives from one file in another.</p>\n\n<p>Fortunately, the example you give <em>does</em> have a fix - implicit method group conversion. You can change your event subscription line to just:</p>\n\n<pre><code>gcInt.MyEvent += gcInt_MyEvent;\n</code></pre>\n\n<p>:)</p>\n" }, { "answer_id": 161488, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>I think there is no typedef. You could only define a specific delegate type instead of the generic one in the GenericClass, i.e.</p>\n\n<pre><code>public delegate GenericHandler EventHandler&lt;EventData&gt;\n</code></pre>\n\n<p>This would make it shorter. But what about the following suggestion:</p>\n\n<p>Use Visual Studio. This way, when you typed</p>\n\n<pre><code>gcInt.MyEvent += \n</code></pre>\n\n<p>it already provides the complete event handler signature from Intellisense. Press TAB and it's there. Accept the generated handler name or change it, and then press TAB again to auto-generate the handler stub.</p>\n" }, { "answer_id": 161870, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 5, "selected": false, "text": "<p>Jon really gave a nice solution, I didn't know you could do that!</p>\n\n<p>At times what I resorted to was inheriting from the class and creating its constructors. E.g.</p>\n\n<pre><code>public class FooList : List&lt;Foo&gt; { ... }\n</code></pre>\n\n<p>Not the best solution (unless your assembly gets used by other people), but it works.</p>\n" }, { "answer_id": 161929, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>C# supports some inherited covariance for event delegates, so a method like this:</p>\n\n<pre><code>void LowestCommonHander( object sender, EventArgs e ) { ... } \n</code></pre>\n\n<p>Can be used to subscribe to your event, no explicit cast required </p>\n\n<pre><code>gcInt.MyEvent += LowestCommonHander;\n</code></pre>\n\n<p>You can even use lambda syntax and the intellisense will all be done for you:</p>\n\n<pre><code>gcInt.MyEvent += (sender, e) =&gt;\n{\n e. //you'll get correct intellisense here\n};\n</code></pre>\n" }, { "answer_id": 9401099, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 5, "selected": false, "text": "<p>If you know what you're doing, you can define a class with implicit operators to convert between the alias class and the actual class.</p>\n\n<pre><code>class TypedefString // Example with a string \"typedef\"\n{\n private string Value = \"\";\n public static implicit operator string(TypedefString ts)\n {\n return ((ts == null) ? null : ts.Value);\n }\n public static implicit operator TypedefString(string val)\n {\n return new TypedefString { Value = val };\n }\n}\n</code></pre>\n\n<p>I don't actually endorse this and haven't ever used something like this, but this could probably work for some specific circumstances.</p>\n" }, { "answer_id": 35973121, "author": "Matt Klein", "author_id": 1672027, "author_profile": "https://Stackoverflow.com/users/1672027", "pm_score": 3, "selected": false, "text": "<p>You can use an open source library and NuGet package called <a href=\"https://github.com/mattklein999/LikeType\" rel=\"noreferrer\">LikeType</a> that I created that will give you the <code>GenericClass&lt;int&gt;</code> behavior that you're looking for.</p>\n\n<p>The code would look like:</p>\n\n<pre><code>public class SomeInt : LikeType&lt;int&gt;\n{\n public SomeInt(int value) : base(value) { }\n}\n\n[TestClass]\npublic class HashSetExample\n{\n [TestMethod]\n public void Contains_WhenInstanceAdded_ReturnsTrueWhenTestedWithDifferentInstanceHavingSameValue()\n {\n var myInt = new SomeInt(42);\n var myIntCopy = new SomeInt(42);\n var otherInt = new SomeInt(4111);\n\n Assert.IsTrue(myInt == myIntCopy);\n Assert.IsFalse(myInt.Equals(otherInt));\n\n var mySet = new HashSet&lt;SomeInt&gt;();\n mySet.Add(myInt);\n\n Assert.IsTrue(mySet.Contains(myIntCopy));\n }\n}\n</code></pre>\n" }, { "answer_id": 37242758, "author": "shakram02", "author_id": 4422856, "author_profile": "https://Stackoverflow.com/users/4422856", "pm_score": 2, "selected": false, "text": "<p>Here is the code for it, enjoy!, I picked that up from the dotNetReference\ntype the \"using\" statement inside the namespace line 106\n<strong><a href=\"http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs\" rel=\"nofollow noreferrer\">http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs</a></strong></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nnamespace UsingStatement\n{\n using Typedeffed = System.Int32;\n using TypeDeffed2 = List&lt;string&gt;;\n class Program\n {\n static void Main(string[] args)\n {\n Typedeffed numericVal = 5;\n Console.WriteLine(numericVal++);\n\n TypeDeffed2 things = new TypeDeffed2 { \"whatever\"};\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 49569473, "author": "Aaron Franke", "author_id": 4441547, "author_profile": "https://Stackoverflow.com/users/4441547", "pm_score": 1, "selected": false, "text": "<p>The best alternative to <code>typedef</code> that I've found in C# is <code>using</code>. For example, I can control float precision via compiler flags with this code:</p>\n\n<pre><code>#if REAL_T_IS_DOUBLE\nusing real_t = System.Double;\n#else\nusing real_t = System.Single;\n#endif\n</code></pre>\n\n<p>Unfortunately, it requires that you place this at the top of <strong>every file</strong> where you use <code>real_t</code>. There is currently no way to declare a global namespace type in C#.</p>\n" }, { "answer_id": 51295920, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": 4, "selected": false, "text": "<p>Both C++ and C# are missing easy ways to create a <em>new</em> type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between <code>void f(string connectionID, string username)</code> to <code>void f(ConID connectionID, UserName username)</code> is obvious ...</p>\n<p>(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)</p>\n<p>It may be tempting to use inheritance but that has some major limitations:</p>\n<ul>\n<li>it will not work for primitive types</li>\n<li>the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose</li>\n<li>we cannot derive from sealed classes (and ie many .NET classes are sealed)</li>\n</ul>\n<p>The only way to achieve a similar thing in C# is by composing our type in a new class:</p>\n<pre><code>class SomeType { \n public void Method() { .. }\n}\n\nsealed class SomeTypeTypeDef {\n public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }\n\n private SomeType Composed { get; }\n\n public override string ToString() =&gt; Composed.ToString();\n public override int GetHashCode() =&gt; HashCode.Combine(Composed);\n public override bool Equals(object obj) =&gt; obj is TDerived o &amp;&amp; Composed.Equals(o.Composed); \n public bool Equals(SomeTypeTypeDefo) =&gt; object.Equals(this, o);\n\n // proxy the methods we want\n public void Method() =&gt; Composed.Method();\n}\n</code></pre>\n<p>While this will work it is very verbose for just a typedef.\nIn addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.</p>\n<p>Below is a helper class that uses the &quot;Curiously Recurring Template Pattern&quot; to make this much simpler:</p>\n<pre><code>namespace Typedef {\n\n [JsonConverter(typeof(JsonCompositionConverter))]\n public abstract class Composer&lt;TDerived, T&gt; : IEquatable&lt;TDerived&gt; where TDerived : Composer&lt;TDerived, T&gt; {\n protected Composer(T composed) { this.Composed = composed; }\n protected Composer(TDerived d) { this.Composed = d.Composed; }\n\n protected T Composed { get; }\n\n public override string ToString() =&gt; Composed.ToString();\n public override int GetHashCode() =&gt; HashCode.Combine(Composed);\n public override bool Equals(object obj) =&gt; obj is Composer&lt;TDerived, T&gt; o &amp;&amp; Composed.Equals(o.Composed); \n public bool Equals(TDerived o) =&gt; object.Equals(this, o);\n }\n\n class JsonCompositionConverter : JsonConverter {\n static FieldInfo GetCompositorField(Type t) {\n var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);\n if (fields.Length!=1) throw new JsonSerializationException();\n return fields[0];\n }\n\n public override bool CanConvert(Type t) {\n var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);\n return fields.Length == 1;\n }\n\n // assumes Compositor&lt;T&gt; has either a constructor accepting T or an empty constructor\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {\n while (reader.TokenType == JsonToken.Comment &amp;&amp; reader.Read()) { };\n if (reader.TokenType == JsonToken.Null) return null; \n var compositorField = GetCompositorField(objectType);\n var compositorType = compositorField.FieldType;\n var compositorValue = serializer.Deserialize(reader, compositorType);\n var ctorT = objectType.GetConstructor(new Type[] { compositorType });\n if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);\n var ctorEmpty = objectType.GetConstructor(new Type[] { });\n if (ctorEmpty is null) throw new JsonSerializationException();\n var res = Activator.CreateInstance(objectType);\n compositorField.SetValue(res, compositorValue);\n return res;\n }\n\n public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {\n var compositorField = GetCompositorField(o.GetType());\n var value = compositorField.GetValue(o);\n serializer.Serialize(writer, value);\n }\n }\n\n}\n</code></pre>\n<p>With Composer the above class becomes simply:</p>\n<pre><code>sealed Class SomeTypeTypeDef : Composer&lt;SomeTypeTypeDef, SomeType&gt; {\n public SomeTypeTypeDef(SomeType composed) : base(composed) {}\n\n // proxy the methods we want\n public void Method() =&gt; Composed.Method();\n}\n</code></pre>\n<p>And in addition the <code>SomeTypeTypeDef</code> will serialize to Json in the same way that <code>SomeType</code> does.</p>\n<p>Hope this helps !</p>\n" }, { "answer_id": 58756912, "author": "Vlad Rudenko", "author_id": 901333, "author_profile": "https://Stackoverflow.com/users/901333", "pm_score": 2, "selected": false, "text": "<p>For non-sealed classes simply inherit from them:</p>\n\n<pre><code>public class Vector : List&lt;int&gt; { }\n</code></pre>\n\n<p>But for sealed classes it's possible to simulate typedef behavior with such base class:</p>\n\n<pre><code>public abstract class Typedef&lt;T, TDerived&gt; where TDerived : Typedef&lt;T, TDerived&gt;, new()\n{\n private T _value;\n\n public static implicit operator T(Typedef&lt;T, TDerived&gt; t)\n {\n return t == null ? default : t._value;\n }\n\n public static implicit operator Typedef&lt;T, TDerived&gt;(T t)\n {\n return t == null ? default : new TDerived { _value = t };\n }\n}\n\n// Usage examples\n\nclass CountryCode : Typedef&lt;string, CountryCode&gt; { }\nclass CurrencyCode : Typedef&lt;string, CurrencyCode&gt; { }\nclass Quantity : Typedef&lt;int, Quantity&gt; { }\n\nvoid Main()\n{\n var canadaCode = (CountryCode)\"CA\";\n var canadaCurrency = (CurrencyCode)\"CAD\";\n CountryCode cc = canadaCurrency; // Compilation error\n Concole.WriteLine(canadaCode == \"CA\"); // true\n Concole.WriteLine(canadaCurrency); // CAD\n\n var qty = (Quantity)123;\n Concole.WriteLine(qty); // 123\n}\n</code></pre>\n" }, { "answer_id": 70776413, "author": "JJJ", "author_id": 5547, "author_profile": "https://Stackoverflow.com/users/5547", "pm_score": 3, "selected": false, "text": "<p>With C# 10 you can now do</p>\n<pre><code>global using Bar = Foo\n</code></pre>\n<p>Which works like a typedef within the project.</p>\n<p>I haven't tested it in depth, so there might be quirks.</p>\n<p>I'm using it like</p>\n<pre><code>global using DateTime = DontUseDateTime\n</code></pre>\n<p>Where DontUseDateTime is a struct marked Obsolete, to force people to use NodaTime.</p>\n" }, { "answer_id": 71799159, "author": "OS Freak", "author_id": 13709083, "author_profile": "https://Stackoverflow.com/users/13709083", "pm_score": 2, "selected": false, "text": "<p>I'd do</p>\n<pre><code>using System.Collections.Generic;\nglobal using CustomerList = List&lt;Customer&gt;;\n</code></pre>\n" }, { "answer_id": 74462218, "author": "Rob Vermeulen", "author_id": 150187, "author_profile": "https://Stackoverflow.com/users/150187", "pm_score": 0, "selected": false, "text": "<p>Since the introduction of C# 10.0, we now have the <code>global using</code> directive.</p>\n<pre><code>global using CustomerList = System.Collections.Generic.List&lt;Customer&gt;;\n</code></pre>\n<p>This introduces <code>CustomerList</code> as alias of <code>List&lt;Customer&gt;</code> on a global scope (throughout the whole project and all references to it).</p>\n<p>Though I would have liked to be able to limit its scope (say for instance 'internal using') this does actually do a terrific job of fulfilling a typedef variant in C#.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following: ``` class GenericClass<T> { public event EventHandler<EventData> MyEvent; public class EventData : EventArgs { /* snip */ } // ... snip } ``` Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this: ``` GenericClass<int> gcInt = new GenericClass<int>; gcInt.MyEvent += new EventHandler<GenericClass<int>.EventData>(gcInt_MyEvent); // ... private void gcInt_MyEvent(object sender, GenericClass<int>.EventData e) { throw new NotImplementedException(); } ``` Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little... Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.
No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g. ``` using CustomerList = System.Collections.Generic.List<Customer>; ``` but that will only impact that source file. In C and C++, my experience is that `typedef` is usually used within .h files which are included widely - so a single `typedef` can be used over a whole project. That ability does not exist in C#, because there's no `#include` functionality in C# that would allow you to include the `using` directives from one file in another. Fortunately, the example you give *does* have a fix - implicit method group conversion. You can change your event subscription line to just: ``` gcInt.MyEvent += gcInt_MyEvent; ``` :)
161,485
<p>How should I configure the class to bind three dropdowns (date, month, year) to a single Date property so that it works the way it works for 'single request parameter per property' scenario ? I guess a should add some custom PropertyEditors by overriding initBinder method. What else ?</p>
[ { "answer_id": 161514, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 1, "selected": false, "text": "<p>You could create a hidden input in your form and populate it using JavaScript when user selects date, then bind to this input in your command object. </p>\n\n<p>Probably you will be using javascript anyway for things like checking correctness of the date, so why not format the ready to use date in one parameter.</p>\n\n<p>Then you need to register a property editor that would convert from string \"2008-05-20\" to Date object.</p>\n" }, { "answer_id": 165952, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 0, "selected": false, "text": "<p>then i would have three fields in my command object - year, month, day and would use standard spring validation for date checking</p>\n" }, { "answer_id": 173783, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 3, "selected": true, "text": "<p>Aleksey Kudryavtsev: you can override the onBind method in your controller, i which you cant fiddle something special in command object, like </p>\n\n<pre><code>dateField = new SimpleFormat(\"YYYY-mm-dd\").parse(this.year + \"-\" + this.month + \"-\" this.day);\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>Calendar c = Calendar.getInstance();\nc.set(year, month, day);\ndateField = calendar.getTime();\n</code></pre>\n\n<p>but i'd rather do validation in javascript and use some available date picker component, there are plenty of them...</p>\n" }, { "answer_id": 5966547, "author": "Simon Gibbs", "author_id": 13935, "author_profile": "https://Stackoverflow.com/users/13935", "pm_score": 0, "selected": false, "text": "<p>I haven't tried it, but you could try binding to <a href=\"http://www.jarvana.com/jarvana/view/joda-time/joda-time/1.6.1/joda-time-1.6.1.jar!/org/joda/time/MutableDateTime.class?classDetails=ok\" rel=\"nofollow\">MutableDateTime in the Joda library</a>. It has separate setters and getters for all three fields.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
How should I configure the class to bind three dropdowns (date, month, year) to a single Date property so that it works the way it works for 'single request parameter per property' scenario ? I guess a should add some custom PropertyEditors by overriding initBinder method. What else ?
Aleksey Kudryavtsev: you can override the onBind method in your controller, i which you cant fiddle something special in command object, like ``` dateField = new SimpleFormat("YYYY-mm-dd").parse(this.year + "-" + this.month + "-" this.day); ``` or: ``` Calendar c = Calendar.getInstance(); c.set(year, month, day); dateField = calendar.getTime(); ``` but i'd rather do validation in javascript and use some available date picker component, there are plenty of them...
161,486
<p>I developing ASP.NET application using a Swedish version of Windows XP and Visual studio Professional. When ever i get an error aka. "yellow screen of death" the error message is in swedish, making it a bit hard to search for info about it.</p> <p>How can i change what language the error messages in ASP.NET uses?</p> <p>I have no language pack installed for the .net framework. I am however running an english windows xp with a swedish language interface pack on it.</p> <p>I also have this in my web.config:</p> <pre><code>&lt;system.web&gt; &lt;globalization uiCulture="en-US" /&gt; &lt;/system.web&gt; </code></pre>
[ { "answer_id": 161496, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 1, "selected": true, "text": "<p>Aren't the error messages dependent on the installed .NET Framework? I.e. you could just uninstall the Swedish language pack for .NET. On the production server, you'll most likely have an English-only Framework anyway.</p>\n" }, { "answer_id": 161503, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 6, "selected": false, "text": "<p>In web.config add:</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;globalization uiCulture=\"en-US\" /&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>or whatever language you prefer (note: uiCulture=\"en-US\" not culture=\"en-US\").</p>\n\n<p>Also you should check that your app is not changing the uiCulture, for example to a user-specific uiCulture in global.asax.</p>\n\n<p>If the error occurs before or during processing the web.config file, this will of course make no difference. In this case, you need to change the regional settings of the account under which the ASP.NET app is running.</p>\n\n<p>If you are developing with VS2005 or later, you're probably running under the Cassini web server, under the identity of the current user - so just change the current user's settings. If you're using IIS, you probably want to change the regional settings of the ASPNET account - you can do this from Regional Settings in the Control Panel by checking the checkbox \"Apply to current user and to the default user profile\". </p>\n" }, { "answer_id": 6582989, "author": "Arek Bee", "author_id": 664252, "author_profile": "https://Stackoverflow.com/users/664252", "pm_score": 2, "selected": false, "text": "<p>You can find your error translated into English on <a href=\"http://finderr.net/search\" rel=\"nofollow\">finderr.net</a> </p>\n\n<p>or</p>\n\n<p>The second solution to this problem is to move, delete or rename a file containing translations of exceptions. These translations are in file:</p>\n\n<blockquote>\n <p>%windir%\\assembly\\mscorlib.resources.dll { version: 2.0.0.0 culture: sv token: b77a5c561934e089}</p>\n</blockquote>\n\n<p>After the change you have to restart .NET framework. \nImportant information: Do it on your own risk and I do not know what are the side effects to this solution. </p>\n" }, { "answer_id": 32086852, "author": "Guru Dile", "author_id": 941415, "author_profile": "https://Stackoverflow.com/users/941415", "pm_score": 4, "selected": false, "text": "<p>I had the same issue recently on IIS version 10 and these steps fixed it.</p>\n\n<ol>\n<li>Open IIS Manager </li>\n<li>Select the server from the Connections panel</li>\n<li>Under the \"ASP.NET\" double click on \".NET Globalization\" </li>\n<li>Edit \"<strong>UI Culture</strong>\" property </li>\n<li>Optionally set the \"File\" property to \"utf-8\"</li>\n<li>Finally click \"Apply\" and restart the server.</li>\n</ol>\n" }, { "answer_id": 50155993, "author": "Djensen", "author_id": 1016987, "author_profile": "https://Stackoverflow.com/users/1016987", "pm_score": 2, "selected": false, "text": "<p>I had this problem aswell. I had given up, untill I today gave it another try, that worked;</p>\n\n<blockquote>\n <p>Open <strong>CMD</strong> as administrator, and then type \"<strong>LPKSETUP</strong>\" and hit enter, and then uninstall the language that is causing the issue.</p>\n</blockquote>\n\n<p>All credit goes to <strong>spunk.funk</strong> (<a href=\"https://www.techsupportforum.com/forums/f217/solved-cant-uninstall-language-packs-554970.html\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<p>This worked for me. \nAnd it seems that the timezone and localized keyboard still works, which is the only localized things I want.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368/" ]
I developing ASP.NET application using a Swedish version of Windows XP and Visual studio Professional. When ever i get an error aka. "yellow screen of death" the error message is in swedish, making it a bit hard to search for info about it. How can i change what language the error messages in ASP.NET uses? I have no language pack installed for the .net framework. I am however running an english windows xp with a swedish language interface pack on it. I also have this in my web.config: ``` <system.web> <globalization uiCulture="en-US" /> </system.web> ```
Aren't the error messages dependent on the installed .NET Framework? I.e. you could just uninstall the Swedish language pack for .NET. On the production server, you'll most likely have an English-only Framework anyway.
161,490
<p>I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes.</p> <p>I've come across an unusual problem. This bit of code is the same in both systems:</p> <pre><code>// ... CCommsProperties props; pController-&gt;GetProperties( props ); if (props.handshake != HANDSHAKE_RTS_CTS) { props.handshake = HANDSHAKE_RTS_CTS; pController-&gt;RefreshCommProperties( props ); } // ... in another file: void CControllerSI::RefreshCommProperties ( const CCommsProperties&amp; props ) { // ... code ... } </code></pre> <p>CommProperties is a wrapper for the comm settings, serialization of etc. and pController is of type ControllerSI which itself is a layer between the actual Comms and the Application.</p> <p>On the original MFC version the setting of handshake to RTS-CTS sticks but when running as the DLL version it resets itself to 0 as soon as the function is entered. The code is contained entirely in the DLL section of the code, so there are no boundaries.</p> <p>The main differences between the original and the new modules is the variables that call the various dialogs have been removed and the removed #includes</p> <p>I've lost an afternoon to this and I don't really want to lose any more...</p>
[ { "answer_id": 161564, "author": "user22044", "author_id": 22044, "author_profile": "https://Stackoverflow.com/users/22044", "pm_score": 1, "selected": false, "text": "<p>It is difficult to see what is wrong from the given code alone. Some general pointers:</p>\n\n<ol>\n<li><p>The object is initialized and processed in different binary modules with incompatible linking (such as C-run times)</p></li>\n<li><p>If the class/structure is shared it is not exported/imported correctly.</p></li>\n<li><p>The class(s) are defined in more than one place, and you are not including the correct definitions.</p></li>\n</ol>\n\n<p>The above three are the most likely causes, especially, if all fields are reset to their default initialized values.</p>\n\n<p>if this is only happening with only one or two fields, the structure may be poorly aligned and you may need to rearrange the fields to correct these (check that in release too).</p>\n\n<p>In general, I am tempted to hypothesize that the object you have intialized is not the one <code>RefreshCommProperties()</code> sees, for some reason, may be one of the three above.</p>\n" }, { "answer_id": 161736, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>To really figure out what is going on, you probably need to post your source code -- or at least as much to replicate the problem. Unfortunately, StackOverflow doesn't seem like it encourages this. You could post your code on an FTP site or go to a site that allows posting of source code (like CodeGuru).</p>\n" }, { "answer_id": 161887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's possible that CCommsProperties are defined in two different places, and each file includes its own version.</p>\n\n<p>To test this theory, in the debugger you need to look at &amp;props.handshake . If debugger tells you that the field has different address inside and outside the function, then the hypothesis is true and you can proceed to examining preprocessor output to figure out why it happens.</p>\n" }, { "answer_id": 162503, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": true, "text": "<p>After Saratv posting, I decided to ditch what I had done and restart it from working source again.</p>\n\n<p>This time however it works...I guess I will never know why passing a structure caused it to change.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes. I've come across an unusual problem. This bit of code is the same in both systems: ``` // ... CCommsProperties props; pController->GetProperties( props ); if (props.handshake != HANDSHAKE_RTS_CTS) { props.handshake = HANDSHAKE_RTS_CTS; pController->RefreshCommProperties( props ); } // ... in another file: void CControllerSI::RefreshCommProperties ( const CCommsProperties& props ) { // ... code ... } ``` CommProperties is a wrapper for the comm settings, serialization of etc. and pController is of type ControllerSI which itself is a layer between the actual Comms and the Application. On the original MFC version the setting of handshake to RTS-CTS sticks but when running as the DLL version it resets itself to 0 as soon as the function is entered. The code is contained entirely in the DLL section of the code, so there are no boundaries. The main differences between the original and the new modules is the variables that call the various dialogs have been removed and the removed #includes I've lost an afternoon to this and I don't really want to lose any more...
After Saratv posting, I decided to ditch what I had done and restart it from working source again. This time however it works...I guess I will never know why passing a structure caused it to change.
161,510
<p>In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s '<strong>ref</strong>' keyword.</p> <p>Example:</p> <pre><code>def func(x) x += 1 end a = 5 func(a) #this should be something like func(ref a) puts a #should read '6' </code></pre> <p>Btw. I know I could just use:</p> <pre><code>a = func(a) </code></pre>
[ { "answer_id": 161589, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 4, "selected": false, "text": "<p>Ruby doesn't support \"pass by reference\" at all. Everything is an object and the references to those objects are always passed by value. Actually, in your example you are passing a copy of the reference to the <code>Fixnum</code> Object by value.</p>\n\n<p>The problem with the your code is, that <code>x += 1</code> doesn't modify the passed <code>Fixnum</code> Object but instead creates a completely new and independent object.</p>\n\n<p>I think, Java programmers would call <code>Fixnum</code> objects <strong>immutable</strong>. </p>\n" }, { "answer_id": 161607, "author": "jmah", "author_id": 3948, "author_profile": "https://Stackoverflow.com/users/3948", "pm_score": 6, "selected": true, "text": "<p>You can accomplish this by explicitly passing in the current binding:</p>\n\n<pre><code>def func(x, bdg)\n eval \"#{x} += 1\", bdg\nend\n\na = 5\nfunc(:a, binding)\nputs a # =&gt; 6\n</code></pre>\n" }, { "answer_id": 161634, "author": "muesan", "author_id": 22154, "author_profile": "https://Stackoverflow.com/users/22154", "pm_score": 4, "selected": false, "text": "<p>In Ruby you can't pass parameters by reference. For your example, you would have to return the new value and assign it to the variable a or create a new class that contains the value and pass an instance of this class around. Example:</p>\n\n<pre><code>class Container\nattr_accessor :value\n def initialize value\n @value = value\n end\nend\n\ndef func(x)\n x.value += 1\nend\n\na = Container.new(5)\nfunc(a)\nputs a.value\n</code></pre>\n" }, { "answer_id": 28804261, "author": "Ivan Gusev", "author_id": 1147597, "author_profile": "https://Stackoverflow.com/users/1147597", "pm_score": 3, "selected": false, "text": "<p>You can try following trick:</p>\n\n<pre><code>def func(x) \n x[0] += 1\nend\n\na = [5]\nfunc(a) #this should be something like func(ref a)\nputs a[0] #should read '6'\n</code></pre>\n" }, { "answer_id": 35740384, "author": "Sam Liao", "author_id": 75501, "author_profile": "https://Stackoverflow.com/users/75501", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://ruby-doc.org/core-2.1.5/Fixnum.html\" rel=\"nofollow noreferrer\">http://ruby-doc.org/core-2.1.5/Fixnum.html</a></p>\n\n<blockquote>\n <p>Fixnum objects have immediate value. This means that when they are assigned or\n passed as parameters, the actual object is passed, rather than a reference to\n that object.</p>\n</blockquote>\n\n<p>Also <a href=\"https://stackoverflow.com/questions/22827566/ruby-parameters-by-reference-or-by-value/22827949#22827949\">Ruby is pass by value</a>.</p>\n" }, { "answer_id": 56168196, "author": "Ivan Cenov", "author_id": 2635665, "author_profile": "https://Stackoverflow.com/users/2635665", "pm_score": -1, "selected": false, "text": "<p>However, it seems that composite objects, like hashes, are passed by reference:</p>\n\n<pre><code>fp = {}\ndef changeit(par)\n par[:abc] = 'cde'\nend\n\nchangeit(fp)\n\np fp\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>{:abc=&gt;\"cde\"}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s '**ref**' keyword. Example: ``` def func(x) x += 1 end a = 5 func(a) #this should be something like func(ref a) puts a #should read '6' ``` Btw. I know I could just use: ``` a = func(a) ```
You can accomplish this by explicitly passing in the current binding: ``` def func(x, bdg) eval "#{x} += 1", bdg end a = 5 func(:a, binding) puts a # => 6 ```
161,519
<p>I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (&lt;b&gt;, &lt;i&gt;, etc.). Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?</p>
[ { "answer_id": 161699, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "<p>AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse <code>&lt;b&gt;, &lt;i&gt;, &lt;a&gt; and &lt;p&gt;,</code> for example. All other tags would have to be ignored.</p>\n" }, { "answer_id": 163511, "author": "Jonathan Yee", "author_id": 16320, "author_profile": "https://Stackoverflow.com/users/16320", "pm_score": 4, "selected": false, "text": "<p>Here's a link to add HTML to the clipboard using VB:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/274326\" rel=\"noreferrer\">http://support.microsoft.com/kb/274326</a></p>\n\n<p>Once you have the HTML on the clipboard, paste it into your word doc using something like this:</p>\n\n<pre><code>ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML\n</code></pre>\n\n<p>This is pretty much the equivalent of you cutting and pasting it in manually. </p>\n" }, { "answer_id": 30892682, "author": "Adz", "author_id": 4238727, "author_profile": "https://Stackoverflow.com/users/4238727", "pm_score": 2, "selected": false, "text": "<p>Use InsertFile</p>\n\n<pre><code>Set objdoc = objInsp.WordEditor\nSet objword = objdoc.Application\nSet objsel = objword.Selection\nobjsel.WholeStory\nvs_html = \"&lt;html&gt;&lt;body&gt;\" + vs_body + \"&lt;/body&gt;&lt;/html&gt;\"\nvs_file = \"C:\\temp\\1.html\"\nCall DumptoFile(vs_file, \"\", vs_html, False)\nRetVal = objsel.InsertFile(vs_file, , , False, False)\n</code></pre>\n" }, { "answer_id": 55554812, "author": "Michael", "author_id": 7595371, "author_profile": "https://Stackoverflow.com/users/7595371", "pm_score": 1, "selected": false, "text": "<p>I'm using 2016. The only thing that worked was Range.InsertFile(path). Pasting Special didn't work.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.). Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?
Here's a link to add HTML to the clipboard using VB: <http://support.microsoft.com/kb/274326> Once you have the HTML on the clipboard, paste it into your word doc using something like this: ``` ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML ``` This is pretty much the equivalent of you cutting and pasting it in manually.
161,524
<p>I'm writing a query for an application that needs to list all the products with the number of times they have been purchased.</p> <p>I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM's, But in this case a query is a much more elegant solution.</p> <p>Can you spot anything wrong (approach wise) with the query?</p> <hr> <pre><code>SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN ( SELECT * FROM orderitems INNER JOIN orders ON orderitems.order_id = orders.id AND orders.paid = 1 ) AS oi ON oi.product_id = products.id GROUP BY products.id </code></pre> <hr> <p>The schema (with relevant fields) looks like this:</p> <pre><code>*orders* id, paid *orderitems* order_id, product_id *products* id </code></pre> <h2>UPDATE</h2> <p>This is for MySQL</p>
[ { "answer_id": 161533, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>Does it give you the right answer?</p>\n\n<p>Except for just modifying it to get rid of the SELECT in the inner query, I don't see anything wrong with it.</p>\n" }, { "answer_id": 161554, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 0, "selected": false, "text": "<p>Well you have \"LEFT OUTER JOIN\" that can be a performance issue depending on your Database.\nLast time I remember it caused hell on MySQL, and it doesn't exist in SQLite. I think Oracle can handle it ok, and I guess DB and MSSQL too.</p>\n\n<p>EDIT: If I remember correctly LEFT OUTER JOIN can be orders of magnitude slower on MySQL, but please correct me if I'm outdated here :)</p>\n" }, { "answer_id": 161555, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Untested code, but try it:</p>\n\n<pre><code>SELECT products.id,\n MIN(products.long_name) AS name, \n count(oi.order_id) AS sold\nFROM (products\nLEFT OUTER JOIN orderitemss AS oi ON oi.product_id = products.id)\nINNER JOIN orders AS o ON oi.order_id = o.id \nWHERE orders.paid = 1\nGROUP BY products.id\n</code></pre>\n\n<p>I don't know if the parentheses are needed for the LEFT OUTER JOIN, neither if MySQL allows multiple joins, however the MIN(products.long_name) gives just the description, since for every products.id you have only one description.</p>\n\n<p>Perhaps the parentheses need to be around the INNER JOIN.</p>\n" }, { "answer_id": 161569, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 3, "selected": true, "text": "<p>I'm not sure about the \"(SELECT *\" ... business.</p>\n\n<p>This executes (always a good start) and I think is equivalent to what was posted.</p>\n\n<pre><code>SELECT products.id, \n products.long_name AS name, \n count(oi.order_id) AS sold\nFROM products\nLEFT OUTER JOIN\n orderitems AS oi\n INNER JOIN \n orders \n ON oi.order_id = orders.id AND orders.paid = 1\n ON oi.product_id = products.id\nGROUP BY products.id\n</code></pre>\n" }, { "answer_id": 162165, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 2, "selected": false, "text": "<p>Here a solution for those of us who are nesting impaired. (I get so confused when I start nesting joins)</p>\n\n<pre><code>SELECT products.id, \n products.long_name AS name, \n count(oi.order_id) AS sold\nFROM orders \n INNER JOIN orderitems AS oi ON oi.order_id = orders.id AND orders.paid = 1\n RIGHT JOIN products ON oi.product_id = products.id\nGROUP BY products.id\n</code></pre>\n\n<p>However, I tested your solution, Mike's and mine on MS SQL Server and the query plans are identical. I can't speak for MySql but if MS SQL Server is anything to go by, you may find the performance of all three solutions equivalent. If that is the case I guess you pick which solution is clearest to you.</p>\n" }, { "answer_id": 168024, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Here's a subquery form.</p>\n\n<pre><code>SELECT\n p.id,\n p.long_name AS name,\n (SELECT COUNT(*) FROM OrderItems oi WHERE oi.order_id in\n (SELECT o.id FROM Orders o WHERE o.Paid = 1 AND o.Product_id = p.id)\n ) as sold\nFROM Products p\n</code></pre>\n\n<p>It should perform roughly equivalent to the join form. If it doesn't, let me know.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1877/" ]
I'm writing a query for an application that needs to list all the products with the number of times they have been purchased. I came up with this and it works, but I am not too sure how optimized it is. My SQL is really rusty due to my heavy usage of ORM's, But in this case a query is a much more elegant solution. Can you spot anything wrong (approach wise) with the query? --- ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN ( SELECT * FROM orderitems INNER JOIN orders ON orderitems.order_id = orders.id AND orders.paid = 1 ) AS oi ON oi.product_id = products.id GROUP BY products.id ``` --- The schema (with relevant fields) looks like this: ``` *orders* id, paid *orderitems* order_id, product_id *products* id ``` UPDATE ------ This is for MySQL
I'm not sure about the "(SELECT \*" ... business. This executes (always a good start) and I think is equivalent to what was posted. ``` SELECT products.id, products.long_name AS name, count(oi.order_id) AS sold FROM products LEFT OUTER JOIN orderitems AS oi INNER JOIN orders ON oi.order_id = orders.id AND orders.paid = 1 ON oi.product_id = products.id GROUP BY products.id ```
161,531
<p>This seems to be a common problem but I cannot find a solution.</p> <p>I type in my username and password which are in a login control I have created. I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event.</p> <p>If I press the submit button then everything works fine.</p>
[ { "answer_id": 161547, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "<p>Pressing ENTER on a text input executes <strong>Form.onsubmit</strong>, not <strong>Button.onclick</strong>.</p>\n\n<p>I suppose this was inspired by the fact that you can have a form without an actual submit button (depending solely on the use of ENTER).</p>\n" }, { "answer_id": 161560, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>If you're using ASP.NET 2.0 or higher, you can set a default button attribute for your page's Form:</p>\n\n<pre><code>&lt;form runat=\"server\" DefaultButton=\"SubmitButton\"&gt;\n</code></pre>\n" }, { "answer_id": 161768, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 3, "selected": true, "text": "<p>using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML.</p>\n\n<p>so you do as Jon said above:</p>\n\n<pre><code>&lt;form runat=\"server\" DefaultButton=\"SubmitButton\"&gt;\n</code></pre>\n\n<p>But ensure you use the Button name that will be rendered.\nYou can achieve this my making the Button public in your control, or a method that will return it's ClientId.</p>\n\n<p>Let's say your button is called btnSubmit, and your implementation of your control ucLogin.</p>\n\n<p>Give your form an id</p>\n\n<pre><code>&lt;form runat=\"server\" id=\"form1\"&gt;\n</code></pre>\n\n<p>Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n form1.DefaultButton = ucLogin.btnSubmit.ClientID;\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469/" ]
This seems to be a common problem but I cannot find a solution. I type in my username and password which are in a login control I have created. I then press enter once I've typed in my password and the page just refreshes. It triggers the page load event but not the button on click event. If I press the submit button then everything works fine.
using your forms default button is correct, but you need to supply it the correct id as it will be rendered to HTML. so you do as Jon said above: ``` <form runat="server" DefaultButton="SubmitButton"> ``` But ensure you use the Button name that will be rendered. You can achieve this my making the Button public in your control, or a method that will return it's ClientId. Let's say your button is called btnSubmit, and your implementation of your control ucLogin. Give your form an id ``` <form runat="server" id="form1"> ``` Then in your page load in your code behind of your page, set the DefaultButton by handing it your button client id. ``` protected void Page_Load(object sender, EventArgs e) { form1.DefaultButton = ucLogin.btnSubmit.ClientID; } ```
161,539
<p>Imagine the following Ruby Module:</p> <pre><code>module Foo def inst_method puts "Called Foo.inst_method" end def self.class_method puts "Called Foo.class_method" end end </code></pre> <p>Obviously <code>Foo.class_method</code> can be called without any class instances. However, what's happening to <code>Foo.inst_method</code>? Is it possible to call <code>Foo.inst_method</code> without previously including/extending a class?</p> <p>Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system.</p>
[ { "answer_id": 161618, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>My answer would be : \"no you can't call module instance methods without first extending or including that module in a class\" </p>\n\n<p>now knowing ruby and all the meta programming trickery it contains there probably <em>is</em> a way to call it but it would be outside the intended use of modules</p>\n\n<pre><code>module Tester\n def inst_meth\n puts \"test inst meth\\n\"\n end\n\n def self.meth\n puts \"test self meth\\n\"\n end\nend\n\nbegin\n Tester.meth\nrescue;\n puts $!\nend\nbegin\n Tester.inst_meth\nrescue\n puts $!\nend\nbegin\n Tester.new.inst_meth\nrescue\n puts $!\nend\nbegin\n extend Tester\n inst_meth\nrescue\n puts $!\nend\nbegin\n include Tester\n inst_meth\nrescue\n puts $!\nend\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>&gt;ruby test.rb\ntest self meth\nundefined method `inst_meth' for Tester:Module\nundefined method `new' for Tester:Module\n test inst meth\n test inst meth\n</code></pre>\n" }, { "answer_id": 162639, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 5, "selected": true, "text": "<p>The primary purpose of instance methods within modules is to give that functionality to classes that include it.</p>\n\n<p>\"Mixing in\" a module this way is most commonly used as a method of simulating <a href=\"http://en.wikipedia.org/wiki/Multiple_inheritance\" rel=\"noreferrer\">multiple inheritance</a>, or in other situations where inheritance is not the right paradigm (not quite a perfect \"is a\" relationship) but you want to share behavior. It's one more tool to keep your code <a href=\"http://en.wikipedia.org/wiki/DRY\" rel=\"noreferrer\">DRY</a>.</p>\n\n<p>A good example of this in core Ruby is noting how <a href=\"http://ruby-doc.org/core/classes/Array.html\" rel=\"noreferrer\"><code>Array</code></a> and <a href=\"http://ruby-doc.org/core/classes/Hash.html\" rel=\"noreferrer\"><code>Hash</code></a> can both be traveled and sorted, etc. They each get this functionality from the <a href=\"http://ruby-doc.org/core/classes/Enumerable.html\" rel=\"noreferrer\"><code>Enumerable</code></a> module (<code>each_with_index</code>, <code>select</code>, <code>reject</code>, <code>sort</code> and more are all defined in the included module, not in the classes).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
Imagine the following Ruby Module: ``` module Foo def inst_method puts "Called Foo.inst_method" end def self.class_method puts "Called Foo.class_method" end end ``` Obviously `Foo.class_method` can be called without any class instances. However, what's happening to `Foo.inst_method`? Is it possible to call `Foo.inst_method` without previously including/extending a class? Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system.
The primary purpose of instance methods within modules is to give that functionality to classes that include it. "Mixing in" a module this way is most commonly used as a method of simulating [multiple inheritance](http://en.wikipedia.org/wiki/Multiple_inheritance), or in other situations where inheritance is not the right paradigm (not quite a perfect "is a" relationship) but you want to share behavior. It's one more tool to keep your code [DRY](http://en.wikipedia.org/wiki/DRY). A good example of this in core Ruby is noting how [`Array`](http://ruby-doc.org/core/classes/Array.html) and [`Hash`](http://ruby-doc.org/core/classes/Hash.html) can both be traveled and sorted, etc. They each get this functionality from the [`Enumerable`](http://ruby-doc.org/core/classes/Enumerable.html) module (`each_with_index`, `select`, `reject`, `sort` and more are all defined in the included module, not in the classes).
161,549
<p>I recently had to rename a table (and a column and FK/PK contraints) in SQL Server 2000 without losing an data. There did not seem to be an obvious DDL T-SQL statements for performing this action, so I used sp_rename to directly fiddle with object names.</p> <p>Was this the only solution to the problem? (other, than give the table the correct name in the first place - doh!)</p>
[ { "answer_id": 161557, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>sp_rename is the correct way to do it.</p>\n\n<pre><code>EXEC sp_rename 'Old_TableName', 'New_TableName'\n</code></pre>\n" }, { "answer_id": 161567, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 0, "selected": false, "text": "<p>Maybe not the only: I guess you could always toy with the master database and update the table name there - but this is highly unrecommendable.</p>\n" }, { "answer_id": 161628, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "<p>There is a solution that can let you work concurrently with both old and new versions of the table. This is particularly important if your data is replicated and/or is accessed through client interface (meaning old versions of the client interface will still work with the old table name):</p>\n\n<ol>\n<li>Modify the constraints (including FKs) on your table through \"<code>ALTER TABLE</code>\" command</li>\n<li><p>Do not change table name or\nfield name but create a view such\nas:</p>\n\n<p><code>SELECT oldTable.oldField1 as newField1, ...</code></p>\n\n<p>save it as newTable (and, if requested, distribute it on your different servers)</p></li>\n</ol>\n\n<hr>\n\n<p>Note that you cannot modify your PK this way.</p>\n" }, { "answer_id": 3043579, "author": "Prageeth godage", "author_id": 366528, "author_profile": "https://Stackoverflow.com/users/366528", "pm_score": 2, "selected": false, "text": "<p>Ya<br>\nEXEC sp_rename 'Old_TableName', 'New_TableName' \nwork fine but are any key word like \n\"alter tabel old_name to new_name \"</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23497/" ]
I recently had to rename a table (and a column and FK/PK contraints) in SQL Server 2000 without losing an data. There did not seem to be an obvious DDL T-SQL statements for performing this action, so I used sp\_rename to directly fiddle with object names. Was this the only solution to the problem? (other, than give the table the correct name in the first place - doh!)
sp\_rename is the correct way to do it. ``` EXEC sp_rename 'Old_TableName', 'New_TableName' ```
161,556
<p>I've got a Method that gets a IDictionary as a parameter. Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant.</p> <p>So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this:</p> <pre><code>private static IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt; ConvertKeysToLowerCase( IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt; dictionaries) { IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt; resultingConvertedDictionaries = new Dictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt;(); foreach(ILanguage keyLanguage in dictionaries.Keys) { IDictionary&lt;string, string&gt; convertedDictionatry = new Dictionary&lt;string, string&gt;(); foreach(string key in dictionaries[keyLanguage].Keys) { convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]); } resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry); } return resultingConvertedDictionaries; } </code></pre> <p>Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing?</p>
[ { "answer_id": 161565, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Yes - pass the Dictionary constructor <code>StringComparer.OrdinalIgnoreCase</code> (or another case-ignoring comparer, depending on your culture-sensitivity needs).</p>\n" }, { "answer_id": 161608, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "<p>You could use the <strong>var</strong> keyword to remove some clutter. Technically the source remains the same. Also I would just pass and return a Dictionary&lt;string, string&gt; because you're not doing anything with that ILanguage parameter and make the method more reusable:</p>\n\n<pre><code>private static IDictionary&lt;string, string&gt; ConvertKeysToLowerCase(\n IDictionary&lt;string, string&gt; dictionaries)\n{\n var convertedDictionatry = new Dictionary&lt;string, string&gt;();\n foreach(string key in dictionaries.Keys)\n {\n convertedDictionatry.Add(key.ToLower(), dictionaries[key]);\n }\n return convertedDictionatry;\n}\n</code></pre>\n\n<p>... and call it like so:</p>\n\n<pre><code>// myLanguageDictionaries is of type IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt;\nforeach (var dictionary in myLanguageDictionaries.Keys)\n{\n myLanguageDictionaries[dictionary].Value = \n ConvertKeysToLowerCase(myLanguageDictionaries[dictionary].Value);\n}\n</code></pre>\n" }, { "answer_id": 161877, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 1, "selected": false, "text": "<p>You could inherit from IDictionary yourself, and simply marshal calls to an internal Dictionary instance.</p>\n\n<pre><code>Add(string key, string value) { dictionary.Add(key.ToLowerInvariant(), value) ; }\npublic string this[string key]\n{\n get { return dictionary[key.ToLowerInvariant()]; }\n set { dictionary[key.ToLowerInvariant()] = value; }\n}\n// And so forth.\n</code></pre>\n" }, { "answer_id": 161920, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": -1, "selected": false, "text": "<p>LINQ version using the <code>IEnumerable&lt;T&gt;</code> extension methods:</p>\n\n<pre><code>\n private static IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt; ConvertKeysToLowerCase(\n IDictionary&lt;ILanguage, IDictionary&lt;string, string&gt;&gt; dictionaries)\n {\n return dictionaries.ToDictionary(\n x => x.Key, v => CloneWithComparer(v.Value, StringComparer.OrdinalIgnoreCase));\n }\n\n static IDictionary&lt;K, V&gt; CloneWithComparer&lt;K,V&gt;(IDictionary&lt;K, V&gt; original, IEqualityComparer&lt;K&gt; comparer)\n {\n return original.ToDictionary(x => x.Key, x => x.Value, comparer);\n }\n</code></pre>\n" }, { "answer_id": 207294, "author": "GregUzelac", "author_id": 27068, "author_profile": "https://Stackoverflow.com/users/27068", "pm_score": 1, "selected": false, "text": "<p>System.Collections.Specialized.StringDictionary() may help. MSDN states:</p>\n\n<p>\"The key is handled in a case-insensitive manner; it is translated to lowercase before it is used with the string dictionary.</p>\n\n<p>In .NET Framework version 1.0, this class uses culture-sensitive string comparisons. However, in .NET Framework version 1.1 and later, this class uses CultureInfo.InvariantCulture when comparing strings. For more information about how culture affects comparisons and sorting, see Comparing and Sorting Data for a Specific Culture and Performing Culture-Insensitive String Operations.\"</p>\n" }, { "answer_id": 528437, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>By using a StringDictionary the keys are converted to lower case at creating time.</p>\n\n<p><a href=\"http://simiansoftware.blogspot.com/2008/11/have-const-string-with-ui-description.html\" rel=\"nofollow noreferrer\">http://simiansoftware.blogspot.com/2008/11/have-const-string-with-ui-description.html</a></p>\n" }, { "answer_id": 60415940, "author": "ANJYR", "author_id": 2126088, "author_profile": "https://Stackoverflow.com/users/2126088", "pm_score": 0, "selected": false, "text": "<p>You can also try this way</p>\n\n<pre><code>convertedDictionatry = convertedDictionatry .ToDictionary(k =&gt; k.Key.ToLower(), k =&gt; k.Value.ToLower());\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
I've got a Method that gets a IDictionary as a parameter. Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant. So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this: ``` private static IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase( IDictionary<ILanguage, IDictionary<string, string>> dictionaries) { IDictionary<ILanguage, IDictionary<string, string>> resultingConvertedDictionaries = new Dictionary<ILanguage, IDictionary<string, string>>(); foreach(ILanguage keyLanguage in dictionaries.Keys) { IDictionary<string, string> convertedDictionatry = new Dictionary<string, string>(); foreach(string key in dictionaries[keyLanguage].Keys) { convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]); } resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry); } return resultingConvertedDictionaries; } ``` Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing?
Yes - pass the Dictionary constructor `StringComparer.OrdinalIgnoreCase` (or another case-ignoring comparer, depending on your culture-sensitivity needs).
161,614
<p>I need to get the Class of an object at runtime.</p> <p>For an non-abstract class I could do something like:</p> <pre><code>public class MyNoneAbstract{ public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass(); </code></pre> <p>But for an abstract class this does NOT work (always gives me <code>Object</code>)</p> <pre><code>public abstract class MyAbstract{ public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass(); </code></pre> <p>This code will be running in JavaME environments.</p>
[ { "answer_id": 161625, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 3, "selected": true, "text": "<p>You just need</p>\n\n<pre><code>MyAbstract.class\n</code></pre>\n\n<p>That expression returns the Class object representing MyAbstract.</p>\n" }, { "answer_id": 162340, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 0, "selected": false, "text": "<p>The code you want in the abstract case is:</p>\n\n<pre><code>public abstract class MyAbstract{\n public static Class MYABSTRACT_CLASS = MyAbstract.class;\n}\n</code></pre>\n\n<p>although I personally wouldn't bother defining the constant and just used MyAbstract.class throughout.</p>\n\n<p>I would have expected the code you wrote to have returned the class 'Class', not the class 'Object'.</p>\n" }, { "answer_id": 166954, "author": "michael aubert", "author_id": 17867, "author_profile": "https://Stackoverflow.com/users/17867", "pm_score": 0, "selected": false, "text": "<p>I think more information is required here.\nIn Java, an abstract class cannot be instantiated.\nThat means an Object at runtime cannot have its class be abstract.\nIt would need to be a subclass that implements all abstract methods.\nIn JavaME, <code>Object.getClass()</code> should be all you need.\nAre you somehow trying to reconstitute your class hierarchy at runtime?</p>\n\n<p>In that case, you could implement something like this instead:</p>\n\n<pre><code>public String getClassHierarchy() {\n return super.getClassHierarchy() + \".MyAbstract\";\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180142/" ]
I need to get the Class of an object at runtime. For an non-abstract class I could do something like: ``` public class MyNoneAbstract{ public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass(); ``` But for an abstract class this does NOT work (always gives me `Object`) ``` public abstract class MyAbstract{ public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass(); ``` This code will be running in JavaME environments.
You just need ``` MyAbstract.class ``` That expression returns the Class object representing MyAbstract.
161,631
<p>I have a rails app that is working fine except for one thing.</p> <p>When I request something that doesn't exist (i.e. /not_a_controller_or_file.txt) and rails throws a "No Route matches..." exception, the response is this (blank line intentional):</p> <pre><code>HTTP/1.1 200 OK Date: Thu, 02 Oct 2008 10:28:02 GMT Content-Type: text/html Content-Length: 122 Vary: Accept-Encoding Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Status: 500 Internal Server Error Content-Type: text/html &lt;html&gt;&lt;body&gt;&lt;h1&gt;500 Internal Server Error&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>I have the ExceptionLogger plugin in /vendor, though that doesn't seem to be the problem. I haven't added any error handling beyond the custom 500.html in public (though the response doesn't contain that HTML) and I have no idea where this bit of html is coming from.</p> <p>So Something, somewhere is adding that <strong>HTTP/1.1 200</strong> status code too early, or the <strong>Status: 500</strong> too late. I suspect it's Apache because I get the appropriate HTTP/1.1 500 header (at the top) when I use Webrick. </p> <p>My production stack is as follows: Apache 2 Mongrel (5 instances) RubyOnRails 2.1.1 (happens in both 1.2 and 2.1.1)</p> <hr> <p>I forgot to mention, <strong>the error is caused by a "no route matches..." exception</strong></p>
[ { "answer_id": 161689, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<p>This html file is coming from Rails. It is encountering some sort of error (probably an exception of some kind, or some other unrecoverable error).</p>\n\n<p>If the extra blank line between the Status: header and the actual headers is there, and not just a typo, then this would go a long way to explaining why Apache is reporting a 200 OK message.</p>\n\n<p>The Status header is how Rails, PHP, or whatever tells Apache \"There was an error, please return this code instead of 200 OK.\" The fact there is a blank line means something extra is going on and Ruby is outputting a blank line before the error output for whatever reason. Maybe it's previous output from your script. The long and short of it is though, the extra blank line means that Apache thinks \"Oh, blank line, no extra headers, this is all content now.\", which would be consistent with the Content-Length header you provided.</p>\n\n<p>My guess for why there's a blank line would be previous script output, perhaps a line ending at the end of a fully script page. As to why the 500 error is happening, there isn't nearly enough info here to tell you that. Maybe a file I/O error.</p>\n\n<p><strong>Edit:</strong> Given the extra information provided by Dave about the internals, I'd say this is actually an issue with the proxying that goes on behind the scenes... I couldn't tell you exactly what though, beyond what's already been said.</p>\n" }, { "answer_id": 195573, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 0, "selected": false, "text": "<p>This is coming from rails itself.</p>\n\n<p><a href=\"http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/dispatcher.rb#L60\" rel=\"nofollow noreferrer\">http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/dispatcher.rb#L60</a></p>\n\n<p>The dispatcher is return an error page with the status code of 200 (Success). </p>\n" }, { "answer_id": 2683657, "author": "metavida", "author_id": 5539, "author_profile": "https://Stackoverflow.com/users/5539", "pm_score": 3, "selected": true, "text": "<p>This is a fairly old thread, but for what it's worth I found a great resource that includes a detailed description of the problem and the solution. Apparently this bug affects Rails &lt; 2.3 when used with Mongrel.</p>\n\n<ul>\n<li><a href=\"http://billkirtley.wordpress.com/2009/03/03/failsafe-handling-with-rails/\" rel=\"nofollow noreferrer\">The article that helped me understand the problem</a> &amp; write my own patch.</li>\n<li><a href=\"https://rails.lighthouseapp.com/projects/8994/tickets/1602-failsafe_response-200-ok\" rel=\"nofollow noreferrer\">An official Rails bug ticket</a> that includes a patch for Rails 2.2.2.</li>\n</ul>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216/" ]
I have a rails app that is working fine except for one thing. When I request something that doesn't exist (i.e. /not\_a\_controller\_or\_file.txt) and rails throws a "No Route matches..." exception, the response is this (blank line intentional): ``` HTTP/1.1 200 OK Date: Thu, 02 Oct 2008 10:28:02 GMT Content-Type: text/html Content-Length: 122 Vary: Accept-Encoding Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Status: 500 Internal Server Error Content-Type: text/html <html><body><h1>500 Internal Server Error</h1></body></html> ``` I have the ExceptionLogger plugin in /vendor, though that doesn't seem to be the problem. I haven't added any error handling beyond the custom 500.html in public (though the response doesn't contain that HTML) and I have no idea where this bit of html is coming from. So Something, somewhere is adding that **HTTP/1.1 200** status code too early, or the **Status: 500** too late. I suspect it's Apache because I get the appropriate HTTP/1.1 500 header (at the top) when I use Webrick. My production stack is as follows: Apache 2 Mongrel (5 instances) RubyOnRails 2.1.1 (happens in both 1.2 and 2.1.1) --- I forgot to mention, **the error is caused by a "no route matches..." exception**
This is a fairly old thread, but for what it's worth I found a great resource that includes a detailed description of the problem and the solution. Apparently this bug affects Rails < 2.3 when used with Mongrel. * [The article that helped me understand the problem](http://billkirtley.wordpress.com/2009/03/03/failsafe-handling-with-rails/) & write my own patch. * [An official Rails bug ticket](https://rails.lighthouseapp.com/projects/8994/tickets/1602-failsafe_response-200-ok) that includes a patch for Rails 2.2.2.
161,639
<p>I have two overloads of a c++ function and I would like to set a breakpoint on one of them:</p> <pre><code>0:000&gt; bu myexe!displayerror Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *) Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT) Ambiguous symbol error at 'myexe!displayerror' </code></pre> <p>Heck I would be fine with setting breakpoints on all overloads, but can't seem to figure out how:</p> <pre><code>0:000&gt; bu myexe!displayerror* Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *) Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT) Ambiguous symbol error at 'myexe!displayerror*' </code></pre>
[ { "answer_id": 161658, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>bu 0xff3c6100\n</code></pre>\n\n<p>If I remember right, WinDbg allows setting breakpoints by address too.</p>\n" }, { "answer_id": 388732, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 3, "selected": false, "text": "<p>Have you tried \"bm myexe!displayerror*\" ?</p>\n" }, { "answer_id": 4176483, "author": "kizzx2", "author_id": 111021, "author_profile": "https://Stackoverflow.com/users/111021", "pm_score": 2, "selected": false, "text": "<pre><code>bm myexe!displayerror\n</code></pre>\n\n<p>This will set breakpoints all all overloads, than you use <code>bc</code> to clear the ones you don't want</p>\n\n<pre><code>bc 1-3\n</code></pre>\n\n<p>Or just disable them</p>\n\n<pre><code>bd 1-3\n</code></pre>\n\n<p>The problem with <code>bm</code> is that the breakpoints it produces will sometimes fail to be evaluate and trigger a break. Annoying sometimes.</p>\n" }, { "answer_id": 4797121, "author": "icon_st", "author_id": 589432, "author_profile": "https://Stackoverflow.com/users/589432", "pm_score": 2, "selected": false, "text": "<p>bp @@( MyClass::MyMethod ) break on methods (useful if the same method is overloaded and thus present on several addresses)</p>\n" }, { "answer_id": 9646178, "author": "EdChum", "author_id": 704848, "author_profile": "https://Stackoverflow.com/users/704848", "pm_score": 1, "selected": false, "text": "<p>Search your dll for all entry point matching your symbol</p>\n\n<pre><code>x myexe!displayerror\n</code></pre>\n\n<p>this will output all symbols matching the search string and their entry points, then set the breakpoint on the address</p>\n\n<pre><code>bp ff3c6100 // for myexe!displayError (int, HRESULT, wchar_t *)\n</code></pre>\n\n<p>This will set a specific breakpoint when that address is hit, or you set bp against the other address. You can set the breakpoint to just hit once, clear the breakpoint and exit</p>\n\n<pre><code>bp /1 ff3c6100\n</code></pre>\n\n<p>and you can also execute commands such as dump the call stack, variables and continue:</p>\n\n<pre><code>bp ff3c6100 \"kb;dv;g\"\n</code></pre>\n\n<p>You may also just open your source code when WinDbg is attached, navigate to the line of code you want to set the breakpoint on and hit F9 (same as you would do using Visual Studio), it will pause for a while before setting a breakpoint at that line, this assumes you have access to the source code.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15071/" ]
I have two overloads of a c++ function and I would like to set a breakpoint on one of them: ``` 0:000> bu myexe!displayerror Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *) Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT) Ambiguous symbol error at 'myexe!displayerror' ``` Heck I would be fine with setting breakpoints on all overloads, but can't seem to figure out how: ``` 0:000> bu myexe!displayerror* Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *) Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT) Ambiguous symbol error at 'myexe!displayerror*' ```
Try: ``` bu 0xff3c6100 ``` If I remember right, WinDbg allows setting breakpoints by address too.
161,654
<p>This is a subjective question as I want to gauge if it's worth me moaning at my co-workers for doing something which I find utterly detestable.</p> <p>The issue is that a bunch of my co-workers will truncate method calls to fit a width. We all use widescreen laptops that can handle large resolutions (mine is 1920x1200) and when it comes to debugging and reading code I find it much easier to read one line method calls as opposed to multiple line calls.</p> <p>Here's an example of a method (how I would like it):</p> <pre><code>IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class, param1, param2, param3); </code></pre> <p>(I do hate really long interface/class names as well :)</p> <p>It seems that this doesn't render well on StackOverflow, but I think most of you know what I mean. Anyway, some of the other devs do the following.</p> <pre><code>IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class, param1, param2, param3); </code></pre> <p>Which is the easier to read at the end of the day for you and would I be unreasonable in asking them to use the first of the two (as it is part of our standard)?</p>
[ { "answer_id": 161670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Maybe you should have as part of your standard build process some sort of checkstyle plugin which checks for exactly that kind of thing? If you've agreed the standard with your co-workers it seems reasonable to ask them to keep to it.</p>\n\n<p>I personally find the second of the two options the more readable, but that's just because I don't have a widescreen monitor ;)</p>\n" }, { "answer_id": 161679, "author": "Jimoc", "author_id": 24079, "author_profile": "https://Stackoverflow.com/users/24079", "pm_score": 2, "selected": false, "text": "<p>If its exlicitly stated in the companies coding standard that method one is the correct method then by all means moan at them, after all they are not adhering to the company standards.\nIf its not exlicitly stated then I guess now would be a good time to get it into the standard.\nOne thing to be aware of though, if you are using an IDE with autoformatting is that it may take it upon itself to reformat the methods to style 2 when its run.\nSo even if everyone is writing to style 1, it may not end up looking like that when they are finished with it.</p>\n\n<p>and like Phil, I find method 2 much more readable, since you can see everything you need to see without having to scroll your eyes sideways :)</p>\n" }, { "answer_id": 161723, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 2, "selected": false, "text": "<p>I find the first example more readable in general, though if it is longer than some predefined limit (120 characters, for me), I would break the lines:</p>\n\n<pre><code>IReallyLongInterfaceName instanceOfInterfaceName =\n OurContainer.retrieveClass(IReallyLongInterfaceName.class,\n param1, param2, param3);\n</code></pre>\n" }, { "answer_id": 161772, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 2, "selected": false, "text": "<p>I prefer the second example. Even though you may have widescreen laptops, you might not always have windows full screen, or in your IDE you may have a lot of other panels around the main coding area that reduce the available width for displaying code.</p>\n\n<p>If the line can't fit without scrolling, then vertical scrolling is preferable to horizontal scrolling. Since we read left-to-right, horizontal scrolling would mean moving backwards and forwards all the time.</p>\n\n<p>I prefer one parameter per line to Avi's suggestion, which is arbitrary to me. If you spread the parameters over multiple lines but have several on each line, it makes it more difficult to find particular parameters when reading the code.</p>\n" }, { "answer_id": 161808, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>I prefer option #2, as well. The issue isn't just how it looks on screen (and if I had 1920 horizontal pixels, I'd have a lot more docked windows), it's how it looks if I need to print it and read it. Long lines will print terribly out of most IDEs, whereas lines broken by an author with the intent to improve legibility will print well.</p>\n\n<p>Another point is general legibility. There's a reason magazines and newspapers are printed in columns -- generally, readability of text (particularly text on-screen) is improved by shorter lines and better layout/formatting.</p>\n\n<p>I think 80 might be overly arbitrary, but I'm using 10pt Consolas, and I seem to be able to get about 100 characters per line on a standard 8.5\" printed page.</p>\n\n<p>Now at the end of the day, this is a holy war. Maybe not as bad as where to put your curly braces, but it's up there. I've given you my preference, but the real question goes back to you: What's your company's standard? It sounds to me like they've standardized on option #2, which means for the sake of the team, you should probably adapt to them.</p>\n" }, { "answer_id": 165609, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 0, "selected": false, "text": "<p>I prefer option 2, but optionally with comments for parameters where the variable name is not obvious. When you have a function call that is asking for a bunch of parameters, it can be pretty hard for reviewers to tell what the code is doing.</p>\n\n<p>So, I generally code like this if there are more than 3 parameters to a given function:</p>\n\n<pre><code>applyEncryptionParameters(key,\n certificate,\n 0, // strength - set to 0 to accept default for platform\n algorithm);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
This is a subjective question as I want to gauge if it's worth me moaning at my co-workers for doing something which I find utterly detestable. The issue is that a bunch of my co-workers will truncate method calls to fit a width. We all use widescreen laptops that can handle large resolutions (mine is 1920x1200) and when it comes to debugging and reading code I find it much easier to read one line method calls as opposed to multiple line calls. Here's an example of a method (how I would like it): ``` IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class, param1, param2, param3); ``` (I do hate really long interface/class names as well :) It seems that this doesn't render well on StackOverflow, but I think most of you know what I mean. Anyway, some of the other devs do the following. ``` IReallyLongInterfaceName instanceOfInterfaceName = OurContainer.retrieveClass(IReallyLongInterfaceName.class, param1, param2, param3); ``` Which is the easier to read at the end of the day for you and would I be unreasonable in asking them to use the first of the two (as it is part of our standard)?
Maybe you should have as part of your standard build process some sort of checkstyle plugin which checks for exactly that kind of thing? If you've agreed the standard with your co-workers it seems reasonable to ask them to keep to it. I personally find the second of the two options the more readable, but that's just because I don't have a widescreen monitor ;)
161,655
<p>Consider the following subversion directory structure</p> <p>/dir1/file.txt</p> <p>/dir2/file.txt</p> <p>I want to move the file.txt in dir1 to replace the same file in dir2 and ensure that the history for the dir1 file is maintained. I don't care about the history of original dir2 file.</p> <p>Is this possible using subversion commands and not hacking the backend?</p>
[ { "answer_id": 161668, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 4, "selected": true, "text": "<p>Firstly you should never consider hacking the backend - it negates the point of using SVN in the first place.</p>\n\n<p>I don't see why you couldn't just do </p>\n\n<pre><code>svn rm /dir2/file.txt\nsvn mv /dir1/file.txt /dir2/file.txt\n</code></pre>\n\n<p>the history of the file will follow it after the move.</p>\n" }, { "answer_id": 161695, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<ol>\n<li>Delete dir2/file.txt and commit</li>\n<li>issue a svn move command to move dir1/file.txt to dir2/file.txt and commit - The history should be preserved.</li>\n</ol>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445016/" ]
Consider the following subversion directory structure /dir1/file.txt /dir2/file.txt I want to move the file.txt in dir1 to replace the same file in dir2 and ensure that the history for the dir1 file is maintained. I don't care about the history of original dir2 file. Is this possible using subversion commands and not hacking the backend?
Firstly you should never consider hacking the backend - it negates the point of using SVN in the first place. I don't see why you couldn't just do ``` svn rm /dir2/file.txt svn mv /dir1/file.txt /dir2/file.txt ``` the history of the file will follow it after the move.
161,666
<p>I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution.</p> <pre><code>(define (big x y) (if (&gt; x y) x y)) (define (p a b c) (cond ((&gt; a b) (+ (square a) (square (big b c)))) (else (+ (square b) (square (big a c)))))) </code></pre>
[ { "answer_id": 161674, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>Looks ok to me, is there anything specific you want to improve on?</p>\n\n<p>You could do something like:</p>\n\n<pre><code>(define (max2 . l)\n (lambda ()\n (let ((a (apply max l)))\n (values a (apply max (remv a l))))))\n\n(define (q a b c)\n (call-with-values (max2 a b c)\n (lambda (a b)\n (+ (* a a) (* b b)))))\n\n(define (skip-min . l)\n (lambda ()\n (apply values (remv (apply min l) l))))\n\n(define (p a b c)\n (call-with-values (skip-min a b c)\n (lambda (a b)\n (+ (* a a) (* b b)))))\n</code></pre>\n\n<p>And this (proc p) can be easily converted to handle any number of arguments.</p>\n" }, { "answer_id": 161675, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p><code>big</code> is called <code>max</code>. Use standard library functionality when it's there.</p>\n\n<p>My approach is different. Rather than lots of tests, I simply add the squares of all three, then subtract the square of the smallest one.</p>\n\n<pre><code>(define (exercise1.3 a b c)\n (let ((smallest (min a b c))\n (square (lambda (x) (* x x))))\n (+ (square a) (square b) (square c) (- (square smallest)))))\n</code></pre>\n\n<p>Whether you prefer this approach, or a bunch of <code>if</code> tests, is up to you, of course.</p>\n\n<hr>\n\n<p>Alternative implementation using <a href=\"http://srfi.schemers.org/srfi-95/srfi-95.html\" rel=\"noreferrer\">SRFI 95</a>:</p>\n\n<pre><code>(define (exercise1.3 . args)\n (let ((sorted (sort! args &gt;))\n (square (lambda (x) (* x x))))\n (+ (square (car sorted)) (square (cadr sorted)))))\n</code></pre>\n\n<p>As above, but as a one-liner (thanks synx @ freenode #scheme); also requires <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html\" rel=\"noreferrer\">SRFI 1</a> and <a href=\"http://srfi.schemers.org/srfi-26/srfi-26.html\" rel=\"noreferrer\">SRFI 26</a>:</p>\n\n<pre><code>(define (exercise1.3 . args)\n (apply + (map! (cut expt &lt;&gt; 2) (take! (sort! args &gt;) 2))))\n</code></pre>\n" }, { "answer_id": 161720, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "<p>You can also sort the list and add the squares of the first and second element of the sorted list:</p>\n\n<pre><code>(require (lib \"list.ss\")) ;; I use PLT Scheme\n\n(define (exercise-1-3 a b c)\n (let* [(sorted-list (sort (list a b c) &gt;))\n (x (first sorted-list))\n (y (second sorted-list))]\n (+ (* x x) (* y y))))\n</code></pre>\n" }, { "answer_id": 610719, "author": "Scott Hoffman", "author_id": 50640, "author_profile": "https://Stackoverflow.com/users/50640", "pm_score": 4, "selected": false, "text": "<p>What about something like this? </p>\n\n<pre><code>(define (p a b c)\n (if (&gt; a b)\n (if (&gt; b c)\n (+ (square a) (square b))\n (+ (square a) (square c)))\n (if (&gt; a c)\n (+ (square a) (square b))\n (+ (square b) (square c)))))\n</code></pre>\n" }, { "answer_id": 612560, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>Here's yet another way to do it:</p>\n\n<pre>\n#!/usr/bin/env mzscheme\n#lang scheme/load\n\n(module ex-1.3 scheme/base\n (define (ex-1.3 a b c)\n (let* ((square (lambda (x) (* x x)))\n (p (lambda (a b c) (+ (square a) (square (if (> b c) b c))))))\n (if (> a b) (p a b c) (p b a c))))\n\n (require scheme/contract)\n (provide/contract [ex-1.3 (-> number? number? number? number?)]))\n\n;; tests\n(module ex-1.3/test scheme/base\n (require (planet \"test.ss\" (\"schematics\" \"schemeunit.plt\" 2))\n (planet \"text-ui.ss\" (\"schematics\" \"schemeunit.plt\" 2)))\n (require 'ex-1.3)\n\n (test/text-ui\n (test-suite\n \"ex-1.3\"\n (test-equal? \"1 2 3\" (ex-1.3 1 2 3) 13)\n (test-equal? \"2 1 3\" (ex-1.3 2 1 3) 13)\n (test-equal? \"2 1. 3.5\" (ex-1.3 2 1. 3.5) 16.25)\n (test-equal? \"-2 -10. 3.5\" (ex-1.3 -2 -10. 3.5) 16.25)\n (test-exn \"2+1i 0 0\" exn:fail:contract? (lambda () (ex-1.3 2+1i 0 0)))\n (test-equal? \"all equal\" (ex-1.3 3 3 3) 18))))\n\n(require 'ex-1.3/test)\n</pre>\n\n<p>Example:</p>\n\n<pre>\n$ mzscheme ex-1.3.ss\n6 success(es) 0 failure(s) 0 error(s) 6 test(s) run\n0\n</pre> \n" }, { "answer_id": 1084304, "author": "Shawn J. Goff", "author_id": 251561, "author_profile": "https://Stackoverflow.com/users/251561", "pm_score": 3, "selected": false, "text": "<p>Using only the concepts introduced up to that point of the text, <em>which I think is rather important</em>, here is a different solution:</p>\n\n<pre><code>(define (smallest-of-three a b c)\n (if (&lt; a b)\n (if (&lt; a c) a c)\n (if (&lt; b c) b c)))\n\n(define (square a)\n (* a a))\n\n(define (sum-of-squares-largest a b c) \n (+ (square a)\n (square b)\n (square c)\n (- (square (smallest-of-three a b c)))))\n</code></pre>\n" }, { "answer_id": 1161816, "author": "Carlos Santos", "author_id": 119399, "author_profile": "https://Stackoverflow.com/users/119399", "pm_score": 5, "selected": false, "text": "<p>Using only the concepts presented at that point of the book, I would do it:</p>\n\n<pre><code>(define (square x) (* x x))\n\n(define (sum-of-squares x y) (+ (square x) (square y)))\n\n(define (min x y) (if (&lt; x y) x y))\n\n(define (max x y) (if (&gt; x y) x y))\n\n(define (sum-squares-2-biggest x y z)\n (sum-of-squares (max x y) (max z (min x y))))\n</code></pre>\n" }, { "answer_id": 1518167, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "<p>I did it with the following code, which uses the built-in <code>min</code>, <code>max</code>, and <code>square</code> procedures. They're simple enough to implement using only what's been introduced in the text up to that point.</p>\n\n<pre><code>(define (sum-of-highest-squares x y z)\n (+ (square (max x y))\n (square (max (min x y) z))))\n</code></pre>\n" }, { "answer_id": 1881239, "author": "Christy John", "author_id": 147671, "author_profile": "https://Stackoverflow.com/users/147671", "pm_score": 2, "selected": false, "text": "<p>With Scott Hoffman's and some irc help I corrected my faulty code, here it is</p>\n\n<pre><code>(define (p a b c)\n (cond ((&gt; a b)\n (cond ((&gt; b c)\n (+ (square a) (square b)))\n (else (+ (square a) (square c)))))\n (else\n (cond ((&gt; a c)\n (+ (square b) (square a))))\n (+ (square b) (square c)))))\n</code></pre>\n" }, { "answer_id": 1997522, "author": "Eric", "author_id": 242969, "author_profile": "https://Stackoverflow.com/users/242969", "pm_score": 0, "selected": false, "text": "<p>I've had a go:</p>\n\n<pre><code>(define (procedure a b c)\n (let ((y (sort (list a b c) &gt;)) (square (lambda (x) (* x x))))\n (+ (square (first y)) (square(second y)))))\n</code></pre>\n" }, { "answer_id": 4664891, "author": "andres.santana", "author_id": 439847, "author_profile": "https://Stackoverflow.com/users/439847", "pm_score": 0, "selected": false, "text": "<pre><code>;exercise 1.3\n(define (sum-square-of-max a b c)\n (+ (if (&gt; a b) (* a a) (* b b))\n (if (&gt; b c) (* b b) (* c c))))\n</code></pre>\n" }, { "answer_id": 9061733, "author": "Scott Miao", "author_id": 1177608, "author_profile": "https://Stackoverflow.com/users/1177608", "pm_score": 3, "selected": false, "text": "<pre><code>(define (sum-sqr x y)\n(+ (square x) (square y)))\n\n(define (sum-squares-2-of-3 x y z)\n (cond ((and (&lt;= x y) (&lt;= x z)) (sum-sqr y z))\n ((and (&lt;= y x) (&lt;= y z)) (sum-sqr x z))\n ((and (&lt;= z x) (&lt;= z y)) (sum-sqr x y))))\n</code></pre>\n" }, { "answer_id": 9065099, "author": "user448810", "author_id": 448810, "author_profile": "https://Stackoverflow.com/users/448810", "pm_score": 3, "selected": false, "text": "<pre><code>(define (f a b c) \n (if (= a (min a b c)) \n (+ (* b b) (* c c)) \n (f b c a)))\n</code></pre>\n" }, { "answer_id": 22533758, "author": "riddhi_agrawal", "author_id": 826050, "author_profile": "https://Stackoverflow.com/users/826050", "pm_score": 1, "selected": false, "text": "<pre><code>(define (sum a b) (+ a b))\n(define (square a) (* a a))\n(define (greater a b ) \n ( if (&lt; a b) b a))\n(define (smaller a b ) \n ( if (&lt; a b) a b))\n(define (sumOfSquare a b)\n (sum (square a) (square b)))\n(define (sumOfSquareOfGreaterNumbers a b c)\n (sumOfSquare (greater a b) (greater (smaller a b) c)))\n</code></pre>\n" }, { "answer_id": 28664937, "author": "Elliot Gorokhovsky", "author_id": 3154996, "author_profile": "https://Stackoverflow.com/users/3154996", "pm_score": 0, "selected": false, "text": "<p>I think this is the smallest and most efficient way:</p>\n\n<pre><code>(define (square-sum-larger a b c)\n (+ \n (square (max a b))\n (square (max (min a b) c))))\n</code></pre>\n" }, { "answer_id": 45962062, "author": "Ethan Barrett", "author_id": 5670477, "author_profile": "https://Stackoverflow.com/users/5670477", "pm_score": 0, "selected": false, "text": "<p>Below is the solution that I came up with. I find it easier to reason about a solution when the code is decomposed into small functions.</p>\n\n<pre><code> ; Exercise 1.3\n(define (sum-square-largest a b c)\n (+ (square (greatest a b))\n (square (greatest (least a b) c))))\n\n(define (greatest a b)\n (cond (( &gt; a b) a)\n (( &lt; a b) b)))\n\n(define (least a b)\n (cond ((&gt; a b) b)\n ((&lt; a b) a)))\n\n(define (square a)\n (* a a))\n</code></pre>\n" }, { "answer_id": 51550302, "author": "Joseph Glass", "author_id": 10142260, "author_profile": "https://Stackoverflow.com/users/10142260", "pm_score": 2, "selected": false, "text": "<p>It's nice to see how other people have solved this problem. This was my solution:</p>\n\n<pre><code>(define (isGreater? x y z)\n(if (and (&gt; x z) (&gt; y z))\n(+ (square x) (square y))\n0))\n\n(define (sumLarger x y z)\n(if (= (isGreater? x y z) 0) \n(sumLarger y z x)\n(isGreater? x y z)))\n</code></pre>\n\n<p>I solved it by iteration, but I like ashitaka's and the (+ (square (max x y)) (square (max (min x y) z))) solutions better, since in my version, if z is the smallest number, isGreater? is called twice, creating an unnecessarily slow and circuitous procedure. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24457/" ]
I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution. ``` (define (big x y) (if (> x y) x y)) (define (p a b c) (cond ((> a b) (+ (square a) (square (big b c)))) (else (+ (square b) (square (big a c)))))) ```
Looks ok to me, is there anything specific you want to improve on? You could do something like: ``` (define (max2 . l) (lambda () (let ((a (apply max l))) (values a (apply max (remv a l)))))) (define (q a b c) (call-with-values (max2 a b c) (lambda (a b) (+ (* a a) (* b b))))) (define (skip-min . l) (lambda () (apply values (remv (apply min l) l)))) (define (p a b c) (call-with-values (skip-min a b c) (lambda (a b) (+ (* a a) (* b b))))) ``` And this (proc p) can be easily converted to handle any number of arguments.
161,672
<p>I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets?</p> <pre><code>DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent ) : QGraphicsScene( screenRect, parent ), myParent( parent ), slideUndoImageCurrentIndex(-1), nextGroupID(0), m_undoInProgress(false), m_deleteItemOnNextUndo(0) line(0), path(0) { /* Setup default brush for background */ scDetail-&gt;bgBrush.setStyle(Qt::SolidPattern); scDetail-&gt;bgBrush.setColor(Qt::white); setBackgroundBrush(scDetail-&gt;bgBrush); } </code></pre>
[ { "answer_id": 161684, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<ul>\n<li>It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors.</li>\n<li>You can't accidentally assign a value twice in the initialiser list.</li>\n<li>The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars).</li>\n<li>Reference types and <code>const</code> members must be initialised in the initialiser list, because you can't assign to a reference or to a <code>const</code> member.</li>\n</ul>\n" }, { "answer_id": 161696, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 2, "selected": false, "text": "<p>Because, in the constructor's body (\"within the curly brackets\") the member variables are already default-constructed. That may have some performance implications, when you have a member variable of a type that has non-trivial construction, when you first have it default-constructed and then you assign it some other value in the constructor, when you could have custom-construct it directly.</p>\n\n<p>Also, some types may not be default-constructed (for example references) and must be constructed in the initialization list.</p>\n" }, { "answer_id": 161705, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 0, "selected": false, "text": "<p>Take a look at the collected wisdom at <a href=\"http://web.tiscali.it/fanelia/cpp-faq-en/ctors.html#faq-10.6\" rel=\"nofollow noreferrer\">http://web.tiscali.it/fanelia/cpp-faq-en/ctors.html#faq-10.6</a></p>\n" }, { "answer_id": 161707, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 2, "selected": false, "text": "<p>If you have const variables, their value can not be set via assignment.</p>\n\n<p>The initialization is also a bit more efficient when assigning values to objects (not built-ins or intrinsics) as a temporary object is not created like it would be for an assignment. </p>\n\n<p>See <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6\" rel=\"nofollow noreferrer\">C++ FAQ-Lite</a> for more details</p>\n" }, { "answer_id": 161711, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 2, "selected": false, "text": "<p>It's better to do the initialization of the members in the initialization list because the members are then only initialized once. This can be a huge difference in performance (and even behavior) if the members are classes themselves. If the members are all non-const, non-reference fundamental data types, then the difference is usually negligible.</p>\n\n<p><strong>NOTE</strong>: There are times where initialization lists are required for fundamental data types -- specifically if the type is constant or a reference. For these types, the data can only be initialized once and thus it cannot be initialized in the body of the constructor. See <a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"nofollow noreferrer\"><strong>this article</strong></a> for more information.</p>\n\n<p>Note that the initialization order of the members is the order the members are declared in the class definition, not the order the members are declared in the initialization list. If the warning can be fixed by changing the order of the initialization list, then I highly recommend that you do so.</p>\n\n<p>It's my recommendation that:</p>\n\n<ul>\n<li>You learn to like initialization lists.</li>\n<li>Your co-worker understand the rules for initialization order of members (and avoid warnings).</li>\n</ul>\n" }, { "answer_id": 161730, "author": "Dominic Rodger", "author_id": 20972, "author_profile": "https://Stackoverflow.com/users/20972", "pm_score": 2, "selected": false, "text": "<p>In addition to Greg Hewgill's <a href=\"https://stackoverflow.com/questions/161672/c-class-initialisation-containing-class-variable-initialisation#161684\">excellent answer</a> - const variables must be set in the initialisation list.</p>\n" }, { "answer_id": 163253, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 0, "selected": false, "text": "<p>Another addition to Greg's answer: members that are of types with no default constructor must be initialized in initialization list.</p>\n" }, { "answer_id": 2782776, "author": "Stephen C. Steel", "author_id": 19131, "author_profile": "https://Stackoverflow.com/users/19131", "pm_score": 0, "selected": false, "text": "<p>Greg Hegwell's answer contains some excellent advice, but it doesn't explain why the compiler is generating a warning.</p>\n\n<p>When the initializer list of a constructor is processed by the compiler, the items are initialized <em>in the order they are declared in the class declaration</em>, not in the order they appear in the initializer list.</p>\n\n<p>Some compilers generate a warning if the order in the initializer list is different from the declaration order (so you won't be surprised when items are not initialized in the order of the list). You don't include your class declaration, but this is the likely cause of the warning you're seeing.</p>\n\n<p>The rationale for this behavior is that the members of a class should always be initialized in the same order: even when the class has more than one constructor (which could have the members ordered differently in their initializer lists).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24459/" ]
I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets? ``` DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent ) : QGraphicsScene( screenRect, parent ), myParent( parent ), slideUndoImageCurrentIndex(-1), nextGroupID(0), m_undoInProgress(false), m_deleteItemOnNextUndo(0) line(0), path(0) { /* Setup default brush for background */ scDetail->bgBrush.setStyle(Qt::SolidPattern); scDetail->bgBrush.setColor(Qt::white); setBackgroundBrush(scDetail->bgBrush); } ```
* It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors. * You can't accidentally assign a value twice in the initialiser list. * The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars). * Reference types and `const` members must be initialised in the initialiser list, because you can't assign to a reference or to a `const` member.
161,676
<p>I'm running zsh as the default shell on a Ubuntu box, and everything works fine using gnome-terminal (which as far as I know emulates xterm). When I login from a windows box via ssh and putty (which also emulates xterm) suddendly the home/end keys no longer work. </p> <p>I've been able to solve that adding these lines to my zshrc file...</p> <pre><code>bindkey '\e[1~' beginning-of-line bindkey '\e[4~' end-of-line </code></pre> <p>...but I'm still wondering what's wrong here. Any idea?</p>
[ { "answer_id": 161892, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 0, "selected": false, "text": "<p>These bindings simply don't appear to be part of the default bindings set in emacs mode.</p>\n\n<p>executing \"where-is beginning-of-line\" on my default zsh installation after running \"bindkey -e\" shows it is only bound to ^a. Perhaps you should ask the zsh developers why :-)</p>\n" }, { "answer_id": 162125, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "<p>It seems a putty thing. Gnome-terminal sends the codes <code>^[OH</code> and <code>^[OF</code> for Home and End respectively, while putty sends <code>^[[1~</code> and <code>^[[4~</code>. There's an option in putty to change the Home/End keys from <em>standard</em> mode to <em>rxvt</em> mode, and that seems to fix the Home key, but not the End key (which now sends <code>^[Ow</code>). Guess it's time to file a bug report somewhere... :-)</p>\n" }, { "answer_id": 686458, "author": "hopla", "author_id": 82011, "author_profile": "https://Stackoverflow.com/users/82011", "pm_score": 7, "selected": true, "text": "<p>I found it's a combination:</p>\n\n<p><strong>One</strong></p>\n\n<p>The ZSH developers do not think that ZSH should define the actions of the <kbd>Home</kbd>, <kbd>End</kbd>, <kbd>Del</kbd>, ... keys.</p>\n\n<p>Debian and Ubuntu fix this by defining the normal actions the average user would expect in the global <code>/etc/zsh/zshrc</code> file. Following the relevant code (it is the same on Debian and Ubuntu):</p>\n\n<pre><code>if [[ \"$TERM\" != emacs ]]; then\n[[ -z \"$terminfo[kdch1]\" ]] || bindkey -M emacs \"$terminfo[kdch1]\" delete-char\n[[ -z \"$terminfo[khome]\" ]] || bindkey -M emacs \"$terminfo[khome]\" beginning-of-line\n[[ -z \"$terminfo[kend]\" ]] || bindkey -M emacs \"$terminfo[kend]\" end-of-line\n[[ -z \"$terminfo[kich1]\" ]] || bindkey -M emacs \"$terminfo[kich1]\" overwrite-mode\n[[ -z \"$terminfo[kdch1]\" ]] || bindkey -M vicmd \"$terminfo[kdch1]\" vi-delete-char\n[[ -z \"$terminfo[khome]\" ]] || bindkey -M vicmd \"$terminfo[khome]\" vi-beginning-of-line\n[[ -z \"$terminfo[kend]\" ]] || bindkey -M vicmd \"$terminfo[kend]\" vi-end-of-line\n[[ -z \"$terminfo[kich1]\" ]] || bindkey -M vicmd \"$terminfo[kich1]\" overwrite-mode\n\n[[ -z \"$terminfo[cuu1]\" ]] || bindkey -M viins \"$terminfo[cuu1]\" vi-up-line-or-history\n[[ -z \"$terminfo[cuf1]\" ]] || bindkey -M viins \"$terminfo[cuf1]\" vi-forward-char\n[[ -z \"$terminfo[kcuu1]\" ]] || bindkey -M viins \"$terminfo[kcuu1]\" vi-up-line-or-history\n[[ -z \"$terminfo[kcud1]\" ]] || bindkey -M viins \"$terminfo[kcud1]\" vi-down-line-or-history\n[[ -z \"$terminfo[kcuf1]\" ]] || bindkey -M viins \"$terminfo[kcuf1]\" vi-forward-char\n[[ -z \"$terminfo[kcub1]\" ]] || bindkey -M viins \"$terminfo[kcub1]\" vi-backward-char\n\n# ncurses fogyatekos\n[[ \"$terminfo[kcuu1]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[kcuu1]/O/[}\" vi-up-line-or-history\n[[ \"$terminfo[kcud1]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[kcud1]/O/[}\" vi-down-line-or-history\n[[ \"$terminfo[kcuf1]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[kcuf1]/O/[}\" vi-forward-char\n[[ \"$terminfo[kcub1]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[kcub1]/O/[}\" vi-backward-char\n[[ \"$terminfo[khome]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[khome]/O/[}\" beginning-of-line\n[[ \"$terminfo[kend]\" == \"^[O\"* ]] &amp;&amp; bindkey -M viins \"${terminfo[kend]/O/[}\" end-of-line\n[[ \"$terminfo[khome]\" == \"^[O\"* ]] &amp;&amp; bindkey -M emacs \"${terminfo[khome]/O/[}\" beginning-of-line\n[[ \"$terminfo[kend]\" == \"^[O\"* ]] &amp;&amp; bindkey -M emacs \"${terminfo[kend]/O/[}\" end-of-line\nfi\n</code></pre>\n\n<p>So, if you are connecting to a Debian or Ubuntu box, you don't have to do anything. Everything should work automagically (if not, see below).</p>\n\n<p>But... if you are connecting to another box (e.g. FreeBSD), there might be no user friendly default <code>zshrc</code>. The solution is of course to add the lines from the Debian/Ubuntu <code>zshrc</code> to your own <code>.zshrc</code>.</p>\n\n<p><strong>Two</strong></p>\n\n<p>Putty sends <code>xterm</code> as terminal type to the remote host. But messes up somewhere and doesn't send the correct control codes for <kbd>Home</kbd>, <kbd>End</kbd>, ... that one would expect from an <code>xterm</code>. Or an <code>xterm</code> terminal isn't expected to send those or whatever... (<kbd>Del</kbd> key does work in <code>xterm</code> however, if you configure it in ZSH). Also notice that your Numpad-keys act funny in Vim for example with <code>xterm</code> terminal.</p>\n\n<p>The solution is to configure Putty to send another terminal type. I've tried <code>xterm-color</code> and <code>linux</code>. <code>xterm-color</code> fixed the <kbd>Home</kbd>/<kbd>End</kbd> problem, but the Numpad was still funny. Setting it to <code>linux</code> fixed both problems.</p>\n\n<p>You can set terminal type in Putty under Connection -> Data. Do not be tempted to set your terminal type in your <code>.zshrc</code> with <code>export TERM=linux</code>, that is just wrong. The terminal type should be specified by your terminal app. So that if, for example, you connect from a Mac box with a Mac SSH client it can set it's own terminal type.</p>\n\n<p>Notice that TERM specifies your terminal type and has nothing to do with the host you are connecting to. I can set my terminal type to <code>linux</code> in Putty and connect to FreeBSD servers without problems.</p>\n\n<p>So, fix both these things and you should be fine :)</p>\n" }, { "answer_id": 1299111, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "<p>On the PuTTY configuration dialog, go to Connection -> Data and type <strong>linux</strong> into the Terminal-type string before connecting.</p>\n" }, { "answer_id": 10377906, "author": "Josh McGee", "author_id": 1271512, "author_profile": "https://Stackoverflow.com/users/1271512", "pm_score": 3, "selected": false, "text": "<p>the appropriate answer that should be portable across <em>all</em> distros (not necessarly all versions of zsh though, ymmv here) is to use the zkbd helper utility from zkbd.</p>\n<blockquote>\n<p>Keyboard Definition<br />\nThe large number of possible combinations of keyboards, workstations, terminals, emulators, and window systems makes it impossible for zsh to have built-in key bindings for every situation. The zkbd utility, found in Functions/Misc, can help you quickly create key bindings for your configuration.</p>\n</blockquote>\n<blockquote>\n<p>Run zkbd either as an autoloaded function, or as a shell script:</p>\n</blockquote>\n<pre><code>zsh -f ~/zsh-4.3.17/Functions/Misc/zkbd\n</code></pre>\n<blockquote>\n<p>When you run zkbd, it first asks you to enter your terminal type; if the default it offers is correct, just press return. It then asks you to press a number of different keys to determine characteristics of your keyboard and terminal; zkbd warns you\nif it finds anything out of the ordinary, such as a Delete key that sends neither ^H nor ^?.</p>\n</blockquote>\n<blockquote>\n<p>The keystrokes read by zkbd are recorded as a definition for an associative array named key, written to a file in the subdirectory .zkbd within either your HOME or ZDOTDIR directory. The name of the file is composed from the TERM, VENDOR and OSTYPE\nparameters, joined by hyphens.</p>\n</blockquote>\n<blockquote>\n<p>You may read this file into your .zshrc or another startup file with the <code>source</code> or <code>.</code> commands, then reference the key parameter in bindkey commands, like this:</p>\n</blockquote>\n<pre><code> source ${ZDOTDIR:-$HOME}/.zkbd/$TERM-$VENDOR-$OSTYPE\n [[ -n ${key[Left]} ]] &amp;&amp; bindkey &quot;${key[Left]}&quot; backward-char\n [[ -n ${key[Right]} ]] &amp;&amp; bindkey &quot;${key[Right]}&quot; forward-char\n # etc.\n</code></pre>\n<blockquote>\n<p>Note that in order for <code>autoload zkbd</code> to work, the <code>zkbd</code> file must be in one of the directories named in your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh installation; if it is not, copy Functions/Misc/zkbd to an appropriate directory.</p>\n</blockquote>\n<p>see <code>man -P &quot;less -p 'keyboard definition'&quot; zshcontrib</code>, or search the meta-manpage <code>zshall</code></p>\n" }, { "answer_id": 26861174, "author": "Rene", "author_id": 3124469, "author_profile": "https://Stackoverflow.com/users/3124469", "pm_score": 3, "selected": false, "text": "<p>This is working for me</p>\n\n<pre><code>bindkey -v\n\nbindkey '\\eOH' beginning-of-line\nbindkey '\\eOF' end-of-line\n</code></pre>\n" }, { "answer_id": 59054483, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 3, "selected": false, "text": "<p>It's now been nearly 11 years since this question was first posted. At the time, some distros did ship with a <code>putty</code> terminfo entry, but it was mediocre at best. In the years since, the situation has improved, and the hacks that were necessary for over a decade are no longer required. PuTTY still defaults to setting <code>TERM</code> to <code>xterm</code> for compatibility, but if you're connecting to modern, up-to-date systems, you'll likely have luck overriding this and setting it to <code>putty-256color</code>:</p>\n\n<ol>\n<li>Ensure the host has a terminfo entry for <code>putty-256color</code>: <code>toe -a | grep -F putty</code></li>\n<li>Undo any hacks you may have enabled to get PuTTY working properly with zsh or other programs.</li>\n<li>Ensure PuTTY is up-to-date. It won't notify you when updates are available, and if it's out-of-date, you're likely going to run into a lot of the same issues. You may want to keep it up-to-date automatically with something like <a href=\"https://chocolatey.org/\" rel=\"noreferrer\">Chocolatey</a>.</li>\n<li>In PuTTY's configuration dialog, go to Connection -> Data and set \"Terminal-type string\" to <code>putty-256color</code>.</li>\n<li>While you're at it, on the same configuration screen, add a new environment variable to enable 24-bit color. This variable isn't standardized, but it's sent by a number of other mainstream terminal emulators (e.g., iTerm2), and many programs understand it.\n\n<ol>\n<li>Variable: <code>COLORTERM</code></li>\n<li>Value: <code>truecolor</code></li>\n</ol></li>\n<li>As of writing, I haven't found a distro that accepts the COLORTERM variable over SSH by default. You'll need to edit your OpenSSH configuration on the host to allow it. For example, on Debian-like distros, edit <code>/etc/ssh/sshd_config</code> and add <code>COLORTERM</code> to the <code>AcceptEnv</code> line.</li>\n<li>Everything should now \"just work\". If it doesn't:\n\n<ol>\n<li>Ensure you've reconnected after making the change, or at least run <code>exec zsh</code> after changing <code>TERM</code>. zsh won't react to changes in <code>TERM</code> while it's running.</li>\n<li>Ensure that <code>TERM</code> is actually set to what you intended: <code>echo $TERM</code></li>\n<li>Are you on the latest version of your distro? If you're on a long-term support lifecycle build, for example, even if your version is technically still supported, it may not have up-to-date terminfo entries.</li>\n<li>Are you using <code>screen</code> or <code>tmux</code>? That's another whole can of worms. Test without those first to narrow down where the issue is occurring. Within tmux, try setting <code>TERM=tmux-256color</code>. Within screen, try <code>TERM=screen-256color</code>.</li>\n<li>Are you on the latest version of PuTTY?</li>\n<li>Do you have RC-files that are implementing keybindings or other hacks? Try using default RC-files.</li>\n<li>Did you already change various PuTTY settings to attempt to fix the issue before attempting the terminfo fix? You'll probably need to reset those settings.</li>\n</ol></li>\n</ol>\n" }, { "answer_id": 70126402, "author": "jordiburgos", "author_id": 1108098, "author_profile": "https://Stackoverflow.com/users/1108098", "pm_score": 0, "selected": false, "text": "<p>This worked for me.</p>\n<p>Adding these lines to ~/.zshrc</p>\n<pre><code>bindkey &quot;\\e[1;5D&quot; backward-word\nbindkey &quot;\\e[1;5C&quot; forward-word\n\n# ctrl-bs and ctrl-del\nbindkey &quot;\\e[3;5~&quot; kill-word\nbindkey &quot;\\C-_&quot; backward-kill-word\n\n# del, home and end\nbindkey &quot;\\e[3~&quot; delete-char\nbindkey &quot;\\e[H&quot; beginning-of-line\nbindkey &quot;\\e[F&quot; end-of-line\n\n# alt-bs\nbindkey &quot;\\e\\d&quot; undo\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
I'm running zsh as the default shell on a Ubuntu box, and everything works fine using gnome-terminal (which as far as I know emulates xterm). When I login from a windows box via ssh and putty (which also emulates xterm) suddendly the home/end keys no longer work. I've been able to solve that adding these lines to my zshrc file... ``` bindkey '\e[1~' beginning-of-line bindkey '\e[4~' end-of-line ``` ...but I'm still wondering what's wrong here. Any idea?
I found it's a combination: **One** The ZSH developers do not think that ZSH should define the actions of the `Home`, `End`, `Del`, ... keys. Debian and Ubuntu fix this by defining the normal actions the average user would expect in the global `/etc/zsh/zshrc` file. Following the relevant code (it is the same on Debian and Ubuntu): ``` if [[ "$TERM" != emacs ]]; then [[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char [[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line [[ -z "$terminfo[kend]" ]] || bindkey -M emacs "$terminfo[kend]" end-of-line [[ -z "$terminfo[kich1]" ]] || bindkey -M emacs "$terminfo[kich1]" overwrite-mode [[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char [[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line [[ -z "$terminfo[kend]" ]] || bindkey -M vicmd "$terminfo[kend]" vi-end-of-line [[ -z "$terminfo[kich1]" ]] || bindkey -M vicmd "$terminfo[kich1]" overwrite-mode [[ -z "$terminfo[cuu1]" ]] || bindkey -M viins "$terminfo[cuu1]" vi-up-line-or-history [[ -z "$terminfo[cuf1]" ]] || bindkey -M viins "$terminfo[cuf1]" vi-forward-char [[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history [[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history [[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char [[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char # ncurses fogyatekos [[ "$terminfo[kcuu1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history [[ "$terminfo[kcud1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history [[ "$terminfo[kcuf1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char [[ "$terminfo[kcub1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char [[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line [[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M viins "${terminfo[kend]/O/[}" end-of-line [[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line [[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M emacs "${terminfo[kend]/O/[}" end-of-line fi ``` So, if you are connecting to a Debian or Ubuntu box, you don't have to do anything. Everything should work automagically (if not, see below). But... if you are connecting to another box (e.g. FreeBSD), there might be no user friendly default `zshrc`. The solution is of course to add the lines from the Debian/Ubuntu `zshrc` to your own `.zshrc`. **Two** Putty sends `xterm` as terminal type to the remote host. But messes up somewhere and doesn't send the correct control codes for `Home`, `End`, ... that one would expect from an `xterm`. Or an `xterm` terminal isn't expected to send those or whatever... (`Del` key does work in `xterm` however, if you configure it in ZSH). Also notice that your Numpad-keys act funny in Vim for example with `xterm` terminal. The solution is to configure Putty to send another terminal type. I've tried `xterm-color` and `linux`. `xterm-color` fixed the `Home`/`End` problem, but the Numpad was still funny. Setting it to `linux` fixed both problems. You can set terminal type in Putty under Connection -> Data. Do not be tempted to set your terminal type in your `.zshrc` with `export TERM=linux`, that is just wrong. The terminal type should be specified by your terminal app. So that if, for example, you connect from a Mac box with a Mac SSH client it can set it's own terminal type. Notice that TERM specifies your terminal type and has nothing to do with the host you are connecting to. I can set my terminal type to `linux` in Putty and connect to FreeBSD servers without problems. So, fix both these things and you should be fine :)
161,687
<p>You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.</p> <p>So an example Perl problem:</p> <p>A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.</p> <p>The question, for Perl developers: What is your best way to accomplish this?</p>
[ { "answer_id": 161740, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": -1, "selected": false, "text": "<p>I write a subroutine that reads a directory with <code>readdir</code>, throws out the \".\" and \"..\" directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use <code>utime</code> or <code>stat</code>). By time the recursion is done, every file should have been examined.</p>\n\n<p>I think all the functions you'd need for this script are described briefly here:\n<a href=\"http://www.cs.cf.ac.uk/Dave/PERL/node70.html\" rel=\"nofollow noreferrer\">http://www.cs.cf.ac.uk/Dave/PERL/node70.html</a></p>\n\n<p>The semantics of input and output are a fairly trivial exercise which I'll leave to you.</p>\n" }, { "answer_id": 161744, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": -1, "selected": false, "text": "<p>I'm riskying to get downvoted, but IMHO 'ls' (with appropriate params) command does it in a best known performant way. In this case it might be quite good solution to pipe 'ls' from perl code through shell, returning results to an array or hash.</p>\n\n<p>Edit: It could also be 'find' used, as proposed in comments. </p>\n" }, { "answer_id": 161760, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~rgarcia/perl-5.10.0/lib/File/Find.pm\" rel=\"nofollow noreferrer\">File::Find</a> is the right way to solve this problem. There is no use in reimplementing stuff that already exists in other modules, but reimplementing something that is in a standard module should really be discouraged.</p>\n" }, { "answer_id": 161762, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>My preferred method is to use the File::Find module as so:</p>\n\n<pre><code>use File::Find;\nfind (\\&amp;checkFile, $directory_to_check_recursively);\n\nsub checkFile()\n{\n #examine each file in here. Filename is in $_ and you are chdired into it's directory\n #directory is also available in $File::Find::dir\n}\n</code></pre>\n" }, { "answer_id": 161766, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 4, "selected": false, "text": "<p>Where the problem is solved mainly by standard libraries use them.</p>\n\n<p>File::Find in this case works nicely.</p>\n\n<p>There may be many ways to do things in perl, but where a very standard library exists to do something, it should be utilised unless it has problems of it's own.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse File::Find();\n\nFile::Find::find( {wanted =&gt; \\&amp;wanted}, \".\");\n\nsub wanted {\n my (@stat);\n my ($time) = time();\n my ($days) = 5 * 60 * 60 * 24;\n\n @stat = stat($_);\n if (($time - $stat[9]) &gt;= $days) {\n print \"$_ \\n\";\n }\n}\n</code></pre>\n" }, { "answer_id": 162436, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 5, "selected": true, "text": "<p>This sounds like a job for <a href=\"http://search.cpan.org/perldoc?File::Find::Rule\" rel=\"nofollow noreferrer\">File::Find::Rule</a>:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse autodie; # Causes built-ins like open to succeed or die.\n # You can 'use Fatal qw(open)' if autodie is not installed.\n\nuse File::Find::Rule;\nuse Getopt::Std;\n\nuse constant SECONDS_IN_DAY =&gt; 24 * 60 * 60;\n\nour %option = (\n m =&gt; 1, # -m switch: days ago modified, defaults to 1\n o =&gt; undef, # -o switch: output file, defaults to STDOUT\n);\n\ngetopts('m:o:', \\%option);\n\n# If we haven't been given directories to search, default to the\n# current working directory.\n\nif (not @ARGV) {\n @ARGV = ( '.' );\n}\n\nprint STDERR \"Finding files changed in the last $option{m} day(s)\\n\";\n\n\n# Convert our time in days into a timestamp in seconds from the epoch.\nmy $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};\n\n# Now find all the regular files, which have been modified in the last\n# $option{m} days, looking in all the locations specified in\n# @ARGV (our remaining command line arguments).\n\nmy @files = File::Find::Rule-&gt;file()\n -&gt;mtime(\"&gt;= $last_modified_timestamp\")\n -&gt;in(@ARGV);\n\n# $out_fh will store the filehandle where we send the file list.\n# It defaults to STDOUT.\n\nmy $out_fh = \\*STDOUT;\n\nif ($option{o}) {\n open($out_fh, '&gt;', $option{o});\n}\n\n# Print our results.\n\nprint {$out_fh} join(\"\\n\", @files), \"\\n\";\n</code></pre>\n" }, { "answer_id": 162502, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 3, "selected": false, "text": "<p>There aren't six ways to do this, there's the old way, and the new way. The old way is with File::Find, and you already have a couple of examples of that. File::Find has a pretty awful callback interface, it was cool 20 years ago, but we've moved on since then. </p>\n\n<p>Here's a real life (lightly amended) program I use to clear out the cruft on one of my production servers. It uses File::Find::Rule, rather than File::Find. File::Find::Rule has a nice declarative interface that reads easily.</p>\n\n<p>Randal Schwartz also wrote File::Finder, as a wrapper over File::Find. It's quite nice but it hasn't really taken off.</p>\n\n<pre><code>#! /usr/bin/perl -w\n\n# delete temp files on agr1\n\nuse strict;\nuse File::Find::Rule;\nuse File::Path 'rmtree';\n\nfor my $file (\n\n File::Find::Rule-&gt;new\n -&gt;mtime( '&lt;' . days_ago(2) )\n -&gt;name( qr/^CGItemp\\d+$/ )\n -&gt;file()\n -&gt;in('/tmp'),\n\n File::Find::Rule-&gt;new\n -&gt;mtime( '&lt;' . days_ago(20) )\n -&gt;name( qr/^listener-\\d{4}-\\d{2}-\\d{2}-\\d{4}.log$/ )\n -&gt;file()\n -&gt;maxdepth(1)\n -&gt;in('/usr/oracle/ora81/network/log'),\n\n File::Find::Rule-&gt;new\n -&gt;mtime( '&lt;' . days_ago(10) )\n -&gt;name( qr/^batch[_-]\\d{8}-\\d{4}\\.run\\.txt$/ )\n -&gt;file()\n -&gt;maxdepth(1)\n -&gt;in('/var/log/req'),\n\n File::Find::Rule-&gt;new\n -&gt;mtime( '&lt;' . days_ago(20) )\n -&gt;or(\n File::Find::Rule-&gt;name( qr/^remove-\\d{8}-\\d{6}\\.txt$/ ),\n File::Find::Rule-&gt;name( qr/^insert-tp-\\d{8}-\\d{4}\\.log$/ ),\n )\n -&gt;file()\n -&gt;maxdepth(1)\n -&gt;in('/home/agdata/import/logs'),\n\n File::Find::Rule-&gt;new\n -&gt;mtime( '&lt;' . days_ago(90) )\n -&gt;or(\n File::Find::Rule-&gt;name( qr/^\\d{8}-\\d{6}\\.txt$/ ),\n File::Find::Rule-&gt;name( qr/^\\d{8}-\\d{4}\\.report\\.txt$/ ),\n )\n -&gt;file()\n -&gt;maxdepth(1)\n -&gt;in('/home/agdata/redo/log'),\n\n) {\n if (unlink $file) {\n print \"ok $file\\n\";\n }\n else {\n print \"fail $file: $!\\n\";\n }\n}\n\n{\n my $now;\n sub days_ago {\n # days as number of seconds\n $now ||= time;\n return $now - (86400 * shift);\n }\n}\n</code></pre>\n" }, { "answer_id": 162781, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 3, "selected": false, "text": "<p>Others have mentioned File::Find, which is the way I'd go, but you asked for an iterator, which File::Find isn't (nor is File::Find::Rule). You might want to look at <a href=\"http://search.cpan.org/dist/File-Next/\" rel=\"nofollow noreferrer\">File::Next</a> or <a href=\"http://search.cpan.org/dist/File-Find-Object/\" rel=\"nofollow noreferrer\">File::Find::Object</a>, which do have an iterative interfaces. Mark Jason Dominus goes over building your own in chapter 4.2.2 of <a href=\"http://hop.perl.plover.com/book/\" rel=\"nofollow noreferrer\">Higher Order Perl</a>.</p>\n" }, { "answer_id": 164929, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 2, "selected": false, "text": "<p>I wrote <a href=\"http://search.cpan.org/dist/File-Find-Closures\" rel=\"nofollow noreferrer\">File::Find::Closures</a> as a set of closures that you can use with File::Find so you don't have to write your own. There's a couple of mtime functions that should handle </p>\n\n<pre>\nuse File::Find;\nuse File::Find::Closures qw(:all);\n\nmy( $wanted, $list_reporter ) = find_by_modified_after( time - 86400 );\n#my( $wanted, $list_reporter ) = find_by_modified_before( time - 86400 );\n\nFile::Find::find( $wanted, @directories );\n\nmy @modified = $list_reporter->();\n</pre>\n\n<p>You don't really need to use the module because I mostly designed it as a way that you could look at the code and steal the parts that you wanted. In this case it's a little trickier because all the subroutines that deal with stat depend on a second subroutine. You'll quickly get the idea from the code though.</p>\n\n<p>Good luck,</p>\n" }, { "answer_id": 171573, "author": "Randal Schwartz", "author_id": 22483, "author_profile": "https://Stackoverflow.com/users/22483", "pm_score": 2, "selected": false, "text": "<p>There's my <a href=\"http://search.cpan.org/perldoc/File::Finder\" rel=\"nofollow noreferrer\">File::Finder</a>, as already mentioned, but there's also my iterator-as-a-tied-hash solution from <a href=\"http://www.stonehenge.com/merlyn/LinuxMag/col30.html\" rel=\"nofollow noreferrer\">Finding Files Incrementally (Linux Magazine)</a>.</p>\n" }, { "answer_id": 4621689, "author": "Hien", "author_id": 566287, "author_profile": "https://Stackoverflow.com/users/566287", "pm_score": 0, "selected": false, "text": "<p>Using standard modules is indeed a good idea but out of interest here is my back to basic approach using no external modules. I know code syntax here might not be everyone's cup of tea. </p>\n\n<p>It could be improved to use less memory via providing an iterator access (input list could temporarily be on hold once it reaches a certain size) and conditional check can be expanded via callback ref.</p>\n\n<pre><code>sub mfind {\n my %done;\n\n sub find {\n my $last_mod = shift;\n my $path = shift;\n\n #determine physical link if symlink\n $path = readlink($path) || $path; \n\n #return if already processed\n return if $done{$path} &gt; 1;\n\n #mark path as processed\n $done{$path}++;\n\n #DFS recursion \n return grep{$_} @_\n ? ( find($last_mod, $path), find($last_mod, @_) ) \n : -d $path\n ? find($last_mod, glob(\"$path/*\") )\n : -f $path &amp;&amp; (stat($path))[9] &gt;= $last_mod \n ? $path : undef;\n }\n\n return find(@_);\n}\n\nprint join \"\\n\", mfind(time - 1 * 86400, \"some path\");\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19468/" ]
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation. So an example Perl problem: A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file. The question, for Perl developers: What is your best way to accomplish this?
This sounds like a job for [File::Find::Rule](http://search.cpan.org/perldoc?File::Find::Rule): ``` #!/usr/bin/perl use strict; use warnings; use autodie; # Causes built-ins like open to succeed or die. # You can 'use Fatal qw(open)' if autodie is not installed. use File::Find::Rule; use Getopt::Std; use constant SECONDS_IN_DAY => 24 * 60 * 60; our %option = ( m => 1, # -m switch: days ago modified, defaults to 1 o => undef, # -o switch: output file, defaults to STDOUT ); getopts('m:o:', \%option); # If we haven't been given directories to search, default to the # current working directory. if (not @ARGV) { @ARGV = ( '.' ); } print STDERR "Finding files changed in the last $option{m} day(s)\n"; # Convert our time in days into a timestamp in seconds from the epoch. my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m}; # Now find all the regular files, which have been modified in the last # $option{m} days, looking in all the locations specified in # @ARGV (our remaining command line arguments). my @files = File::Find::Rule->file() ->mtime(">= $last_modified_timestamp") ->in(@ARGV); # $out_fh will store the filehandle where we send the file list. # It defaults to STDOUT. my $out_fh = \*STDOUT; if ($option{o}) { open($out_fh, '>', $option{o}); } # Print our results. print {$out_fh} join("\n", @files), "\n"; ```
161,717
<p>If I create a function with jQuery that adds an empty div, performs some animation inside the blank space created by the div, then removes the div, the browser never makes room for the empty div (height and width are set).</p> <p>If I don't remove the empty div in my function, then the browser will create the needed space and everything works correctly. However, I really need the blank space created by the div to be removed when the animation is complete.</p> <p>Is there a way to queue up the div removall so that the browser will show the desired behavior?</p>
[ { "answer_id": 161729, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>Doesn't it work if you use a setTimeout ?-)</p>\n" }, { "answer_id": 161809, "author": "Joe Brinkman", "author_id": 4820, "author_profile": "https://Stackoverflow.com/users/4820", "pm_score": 1, "selected": false, "text": "<p>By doing a Google search on jQuery and setTimeout, I found an example which sent me down a different track. The problem occurs, I think, because the div manipulation is on a separate selector from the actual animation. This causes the div to be created and removed even while the animation is still occuring. By adding a simple animate statement to the div which delays the removal until after the main animation completes, then I can achieve the desired effect.</p>\n" }, { "answer_id": 165128, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 0, "selected": false, "text": "<p>The problem is that the DOM isn't updated until your function ends. So using setTimeout will cause the dom to update and 100ms later the rest of your function can continue. If you don't want the new div to be seen, I'd set the position to absolute and the top to something like -5000. It will have dimensions etc, just wont' be visible. You can also set the visibility (in css) to hidden just incase you are worried it will show up on screen.</p>\n" }, { "answer_id": 263947, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 2, "selected": false, "text": "<p>Some jQuery effects have callbacks, which will are run after the effect, for example:</p>\n\n<pre><code>$('#someDiv').slideDown(100, function() { \n $(this).remove(); \n});\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820/" ]
If I create a function with jQuery that adds an empty div, performs some animation inside the blank space created by the div, then removes the div, the browser never makes room for the empty div (height and width are set). If I don't remove the empty div in my function, then the browser will create the needed space and everything works correctly. However, I really need the blank space created by the div to be removed when the animation is complete. Is there a way to queue up the div removall so that the browser will show the desired behavior?
Some jQuery effects have callbacks, which will are run after the effect, for example: ``` $('#someDiv').slideDown(100, function() { $(this).remove(); }); ```
161,738
<p>How can I check if a given string is a valid URL address?</p> <p>My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.</p>
[ { "answer_id": 161749, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "<p>The post <a href=\"https://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex#27755\">Getting parts of a URL (Regex)</a> discusses parsing a URL to identify its various components. If you want to check if a URL is well-formed, it should be sufficient for your needs.</p>\n\n<p>If you need to check if it's actually valid, you'll eventually have to try to access whatever's on the other end.</p>\n\n<p>In general, though, you'd probably be better off using a function that's supplied to you by your framework or another library. Many platforms include functions that parse URLs. For example, there's Python's <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"noreferrer\">urlparse</a> module, and in .NET you could use the <a href=\"http://msdn.microsoft.com/en-us/library/aa332621.aspx\" rel=\"noreferrer\">System.Uri class's constructor</a> as a means of validating the URL.</p>\n" }, { "answer_id": 161756, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 6, "selected": false, "text": "<p>What platform? If using .NET, use <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.trycreate\" rel=\"noreferrer\"><code>System.Uri.TryCreate</code></a>, not a regex.</p>\n\n<p>For example:</p>\n\n<pre><code>static bool IsValidUrl(string urlString)\n{\n Uri uri;\n return Uri.TryCreate(urlString, UriKind.Absolute, out uri)\n &amp;&amp; (uri.Scheme == Uri.UriSchemeHttp\n || uri.Scheme == Uri.UriSchemeHttps\n || uri.Scheme == Uri.UriSchemeFtp\n || uri.Scheme == Uri.UriSchemeMailto\n /*...*/);\n}\n\n// In test fixture...\n\n[Test]\nvoid IsValidUrl_Test()\n{\n Assert.True(IsValidUrl(\"http://www.example.com\"));\n Assert.False(IsValidUrl(\"javascript:alert('xss')\"));\n Assert.False(IsValidUrl(\"\"));\n Assert.False(IsValidUrl(null));\n}\n</code></pre>\n\n<p>(Thanks to <a href=\"https://stackoverflow.com/users/450141/yoshi\">@Yoshi</a> for the tip about <code>javascript:</code>)</p>\n" }, { "answer_id": 161771, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": false, "text": "<p>If you really search for the <strong>ultimate</strong> match, you probably find it on \"<a href=\"http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/\" rel=\"nofollow noreferrer\">A Good Url Regular Expression?</a>\".</p>\n\n<p>But a regex that really matches all possible domains and allows anything that is allowed according to RFCs is horribly long and unreadable, trust me ;-)</p>\n" }, { "answer_id": 161779, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 4, "selected": false, "text": "<h1>Non-validating URI-reference Parser</h1>\n<p>For reference purposes, here's the IETF Spec: (<a href=\"http://www.ietf.org/rfc/rfc3986.txt\" rel=\"nofollow noreferrer\">TXT</a> | <a href=\"https://www.rfc-editor.org/rfc/rfc3986#appendix-B\" rel=\"nofollow noreferrer\">HTML</a>). In particular, <em>Appendix B. <strong>Parsing</strong> a URI Reference with a Regular Expression</em> demonstrates how to parse a <strong>valid regex</strong>. This is described as,</p>\n<blockquote>\n<p>for an example of a non-validating URI-reference parser that will take any given string and extract the URI components.</p>\n</blockquote>\n<p>Here's the regex they provide:</p>\n<pre><code> ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n</code></pre>\n<p>As someone else said, it's probably best to leave this to a lib/framework you're already using.</p>\n" }, { "answer_id": 163684, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 6, "selected": false, "text": "<p>Here's what <a href=\"http://en.wikipedia.org/wiki/RegexBuddy\" rel=\"nofollow noreferrer\">RegexBuddy</a> uses.</p>\n<pre><code>(\\b(https?|ftp|file)://)?[-A-Za-z0-9+&amp;@#/%?=~_|!:,.;]+[-A-Za-z0-9+&amp;@#/%=~_|]\n</code></pre>\n<p>It matches these below (inside the <code>** **</code> marks):</p>\n<pre><code>**http://www.regexbuddy.com** \n**http://www.regexbuddy.com/** \n**http://www.regexbuddy.com/index.html** \n**http://www.regexbuddy.com/index.html?source=library** \n**http://www.regexbuddy.com/index.html?source=library#copyright** \n</code></pre>\n<p>You can download RegexBuddy at <strong><a href=\"http://www.regexbuddy.com/download.html\" rel=\"nofollow noreferrer\">http://www.regexbuddy.com/download.html</a></strong>.</p>\n" }, { "answer_id": 190405, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 9, "selected": false, "text": "<p>I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 (<a href=\"http://www.faqs.org/rfcs/rfc3987.html\" rel=\"noreferrer\">http://www.faqs.org/rfcs/rfc3987.html</a>). These are in PCRE syntax.</p>\n\n<p>For absolute IRIs (internationalized):</p>\n\n<pre><code>/^[a-z](?:[-a-z0-9\\+\\.])*:(?:\\/\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:])*@)?(?:\\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9\\._~!\\$&amp;'\\(\\)\\*\\+,;=:]+)\\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=])*)(?::[0-9]*)?(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|\\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])))(?:\\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\x{E000}-\\x{F8FF}\\x{F0000}-\\x{FFFFD}\\x{100000}-\\x{10FFFD}\\/\\?])*)?(?:\\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\/\\?])*)?$/i\n</code></pre>\n\n<p>To also allow relative IRIs:</p>\n\n<pre><code>/^(?:[a-z](?:[-a-z0-9\\+\\.])*:(?:\\/\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:])*@)?(?:\\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9\\._~!\\$&amp;'\\(\\)\\*\\+,;=:]+)\\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=])*)(?::[0-9]*)?(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|\\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])))(?:\\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\x{E000}-\\x{F8FF}\\x{F0000}-\\x{FFFFD}\\x{100000}-\\x{10FFFD}\\/\\?])*)?(?:\\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\/\\?])*)?|(?:\\/\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:])*@)?(?:\\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9\\._~!\\$&amp;'\\(\\)\\*\\+,;=:]+)\\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=])*)(?::[0-9]*)?(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|\\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=@])+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])))(?:\\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\x{E000}-\\x{F8FF}\\x{F0000}-\\x{FFFFD}\\x{100000}-\\x{10FFFD}\\/\\?])*)?(?:\\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\/\\?])*)?)$/i\n</code></pre>\n\n<p>How they were compiled (in PHP):</p>\n\n<pre><code>&lt;?php\n\n/* Regex convenience functions (character class, non-capturing group) */\nfunction cc($str, $suffix = '', $negate = false) {\n return '[' . ($negate ? '^' : '') . $str . ']' . $suffix;\n}\nfunction ncg($str, $suffix = '') {\n return '(?:' . $str . ')' . $suffix;\n}\n\n/* Preserved from RFC3986 */\n\n$ALPHA = 'a-z';\n$DIGIT = '0-9';\n$HEXDIG = $DIGIT . 'a-f';\n\n$sub_delims = '!\\\\$&amp;\\'\\\\(\\\\)\\\\*\\\\+,;=';\n$gen_delims = ':\\\\/\\\\?\\\\#\\\\[\\\\]@';\n$reserved = $gen_delims . $sub_delims;\n$unreserved = '-' . $ALPHA . $DIGIT . '\\\\._~';\n\n$pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG);\n\n$dec_octet = ncg(implode('|', array(\n cc($DIGIT),\n cc('1-9') . cc($DIGIT),\n '1' . cc($DIGIT) . cc($DIGIT),\n '2' . cc('0-4') . cc($DIGIT),\n '25' . cc('0-5')\n)));\n\n$IPv4address = $dec_octet . ncg('\\\\.' . $dec_octet, '{3}');\n\n$h16 = cc($HEXDIG, '{1,4}');\n$ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address);\n\n$IPv6address = ncg(implode('|', array(\n ncg($h16 . ':', '{6}') . $ls32,\n '::' . ncg($h16 . ':', '{5}') . $ls32,\n ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32,\n ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32,\n ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32,\n ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32,\n ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32,\n ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16,\n ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::',\n)));\n\n$IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+');\n\n$IP_literal = '\\\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\\\]';\n\n$port = cc($DIGIT, '*');\n\n$scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\\\+\\\\.'), '*');\n\n/* New or changed in RFC3987 */\n\n$iprivate = '\\x{E000}-\\x{F8FF}\\x{F0000}-\\x{FFFFD}\\x{100000}-\\x{10FFFD}';\n\n$ucschar = '\\x{A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}' .\n '\\x{10000}-\\x{1FFFD}\\x{20000}-\\x{2FFFD}\\x{30000}-\\x{3FFFD}' .\n '\\x{40000}-\\x{4FFFD}\\x{50000}-\\x{5FFFD}\\x{60000}-\\x{6FFFD}' .\n '\\x{70000}-\\x{7FFFD}\\x{80000}-\\x{8FFFD}\\x{90000}-\\x{9FFFD}' .\n '\\x{A0000}-\\x{AFFFD}\\x{B0000}-\\x{BFFFD}\\x{C0000}-\\x{CFFFD}' .\n '\\x{D0000}-\\x{DFFFD}\\x{E1000}-\\x{EFFFD}';\n\n$iunreserved = '-' . $ALPHA . $DIGIT . '\\\\._~' . $ucschar;\n\n$ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@'));\n\n$ifragment = ncg($ipchar . '|' . cc('\\\\/\\\\?'), '*');\n\n$iquery = ncg($ipchar . '|' . cc($iprivate . '\\\\/\\\\?'), '*');\n\n$isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+');\n$isegment_nz = ncg($ipchar, '+');\n$isegment = ncg($ipchar, '*');\n\n$ipath_empty = '(?!' . $ipchar . ')';\n$ipath_rootless = ncg($isegment_nz) . ncg('\\\\/' . $isegment, '*');\n$ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\\\/' . $isegment, '*');\n$ipath_absolute = '\\\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( \"/\" isegment )\n$ipath_abempty = ncg('\\\\/' . $isegment, '*');\n\n$ipath = ncg(implode('|', array(\n $ipath_abempty,\n $ipath_absolute,\n $ipath_noscheme,\n $ipath_rootless,\n $ipath_empty\n))) . ')';\n\n$ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*');\n\n$ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name)));\n$iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*');\n$iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?');\n\n$irelative_part = ncg(implode('|', array(\n '\\\\/\\\\/' . $iauthority . $ipath_abempty . '',\n '' . $ipath_absolute . '',\n '' . $ipath_noscheme . '',\n '' . $ipath_empty . ''\n)));\n\n$irelative_ref = $irelative_part . ncg('\\\\?' . $iquery, '?') . ncg('\\\\#' . $ifragment, '?');\n\n$ihier_part = ncg(implode('|', array(\n '\\\\/\\\\/' . $iauthority . $ipath_abempty . '',\n '' . $ipath_absolute . '',\n '' . $ipath_rootless . '',\n '' . $ipath_empty . ''\n)));\n\n$absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\\\?' . $iquery, '?');\n\n$IRI = $scheme . ':' . $ihier_part . ncg('\\\\?' . $iquery, '?') . ncg('\\\\#' . $ifragment, '?');\n\n$IRI_reference = ncg($IRI . '|' . $irelative_ref);\n</code></pre>\n\n<p>Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way:</p>\n\n<pre><code>$escape_backslash = '/(?&lt;!\\\\)\\\\(?![\\[\\]\\\\\\^\\$\\.\\|\\*\\+\\(\\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\\{[0-9a-f]{1,4}\\}|\\c[A-Z]|)/';\n$absolute_IRI = preg_replace($escape_backslash, '\\\\\\\\', $absolute_IRI);\n$IRI = preg_replace($escape_backslash, '\\\\\\\\', $IRI);\n$IRI_reference = preg_replace($escape_backslash, '\\\\\\\\', $IRI_reference);\n</code></pre>\n" }, { "answer_id": 2015516, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>With regard to <strong>eyelidness</strong>' answer post that reads \"This is based on my reading of the URI specification.\": Thanks Eyelidness, yours is the perfect solution I sought, as it is based on the URI spec! Superb work. :)</p>\n\n<p>I had to make two amendments. The first to get the regexp to match IP address URLs correctly in PHP (v5.2.10) with the preg_match() function.</p>\n\n<p>I had to add one more set of parenthesis to the line above \"IP Address\" around the pipes:</p>\n\n<pre><code>)|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}(?#\n</code></pre>\n\n<p>Not sure why.</p>\n\n<p>I have also reduced the top level domain minimum length from 3 to 2 letters to support .co.uk and similar.</p>\n\n<p>Final code:</p>\n\n<pre><code>/^(https?|ftp):\\/\\/(?# protocol\n)(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+(?# username\n)(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+)?(?# password\n)@)?(?# auth requires @\n)((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*(?# domain segments AND\n)[a-z][a-z0-9-]*[a-z0-9](?# top level domain OR\n)|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}(?#\n )(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])(?# IP address\n))(:\\d+)?(?# port\n))(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)*(?# path\n)(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)(?# query string\n)?)?)?(?# path and query string optional\n)(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)?(?# fragment\n)$/i\n</code></pre>\n\n<p>This modified version was not checked against the URI specification so I can't vouch for it's compliance, it was altered to handle URLs on local network environments and two digit TLDs as well as other kinds of Web URL, and to work better in the PHP setup I use.</p>\n\n<p>As <strong>PHP</strong> code:</p>\n\n<pre><code>define('URL_FORMAT', \n'/^(https?):\\/\\/'. // protocol\n'(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+'. // username\n'(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+)?'. // password\n'@)?(?#'. // auth requires @\n')((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*'. // domain segments AND\n'[a-z][a-z0-9-]*[a-z0-9]'. // top level domain OR\n'|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}'.\n'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])'. // IP address\n')(:\\d+)?'. // port\n')(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)*'. // path\n'(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)'. // query string\n'?)?)?'. // path and query string optional\n'(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)?'. // fragment\n'$/i');\n</code></pre>\n\n<p>Here is a test program in PHP which validates a variety of URLs using the regex:</p>\n\n<pre><code>&lt;?php\n\ndefine('URL_FORMAT',\n'/^(https?):\\/\\/'. // protocol\n'(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+'. // username\n'(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&amp;=-]|%[0-9a-f]{2})+)?'. // password\n'@)?(?#'. // auth requires @\n')((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*'. // domain segments AND\n'[a-z][a-z0-9-]*[a-z0-9]'. // top level domain OR\n'|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}'.\n'(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])'. // IP address\n')(:\\d+)?'. // port\n')(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)*'. // path\n'(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)'. // query string\n'?)?)?'. // path and query string optional\n'(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&amp;=-]|%[0-9a-f]{2})*)?'. // fragment\n'$/i');\n\n/**\n * Verify the syntax of the given URL. \n * \n * @access public\n * @param $url The URL to verify.\n * @return boolean\n */\nfunction is_valid_url($url) {\n if (str_starts_with(strtolower($url), 'http://localhost')) {\n return true;\n }\n return preg_match(URL_FORMAT, $url);\n}\n\n\n/**\n * String starts with something\n * \n * This function will return true only if input string starts with\n * niddle\n * \n * @param string $string Input string\n * @param string $niddle Needle string\n * @return boolean\n */\nfunction str_starts_with($string, $niddle) {\n return substr($string, 0, strlen($niddle)) == $niddle;\n}\n\n\n/**\n * Test a URL for validity and count results.\n * @param url url\n * @param expected expected result (true or false)\n */\n\n$numtests = 0;\n$passed = 0;\n\nfunction test_url($url, $expected) {\n global $numtests, $passed;\n $numtests++;\n $valid = is_valid_url($url);\n echo \"URL Valid?: \" . ($valid?\"yes\":\"no\") . \" for URL: $url. Expected: \".($expected?\"yes\":\"no\").\". \";\n if($valid == $expected) {\n echo \"PASS\\n\"; $passed++;\n } else {\n echo \"FAIL\\n\";\n }\n}\n\necho \"URL Tests:\\n\\n\";\n\ntest_url(\"http://localserver/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css\", true);\ntest_url(\"http://www.google.com\", true);\ntest_url(\"http://www.google.co.uk/projects/my%20folder/test.php\", true);\ntest_url(\"https://myserver.localdomain\", true);\ntest_url(\"http://192.168.1.120/projects/index.php\", true);\ntest_url(\"http://192.168.1.1/projects/index.php\", true);\ntest_url(\"http://projectpier-server.localdomain/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css\", true);\ntest_url(\"https://2.4.168.19/project-pier?c=test&amp;a=b\", true);\ntest_url(\"https://localhost/a/b/c/test.php?c=controller&amp;arg1=20&amp;arg2=20\", true);\ntest_url(\"http://user:password@localhost/a/b/c/test.php?c=controller&amp;arg1=20&amp;arg2=20\", true);\n\necho \"\\n$passed out of $numtests tests passed.\\n\\n\";\n\n?&gt;\n</code></pre>\n\n<p>Thanks again to <strong>eyelidness</strong> for the regex!</p>\n" }, { "answer_id": 5268056, "author": "ridgerunner", "author_id": 433790, "author_profile": "https://Stackoverflow.com/users/433790", "pm_score": 3, "selected": false, "text": "<p>I've been working on an in-depth article discussing URI validation using regular expressions. It is based on RFC3986. </p>\n\n<p><a href=\"http://jmrware.com/articles/2009/uri_regexp/URI_regex.html\" rel=\"nofollow\">Regular Expression URI Validation</a></p>\n\n<p>Although the article is not yet complete, I have come up with a PHP function which does a pretty good job of validating HTTP and FTP URLs. Here is the current version:</p>\n\n\n\n<pre class=\"lang-php prettyprint-override\"><code>// function url_valid($url) { Rev:20110423_2000\n//\n// Return associative array of valid URI components, or FALSE if $url is not\n// RFC-3986 compliant. If the passed URL begins with: \"www.\" or \"ftp.\", then\n// \"http://\" or \"ftp://\" is prepended and the corrected full-url is stored in\n// the return array with a key name \"url\". This value should be used by the caller.\n//\n// Return value: FALSE if $url is not valid, otherwise array of URI components:\n// e.g.\n// Given: \"http://www.jmrware.com:80/articles?height=10&amp;width=75#fragone\"\n// Array(\n// [scheme] =&gt; http\n// [authority] =&gt; www.jmrware.com:80\n// [userinfo] =&gt;\n// [host] =&gt; www.jmrware.com\n// [IP_literal] =&gt;\n// [IPV6address] =&gt;\n// [ls32] =&gt;\n// [IPvFuture] =&gt;\n// [IPv4address] =&gt;\n// [regname] =&gt; www.jmrware.com\n// [port] =&gt; 80\n// [path_abempty] =&gt; /articles\n// [query] =&gt; height=10&amp;width=75\n// [fragment] =&gt; fragone\n// [url] =&gt; http://www.jmrware.com:80/articles?height=10&amp;width=75#fragone\n// )\nfunction url_valid($url) {\n if (strpos($url, 'www.') === 0) $url = 'http://'. $url;\n if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;\n if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.\n ^\n (?P&lt;scheme&gt;[A-Za-z][A-Za-z0-9+\\-.]*):\\/\\/\n (?P&lt;authority&gt;\n (?:(?P&lt;userinfo&gt;(?:[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?\n (?P&lt;host&gt;\n (?P&lt;IP_literal&gt;\n \\[\n (?:\n (?P&lt;IPV6address&gt;\n (?: (?:[0-9A-Fa-f]{1,4}:){6}\n | ::(?:[0-9A-Fa-f]{1,4}:){5}\n | (?: [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}:\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::\n )\n (?P&lt;ls32&gt;[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}\n | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}\n (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n )\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}\n | (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::\n )\n | (?P&lt;IPvFuture&gt;[Vv][0-9A-Fa-f]+\\.[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=:]+)\n )\n \\]\n )\n | (?P&lt;IPv4address&gt;(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}\n (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\n | (?P&lt;regname&gt;(?:[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=]|%[0-9A-Fa-f]{2})+)\n )\n (?::(?P&lt;port&gt;[0-9]*))?\n )\n (?P&lt;path_abempty&gt;(?:\\/(?:[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)\n (?:\\?(?P&lt;query&gt; (?:[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=:@\\\\/?]|%[0-9A-Fa-f]{2})*))?\n (?:\\#(?P&lt;fragment&gt; (?:[A-Za-z0-9\\-._~!$&amp;\\'()*+,;=:@\\\\/?]|%[0-9A-Fa-f]{2})*))?\n $\n /mx', $url, $m)) return FALSE;\n switch ($m['scheme']) {\n case 'https':\n case 'http':\n if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.\n break;\n case 'ftps':\n case 'ftp':\n break;\n default:\n return FALSE; // Unrecognized URI scheme. Default to FALSE.\n }\n // Validate host name conforms to DNS \"dot-separated-parts\".\n if ($m['regname']) { // If host regname specified, check for DNS conformance.\n if (!preg_match('/# HTTP DNS host name.\n ^ # Anchor to beginning of string.\n (?!.{256}) # Overall host length is less than 256 chars.\n (?: # Group dot separated host part alternatives.\n [A-Za-z0-9]\\. # Either a single alphanum followed by dot\n | # or... part has more than one char (63 chars max).\n [A-Za-z0-9] # Part first char is alphanum (no dash).\n [A-Za-z0-9\\-]{0,61} # Internal chars are alphanum plus dash.\n [A-Za-z0-9] # Part last char is alphanum (no dash).\n \\. # Each part followed by literal dot.\n )* # Zero or more parts before top level domain.\n (?: # Explicitly specify top level domains.\n com|edu|gov|int|mil|net|org|biz|\n info|name|pro|aero|coop|museum|\n asia|cat|jobs|mobi|tel|travel|\n [A-Za-z]{2}) # Country codes are exactly two alpha chars.\n \\.? # Top level domain can end in a dot.\n $ # Anchor to end of string.\n /ix', $m['host'])) return FALSE;\n }\n $m['url'] = $url;\n for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);\n return $m; // return TRUE == array of useful named $matches plus the valid $url.\n}\n</code></pre>\n\n<p>This function utilizes two regexes; one to match a subset of valid generic URIs (absolute ones having a non-empty host), and a second to validate the DNS \"dot-separated-parts\" host name. Although this function currently validates only HTTP and FTP schemes, it is structured such that it can be easily extended to handle other schemes.</p>\n" }, { "answer_id": 6789329, "author": "vortex", "author_id": 757375, "author_profile": "https://Stackoverflow.com/users/757375", "pm_score": 2, "selected": false, "text": "<p>I think some people weren't able to use your php code because of the modifiers implied. I copied your code as is and used as an example:</p>\n\n<pre><code>if(\n preg_match(\n \"/^{$IRI_reference}$/iu\",\n 'http://www.url.com'\n )\n){\n echo 'true';\n}\n</code></pre>\n\n<p>Notice the \"i\" and \"u\" modifiers. without \"u\" php throws an exception saying:</p>\n\n<pre><code>Warning: preg_match() [function.preg-match]: Compilation failed: character value in \\x{...} sequence is too large at offset XX\n</code></pre>\n" }, { "answer_id": 8234912, "author": "Matthew O'Riordan", "author_id": 139607, "author_profile": "https://Stackoverflow.com/users/139607", "pm_score": 8, "selected": false, "text": "<p>I've just written up a blog post for a great solution for recognizing URLs in most used formats such as:</p>\n\n<ul>\n<li><code>www.google.com</code></li>\n<li><code>http://www.google.com</code></li>\n<li><code>mailto:[email protected]</code></li>\n<li><code>[email protected]</code></li>\n<li><code>www.url-with-querystring.com/?url=has-querystring</code></li>\n</ul>\n\n<p>The regular expression used is:</p>\n\n<pre><code>/((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&amp;=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&amp;=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&amp;;%@.\\w_]*)#?(?:[\\w]*))?)/\n</code></pre>\n" }, { "answer_id": 9284473, "author": "Kiril", "author_id": 28760, "author_profile": "https://Stackoverflow.com/users/28760", "pm_score": 6, "selected": false, "text": "<p>Mathias Bynens has a great article on the best comparison of a lot of regular expressions: <a href=\"https://mathiasbynens.be/demo/url-regex\" rel=\"nofollow noreferrer\">In search of the perfect URL validation regex</a></p>\n<p><a href=\"https://gist.github.com/729294\" rel=\"nofollow noreferrer\" title=\"Regular Expression for URL validation\">The best one posted</a> is a little long, but it matches just about anything you can throw at it.</p>\n<h3>JavaScript version</h3>\n<pre><code>/^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u00a1-\\uffff][a-z0-9\\u00a1-\\uffff_-]{0,62})?[a-z0-9\\u00a1-\\uffff]\\.)+(?:[a-z\\u00a1-\\uffff]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$/i\n</code></pre>\n<h3>PHP version (uses <code>%</code> symbol as delimiter)</h3>\n<pre><code>%^(?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\x{00a1}-\\x{ffff}][a-z0-9\\x{00a1}-\\x{ffff}_-]{0,62})?[a-z0-9\\x{00a1}-\\x{ffff}]\\.)+(?:[a-z\\x{00a1}-\\x{ffff}]{2,}\\.?))(?::\\d{2,5})?(?:[/?#]\\S*)?$%iuS\n</code></pre>\n" }, { "answer_id": 13048893, "author": "DroidOS", "author_id": 1077485, "author_profile": "https://Stackoverflow.com/users/1077485", "pm_score": 0, "selected": false, "text": "<p>This is a rather old thread now and the question asks for a regex based URL validator. I ran into the thread whilst looking for precisely the same thing. While it may well be possible to write a really comprehensive regex to validate URLs. I eventually settled on another way to do things - by using PHP's <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow noreferrer\">parse_url</a> function. </p>\n\n<p>It returns boolean false if the url cannot be parsed. Otherwise, it returns the scheme, the host and other information. This may well not be enough for a comprehensive URL check on its own, but can be drilled down into for further analysis. If the intent is to simply catch typos, invalid schemes etc. It is perfectly adequate!</p>\n" }, { "answer_id": 13069066, "author": "LifeInstructor", "author_id": 1524615, "author_profile": "https://Stackoverflow.com/users/1524615", "pm_score": 3, "selected": false, "text": "<pre><code>function validateURL(textval) {\n var urlregex = new RegExp(\n \"^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&amp;amp;%\\$#\\=~])*$\");\n return urlregex.test(textval);\n }\n</code></pre>\n\n<p>Matches \n<a href=\"http://www.asdah.com/~joe\">http://www.asdah.com/~joe</a> | <a href=\"ftp://ftp.asdah.co.uk:2828/asdah%20asdah.gif\">ftp://ftp.asdah.co.uk:2828/asdah%20asdah.gif</a> | <a href=\"https://asdah.gov/asdh-ah.as\">https://asdah.gov/asdh-ah.as</a></p>\n" }, { "answer_id": 13069128, "author": "LifeInstructor", "author_id": 1524615, "author_profile": "https://Stackoverflow.com/users/1524615", "pm_score": 3, "selected": false, "text": "<pre><code> function validateURL(textval) {\n var urlregex = new RegExp(\n \"^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&amp;amp;%\\$\\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\?\\'\\\\\\+&amp;amp;%\\$#\\=~_\\-]+))*$\");\n return urlregex.test(textval);\n }\n</code></pre>\n\n<p>Matches \n<a href=\"http://site.com/dir/file.php?var=moo\" rel=\"noreferrer\">http://site.com/dir/file.php?var=moo</a> | <a href=\"ftp://user:[email protected]:21/file/dir\" rel=\"noreferrer\">ftp://user:[email protected]:21/file/dir</a></p>\n\n<p>Non-Matches \nsite.com | <a href=\"http://site.com/dir//\" rel=\"noreferrer\">http://site.com/dir//</a></p>\n" }, { "answer_id": 13713556, "author": "Christopher Rivera", "author_id": 1259947, "author_profile": "https://Stackoverflow.com/users/1259947", "pm_score": 3, "selected": false, "text": "<p>I wrote a little groovy version that you can run</p>\n<p>it matches the following URLs (which is good enough for me)</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(args) {\n String url = &quot;go to http://www.m.abut.ly/abc its awesome&quot;\n url = url.replaceAll(/https?:\\/\\/w{0,3}\\w*?\\.(\\w*?\\.)?\\w{2,3}\\S*|www\\.(\\w*?\\.)?\\w*?\\.\\w{2,3}\\S*|(\\w*?\\.)?\\w*?\\.\\w{2,3}[\\/\\?]\\S*/ , { it -&gt;\n &quot;woof${it}woof&quot;\n })\n println url \n}\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>http://google.com\nhttp://google.com/help.php\nhttp://google.com/help.php?a=5\n\nhttp://www.google.com\nhttp://www.google.com/help.php\nhttp://www.google.com?a=5\n\ngoogle.com?a=5\ngoogle.com/help.php\ngoogle.com/help.php?a=5\n\nhttp://www.m.google.com/help.php?a=5 (and all its permutations)\nwww.m.google.com/help.php?a=5 (and all its permutations)\nm.google.com/help.php?a=5 (and all its permutations)\n</code></pre>\n<p>The important thing for any URLs that don't start with <code>http</code> or <code>www</code> is that they must include a <code>/</code> or <code>?</code></p>\n<p>I bet this can be tweaked a little more but it does the job pretty nice for being so short and compact... because you can pretty much split it in 3:</p>\n<p>find anything that starts with <code>http</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>https?:\\/\\/w{0,3}\\w*?\\.\\w{2,3}\\S*\n</code></pre>\n<p>find anything that starts with <code>www</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>www\\.\\w*?\\.\\w{2,3}\\S*\n</code></pre>\n<p>or find anything that must have a text then a dot then at least 2 letters and then a <code>?</code> or <code>/</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>\\w*?\\.\\w{2,3}[\\/\\?]\\S*\n</code></pre>\n" }, { "answer_id": 13739087, "author": "Ashish", "author_id": 1680395, "author_profile": "https://Stackoverflow.com/users/1680395", "pm_score": 2, "selected": false, "text": "<p>I tried to formulate my version of url. My requirement was to capture instances in a String where possible url can be cse.uom.ac.mu - noting that it is not preceded by http nor www</p>\n\n<pre><code>String regularExpression = \"((((ht{2}ps?://)?)((w{3}\\\\.)?))?)[^.&amp;&amp;[a-zA-Z0-9]][a-zA-Z0-9.-]+[^.&amp;&amp;[a-zA-Z0-9]](\\\\.[a-zA-Z]{2,3})\";\n\nassertTrue(\"www.google.com\".matches(regularExpression));\nassertTrue(\"www.google.co.uk\".matches(regularExpression));\nassertTrue(\"http://www.google.com\".matches(regularExpression));\nassertTrue(\"http://www.google.co.uk\".matches(regularExpression));\nassertTrue(\"https://www.google.com\".matches(regularExpression));\nassertTrue(\"https://www.google.co.uk\".matches(regularExpression));\nassertTrue(\"google.com\".matches(regularExpression));\nassertTrue(\"google.co.uk\".matches(regularExpression));\nassertTrue(\"google.mu\".matches(regularExpression));\nassertTrue(\"mes.intnet.mu\".matches(regularExpression));\nassertTrue(\"cse.uom.ac.mu\".matches(regularExpression));\n\n//cannot contain 2 '.' after www\nassertFalse(\"www..dr.google\".matches(regularExpression));\n\n//cannot contain 2 '.' just before com\nassertFalse(\"www.dr.google..com\".matches(regularExpression));\n\n// to test case where url www must be followed with a '.'\nassertFalse(\"www:google.com\".matches(regularExpression));\n\n// to test case where url www must be followed with a '.'\n//assertFalse(\"http://wwwe.google.com\".matches(regularExpression));\n\n// to test case where www must be preceded with a '.'\nassertFalse(\"https://[email protected]\".matches(regularExpression));\n</code></pre>\n" }, { "answer_id": 16425824, "author": "Ewan", "author_id": 1401034, "author_profile": "https://Stackoverflow.com/users/1401034", "pm_score": 2, "selected": false, "text": "<p>For Python, this is the actual URL validating regex used in Django 1.5.1:</p>\n\n<pre><code>import re\nregex = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' # ...or ipv4\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)' # ...or ipv6\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n</code></pre>\n\n<p>This does both ipv4 and ipv6 addresses as well as ports and GET parameters.</p>\n\n<p>Found in the <a href=\"https://github.com/django/django/blob/master/django/core/validators.py\" rel=\"nofollow\">code here</a>, Line 44.</p>\n" }, { "answer_id": 17181268, "author": "jojojohn", "author_id": 971563, "author_profile": "https://Stackoverflow.com/users/971563", "pm_score": 2, "selected": false, "text": "<p>whats wrong with plain and simple FILTER_VALIDATE_URL ?</p>\n\n<pre><code> $url = \"http://www.example.com\";\n\nif(!filter_var($url, FILTER_VALIDATE_URL))\n {\n echo \"URL is not valid\";\n }\nelse\n {\n echo \"URL is valid\";\n }\n</code></pre>\n\n<p>I know its not the question exactly but it did the job for me when I needed to validate urls so thought it might be useful to others who come across this post looking for the same thing</p>\n" }, { "answer_id": 17185781, "author": "thermz", "author_id": 954680, "author_profile": "https://Stackoverflow.com/users/954680", "pm_score": 3, "selected": false, "text": "<p>I was not able to find the regex I was looking for so I modified a regex to fullfill my requirements, and apparently it seems to work fine now. My requirements were:</p>\n\n<ul>\n<li>Match URLs w/o protocol (www.gooogle.com)</li>\n<li>Match URLs with query parameters and path (<a href=\"http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&amp;key2=value2e\" rel=\"noreferrer\">http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&amp;key2=value2e</a>)</li>\n<li>Don't match URLs where there are not acceptable characters (e.g. \"'£), for instance: (www.google.com/somthing\"/somethingmore)</li>\n</ul>\n\n<p>Here what I came up with, any suggestion is appreciated:</p>\n\n<pre><code>@Test\n public void testWebsiteUrl(){\n String regularExpression = \"((http|ftp|https):\\\\/\\\\/)?[\\\\w\\\\-_]+(\\\\.[\\\\w\\\\-_]+)+([\\\\w\\\\-\\\\.,@?^=%&amp;amp;:/~\\\\+#]*[\\\\w\\\\-\\\\@?^=%&amp;amp;/~\\\\+#])?\";\n\n assertTrue(\"www.google.com\".matches(regularExpression));\n assertTrue(\"www.google.co.uk\".matches(regularExpression));\n assertTrue(\"http://www.google.com\".matches(regularExpression));\n assertTrue(\"http://www.google.co.uk\".matches(regularExpression));\n assertTrue(\"https://www.google.com\".matches(regularExpression));\n assertTrue(\"https://www.google.co.uk\".matches(regularExpression));\n assertTrue(\"google.com\".matches(regularExpression));\n assertTrue(\"google.co.uk\".matches(regularExpression));\n assertTrue(\"google.mu\".matches(regularExpression));\n assertTrue(\"mes.intnet.mu\".matches(regularExpression));\n assertTrue(\"cse.uom.ac.mu\".matches(regularExpression));\n\n assertTrue(\"http://www.google.com/path\".matches(regularExpression));\n assertTrue(\"http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&amp;key2=value2e\".matches(regularExpression));\n assertTrue(\"http://www.google.com/?queryparam=123\".matches(regularExpression));\n assertTrue(\"http://www.google.com/path?queryparam=123\".matches(regularExpression));\n\n assertFalse(\"www..dr.google\".matches(regularExpression));\n\n assertFalse(\"www:google.com\".matches(regularExpression));\n\n assertFalse(\"https://[email protected]\".matches(regularExpression));\n\n assertFalse(\"https://www.google.com\\\"\".matches(regularExpression));\n assertFalse(\"https://www.google.com'\".matches(regularExpression));\n\n assertFalse(\"http://www.google.com/path'\".matches(regularExpression));\n assertFalse(\"http://subdomain.web-site.com/cgi-bin/perl.cgi?key1=value1&amp;key2=value2e'\".matches(regularExpression));\n assertFalse(\"http://www.google.com/?queryparam=123'\".matches(regularExpression));\n assertFalse(\"http://www.google.com/path?queryparam=12'3\".matches(regularExpression));\n\n }\n</code></pre>\n" }, { "answer_id": 17511761, "author": "Shantonu", "author_id": 1564801, "author_profile": "https://Stackoverflow.com/users/1564801", "pm_score": 2, "selected": false, "text": "<p>This one works for me very well. <code>(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?\\.[a-zA-Z0-9-]+(\\:|\\.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?</code></p>\n" }, { "answer_id": 17714711, "author": "S.p", "author_id": 1503110, "author_profile": "https://Stackoverflow.com/users/1503110", "pm_score": 4, "selected": false, "text": "<p>The best regular expression for URL for me would be:</p>\n\n<pre><code>\"(([\\w]+:)?//)?(([\\d\\w]|%[a-fA-F\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?([\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,4}(:[\\d]+)?(/([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(\\?(&amp;?([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?\"\n</code></pre>\n" }, { "answer_id": 18724720, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 5, "selected": false, "text": "<p><strong>This might not be a job for regexes, but for existing tools in your language of choice.</strong> You probably want to use existing code that has already been written, tested, and debugged.</p>\n\n<p>In PHP, use the <a href=\"http://php.net/manual/en/function.parse-url.php\"><code>parse_url</code></a> function.</p>\n\n<p>Perl: <a href=\"http://search.cpan.org/dist/URI/\"><code>URI</code> module</a>.</p>\n\n<p>Ruby: <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html\"><code>URI</code> module</a>.</p>\n\n<p>.NET: <a href=\"http://msdn.microsoft.com/en-us/library/txt7706a.aspx\">'Uri' class</a></p>\n\n<p><strong>Regexes are not a magic wand you wave at every problem that happens to involve strings.</strong></p>\n" }, { "answer_id": 19280767, "author": "Mohammad Anini", "author_id": 1711813, "author_profile": "https://Stackoverflow.com/users/1711813", "pm_score": 2, "selected": false, "text": "<p>The following RegEx will work:</p>\n\n<pre><code>\"@((((ht)|(f))tp[s]?://)|(www\\.))([a-z][-a-z0-9]+\\.)?([a-z][-a-z0-9]+\\.)?[a-z][-a-z0-9]+\\.[a-z]+[/]?[a-z0-9._\\/~#&amp;=;%+?-]*@si\"\n</code></pre>\n" }, { "answer_id": 20542241, "author": "Reetika", "author_id": 2667029, "author_profile": "https://Stackoverflow.com/users/2667029", "pm_score": 1, "selected": false, "text": "<p>To Check URL regex would be:</p>\n\n<pre><code>^http(s{0,1})://[a-zA-Z0-9_/\\\\-\\\\.]+\\\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\\\&amp;\\\\?\\\\=\\\\-\\\\.\\\\~\\\\%]*\n</code></pre>\n" }, { "answer_id": 23909979, "author": "Vinoth K S", "author_id": 3409006, "author_profile": "https://Stackoverflow.com/users/3409006", "pm_score": 2, "selected": false, "text": "<p>Use this one its working for me</p>\n\n<pre><code>function validUrl(Url) {\n var myRegExp =/^(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/i;\n\n if (!RegExp.test(Url.value)) {\n $(\"#urlErrorLbl\").removeClass('highlightNew');\n return false;\n } \n\n $(\"#urlErrorLbl\").addClass('highlightNew'); \n return true; \n}\n</code></pre>\n" }, { "answer_id": 24058129, "author": "Besnik Kastrati", "author_id": 2311058, "author_profile": "https://Stackoverflow.com/users/2311058", "pm_score": 5, "selected": false, "text": "<p>This will match all URLs</p>\n\n<ul>\n<li>with or without <em>http</em>/<em>https</em> </li>\n<li>with or without <em>www</em></li>\n</ul>\n\n<p>...including sub-domains and those new top-level domain name extensions such as \n .<em>museum</em>, \n .<em>academy</em>, \n .<em>foundation</em>\n etc. which can have up to 63 characters (not just .<em>com</em>, .<em>net</em>, .<em>info</em> etc.)</p>\n\n<pre><code>(([\\w]+:)?//)?(([\\d\\w]|%[a-fA-f\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?([\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,63}(:[\\d]+)?(/([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(\\?(&amp;?([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?\n</code></pre>\n\n<p>Because today maximum length of the available top-level domain name extension is 13 characters such as .<em>international</em>, you can change the number 63 in expression to 13 to prevent someone misusing it.</p>\n\n<p>as javascript</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var urlreg=/(([\\w]+:)?\\/\\/)?(([\\d\\w]|%[a-fA-f\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?([\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,63}(:[\\d]+)?(\\/([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(\\?(&amp;?([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?/;\r\n\r\n$('textarea').on('input',function(){\r\n var url = $(this).val();\r\n $(this).toggleClass('invalid', urlreg.test(url) == false)\r\n});\r\n\r\n$('textarea').trigger('input');</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>textarea{color:green;}\r\n.invalid{color:red;}</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;textarea&gt;http://www.google.com&lt;/textarea&gt;\r\n&lt;textarea&gt;http//www.google.com&lt;/textarea&gt;\r\n&lt;textarea&gt;googlecom&lt;/textarea&gt;\r\n&lt;textarea&gt;https://www.google.com&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Wikipedia Article: <a href=\"http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains\" rel=\"noreferrer\">List of all internet top-level domains</a></p>\n" }, { "answer_id": 25538699, "author": "Mikael Engver", "author_id": 579697, "author_profile": "https://Stackoverflow.com/users/579697", "pm_score": 3, "selected": false, "text": "<p>I use this regex:</p>\n\n<pre><code>((https?:)?//)?(([\\d\\w]|%[a-fA-f\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?([\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,63}(:[\\d]+)?(/([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(\\?(&amp;?([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?\n</code></pre>\n\n<p>To support both:</p>\n\n<pre><code>http://stackoverflow.com\nhttps://stackoverflow.com\n</code></pre>\n\n<p>And: </p>\n\n<pre><code>//stackoverflow.com\n</code></pre>\n" }, { "answer_id": 25831196, "author": "M.R.Safari", "author_id": 1761442, "author_profile": "https://Stackoverflow.com/users/1761442", "pm_score": 0, "selected": false, "text": "<p>Here is the best and the most matched regex for this situation</p>\n\n<pre><code>^(?:http(?:s)?:\\/\\/)?(?:www\\.)?(?:[\\w-]*)\\.\\w{2,}$\n</code></pre>\n" }, { "answer_id": 27379352, "author": "miphe", "author_id": 563915, "author_profile": "https://Stackoverflow.com/users/563915", "pm_score": 2, "selected": false, "text": "<p>For convenience here's a one-liner regexp for URL's that will also match localhost where you're more likely to have ports than <code>.com</code> or similar.</p>\n\n<pre><code>(http(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}(\\.[a-z]{2,6}|:[0-9]{3,4})\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;\\/\\/=]*)\n</code></pre>\n" }, { "answer_id": 27945109, "author": "runlevel0", "author_id": 2850382, "author_profile": "https://Stackoverflow.com/users/2850382", "pm_score": 0, "selected": false, "text": "<p>To match the URL up to the domain: </p>\n\n<pre><code>(^(\\bhttp)(|s):\\/{2})(?=[a-z0-9-_]{1,255})\\.\\1\\.([a-z]{3,7}$)\n</code></pre>\n\n<p>It can be simplified to: </p>\n\n<pre><code>(^(\\bhttp)(|s):\\/{2})(?=[a-z0-9-_.]{1,255})\\.([a-z]{3,7})\n</code></pre>\n\n<p>the latter does not check for the end for the end line so that it can be later used create full blown URL with full paths and query strings.</p>\n" }, { "answer_id": 28527268, "author": "kash", "author_id": 1126904, "author_profile": "https://Stackoverflow.com/users/1126904", "pm_score": 3, "selected": false, "text": "<p>Here's a ready-to-go Java version from the Android source code. This is the best one I've found.</p>\n\n<pre><code>public static final Matcher WEB = Pattern.compile(new StringBuilder() \n.append(\"((?:(http|https|Http|Https|rtsp|Rtsp):\") \n.append(\"\\\\/\\\\/(?:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\") \n.append(\"\\\\,\\\\;\\\\?\\\\&amp;\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,64}(?:\\\\:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\") \n.append(\"\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\;\\\\?\\\\&amp;\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,25})?\\\\@)?)?\") \n.append(\"((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}\\\\.)+\") // named host \n.append(\"(?:\") // plus top level domain \n.append(\"(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])\") \n.append(\"|(?:biz|b[abdefghijmnorstvwyz])\") \n.append(\"|(?:cat|com|coop|c[acdfghiklmnoruvxyz])\") \n.append(\"|d[ejkmoz]\") \n.append(\"|(?:edu|e[cegrstu])\") \n.append(\"|f[ijkmor]\") \n.append(\"|(?:gov|g[abdefghilmnpqrstuwy])\") \n.append(\"|h[kmnrtu]\") \n.append(\"|(?:info|int|i[delmnoqrst])\") \n.append(\"|(?:jobs|j[emop])\") \n.append(\"|k[eghimnrwyz]\") \n.append(\"|l[abcikrstuvy]\") \n.append(\"|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])\") \n.append(\"|(?:name|net|n[acefgilopruz])\") \n.append(\"|(?:org|om)\") \n.append(\"|(?:pro|p[aefghklmnrstwy])\") \n.append(\"|qa\") \n.append(\"|r[eouw]\") \n.append(\"|s[abcdeghijklmnortuvyz]\") \n.append(\"|(?:tel|travel|t[cdfghjklmnoprtvwz])\") \n.append(\"|u[agkmsyz]\") \n.append(\"|v[aceginu]\") \n.append(\"|w[fs]\") \n.append(\"|y[etu]\") \n.append(\"|z[amw]))\") \n.append(\"|(?:(?:25[0-5]|2[0-4]\") // or ip address \n.append(\"[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\\\.(?:25[0-5]|2[0-4][0-9]\") \n.append(\"|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(?:25[0-5]|2[0-4][0-9]|[0-1]\") \n.append(\"[0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}\") \n.append(\"|[1-9][0-9]|[0-9])))\") \n.append(\"(?:\\\\:\\\\d{1,5})?)\") // plus option port number \n.append(\"(\\\\/(?:(?:[a-zA-Z0-9\\\\;\\\\/\\\\?\\\\:\\\\@\\\\&amp;\\\\=\\\\#\\\\~\") // plus option query params \n.append(\"\\\\-\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\_])|(?:\\\\%[a-fA-F0-9]{2}))*)?\") \n.append(\"(?:\\\\b|$)\").toString() \n).matcher(\"\");\n</code></pre>\n" }, { "answer_id": 29472385, "author": "Daniel Mihai", "author_id": 2123170, "author_profile": "https://Stackoverflow.com/users/2123170", "pm_score": 0, "selected": false, "text": "<p>This should work:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validateUrl(value){\r\n return /^(http(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)$/gi.test(value);\r\n}\r\n\r\nconsole.log(validateUrl('google.com')); // true\r\nconsole.log(validateUrl('www.google.com')); // true\r\nconsole.log(validateUrl('http://www.google.com')); // true\r\nconsole.log(validateUrl('http:/www.google.com')); // false\r\nconsole.log(validateUrl('www.google.com/test')); // true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 30238449, "author": "Fredmat", "author_id": 1466704, "author_profile": "https://Stackoverflow.com/users/1466704", "pm_score": 2, "selected": false, "text": "<p>You don't specify which language you're using.\nIf PHP is, there is a native function for that:</p>\n\n<pre><code>$url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1&amp;param2/';\n\nif ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {\n // Wrong\n}\nelse {\n // Valid\n}\n</code></pre>\n\n<p>Returns the filtered data, or FALSE if the filter fails.</p>\n\n<p><a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow\">Check it here >></a></p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 33028229, "author": "Rahul Desai", "author_id": 586051, "author_profile": "https://Stackoverflow.com/users/586051", "pm_score": 2, "selected": false, "text": "<p>I found the following Regex for URLs, <strong>tested successfully with 500+ URLs</strong>:</p>\n\n<p><code>/\\b(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?\\b/gi</code></p>\n\n<p><em>I know it looks ugly, but the good thing is that it works. :)</em></p>\n\n<p><a href=\"https://regex101.com/r/hU9aV3/5\" rel=\"nofollow\">Explanation and demo with <strong>581 random URLs</strong> on regex101.</a></p>\n\n<p>Source: <a href=\"https://mathiasbynens.be/demo/url-regex\" rel=\"nofollow\">In search of the perfect URL validation regex</a></p>\n" }, { "answer_id": 39198430, "author": "MithPaul", "author_id": 3183039, "author_profile": "https://Stackoverflow.com/users/3183039", "pm_score": 0, "selected": false, "text": "<p>I think I found a more general regexp to validate urls, particularly websites</p>\n\n<pre><code>​(https?:\\/\\/)?(www\\.)[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)|(https?:\\/\\/)?(www\\.)?(?!ww)[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)\n</code></pre>\n\n<p>it does not allow for instance www.something or <a href=\"http://www\">http://www</a> or <a href=\"http://www.something\" rel=\"nofollow\">http://www.something</a></p>\n\n<p>Check it here: <a href=\"http://regexr.com/3e4a2\" rel=\"nofollow\">http://regexr.com/3e4a2</a></p>\n" }, { "answer_id": 39478555, "author": "ctwheels", "author_id": 3600709, "author_profile": "https://Stackoverflow.com/users/3600709", "pm_score": 0, "selected": false, "text": "<p>I created a similar regex (<strong>PCRE</strong>) to the one @eyelidlessness provided following RFC3987 along with other RFC documents. The major difference between @eyelidlessness and my regex are mainly readability and also URN support.</p>\n\n<p>The regex below is all one piece (instead of being mixed with PHP) so it can be used in different languages very easily (so long as they support PCRE)</p>\n\n<p><strong>The easiest way to test this regex is to use <a href=\"http://regex101.com\" rel=\"nofollow\">regex101</a> and copy paste the code and test strings below with the appropriate modifiers (<code>gmx</code>).</strong></p>\n\n<p>To use this regex in PHP, insert the regex below into the following code:</p>\n\n<pre><code>$regex = &lt;&lt;&lt;'EOD'\n// Put the regex here\nEOD;\n</code></pre>\n\n<p><hr>\nYou can match a link without a scheme by doing the following:<br/>\nTo match a link without a scheme (i.e. <code>[email protected]</code> or <code>www.google.com/pathtofile.php?query</code>), replace this section:</p>\n\n<pre><code> (?:\n (?&lt;scheme&gt;\n (?&lt;urn&gt;urn)|\n (?&amp;d_scheme)\n )\n :\n )?\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code> (?:\n (?&lt;scheme&gt;\n (?&lt;urn&gt;urn)|\n (?&amp;d_scheme)\n )\n :\n )?\n</code></pre>\n\n<p>Note, however, that by replacing this, the regex does not become 100% reliable.\n<hr>\n<strong>Regex (PCRE)</strong> with <code>gmx</code> modifiers for the multi-line test string below</p>\n\n<pre><code>(?(DEFINE)\n # Definitions\n (?&lt;ALPHA&gt;[\\p{L}])\n (?&lt;DIGIT&gt;[0-9])\n (?&lt;HEX&gt;[0-9a-fA-F])\n (?&lt;NCCHAR&gt;\n (?&amp;UNRESERVED)|\n (?&amp;PCT_ENCODED)|\n (?&amp;SUB_DELIMS)|\n @\n )\n (?&lt;PCHAR&gt;\n (?&amp;UNRESERVED)|\n (?&amp;PCT_ENCODED)|\n (?&amp;SUB_DELIMS)|\n :|\n @|\n \\/\n )\n (?&lt;UCHAR&gt;\n (?&amp;UNRESERVED)|\n (?&amp;PCT_ENCODED)|\n (?&amp;SUB_DELIMS)|\n :\n )\n (?&lt;RCHAR&gt;\n (?&amp;UNRESERVED)|\n (?&amp;PCT_ENCODED)|\n (?&amp;SUB_DELIMS)\n )\n (?&lt;PCT_ENCODED&gt;%(?&amp;HEX){2})\n (?&lt;UNRESERVED&gt;\n ((?&amp;ALPHA)|(?&amp;DIGIT)|[-._~])\n )\n (?&lt;RESERVED&gt;(?&amp;GEN_DELIMS)|(?&amp;SUB_DELIMS))\n (?&lt;GEN_DELIMS&gt;[:\\/?#\\[\\]@])\n (?&lt;SUB_DELIMS&gt;[!$&amp;'()*+,;=])\n # URI Parts\n (?&lt;d_scheme&gt;\n (?!urn)\n (?:\n (?&amp;ALPHA)\n ((?&amp;ALPHA)|(?&amp;DIGIT)|[+-.])*\n (?=:)\n )\n )\n (?&lt;d_hier_part_slashes&gt;\n (\\/{2})?\n )\n (?&lt;d_authority&gt;(?&amp;d_userinfo)?)\n (?&lt;d_userinfo&gt;(?&amp;UCHAR)*)\n (?&lt;d_ipv6&gt;\n (?![^:]*::[^:]*::[^:]*)\n (\n (\n ((?&amp;HEX){0,4})\n :\n ){1,7}\n ((?&amp;d_ipv4)|:|(?&amp;HEX){1,4})\n )\n )\n (?&lt;d_ipv4&gt;\n ((?&amp;octet)\\.){3}\n (?&amp;octet)\n )\n (?&lt;octet&gt;\n (\n 25[]0-5]|\n 2[0-4](?&amp;DIGIT)|\n 1(?&amp;DIGIT){2}|\n [1-9](?&amp;DIGIT)|\n (?&amp;DIGIT)\n )\n )\n (?&lt;d_reg_name&gt;(?&amp;RCHAR)*)\n (?&lt;d_urn_name&gt;(?&amp;UCHAR)*)\n (?&lt;d_port&gt;(?&amp;DIGIT)*)\n (?&lt;d_path&gt;\n (\n \\/\n ((?&amp;PCHAR)*)*\n (?=\\?|\\#|$)\n )\n )\n (?&lt;d_query&gt;\n (\n ((?&amp;PCHAR)|\\/|\\?)*\n )?\n )\n (?&lt;d_fragment&gt;\n (\n ((?&amp;PCHAR)|\\/|\\?)*\n )?\n )\n)\n^\n(?&lt;link&gt;\n (?:\n (?&lt;scheme&gt;\n (?&lt;urn&gt;urn)|\n (?&amp;d_scheme)\n )\n :\n )\n (?(urn)\n (?:\n (?&lt;namespace_identifier&gt;[0-9a-zA-Z\\-]+)\n :\n (?&lt;namespace_specific_string&gt;(?&amp;d_urn_name)+)\n )\n |\n (?&lt;hier_part&gt;\n (?&lt;slashes&gt;(?&amp;d_hier_part_slashes))\n (?&lt;authority&gt;\n (?:\n (?&lt;userinfo&gt;(?&amp;d_authority))\n @\n )?\n (?&lt;host&gt;\n (?&lt;ipv4&gt;\\[?(?&amp;d_ipv4)\\]?)|\n (?&lt;ipv6&gt;\\[(?&amp;d_ipv6)\\])|\n (?&lt;domain&gt;(?&amp;d_reg_name))\n )\n (?:\n :\n (?&lt;port&gt;(?&amp;d_port))\n )?\n )\n (?&lt;path&gt;(?&amp;d_path))?\n )\n (?:\n \\?\n (?&lt;query&gt;(?&amp;d_query))\n )?\n (?:\n \\#\n (?&lt;fragment&gt;(?&amp;d_fragment))\n )?\n )\n)\n$\n</code></pre>\n\n<p><strong>Test Strings</strong></p>\n\n<pre><code># Valid URIs\nftp://cnn.example.com&amp;[email protected]/top_story.htm\nftp://ftp.is.co.za/rfc/rfc1808.txt\nhttp://www.ietf.org/rfc/rfc2396.txt\nldap://[2001:db8::7]/c=GB?objectClass?one\nmailto:[email protected]\nnews:comp.infosystems.www.servers.unix\ntel:+1-816-555-1212\ntelnet://192.0.2.16:80/\nurn:isbn:0451450523\nurn:oid:2.16.840\nurn:isan:0000-0000-9E59-0000-O-0000-0000-2\nurn:oasis:names:specification:docbook:dtd:xml:4.1.2\nhttp://localhost/test/somefile.php?query=someval&amp;variable=value#fragment\nhttp://[2001:db8:a0b:12f0::1]/test\nftp://username:[email protected]/path/to/file/somefile.html?queryVariable=value#fragment\nhttps://subdomain.domain.com/path/to/file.php?query=value#fragment\nhttps://subdomain.example.com/path/to/file.php?query=value#fragment\nmailto:john.smith(comment)@example.com\nmailto:user@[2001:DB8::1]\nmailto:user@[255:192:168:1]\nmailto:[email protected]\nhttp://localhost:4433/path/to/file?query#fragment\n# Note that the example below IS a valid as it does follow RFC standards\nlocalhost:4433/path/to/file\n\n# These work with the optional scheme group although I'd suggest making the scheme mandatory as misinterpretations can occur\[email protected]\nwww.google.com/pathtofile.php?query\n[192a:123::192.168.1.1]:80/path/to/file.html?query#fragment\n</code></pre>\n" }, { "answer_id": 39908190, "author": "maxspan", "author_id": 2209468, "author_profile": "https://Stackoverflow.com/users/2209468", "pm_score": 2, "selected": false, "text": "<p>To Match a URL there are various option and it depend on you requirement.\nbelow are few.</p>\n\n<pre><code>_(^|[\\s.:;?\\-\\]&lt;\\(])(https?://[-\\w;/?:@&amp;=+$\\|\\_.!~*\\|'()\\[\\]%#,☺]+[\\w/#](\\(\\))?)(?=$|[\\s',\\|\\(\\).:;?\\-\\[\\]&gt;\\)])_i\n\n#\\b(([\\w-]+://?|www[.])[^\\s()&lt;&gt;]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))#iS\n</code></pre>\n\n<p>And there is a link which gives you more than 10 different variations of validation for URL.</p>\n\n<p><a href=\"https://mathiasbynens.be/demo/url-regex\" rel=\"nofollow\">https://mathiasbynens.be/demo/url-regex</a></p>\n" }, { "answer_id": 45728224, "author": "Johann", "author_id": 753632, "author_profile": "https://Stackoverflow.com/users/753632", "pm_score": 1, "selected": false, "text": "<p>This is not a regular expression but accomplishes the same thing (Javascript only):</p>\n\n<pre><code>function isAValidUrl(url) {\n try {\n new URL(url);\n return true;\n } catch(e) {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 45966320, "author": "Divya-Systematix", "author_id": 5711511, "author_profile": "https://Stackoverflow.com/users/5711511", "pm_score": 3, "selected": false, "text": "<p>I hope it's helpful for you...</p>\n\n<pre><code>^(http|https):\\/\\/+[\\www\\d]+\\.[\\w]+(\\/[\\w\\d]+)?\n</code></pre>\n" }, { "answer_id": 46088854, "author": "tk_", "author_id": 3168721, "author_profile": "https://Stackoverflow.com/users/3168721", "pm_score": 1, "selected": false, "text": "<p>How about this: </p>\n\n<pre><code>^(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]\\.[^\\s]{2,})$\n</code></pre>\n\n<p>These are the test cases:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Mm9y0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Mm9y0.png\" alt=\"Test cases\"></a></p>\n\n<p>You can try it out in <a href=\"https://regex101.com/r/mS9gD7/41\" rel=\"nofollow noreferrer\">here : https://regex101.com/r/mS9gD7/41</a></p>\n" }, { "answer_id": 48048416, "author": "IT Eng - BU", "author_id": 8743681, "author_profile": "https://Stackoverflow.com/users/8743681", "pm_score": 0, "selected": false, "text": "<p>As far as I have found, this expression is good for me-</p>\n\n<pre><code>(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]\\.[^\\s]{2,})\n</code></pre>\n\n<p>Working example-</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 RegExForUrlMatch()\r\n{\r\n var expression = /(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9]\\.[^\\s]{2,})/g;\r\n\r\n var regex = new RegExp(expression);\r\n var t = document.getElementById(\"url\").value;\r\n\r\n if (t.match(regex)) {\r\n document.getElementById(\"demo\").innerHTML = \"Successful match\";\r\n } else {\r\n document.getElementById(\"demo\").innerHTML = \"No match\";\r\n }\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" id=\"url\" placeholder=\"url\" onkeyup=\"RegExForUrlMatch()\"&gt;\r\n\r\n&lt;p id=\"demo\"&gt;Please enter a URL to test&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 48408597, "author": "Ravi Matani", "author_id": 4017996, "author_profile": "https://Stackoverflow.com/users/4017996", "pm_score": 0, "selected": false, "text": "<p>Below expression will work for all popular domains. It will accept following urls:</p>\n\n<ul>\n<li>www.yourwebsite.com</li>\n<li><a href=\"http://www.yourwebsite.com\" rel=\"nofollow noreferrer\">http://www.yourwebsite.com</a> </li>\n<li>www.yourwebsite.com</li>\n<li>yourwebsite.com</li>\n<li>yourwebsite.co.in</li>\n</ul>\n\n<p>In addition it will make message with url as link also<br/>\ne.g. <code>please visit yourwebsite.com</code><br/>\nIn above example it will make <code>yourwebsite.com</code> as hyperlink</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>if (new RegExp(\"([-a-z0-9]{1,63}\\\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\\\.(com|com/|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au|org/|gov/|cm/|net/|online/|live/|biz/|us/|uk/|co.us/|co.uk/|in/|co.in/|int/|info/|edu/|mil/|ca/|co/|co.au/)(/[-\\\\w@\\\\+\\\\.~#\\\\?*&amp;/=% ]*)?$\").test(strMessage) || (new RegExp(\"^[a-z ]+[\\.]?[a-z ]+?[\\.]+[a-z ]+?[\\.]+[a-z ]+?[-\\\\w@\\\\+\\\\.~#\\\\?*&amp;/=% ]*\").test(strMessage) &amp;&amp; new RegExp(\"([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?\").test(strMessage)) || (new RegExp(\"^[a-z ]+[\\.]?[a-z ]+?[-\\\\w@\\\\+\\\\.~#\\\\?*&amp;/=% ]*\").test(strMessage) &amp;&amp; new RegExp(\"([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?\").test(strMessage))) {\n if (new RegExp(\"^[a-z ]+[\\.]?[a-z ]+?[\\.]+[a-z ]+?[\\.]+[a-z ]+?$\").test(strMessage) &amp;&amp; new RegExp(\"([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?\").test(strMessage)) {\n var url1 = /(^|&amp;lt;|\\s)([\\w\\.]+\\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au))(\\s|&amp;gt;|$)/g;\n var html = $.trim(strMessage);\n if (html) {\n html = html.replace(url1, '$1&lt;a style=\"color:blue; text-decoration:underline;\" target=\"_blank\" href=\"http://$2\"&gt;$2&lt;/a&gt;$3');\n }\n returnString = html;\n return returnString;\n } else {\n var url1 = /(^|&amp;lt;|\\s)(www\\..+?\\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\\s]*)(\\s|&amp;gt;|$)/g,\n url2 = /(^|&amp;lt;|\\s)(((https?|ftp):\\/\\/|mailto:).+?\\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\\s]*)(\\s|&amp;gt;|$)/g,\n url3 = /(^|&amp;lt;|\\s)([\\w\\.]+\\.(?:com|org|gov|cm|net|online|live|biz|us|uk|co.us|co.uk|in|co.in|int|info|edu|mil|ca|co|co.au)[^,\\s]*)(\\s|&amp;gt;|$)/g;\n\n var html = $.trim(strMessage);\n if (html) {\n html = html.replace(url1, '$1&lt;a style=\"color:blue; text-decoration:underline;\" target=\"_blank\" href=\"http://$2\"&gt;$2&lt;/a&gt;$3').replace(url2, '$1&lt;a style=\"color:blue; text-decoration:underline;\" target=\"_blank\" href=\"$2\"&gt;$2&lt;/a&gt;$5').replace(url3, '$1&lt;a style=\"color:blue; text-decoration:underline;\" target=\"_blank\" href=\"http://$2\"&gt;$2&lt;/a&gt;$3');\n }\n returnString = html;\n\n return returnString;\n }\n}\n</code></pre>\n" }, { "answer_id": 49154622, "author": "dev_khan", "author_id": 1722028, "author_profile": "https://Stackoverflow.com/users/1722028", "pm_score": 0, "selected": false, "text": "<p>After rigorous searching i finally settled with the following </p>\n\n<pre><code>^[a-zA-Z0-9]+\\:\\/\\/[a-zA-Z0-9]+\\.[-a-zA-Z0-9]+\\.?[a-zA-Z0-9]+$|^[a-zA-Z0-9]+\\.[-a-zA-Z0-9]+\\.[a-zA-Z0-9]+$\n</code></pre>\n\n<p>And this thing work for general in future URLs.</p>\n" }, { "answer_id": 51560709, "author": "Nike Kov", "author_id": 5790492, "author_profile": "https://Stackoverflow.com/users/5790492", "pm_score": 0, "selected": false, "text": "<p>The best regex, i've found is: <code>/(^|\\s)((https?:\\/\\/)?[\\w-]+(\\.[\\w-]+)+\\.?(:\\d+)?(\\/\\S*)?)/gi</code></p>\n\n<p>For ios swift : <code>(^|\\\\s)((https?:\\\\/\\\\/)?[\\\\w-]+(\\\\.[\\\\w-]+)+\\\\.?(:\\\\d+)?(\\\\/\\\\S*)?)</code></p>\n\n<p><a href=\"http://jsfiddle.net/9BYdp/1/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/9BYdp/1/</a></p>\n\n<p>Found <a href=\"https://codegolf.stackexchange.com/a/480\">here</a></p>\n" }, { "answer_id": 52508260, "author": "Erick Maynard", "author_id": 4469176, "author_profile": "https://Stackoverflow.com/users/4469176", "pm_score": 0, "selected": false, "text": "<p>Interestingly, none of the answers above worked for what I needed, so I figured I would offer my solution. I needed to be able to do the following:</p>\n\n<ul>\n<li>Match <code>http(s)://www.google.com</code>, <code>http://google.com</code>, <code>www.google.com</code>, and <code>google.com</code></li>\n<li>Match Github markdown style links like <code>[Google](http://www.google.com)</code></li>\n<li>Match all possible domain extensions, like .com, or .io, or .guru, etc. Basically anything between 2-6 characters in length</li>\n<li>Split everything into proper groupings so that I could access each part as needed.</li>\n</ul>\n\n<p>Here was the solution:</p>\n\n<pre><code>/^(\\[[A-z0-9 _]*\\]\\()?((?:(http|https):\\/\\/)?(?:[\\w-]+\\.)+[a-z]{2,6})(\\))?$\n</code></pre>\n\n<p>This gives me all of the above requirements. You could optionally add the ability for ftp and file if necessary:</p>\n\n<pre><code>/^(\\[[A-z0-9 _]*\\]\\()?((?:(http|https|ftp|file):\\/\\/)?(?:[\\w-]+\\.)+[a-z]{2,6})(\\))?$\n</code></pre>\n" }, { "answer_id": 53480857, "author": "Mahfuzur Rahman", "author_id": 6570691, "author_profile": "https://Stackoverflow.com/users/6570691", "pm_score": 0, "selected": false, "text": "<p>I think it is a very simple way. And it works very good.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var hasURL = (str) =&gt;{\r\n var url_pattern = new RegExp(\"(www.|http://|https://|ftp://)\\w*\");\r\n if(!url_pattern.test(str)){\r\n document.getElementById(\"demo\").innerHTML = 'No URL';\r\n }\r\n else\r\n document.getElementById(\"demo\").innerHTML = 'String has a URL';\r\n};</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;Please enter a string and test it has any url or not&lt;/p&gt;\r\n&lt;input type=\"text\" id=\"url\" placeholder=\"url\" onkeyup=\"hasURL(document.getElementById('url').value)\"&gt;\r\n&lt;p id=\"demo\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 53711623, "author": "Elie G.", "author_id": 5647659, "author_profile": "https://Stackoverflow.com/users/5647659", "pm_score": 3, "selected": false, "text": "<p>Here is a regex I made which extracts the different parts from an URL:</p>\n<p><code>^((?:(?:http|ftp|ws)s?|sftp):\\/\\/?)?([^:/\\s.#?]+\\.[^:/\\s#?]+|localhost)(:\\d+)?((?:\\/\\w+)*\\/)?([\\w\\-.]+[^#?\\s]+)?([^#]+)?(#[\\w-]*)?$</code></p>\n<p><code>((?:(?:http|ftp|ws)s?|sftp):\\/\\/?)?</code><em>(group 1)</em>: extracts the protocol<br>\n<code>([^:/\\s.#?]+\\.[^:/\\s#?]+|localhost)</code><em>(group 2)</em>: extracts the hostname<br>\n<code>(:\\d+)?</code><em>(group 3)</em>: extracts the port number<br>\n<code>((?:\\/\\w+)*\\/)?([\\w\\-.]+[^#?\\s]+)?</code><em>(groups 4 &amp; 5)</em>: extracts the path part<br>\n<code>([^#]+)?</code><em>(group 6)</em>: extracts the query part<br>\n<code>(#[\\w-]*)?</code><em>(group 7)</em>: extracts the hash part</p>\n<p>For every part of the regex listed above, you can remove the ending <code>?</code> to force it (or add one to make it facultative). You can also remove the <code>^</code> at the beginning and <code>$</code> at the end of the regex so it won't need to match the whole string.</p>\n<p>See it on <a href=\"https://regex101.com/r/Q2ilqN/17\" rel=\"nofollow noreferrer\">regex101</a>.</p>\n<p><em><strong>Note:</strong> this regex is not 100% safe and may accept some strings which are not necessarily valid URLs but it does indeed validate some criterias. Its main goal was to extract the different parts of an URL not to validate it.</em></p>\n" }, { "answer_id": 54690403, "author": "Sajeeb Chandan Saha", "author_id": 9518407, "author_profile": "https://Stackoverflow.com/users/9518407", "pm_score": 2, "selected": false, "text": "<pre><code>https?:\\/{2}(?:[\\/-\\w.]|(?:%[\\da-fA-F]{2}))+\n</code></pre>\n\n<p>You can use this pattern for detecting URLs. </p>\n\n<p>Following is the proof of concept</p>\n\n<p><a href=\"https://regexr.com/48chr\" rel=\"nofollow noreferrer\">RegExr: URL Detector</a> </p>\n" }, { "answer_id": 55468411, "author": "Nodarii", "author_id": 2460760, "author_profile": "https://Stackoverflow.com/users/2460760", "pm_score": 4, "selected": false, "text": "<pre><code>^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$\n</code></pre>\n\n<p>live demo: <a href=\"https://regex101.com/r/HUNasA/2\" rel=\"noreferrer\">https://regex101.com/r/HUNasA/2</a></p>\n\n<p>I have tested various expressions to match my requirements. </p>\n\n<p>As a user I can hit browser search bar with following strings:</p>\n\n<p><strong>valid urls</strong></p>\n\n<ul>\n<li><a href=\"https://www.google.com\" rel=\"noreferrer\">https://www.google.com</a></li>\n<li><a href=\"http://www.google.com\" rel=\"noreferrer\">http://www.google.com</a></li>\n<li><a href=\"http://google.com/\" rel=\"noreferrer\">http://google.com/</a></li>\n<li><a href=\"https://google.com/\" rel=\"noreferrer\">https://google.com/</a></li>\n<li>www.google.com</li>\n<li>google.com</li>\n<li><a href=\"https://www.google.com.ua\" rel=\"noreferrer\">https://www.google.com.ua</a></li>\n<li><a href=\"http://www.google.com.ua\" rel=\"noreferrer\">http://www.google.com.ua</a></li>\n<li><a href=\"http://google.com.ua\" rel=\"noreferrer\">http://google.com.ua</a></li>\n<li><a href=\"https://google.com.ua/\" rel=\"noreferrer\">https://google.com.ua/</a></li>\n<li>www.google.com.ua</li>\n<li>google.com.ua</li>\n<li><a href=\"https://mail.google.com\" rel=\"noreferrer\">https://mail.google.com</a></li>\n<li><a href=\"http://mail.google.com\" rel=\"noreferrer\">http://mail.google.com</a></li>\n<li>mail.google.com</li>\n</ul>\n\n<p><strong>invalid urls</strong></p>\n\n<ul>\n<li><a href=\"http://google\" rel=\"noreferrer\">http://google</a></li>\n<li><a href=\"https://google.c\" rel=\"noreferrer\">https://google.c</a></li>\n<li>google</li>\n<li>google.</li>\n<li>.google</li>\n<li>.google.com</li>\n<li>goole.c</li>\n<li>...</li>\n</ul>\n" }, { "answer_id": 55952338, "author": "Dragana Le Mitova", "author_id": 4317831, "author_profile": "https://Stackoverflow.com/users/4317831", "pm_score": 1, "selected": false, "text": "<p><strong>IMPROVED</strong></p>\n\n<p>Detects Urls like these:</p>\n\n<ul>\n<li><a href=\"https://www.example.pl\" rel=\"nofollow noreferrer\">https://www.example.pl</a> </li>\n<li><a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a></li>\n<li>www.example.pl</li>\n<li>example.com</li>\n<li><a href=\"http://blog.example.com\" rel=\"nofollow noreferrer\">http://blog.example.com</a></li>\n<li><a href=\"http://www.example.com/product\" rel=\"nofollow noreferrer\">http://www.example.com/product</a></li>\n<li><a href=\"http://www.example.com/products?id=1&amp;page=2\" rel=\"nofollow noreferrer\">http://www.example.com/products?id=1&amp;page=2</a></li>\n<li><a href=\"http://www.example.com#up\" rel=\"nofollow noreferrer\">http://www.example.com#up</a></li>\n<li><a href=\"http://255.255.255.255\" rel=\"nofollow noreferrer\">http://255.255.255.255</a></li>\n<li>255.255.255.255</li>\n<li>http:// www.site.com:8008</li>\n</ul>\n\n<p>Regex:</p>\n\n<pre><code>/^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&amp;'\\(\\)\\*\\+,;=.]+$/gm\n</code></pre>\n" }, { "answer_id": 56037210, "author": "Kerem", "author_id": 1139130, "author_profile": "https://Stackoverflow.com/users/1139130", "pm_score": 0, "selected": false, "text": "<p>If you would like to apply a more strict rule, here is what I have developed:</p>\n\n<pre><code>isValidUrl(input) {\n var regex = /^(((H|h)(T|t)(T|t)(P|p)(S|s)?):\\/\\/)?[-a-zA-Z0-9@:%._\\+~#=]{2,100}\\.[a-zA-Z]{2,10}(\\/([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*))?/\n return regex.test(input)\n}\n</code></pre>\n" }, { "answer_id": 56056825, "author": "Dmytro Huz", "author_id": 5907412, "author_profile": "https://Stackoverflow.com/users/5907412", "pm_score": 4, "selected": false, "text": "<p>Here is a good rule that covers all possible cases: ports, params and etc</p>\n\n<pre><code>/(https?:\\/\\/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])(:?\\d*)\\/?([a-z_\\/0-9\\-#.]*)\\??([a-z_\\/0-9\\-#=&amp;]*)/g\n</code></pre>\n" }, { "answer_id": 63103782, "author": "medBouzid", "author_id": 2392106, "author_profile": "https://Stackoverflow.com/users/2392106", "pm_score": 0, "selected": false, "text": "<p>Regardless the broad question asked, I post this for anyone in the future who is looking for something simple... as I think validating a URL has no perfect regular expression that fit all needs, it depends on your requirements, i.e: in my case, I just needed to verify if a URL is in the form of <code>domain.extension</code> and I wanted to allow the <code>www</code> or any other subdomain like <code>blog.domain.extension</code> I don't care about http(s) as in my app I have a field which says &quot;enter the URL&quot; so it's obvious what that entered string is.</p>\n<p>so here is the regEx:</p>\n<pre><code>/^(www\\.|[a-zA-Z0-9](.*[a-zA-Z0-9])?\\.)?((?!www)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])\\.[a-z]{2,5}(:[0-9]{1,5})?$/i\n</code></pre>\n<p>The first block in this regExp is:</p>\n<p><code>(www\\.|[a-zA-Z0-9](.*[a-zA-Z0-9])?\\.)?</code> ---&gt; we start to check if the URL start with <code>www.</code> or <code>[a-zA-Z0-9](.*[a-zA-Z0-9])?</code> which means a letterOrNumber + <strong>(anyCharacter(0 or multiple times) + another letterOrNumber) followed with a dot</strong></p>\n<p>Note that the <code>(.*[a-zA-Z0-9])?\\.)?</code> we translated by <strong>(anyCharacter(0 or multiple times) + another letterOrNumber)</strong>\nis optional (can be or not) that's why we grouped it between parentheses and followed with the question mark <code>?</code></p>\n<p>the whole block we discussed so far is also put between parentheses and followed by ? which means both www or any other word (that represents a subdomain) is optional.</p>\n<p>The second part is: <code>((?!www)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9])\\.</code> ---&gt; which represents the &quot;domain&quot; part, it can be any word (except www) starting with an alphabet or a number + any other alphabet (including dash &quot;-&quot;) repeated one or more time, and ending with any alphabet or number followed with a dot.</p>\n<p>The final part is <code>[a-z]{2,}</code> ---&gt; which represent the &quot;extension&quot;, it can be any alphabet repeated 2 or more times, so it can be com, net, org, art basically any extension</p>\n" }, { "answer_id": 63991456, "author": "manmeet", "author_id": 1161987, "author_profile": "https://Stackoverflow.com/users/1161987", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-none prettyprint-override\"><code>/^(http|HTTP)+(s|S)?:\\/\\/[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._\\$\\(\\)/]+$/g\n</code></pre>\n<p>check demo with tests:</p>\n<p><a href=\"https://regexr.com/5cedu\" rel=\"nofollow noreferrer\">https://regexr.com/5cedu</a></p>\n" }, { "answer_id": 64206393, "author": "Qasim Rizvi", "author_id": 3616731, "author_profile": "https://Stackoverflow.com/users/3616731", "pm_score": 0, "selected": false, "text": "<p>A simple check for URL is</p>\n<pre><code>^(ftp|http|https):\\/\\/[^ &quot;]+$\n</code></pre>\n" }, { "answer_id": 66998354, "author": "Nabijon Azamov", "author_id": 6244001, "author_profile": "https://Stackoverflow.com/users/6244001", "pm_score": 0, "selected": false, "text": "<p>The following Regex works for me:</p>\n<pre><code>(http(s)?:\\/\\/.)?(ftp(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{0,256}\\.[a-z] \n{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)\n</code></pre>\n<p>matches:</p>\n<pre><code>https://google.com t.me https://t.me ftp://google.com http://sm.tj http://bro.tj t.me/rshss https:google.com www.cool.com.au http://www.cool.com.au http://www.cool.com.au/ersdfs http://www.cool.com.au/ersdfs?dfd=dfgd@s=1 http://www.cool.com:81/index.html\n</code></pre>\n" }, { "answer_id": 70034706, "author": "Hans", "author_id": 15096247, "author_profile": "https://Stackoverflow.com/users/15096247", "pm_score": -1, "selected": false, "text": "<p>The best regex is a combination of the best answers here! hahaha! I have just tested them all, and put the best together! I changed it a little to only have one capture group! I was able to find 637 URLs in the source code of this page! Only a few false positives!</p>\n<pre><code>((?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@|\\d{1,3}(?:\\.\\d{1,3}){3}|(?:(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)(?:\\.(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)*(?:\\.[a-z\\x{00a1}-\\x{ffff}]{2,6}))(?::\\d+)?(?:[^\\s]*)|(?:(?:(?:[A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&amp;=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+(?::[0-9]+)?|(?:www.|[-;:&amp;=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)(?:(?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&amp;;%@.\\w_]*)#?(?:[\\w]*))?)|(?:(?:(?:(?:[A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&amp;=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&amp;=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)(?:(?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&amp;;%@.\\w_]*)#?(?:[\\w]*))?))|(?:(?:(?:[\\\\w]+:)?//)?(?:(?:[\\\\d\\\\w]|%[a-fA-f\\\\d]{2,2})+(?::(?:[\\\\d\\\\w]|%[a-fA-f\\\\d]{2,2})+)?@)?(?:[\\\\d\\\\w][-\\\\d\\\\w]{0,253}[\\\\d\\\\w]\\\\.)+[\\\\w]{2,4}(?::[\\\\d]+)?(?:/(?:[-+_~.\\\\d\\\\w]|%[a-fA-f\\\\d]{2,2})*)*(?:\\\\?(?:&amp;?(?:[-+_~.\\\\d\\\\w]|%[a-fA-f\\\\d]{2,2})=?)*)?(?:#(?:[-+_~.\\\\d\\\\w]|%[a-fA-f\\\\d]{2,2})*)?)|(?:https?:\\/\\/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])(?::?\\d*)\\/?(?:[a-z_\\/0-9\\-#.]*)\\??(?:[a-z_\\/0-9\\-#=&amp;]*)|(?:(?:(?:https?:)?(?:\\/?\\/))(?:(?:[\\d\\w]|%[a-fA-f\\d]{2,2})+(?::(?:[\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?(?:[\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,63}(?::[\\d]+)?(?:/(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)*(?:\\?(?:&amp;?(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(?:#(?:[-+_~.\\d\\w]|%[a-fA-f\\d]{2,2})*)?)|(?:(?:https?|ftp)://(?:www\\d?|[a-zA-Z0-9]+)?\\.[a-zA-Z0-9-]+(?:\\:|\\.)(?:[a-zA-Z0-9.]+|(?:\\d+)?)(?:[/?:].*)?)|(?:\\b(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?\\b))\n</code></pre>\n" }, { "answer_id": 70067237, "author": "suchislife", "author_id": 687137, "author_profile": "https://Stackoverflow.com/users/687137", "pm_score": 0, "selected": false, "text": "<p>Javascript now has a URL Constructor called <code>new URL()</code>. It allows you to skip REGEX completely.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\n * \n * The URL() constructor returns a newly created URL object representing \n * the URL defined by the parameters. \n * \n * https://developer.mozilla.org/en-US/docs/Web/API/URL/URL\n * \n */\nlet requestUrl = new URL('https://username:[email protected]:8080/en-US/docs/search.html?par1=abc&amp;par2=123&amp;par3=true#Recent');\n\nlet urlParts = {\n origin: requestUrl.origin,\n href: requestUrl.href,\n protocol: requestUrl.protocol,\n username: requestUrl.username,\n password: requestUrl.password,\n host: requestUrl.host,\n hostname: requestUrl.hostname,\n port: requestUrl.port,\n pathname: requestUrl.pathname,\n search: requestUrl.search,\n searchParams: {\n par1: String(requestUrl.searchParams.get('par1')),\n par2: Number(requestUrl.searchParams.get('par2')),\n par3: Boolean(requestUrl.searchParams.get('par3')),\n },\n hash: requestUrl.hash \n};\n\nconsole.log(urlParts);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 71875638, "author": "Trashman", "author_id": 3608565, "author_profile": "https://Stackoverflow.com/users/3608565", "pm_score": 0, "selected": false, "text": "<p>Thank you to @eyelidlessness for the extremely thorough (albeit long) RFC based regular expression.</p>\n<p>For those of us using EICMAScript / JavaScript / Apps Script it doesn't work, however. Here is an otherwise exact replica of his answer that will work with these (along with a snippet to run for example - neat new feature!):</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>regEx_valid_URL = /^[a-z](?:[-a-z0-9\\+\\.])*:(?:\\/\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:])*@)?(?:\\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\\.[-a-z0-9\\._~!\\$&amp;'\\(\\)\\*\\+,;=:]+)\\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=])*)(?::[0-9]*)?(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|\\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@]))+)(?:\\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@])))(?:\\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\uE000-\\uF8FF}\\uF0000-\\uFFFFD\\u100000-\\u10FFFD\\/\\?])*)?(?:\\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\\._~\\uA0}-\\uD7FF}\\uF900-\\uFDCF}\\uFDF0}-\\uFFEF}\\u10000-\\u1FFFD\\u20000-\\u2FFFD\\u30000-\\u3FFFD\\u40000-\\u4FFFD\\u50000-\\u5FFFD\\u60000-\\u6FFFD\\u70000-\\u7FFFD\\u80000-\\u8FFFD\\u90000-\\u9FFFD\\uA0000-\\uAFFFD\\uB0000-\\uBFFFD\\uC0000-\\uCFFFD\\uD0000-\\uDFFFD\\uE1000-\\uEFFFD!\\$&amp;'\\(\\)\\*\\+,;=:@])|[\\/\\?])*)?$/i;\n\ncheckedURL = RegExp(regEx_valid_URL).exec('gopher://example.somewhere.university/');\n\nif (checkedURL != null) {\n console.log('The URL ' + checkedURL + ' is valid');\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 73117746, "author": "Mikey J Lee", "author_id": 2063880, "author_profile": "https://Stackoverflow.com/users/2063880", "pm_score": 0, "selected": false, "text": "<p>I use this: <code>/((https?:\\/\\/|ftp:\\/\\/|www\\.)\\S+\\.[^()\\n ]+((?:\\([^)]*\\))|[^.,;:?!&quot;'\\n\\)\\]&lt;* ])+)/</code></p>\n<p>It's short, but it handles edge cases like certain Wikipedia links (<a href=\"https://en.wikipedia.org/wiki/Sally_(name)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Sally_(name)</a>) that ends in a bracket, which the most voted answers here don't seem to cover.</p>\n" }, { "answer_id": 73745423, "author": "Luca Migliori", "author_id": 6360503, "author_profile": "https://Stackoverflow.com/users/6360503", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>[(http(s)?):\\/\\/(www\\.)?a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842864/" ]
How can I check if a given string is a valid URL address? My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.
I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 (<http://www.faqs.org/rfcs/rfc3987.html>). These are in PCRE syntax. For absolute IRIs (internationalized): ``` /^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i ``` To also allow relative IRIs: ``` /^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i ``` How they were compiled (in PHP): ``` <?php /* Regex convenience functions (character class, non-capturing group) */ function cc($str, $suffix = '', $negate = false) { return '[' . ($negate ? '^' : '') . $str . ']' . $suffix; } function ncg($str, $suffix = '') { return '(?:' . $str . ')' . $suffix; } /* Preserved from RFC3986 */ $ALPHA = 'a-z'; $DIGIT = '0-9'; $HEXDIG = $DIGIT . 'a-f'; $sub_delims = '!\\$&\'\\(\\)\\*\\+,;='; $gen_delims = ':\\/\\?\\#\\[\\]@'; $reserved = $gen_delims . $sub_delims; $unreserved = '-' . $ALPHA . $DIGIT . '\\._~'; $pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG); $dec_octet = ncg(implode('|', array( cc($DIGIT), cc('1-9') . cc($DIGIT), '1' . cc($DIGIT) . cc($DIGIT), '2' . cc('0-4') . cc($DIGIT), '25' . cc('0-5') ))); $IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}'); $h16 = cc($HEXDIG, '{1,4}'); $ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address); $IPv6address = ncg(implode('|', array( ncg($h16 . ':', '{6}') . $ls32, '::' . ncg($h16 . ':', '{5}') . $ls32, ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32, ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32, ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32, ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32, ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32, ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16, ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::', ))); $IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+'); $IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]'; $port = cc($DIGIT, '*'); $scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*'); /* New or changed in RFC3987 */ $iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}'; $ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' . '\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' . '\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' . '\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' . '\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' . '\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}'; $iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar; $ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@')); $ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*'); $iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*'); $isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+'); $isegment_nz = ncg($ipchar, '+'); $isegment = ncg($ipchar, '*'); $ipath_empty = '(?!' . $ipchar . ')'; $ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*'); $ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*'); $ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment ) $ipath_abempty = ncg('\\/' . $isegment, '*'); $ipath = ncg(implode('|', array( $ipath_abempty, $ipath_absolute, $ipath_noscheme, $ipath_rootless, $ipath_empty ))) . ')'; $ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*'); $ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name))); $iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*'); $iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?'); $irelative_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_noscheme . '', '' . $ipath_empty . '' ))); $irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?'); $ihier_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_rootless . '', '' . $ipath_empty . '' ))); $absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?'); $IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?'); $IRI_reference = ncg($IRI . '|' . $irelative_ref); ``` Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way: ``` $escape_backslash = '/(?<!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/'; $absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI); $IRI = preg_replace($escape_backslash, '\\\\', $IRI); $IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference); ```
161,747
<p>I would like to allow the logged user to edit MediaWiki/Common.css without adding them to the sysop group.</p> <p>I understand that this will allow user to change it to harful ways but it is a closed wiki so that is not a problem.</p> <p>Any solution is acceptable even changing php code :)</p>
[ { "answer_id": 295808, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 5, "selected": true, "text": "<p>Create a new group, add give it \"editinterface\" privilege. In LocalSettings.php it's done like this:</p>\n\n<pre><code>$wgGroupPermissions['mynewgroup']['editinterface'] = true;\n</code></pre>\n\n<p>Then add the user to you new group.</p>\n\n<p>Or if you want to give that right to all logged-in users, do it like this:</p>\n\n<pre><code>$wgGroupPermissions['user']['editinterface'] = true;\n// user is the default group for all logged-in users\n</code></pre>\n\n<p>For details see <a href=\"http://www.mediawiki.org/wiki/Manual:User_rights\" rel=\"noreferrer\">MediaWiki manual</a>.</p>\n" }, { "answer_id": 25591535, "author": "Lee Miller", "author_id": 1905376, "author_profile": "https://Stackoverflow.com/users/1905376", "pm_score": 0, "selected": false, "text": "<p>Probably safer to use;</p>\n\n<pre><code>$wgAllowUserCss = true;\n</code></pre>\n\n<p><a href=\"https://www.mediawiki.org/wiki/Manual:$wgAllowUserCss\" rel=\"nofollow\">See Mediawiki Manual</a> for the complete details.</p>\n\n<p><em>\"When enabled, users are able to make personalised customisations over and above the normal choice of skins within the 'preferences' display.\"</em></p>\n\n<p>A similar setting is available for Javascript.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4508/" ]
I would like to allow the logged user to edit MediaWiki/Common.css without adding them to the sysop group. I understand that this will allow user to change it to harful ways but it is a closed wiki so that is not a problem. Any solution is acceptable even changing php code :)
Create a new group, add give it "editinterface" privilege. In LocalSettings.php it's done like this: ``` $wgGroupPermissions['mynewgroup']['editinterface'] = true; ``` Then add the user to you new group. Or if you want to give that right to all logged-in users, do it like this: ``` $wgGroupPermissions['user']['editinterface'] = true; // user is the default group for all logged-in users ``` For details see [MediaWiki manual](http://www.mediawiki.org/wiki/Manual:User_rights).
161,755
<p>Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.</p> <pre><code>**/CVS/* # All files immediately under a CVS directory. mydir/mysubdir/** # All files recursively under mysubdir </code></pre> <p>More examples can be seen here:</p> <p><a href="http://ant.apache.org/manual/dirtasks.html" rel="nofollow noreferrer">http://ant.apache.org/manual/dirtasks.html</a></p> <p>How would you implement this in python, so that you could do something like:</p> <pre><code>files = get_files("**/CVS/*") for file in files: print file =&gt; CVS/Repository mydir/mysubdir/CVS/Entries mydir/mysubdir/foo/bar/CVS/Entries </code></pre>
[ { "answer_id": 161858, "author": "dkagedal", "author_id": 24458, "author_profile": "https://Stackoverflow.com/users/24458", "pm_score": 2, "selected": false, "text": "<p><code>os.walk</code> is your friend. Look at the example in the Python manual \n(<a href=\"https://docs.python.org/2/library/os.html#os.walk\" rel=\"nofollow noreferrer\">https://docs.python.org/2/library/os.html#os.walk</a>) and try to build something from that.</p>\n\n<p>To match \"<code>**/CVS/*</code>\" against a file name you get, you can do something like this:</p>\n\n<pre><code>def match(pattern, filename):\n if pattern.startswith(\"**\"):\n return fnmatch.fnmatch(file, pattern[1:])\n else:\n return fnmatch.fnmatch(file, pattern)\n</code></pre>\n\n<p>In <code>fnmatch.fnmatch</code>, \"*\" matches anything (including slashes).</p>\n" }, { "answer_id": 161891, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 0, "selected": false, "text": "<p>Yup. Your best bet is, as has already been suggested, to work with 'os.walk'. Or, write wrappers around '<a href=\"http://docs.python.org/library/glob.html\" rel=\"nofollow noreferrer\">glob</a>' and '<a href=\"http://docs.python.org/library/fnmatch.html\" rel=\"nofollow noreferrer\">fnmatch</a>' modules, perhaps.</p>\n" }, { "answer_id": 162716, "author": "Jack M.", "author_id": 3421, "author_profile": "https://Stackoverflow.com/users/3421", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.python.org/doc/2.6/library/os.html#os.walk\" rel=\"nofollow noreferrer\">os.walk</a> is your best bet for this. I did the example below with .svn because I had that handy, and it worked great:</p>\n\n<pre><code>import re\n\nfor (dirpath, dirnames, filenames) in os.walk(\".\"):\n if re.search(r'\\.svn$', dirpath):\n for file in filenames:\n print file\n</code></pre>\n" }, { "answer_id": 163212, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": true, "text": "<p>As soon as you come across a <code>**</code>, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like:</p>\n\n<pre><code>def glob_to_regex(pat, dirsep=os.sep):\n dirsep = re.escape(dirsep)\n print re.escape(pat)\n regex = (re.escape(pat).replace(\"\\\\*\\\\*\"+dirsep,\".*\")\n .replace(\"\\\\*\\\\*\",\".*\")\n .replace(\"\\\\*\",\"[^%s]*\" % dirsep)\n .replace(\"\\\\?\",\"[^%s]\" % dirsep))\n return re.compile(regex+\"$\")\n</code></pre>\n\n<p>(Though note that this isn't that fully featured - it doesn't support <code>[a-z]</code> style glob patterns for instance, though this could probably be added). (The first <code>\\*\\*/</code> match is to cover cases like <code>\\*\\*/CVS</code> matching <code>./CVS</code>, as well as having just <code>\\*\\*</code> to match at the tail.)</p>\n\n<p>However, obviously you don't want to recurse through everything below the current dir when not processing a <code>**</code> pattern, so I think you'll need a two-phase approach. I haven't tried implementing the below, and there are probably a few corner cases, but I think it should work:</p>\n\n<ol>\n<li><p>Split the pattern on your directory seperator. ie <code>pat.split('/') -&gt; ['**','CVS','*']</code></p></li>\n<li><p>Recurse through the directories, and look at the relevant part of the pattern for this level. ie. <code>n levels deep -&gt; look at pat[n]</code>.</p></li>\n<li><p>If <code>pat[n] == '**'</code> switch to the above strategy:</p>\n\n<ul>\n<li>Reconstruct the pattern with <code>dirsep.join(pat[n:])</code></li>\n<li>Convert to a regex with <code>glob\\_to\\_regex()</code></li>\n<li>Recursively <code>os.walk</code> through the current directory, building up the path relative to the level you started at. If the path matches the regex, yield it.</li>\n</ul></li>\n<li><p>If pat doesn't match <code>\"**\"</code>, and it is the last element in the pattern, then yield all files/dirs matching <code>glob.glob(os.path.join(curpath,pat[n]))</code></p></li>\n<li><p>If pat doesn't match <code>\"**\"</code>, and it is NOT the last element in the pattern, then for each directory, check if it matches (with glob) <code>pat[n]</code>. If so, recurse down through it, incrementing depth (so it will look at <code>pat[n+1]</code>)</p></li>\n</ol>\n" }, { "answer_id": 4525760, "author": "GoraKhargosh", "author_id": 422589, "author_profile": "https://Stackoverflow.com/users/422589", "pm_score": 1, "selected": false, "text": "<p>There's an implementation in the 'waf' build system source code.\n<a href=\"http://code.google.com/p/waf/source/browse/trunk/waflib/Node.py?r=10755#471\" rel=\"nofollow\">http://code.google.com/p/waf/source/browse/trunk/waflib/Node.py?r=10755#471</a>\nMay be this should be wrapped up in a library of its own?</p>\n" }, { "answer_id": 10597029, "author": "Andrew Alcock", "author_id": 1395668, "author_profile": "https://Stackoverflow.com/users/1395668", "pm_score": 3, "selected": false, "text": "<p>Sorry, this is quite a long time after your OP. I have just released a Python package which does exactly this - it's called Formic and it's available at the <a href=\"http://pypi.python.org/pypi/formic\" rel=\"noreferrer\">PyPI Cheeseshop</a>. With Formic, your problem is solved with:</p>\n\n<pre><code>import formic\nfileset = formic.FileSet(include=\"**/CVS/*\", default_excludes=False)\nfor file_name in fileset.qualified_files():\n print file_name\n</code></pre>\n\n<p>There is one slight complexity: default_excludes. Formic, just like Ant, excludes CVS directories by default (as for the most part collecting files from them for a build is dangerous), the default answer to the question would result in no files. Setting default_excludes=False disables this behaviour.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
Ant has a nice way to select groups of files, most handily using \*\* to indicate a directory tree. E.g. ``` **/CVS/* # All files immediately under a CVS directory. mydir/mysubdir/** # All files recursively under mysubdir ``` More examples can be seen here: <http://ant.apache.org/manual/dirtasks.html> How would you implement this in python, so that you could do something like: ``` files = get_files("**/CVS/*") for file in files: print file => CVS/Repository mydir/mysubdir/CVS/Entries mydir/mysubdir/foo/bar/CVS/Entries ```
As soon as you come across a `**`, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like: ``` def glob_to_regex(pat, dirsep=os.sep): dirsep = re.escape(dirsep) print re.escape(pat) regex = (re.escape(pat).replace("\\*\\*"+dirsep,".*") .replace("\\*\\*",".*") .replace("\\*","[^%s]*" % dirsep) .replace("\\?","[^%s]" % dirsep)) return re.compile(regex+"$") ``` (Though note that this isn't that fully featured - it doesn't support `[a-z]` style glob patterns for instance, though this could probably be added). (The first `\*\*/` match is to cover cases like `\*\*/CVS` matching `./CVS`, as well as having just `\*\*` to match at the tail.) However, obviously you don't want to recurse through everything below the current dir when not processing a `**` pattern, so I think you'll need a two-phase approach. I haven't tried implementing the below, and there are probably a few corner cases, but I think it should work: 1. Split the pattern on your directory seperator. ie `pat.split('/') -> ['**','CVS','*']` 2. Recurse through the directories, and look at the relevant part of the pattern for this level. ie. `n levels deep -> look at pat[n]`. 3. If `pat[n] == '**'` switch to the above strategy: * Reconstruct the pattern with `dirsep.join(pat[n:])` * Convert to a regex with `glob\_to\_regex()` * Recursively `os.walk` through the current directory, building up the path relative to the level you started at. If the path matches the regex, yield it. 4. If pat doesn't match `"**"`, and it is the last element in the pattern, then yield all files/dirs matching `glob.glob(os.path.join(curpath,pat[n]))` 5. If pat doesn't match `"**"`, and it is NOT the last element in the pattern, then for each directory, check if it matches (with glob) `pat[n]`. If so, recurse down through it, incrementing depth (so it will look at `pat[n+1]`)
161,775
<p>I am working on a script that downloads emails and stores them in a db, I usually receive thousands of emails on this account, once downloaded the mails are deleted.</p> <p>Being paranoic, I want to have at least one month backup of my emails, but I cannot clutter my main mailbox address leaving them in there.</p> <p>So i need to move the mails (via php code) from one mailbox to another. I came up with this solution that uses imap_append(). This solution, however recreates the email, and does not really move it.</p> <p>Do you have any suggestions or alternative ways of doing this?</p> <p>Remember: it must be done in php, because I need to integrate it in my readmail script.</p> <p>I have already seen this thread <a href="https://stackoverflow.com/questions/57547/imap-forwarder">where a fetchmail solution was proposed</a></p> <p>Here follows the code I wrote for this task</p> <pre><code>&lt;?php /** * Conn params */ $fromMboxServerPath = "{imap.from.server/notls/imap:143}"; $fromMboxMailboxPath = "INBOX"; $fromMboxMailAddress = "login"; $fromMboxMailPass = "pass"; $toMboxServerPath = "{imap.to.server/notls/imap:143}"; $toMboxMailboxPath = "INBOX"; $toMboxMailAddress = "login"; $toMboxMailPass = "pass"; $fromMboxConnStr = $fromMboxServerPath.$fromMboxMailboxPath; $toMboxConnStr = $toMboxServerPath.$toMboxMailboxPath; $fetchStartSeq = 1; $fetchEndSeq = 10; function myLog($str) { echo "Log [".date('Y-m-d H:i:s')."]: $str\n"; } myLog("Connecting to mailbox"); function mboxConn($connstr,$addr,$pass) { if(!($mbox = @imap_open($connstr, $addr, $pass))) { myLog("Error: ".imap_last_error()); die; } else { myLog("Connected to: $addr $connstr"); return $mbox; } } function mboxCheck($mbox) { if(!($mbox_data = imap_check($mbox))) { myLog("Error: ".imap_last_error()); die; } else { myLog("Mailbox check ".$mbox_data-&gt;Mailbox." OK"); myLog($mbox_data-&gt;Nmsgs." messages present"); return $mbox_data-&gt;Nmsgs; } } $fromMbox = mboxConn($fromMboxConnStr, $fromMboxMailAddress, $fromMboxMailPass); $toMbox = mboxConn($toMboxConnStr, $toMboxMailAddress, $toMboxMailPass); $fromMboxCount = mboxCheck($fromMbox); $toMboxCount = mboxCheck($toMbox); /** * Loop on mails */ $fetchStartUID = imap_uid($fromMbox,$fetchStartSeq); if ($fromMboxCount &lt; $fetchEndSeq) { $fetchEndSeq = $fromMboxCount; } $fetchEndUID = imap_uid($fromMbox,$fetchEndSeq); /** * Loop on mails */ myLog("Do stuff and backup from UID [$fetchStartUID] to UID [$fetchEndUID]"); for ($i=$fetchStartSeq;$i&lt;=$fetchEndSeq;$i++) { $pfx = "Msg #$i : "; $h = imap_header($fromMbox, $i); $fh = imap_fetchheader($fromMbox, $i); $fb = imap_body($fromMbox, $i); $message = $fh.$fb; $msgUID = imap_uid($fromMbox,$i); $struct = imap_fetchstructure ($fromMbox, $i); /** * We do some logging */ myLog($pfx."UID [".$msgUID."] SEQ [".imap_msgno($fromMbox,$msgUID)."] Flags: [". $h-&gt;Unseen . $h-&gt;Recent . $h-&gt;Deleted . $h-&gt;Answered . $h-&gt;Draft . $h-&gt;Flagged."]"); myLog($pfx."From: [". htmlspecialchars($h-&gt;fromaddress) . "] To: [".htmlspecialchars($h-&gt;toaddress)."]"); myLog($pfx."Subject: [$h-&gt;subject]"); /** * Here you do whaterver you need with your email */ /** * Backup email */ if (!($ret = imap_append($toMbox,$toMboxServerPath.$toMboxMailboxPath,$message))) { myLog("Error: ".imap_last_error()); die; } else { myLog("everything ok, mail [$fetchStartUID:$fetchEndUID] downloaded and moved in $newMailboxNameMOVE"); } } /** * End */ imap_close($fromMbox); imap_close($toMbox); myLog("Connection closed"); ?&gt; </code></pre>
[ { "answer_id": 161786, "author": "tpk", "author_id": 8437, "author_profile": "https://Stackoverflow.com/users/8437", "pm_score": 0, "selected": false, "text": "<p>Why separate account and all the hassle that will be involved? Can't you either</p>\n\n<p>a) backup the mail account using standard backup tools like, eg. rdiff-backup?</p>\n\n<p>b) back them up in the db?</p>\n\n<p>or even</p>\n\n<p>c) create an alias so that emails go to both accounts and you have different criteria for removing mails from both accounts (ie. keep them for one more month in the backup account)</p>\n" }, { "answer_id": 179214, "author": "Craig", "author_id": 25639, "author_profile": "https://Stackoverflow.com/users/25639", "pm_score": 1, "selected": false, "text": "<p>First, IMAP does not have a MOVE command only copy but even if it did you can copy from one IMAP server to another directly.</p>\n\n<p>Why not use a subfolder in the account for backups. Download them to your local machine then COPY them to the subfolder and then DELETE them from the INBOX.</p>\n\n<p>COPY and DELETE are imap server side commands so they don't have to leave the server to do the \"move\"</p>\n\n<p>If both accounts are on the same server there is another option, allow access to the backup account's INBOX to the primary account user. Then you can use server side copy/delete to move it to the backup folder.</p>\n\n<p>Not all IMAP servers allow for shared folders.</p>\n\n<p>php does have a imap_move function but I assume it does a copy/delete.</p>\n" }, { "answer_id": 5835167, "author": "Manuel Richarz", "author_id": 719628, "author_profile": "https://Stackoverflow.com/users/719628", "pm_score": 1, "selected": false, "text": "<p>I don't know any other solution like PHP.</p>\n\n<p>But for your code and testing you should use:</p>\n\n<pre><code>$fromMboxServerPath = \"{imap.from.server/notls/imap/readonly:143}\"; //ReadOnly\n</code></pre>\n\n<p>in imap_append() you should give the date from emailheader. see PHP Manual: <a href=\"http://php.net/manual/en/function.imap-append.php\" rel=\"nofollow\">http://php.net/manual/en/function.imap-append.php</a></p>\n\n<p>after that you will have a 1to1 copy of your mail in the target IMAP-Server.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15780/" ]
I am working on a script that downloads emails and stores them in a db, I usually receive thousands of emails on this account, once downloaded the mails are deleted. Being paranoic, I want to have at least one month backup of my emails, but I cannot clutter my main mailbox address leaving them in there. So i need to move the mails (via php code) from one mailbox to another. I came up with this solution that uses imap\_append(). This solution, however recreates the email, and does not really move it. Do you have any suggestions or alternative ways of doing this? Remember: it must be done in php, because I need to integrate it in my readmail script. I have already seen this thread [where a fetchmail solution was proposed](https://stackoverflow.com/questions/57547/imap-forwarder) Here follows the code I wrote for this task ``` <?php /** * Conn params */ $fromMboxServerPath = "{imap.from.server/notls/imap:143}"; $fromMboxMailboxPath = "INBOX"; $fromMboxMailAddress = "login"; $fromMboxMailPass = "pass"; $toMboxServerPath = "{imap.to.server/notls/imap:143}"; $toMboxMailboxPath = "INBOX"; $toMboxMailAddress = "login"; $toMboxMailPass = "pass"; $fromMboxConnStr = $fromMboxServerPath.$fromMboxMailboxPath; $toMboxConnStr = $toMboxServerPath.$toMboxMailboxPath; $fetchStartSeq = 1; $fetchEndSeq = 10; function myLog($str) { echo "Log [".date('Y-m-d H:i:s')."]: $str\n"; } myLog("Connecting to mailbox"); function mboxConn($connstr,$addr,$pass) { if(!($mbox = @imap_open($connstr, $addr, $pass))) { myLog("Error: ".imap_last_error()); die; } else { myLog("Connected to: $addr $connstr"); return $mbox; } } function mboxCheck($mbox) { if(!($mbox_data = imap_check($mbox))) { myLog("Error: ".imap_last_error()); die; } else { myLog("Mailbox check ".$mbox_data->Mailbox." OK"); myLog($mbox_data->Nmsgs." messages present"); return $mbox_data->Nmsgs; } } $fromMbox = mboxConn($fromMboxConnStr, $fromMboxMailAddress, $fromMboxMailPass); $toMbox = mboxConn($toMboxConnStr, $toMboxMailAddress, $toMboxMailPass); $fromMboxCount = mboxCheck($fromMbox); $toMboxCount = mboxCheck($toMbox); /** * Loop on mails */ $fetchStartUID = imap_uid($fromMbox,$fetchStartSeq); if ($fromMboxCount < $fetchEndSeq) { $fetchEndSeq = $fromMboxCount; } $fetchEndUID = imap_uid($fromMbox,$fetchEndSeq); /** * Loop on mails */ myLog("Do stuff and backup from UID [$fetchStartUID] to UID [$fetchEndUID]"); for ($i=$fetchStartSeq;$i<=$fetchEndSeq;$i++) { $pfx = "Msg #$i : "; $h = imap_header($fromMbox, $i); $fh = imap_fetchheader($fromMbox, $i); $fb = imap_body($fromMbox, $i); $message = $fh.$fb; $msgUID = imap_uid($fromMbox,$i); $struct = imap_fetchstructure ($fromMbox, $i); /** * We do some logging */ myLog($pfx."UID [".$msgUID."] SEQ [".imap_msgno($fromMbox,$msgUID)."] Flags: [". $h->Unseen . $h->Recent . $h->Deleted . $h->Answered . $h->Draft . $h->Flagged."]"); myLog($pfx."From: [". htmlspecialchars($h->fromaddress) . "] To: [".htmlspecialchars($h->toaddress)."]"); myLog($pfx."Subject: [$h->subject]"); /** * Here you do whaterver you need with your email */ /** * Backup email */ if (!($ret = imap_append($toMbox,$toMboxServerPath.$toMboxMailboxPath,$message))) { myLog("Error: ".imap_last_error()); die; } else { myLog("everything ok, mail [$fetchStartUID:$fetchEndUID] downloaded and moved in $newMailboxNameMOVE"); } } /** * End */ imap_close($fromMbox); imap_close($toMbox); myLog("Connection closed"); ?> ```
First, IMAP does not have a MOVE command only copy but even if it did you can copy from one IMAP server to another directly. Why not use a subfolder in the account for backups. Download them to your local machine then COPY them to the subfolder and then DELETE them from the INBOX. COPY and DELETE are imap server side commands so they don't have to leave the server to do the "move" If both accounts are on the same server there is another option, allow access to the backup account's INBOX to the primary account user. Then you can use server side copy/delete to move it to the backup folder. Not all IMAP servers allow for shared folders. php does have a imap\_move function but I assume it does a copy/delete.
161,788
<p>Are there any downsides to passing structs by value in C, rather than passing a pointer?</p> <p>If the struct is large, there is obviously the performance aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function.</p> <p>It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that.</p> <p>Are there any reasons for or against this?</p> <p>Since it might not be obvious to everyone what I'm talking about here, I'll give a simple example.</p> <p>If you're programming in C, you'll sooner or later start writing functions that look like this:</p> <pre><code>void examine_data(const char *ptr, size_t len) { ... } char *p = ...; size_t l = ...; examine_data(p, l); </code></pre> <p>This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions.</p> <p>But what happens when you want to return the same kind of information? You typically get something like this:</p> <pre><code>char *get_data(size_t *len); { ... *len = ...datalen...; return ...data...; } size_t len; char *p = get_data(&amp;len); </code></pre> <p>This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function <code>get_data</code> isn't allowed to look at what <code>len</code> points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly.</p> <p>So, the solution I propose is the simple struct</p> <pre><code>struct blob { char *ptr; size_t len; } </code></pre> <p>The examples can be rewritten like this:</p> <pre><code>void examine_data(const struct blob data) { ... use data.tr and data.len ... } struct blob = { .ptr = ..., .len = ... }; examine_data(blob); struct blob get_data(void); { ... return (struct blob){ .ptr = ...data..., .len = ...len... }; } struct blob data = get_data(); </code></pre> <p>For some reason, I think that most people would instinctively make <code>examine_data</code> take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much clearer that they go together. And in the <code>get_data</code> case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length.</p>
[ { "answer_id": 161799, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>I'd say passing (not-too-large) structs by value, both as parameters and as return values, is a perfectly legitimate technique. One has to take care, of course, that the struct is either a POD type, or the copy semantics are well-specified.</p>\n\n<p>Update: Sorry, I had my C++ thinking cap on. I recall a time when it was not legal in C to return a struct from a function, but this has probably changed since then. I would still say it's valid as long as all the compilers you expect to use support the practice.</p>\n" }, { "answer_id": 161802, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "<p>I think that your question has summed things up pretty well.</p>\n\n<p>One other advantage of passing structs by value is that memory ownership is explicit. There is no wondering about if the struct is from the heap, and who has the responsibility for freeing it.</p>\n" }, { "answer_id": 161832, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 4, "selected": false, "text": "<p>Simple solution will be return an error code as a return value and everything else as a parameter in the function,<br>\nThis parameter can be a struct of course but don't see any particular advantage passing this by value, just sent a pointer.<br>\nPassing structure by value is dangerous, you need to be very careful what are you passing are, remember there is no copy constructor in C, if one of structure parameters is a pointer the pointer value will be copied it might be very confusing and hard to maintain. </p>\n\n<p>Just to complete the answer (full credit to <a href=\"https://stackoverflow.com/questions/161788/passing-structs-by-value-why-not#161845\">Roddy</a> ) the stack usage is another reason not pass structure by value, believe me debugging stack overflow is real PITA. </p>\n\n<p>Replay to comment: </p>\n\n<p>Passing struct by pointer meaning that some entity has an ownership on this object and have a full knowledge of what and when should be released. Passing struct by value create a hidden references to the internal data of struct (pointers to another structures etc .. ) at this is hard to maintain (possible but why ?) .</p>\n" }, { "answer_id": 161845, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 8, "selected": false, "text": "<p>For small structs (eg point, rect) passing by value is perfectly acceptable. But, apart from speed, there is one other reason why you should be careful passing/returning large structs by value: Stack space.</p>\n<p>A lot of C programming is for embedded systems, where memory is at a premium, and stack sizes may be measured in KB or even Bytes... If you're passing or returning structs by value, copies of those structs will get placed on the stack, potentially causing the situation that <a href=\"https://www.stackoverflow.com\">this site</a> is named after...</p>\n<p>If I see an application that seems to have excessive stack usage, structs passed by value is one of the things I look for first.</p>\n" }, { "answer_id": 162140, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 4, "selected": false, "text": "<p>One thing people here have forgotten to mention so far (or I overlooked it) is that structs usually have a padding!</p>\n\n<pre><code>struct {\n short a;\n char b;\n short c;\n char d;\n}\n</code></pre>\n\n<p>Every char is 1 byte, every short is 2 bytes. How large is the struct? Nope, it's not 6 bytes. At least not on any more commonly used systems. On most systems it will be 8. The problem is, the alignment is not constant, it's system dependent, so the same struct will have different alignment and different sizes on different systems.</p>\n\n<p>Not only that padding will further eat up your stack, it also adds the uncertainty of not being able to predict the padding in advance, unless you know how your system pads and then look at every single struct you have in your app and calculate the size for it. Passing a pointer takes a predictable amount of space -- there is no uncertainty. The size of a pointer is known for the system, it is always equal, regardless of what the struct looks like and pointer sizes are always chosen in a way that they are aligned and need no padding.</p>\n" }, { "answer_id": 166947, "author": "tonylo", "author_id": 4071, "author_profile": "https://Stackoverflow.com/users/4071", "pm_score": 6, "selected": false, "text": "<p>One reason not to do this which has not been mentioned is that this can cause an issue where binary compatibility matters.</p>\n<p>Depending on the compiler used, structures can be passed via the stack or registers depending on compiler options/implementation</p>\n<p>See: <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html\" rel=\"noreferrer\">http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html</a></p>\n<blockquote>\n<p>-fpcc-struct-return</p>\n<p>-freg-struct-return</p>\n</blockquote>\n<p>If two compilers disagree, things can blow up. Needless to say the main reasons not to do this are illustrated are stack consumption and performance reasons.</p>\n" }, { "answer_id": 3355560, "author": "kizzx2", "author_id": 111021, "author_profile": "https://Stackoverflow.com/users/111021", "pm_score": 5, "selected": false, "text": "<p>To <em>really</em> answer this question, one needs to dig deep into the assembly land:</p>\n\n<p>(The following example uses gcc on x86_64. Anyone is welcome to add other architectures like MSVC, ARM, etc.)</p>\n\n<p>Let's have our example program:</p>\n\n<pre><code>// foo.c\n\ntypedef struct\n{\n double x, y;\n} point;\n\nvoid give_two_doubles(double * x, double * y)\n{\n *x = 1.0;\n *y = 2.0;\n}\n\npoint give_point()\n{\n point a = {1.0, 2.0};\n return a;\n}\n\nint main()\n{\n return 0;\n}\n</code></pre>\n\n<p>Compile it with full optimizations</p>\n\n<pre><code>gcc -Wall -O3 foo.c -o foo\n</code></pre>\n\n<p>Look at the assembly:</p>\n\n<pre><code>objdump -d foo | vim -\n</code></pre>\n\n<p>This is what we get:</p>\n\n<pre><code>0000000000400480 &lt;give_two_doubles&gt;:\n 400480: 48 ba 00 00 00 00 00 mov $0x3ff0000000000000,%rdx\n 400487: 00 f0 3f \n 40048a: 48 b8 00 00 00 00 00 mov $0x4000000000000000,%rax\n 400491: 00 00 40 \n 400494: 48 89 17 mov %rdx,(%rdi)\n 400497: 48 89 06 mov %rax,(%rsi)\n 40049a: c3 retq \n 40049b: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)\n\n00000000004004a0 &lt;give_point&gt;:\n 4004a0: 66 0f 28 05 28 01 00 movapd 0x128(%rip),%xmm0\n 4004a7: 00 \n 4004a8: 66 0f 29 44 24 e8 movapd %xmm0,-0x18(%rsp)\n 4004ae: f2 0f 10 05 12 01 00 movsd 0x112(%rip),%xmm0\n 4004b5: 00 \n 4004b6: f2 0f 10 4c 24 f0 movsd -0x10(%rsp),%xmm1\n 4004bc: c3 retq \n 4004bd: 0f 1f 00 nopl (%rax)\n</code></pre>\n\n<p>Excluding the <code>nopl</code> pads, <code>give_two_doubles()</code> has 27 bytes while <code>give_point()</code> has 29 bytes. On the other hand, <code>give_point()</code> yields one fewer instruction than <code>give_two_doubles()</code></p>\n\n<p>What's interesting is that we notice the compiler has been able to optimize <code>mov</code> into the faster SSE2 variants <a href=\"http://en.wikipedia.org/wiki/MOVAPD\" rel=\"noreferrer\"><code>movapd</code></a> and <code>movsd</code>. Furthermore, <code>give_two_doubles()</code> actually moves data in and out from memory, which makes things slow.</p>\n\n<p>Apparently much of this may not be applicable in embedded environments (which is where the playing field for C is most of the time nowdays). I'm not an assembly wizard so any comments would be welcome!</p>\n" }, { "answer_id": 5746156, "author": "Jingguo Yao", "author_id": 431698, "author_profile": "https://Stackoverflow.com/users/431698", "pm_score": 3, "selected": false, "text": "<p>Page 150 of PC Assembly Tutorial on <a href=\"http://www.drpaulcarter.com/pcasm/\" rel=\"nofollow\">http://www.drpaulcarter.com/pcasm/</a> has a clear explanation about how C allows a function to return a struct:</p>\n\n<blockquote>\n <p>C also allows a structure type to be\n used as the return value of a func-\n tion. Obviously a structure can not be\n returned in the EAX register.\n Different compilers handle this\n situation differently. A common\n solution that compilers use is to\n internally rewrite the function as one\n that takes a structure pointer as a\n parameter. The pointer is used to put\n the return value into a structure\n defined outside of the routine called.</p>\n</blockquote>\n\n<p>I use the following C code to verify the above statement:</p>\n\n<pre><code>struct person {\n int no;\n int age;\n};\n\nstruct person create() {\n struct person jingguo = { .no = 1, .age = 2};\n return jingguo;\n}\n\nint main(int argc, const char *argv[]) {\n struct person result;\n result = create();\n return 0;\n}\n</code></pre>\n\n<p>Use \"gcc -S\" to generate assembly for this piece of C code:</p>\n\n<pre><code> .file \"foo.c\"\n .text\n.globl create\n .type create, @function\ncreate:\n pushl %ebp\n movl %esp, %ebp\n subl $16, %esp\n movl 8(%ebp), %ecx\n movl $1, -8(%ebp)\n movl $2, -4(%ebp)\n movl -8(%ebp), %eax\n movl -4(%ebp), %edx\n movl %eax, (%ecx)\n movl %edx, 4(%ecx)\n movl %ecx, %eax\n leave\n ret $4\n .size create, .-create\n.globl main\n .type main, @function\nmain:\n pushl %ebp\n movl %esp, %ebp\n subl $20, %esp\n leal -8(%ebp), %eax\n movl %eax, (%esp)\n call create\n subl $4, %esp\n movl $0, %eax\n leave\n ret\n .size main, .-main\n .ident \"GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3\"\n .section .note.GNU-stack,\"\",@progbits\n</code></pre>\n\n<p>The stack before call create:</p>\n\n<pre><code> +---------------------------+\nebp | saved ebp |\n +---------------------------+\nebp-4 | age part of struct person | \n +---------------------------+\nebp-8 | no part of struct person |\n +---------------------------+ \nebp-12 | |\n +---------------------------+\nebp-16 | |\n +---------------------------+\nebp-20 | ebp-8 (address) |\n +---------------------------+\n</code></pre>\n\n<p>The stack right after calling create:</p>\n\n<pre><code> +---------------------------+\n | ebp-8 (address) |\n +---------------------------+\n | return address |\n +---------------------------+\nebp,esp | saved ebp |\n +---------------------------+\n</code></pre>\n" }, { "answer_id": 7550748, "author": "Chris Lutz", "author_id": 60777, "author_profile": "https://Stackoverflow.com/users/60777", "pm_score": 3, "selected": false, "text": "<p>Here's something no one mentioned:</p>\n\n<pre><code>void examine_data(const char *c, size_t l)\n{\n c[0] = 'l'; // compiler error\n}\n\nvoid examine_data(const struct blob blob)\n{\n blob.ptr[0] = 'l'; // perfectly legal, quite likely to blow up at runtime\n}\n</code></pre>\n\n<p>Members of a <code>const struct</code> are <code>const</code>, but if that member is a pointer (like <code>char *</code>), it becomes <code>char *const</code> rather than the <code>const char *</code> we really want. Of course, we could assume that the <code>const</code> is documentation of intent, and that anyone who violates this is writing bad code (which they are), but that's not good enough for some (especially those who just spent four hours tracking down the cause of a crash).</p>\n\n<p>The alternative might be to make a <code>struct const_blob { const char *c; size_t l }</code> and use that, but that's rather messy - it gets into the same naming-scheme problem I have with <code>typedef</code>ing pointers. Thus, most people stick to just having two parameters (or, more likely for this case, using a string library).</p>\n" }, { "answer_id": 39333291, "author": "Vad", "author_id": 1091644, "author_profile": "https://Stackoverflow.com/users/1091644", "pm_score": 0, "selected": false, "text": "<p>I just want to point one advantage of passing your structs by value is that an optimizing compiler may better optimize your code.</p>\n" }, { "answer_id": 73072913, "author": "Watachiaieto", "author_id": 1390652, "author_profile": "https://Stackoverflow.com/users/1390652", "pm_score": 0, "selected": false, "text": "<p>Taking into account all of the things people have said...</p>\n<ol>\n<li>Returning a struct was not always allowed in C. Now it is.</li>\n<li>Returning a struct can be done in three ways...\na. Returning each member in a register (probably optimal, but unlikely to be the actual...)\nb. Returning the struct in the stack (slower than registers, but still better than a cold access of heap ram... yay caching!)\nc. Returning the struct in a pointer to the heap (It only hurts you when you read or write to it? A Good compiler will pass the pointers it read just once and tried to access, did instruction reordering and accesses it much earlier than needed so it was ready when you were? to make life better? (shiver))</li>\n<li>Different compiler settings can cause different problems when the code interfaces because of this. (Different size registers, different amounts of padding, different optimizations turned on)</li>\n<li>const-ness or volatile-ness doesn't permeate through a struct, and can result in some miserably un-efficient or possibly lead to broken code (E.G. a const struct foo does not result in foo-&gt;bar being const.)</li>\n</ol>\n<p>Some simple measures I will take after reading this...</p>\n<ol>\n<li>Make your functions accept parameters rather than structs. It allows fine grained control over const-ness and volatile-ness etc, it also ensures that all the variables passed are relevant to the function using them. If the parameters are all the same kind, use some other method to enforce ordering. (Make type defs to make your function calls more strongly typed, which an OS does routinely.)</li>\n<li>Instead of allowing the final base function to return a pointer to a structure made in the heap, provide a pointer to a struct to put the results into. that struct still might be in the heap, but it is possible that the struct is actually in the stack - and will get better runtime performance. It also means that you do not need to rely on compilers providing you a struct return type.</li>\n<li>By passing the parameters as pieces and being clear about the const-ness, volatile-ness, or the restrict-ness, you better convey your intentions to the complier and that will allow it to make better optimizations.</li>\n</ol>\n<p>I am not sure where 'too big' and 'too small' is at, but I guess the answer is between 2 and register count + 1 members.\nIf I made a struct that holds 1 member that is an int, then clearly we should not pass the struct. (Not only is it inefficient, it also makes intention VERY murky... I suppose it has a use somewhere, but not common)</p>\n<p>If I make a struct that holds two items, it might have value in clarity, as well as compliers might optimize it into two variables that travel as pairs. (risc-v specifies that a struct with two members returns both members in registers, assuming they are ints or smaller...)</p>\n<p>If I make a structure that holds as many ints and double as there are in the registers for in the processor, it is TECHNICALLY a possible optimization.\nThe instance I surpass the register amounts though, it probably would have been worth it to keep the result struct in a pointer, and pass in only the parameters that were relevant. (That, and probably make the struct smaller and the function do less, because we have a LOT of registers on systems nowadays, even in the embedded world...)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24458/" ]
Are there any downsides to passing structs by value in C, rather than passing a pointer? If the struct is large, there is obviously the performance aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function. It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that. Are there any reasons for or against this? Since it might not be obvious to everyone what I'm talking about here, I'll give a simple example. If you're programming in C, you'll sooner or later start writing functions that look like this: ``` void examine_data(const char *ptr, size_t len) { ... } char *p = ...; size_t l = ...; examine_data(p, l); ``` This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions. But what happens when you want to return the same kind of information? You typically get something like this: ``` char *get_data(size_t *len); { ... *len = ...datalen...; return ...data...; } size_t len; char *p = get_data(&len); ``` This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function `get_data` isn't allowed to look at what `len` points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly. So, the solution I propose is the simple struct ``` struct blob { char *ptr; size_t len; } ``` The examples can be rewritten like this: ``` void examine_data(const struct blob data) { ... use data.tr and data.len ... } struct blob = { .ptr = ..., .len = ... }; examine_data(blob); struct blob get_data(void); { ... return (struct blob){ .ptr = ...data..., .len = ...len... }; } struct blob data = get_data(); ``` For some reason, I think that most people would instinctively make `examine_data` take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much clearer that they go together. And in the `get_data` case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length.
For small structs (eg point, rect) passing by value is perfectly acceptable. But, apart from speed, there is one other reason why you should be careful passing/returning large structs by value: Stack space. A lot of C programming is for embedded systems, where memory is at a premium, and stack sizes may be measured in KB or even Bytes... If you're passing or returning structs by value, copies of those structs will get placed on the stack, potentially causing the situation that [this site](https://www.stackoverflow.com) is named after... If I see an application that seems to have excessive stack usage, structs passed by value is one of the things I look for first.
161,790
<p>I have the following class in C++:</p> <pre><code>class a { const int b[2]; // other stuff follows // and here's the constructor a(void); } </code></pre> <p>The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is <code>const</code>?</p> <p>This doesn't work:</p> <pre><code>a::a(void) : b([2,3]) { // other initialization stuff } </code></pre> <p>Edit: The case in point is when I can have different values for <code>b</code> for different instances, but the values are known to be constant for the lifetime of the instance.</p>
[ { "answer_id": 161806, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 2, "selected": false, "text": "<p>You can't do that from the initialization list, </p>\n\n<p>Have a look at this:</p>\n\n<p><a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"nofollow noreferrer\">http://www.cprogramming.com/tutorial/initialization-lists-c++.html</a></p>\n\n<p>:)</p>\n" }, { "answer_id": 161816, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 5, "selected": false, "text": "<p>It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see <a href=\"http://www.artima.com/cppsource/cpp0x.html\" rel=\"noreferrer\">A Brief Look at C++0x</a>, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).</p>\n" }, { "answer_id": 161829, "author": "Daniel Bungert", "author_id": 21093, "author_profile": "https://Stackoverflow.com/users/21093", "pm_score": 2, "selected": false, "text": "<p>Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nclass a {\n static const int b[2];\npublic:\n a(void) {\n for(int i = 0; i &lt; 2; i++) {\n printf(\"b[%d] = [%d]\\n\", i, b[i]);\n }\n }\n};\n\nconst int a::b[2] = { 4, 2 };\n\nint main(int argc, char **argv)\n{\n a foo;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 161875, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 3, "selected": false, "text": "<p>ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:</p>\n\n<pre><code>a::a(void) :\nb({2,3})\n{\n // other initialization stuff\n}\n</code></pre>\n\n<p>Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass A \n{\npublic:\n A();\n static const int a[2];\n};\n\nconst int A::a[2] = {0, 1};\n\nA::A()\n{\n}\n\nint main (int argc, char * const argv[]) \n{\n std::cout &lt;&lt; \"A::a =&gt; \" &lt;&lt; A::a[0] &lt;&lt; \", \" &lt;&lt; A::a[1] &lt;&lt; \"\\n\";\n return 0;\n}\n</code></pre>\n\n<p>The output being:</p>\n\n<pre><code>A::a =&gt; 0, 1\n</code></pre>\n\n<p>Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nclass A \n{\npublic:\n A();\n int a[2];\n};\n\nA::A()\n{\n a[0] = 9; // or some calculation\n a[1] = 10; // or some calculation\n}\n\nint main (int argc, char * const argv[]) \n{\n A v;\n std::cout &lt;&lt; \"v.a =&gt; \" &lt;&lt; v.a[0] &lt;&lt; \", \" &lt;&lt; v.a[1] &lt;&lt; \"\\n\";\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 162372, "author": "Weipeng", "author_id": 192280, "author_profile": "https://Stackoverflow.com/users/192280", "pm_score": 6, "selected": true, "text": "<p>Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.</p>\n\n<pre><code>int* a = new int[N];\n// fill a\n\nclass C {\n const std::vector&lt;int&gt; v;\npublic:\n C():v(a, a+N) {}\n};\n</code></pre>\n" }, { "answer_id": 922255, "author": "Nefzen", "author_id": 112830, "author_profile": "https://Stackoverflow.com/users/112830", "pm_score": 2, "selected": false, "text": "<p>interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:</p>\n\n<pre><code>readonly DateTime a = DateTime.Now;\n</code></pre>\n\n<p>I agree, if you have a const pre-defined array you might as well make it static.\nAt that point you can use this interesting syntax:</p>\n\n<pre><code>//in header file\nclass a{\n static const int SIZE;\n static const char array[][10];\n};\n//in cpp file:\nconst int a::SIZE = 5;\nconst char array[SIZE][10] = {\"hello\", \"cruel\",\"world\",\"goodbye\", \"!\"};\n</code></pre>\n\n<p>however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.</p>\n" }, { "answer_id": 2642704, "author": "Matthew", "author_id": 317152, "author_profile": "https://Stackoverflow.com/users/317152", "pm_score": 4, "selected": false, "text": "<p><code>std::vector</code> uses the heap. Geez, what a waste that would be just for the sake of a <code>const</code> sanity-check. The point of <code>std::vector</code> is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n\ntemplate &lt;class Type, size_t MaxLength&gt;\nclass ConstFixedSizeArrayFiller {\nprivate:\n size_t length;\n\npublic:\n ConstFixedSizeArrayFiller() : length(0) {\n }\n\n virtual ~ConstFixedSizeArrayFiller() {\n }\n\n virtual void Fill(Type *array) = 0;\n\nprotected:\n void add_element(Type *array, const Type &amp; element)\n {\n if(length &gt;= MaxLength) {\n // todo: throw more appropriate out-of-bounds exception\n throw 0;\n }\n array[length] = element;\n length++;\n }\n};\n\n\ntemplate &lt;class Type, size_t Length&gt;\nclass ConstFixedSizeArray {\nprivate:\n Type array[Length];\n\npublic:\n explicit ConstFixedSizeArray(\n ConstFixedSizeArrayFiller&lt;Type, Length&gt; &amp; filler\n ) {\n filler.Fill(array);\n }\n\n const Type *Array() const {\n return array;\n }\n\n size_t ArrayLength() const {\n return Length;\n }\n};\n\n\nclass a {\nprivate:\n class b_filler : public ConstFixedSizeArrayFiller&lt;int, 2&gt; {\n public:\n virtual ~b_filler() {\n }\n\n virtual void Fill(int *array) {\n add_element(array, 87);\n add_element(array, 96);\n }\n };\n\n const ConstFixedSizeArray&lt;int, 2&gt; b;\n\npublic:\n a(void) : b(b_filler()) {\n }\n\n void print_items() {\n size_t i;\n for(i = 0; i &lt; b.ArrayLength(); i++)\n {\n printf(\"%d\\n\", b.Array()[i]);\n }\n }\n};\n\n\nint main()\n{\n a x;\n x.print_items();\n return 0;\n}\n</code></pre>\n\n<p><code>ConstFixedSizeArrayFiller</code> and <code>ConstFixedSizeArray</code> are reusable.</p>\n\n<p>The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become <code>const</code> after this initialization.</p>\n\n<p>The second allows the array to be allocated <em>inside</em> another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.</p>\n\n<p><code>b_filler</code> is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.</p>\n\n<p>I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.</p>\n" }, { "answer_id": 2861574, "author": "CharlesB", "author_id": 11343, "author_profile": "https://Stackoverflow.com/users/11343", "pm_score": 2, "selected": false, "text": "<p>A solution without using the heap with <code>std::vector</code> is to use <code>boost::array</code>, though you can't initialize array members directly in the constructor.</p>\n\n<pre><code>#include &lt;boost/array.hpp&gt;\n\nconst boost::array&lt;int, 2&gt; aa={ { 2, 3} };\n\nclass A {\n const boost::array&lt;int, 2&gt; b;\n A():b(aa){};\n};\n</code></pre>\n" }, { "answer_id": 6308072, "author": "Pete", "author_id": 782738, "author_profile": "https://Stackoverflow.com/users/782738", "pm_score": 2, "selected": false, "text": "<p>How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:</p>\n\n<pre><code>class a {\n int privateB[2];\npublic:\n a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }\n int b(const int idx) { return privateB[idx]; }\n}\n</code></pre>\n\n<p>Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.</p>\n\n<pre><code>a aobj(2,3); // initialize \"constant array\" b[]\nn = aobj.b(1); // read b[1] (write impossible from here)\n</code></pre>\n\n<p>If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer <a href=\"http://coding.derkeiler.com/Archive/C_CPP/comp.lang.cpp/2004-10/1388.html\" rel=\"nofollow\">John Harrison's comp.lang.c++ post using a const class.</a></p>\n" }, { "answer_id": 7806293, "author": "Flexo", "author_id": 168175, "author_profile": "https://Stackoverflow.com/users/168175", "pm_score": 6, "selected": false, "text": "<p>With C++11 the answer to this question has now changed and you can in fact do:</p>\n\n<pre><code>struct a {\n const int b[2];\n // other bits follow\n\n // and here's the constructor\n a();\n};\n\na::a() :\n b{2,3}\n{\n // other constructor work\n}\n\nint main() {\n a a;\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084/" ]
I have the following class in C++: ``` class a { const int b[2]; // other stuff follows // and here's the constructor a(void); } ``` The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is `const`? This doesn't work: ``` a::a(void) : b([2,3]) { // other initialization stuff } ``` Edit: The case in point is when I can have different values for `b` for different instances, but the values are known to be constant for the lifetime of the instance.
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead. ``` int* a = new int[N]; // fill a class C { const std::vector<int> v; public: C():v(a, a+N) {} }; ```
161,794
<p>I am not sure if I formulated the question right, but still ...</p> <p>I have a view that shows a flash embed and this flash take as parameter a <code>/controller/action</code> URL that generates a XML. I nee to send, from this view, an array to the XML generator action. How is the best way ? Is there some <code>helper-&gt;set()</code> method like or I have to create an specific URL to send this array to that action ?</p> <p>Here goes my structure:</p> <p><strong><code>my_controller.php</code></strong></p> <pre><code>function player() {} </code></pre> <p><strong><code>player.ctp</code></strong></p> <pre><code>&lt;div id="myDiv"&gt;Here it Goes&lt;/div&gt; &lt;script type="text/javascript"&gt; var so = new SWFObject('player.swf','test','50','50','8'); so.addVariable('file','/xml/generate'); // need to pass an array here so.write('myDiv'); &lt;/script&gt; </code></pre> <p><strong><code>xml_controller.php</code></strong></p> <pre><code>public function generate() { // I need to read an array here } </code></pre> <p><strong><code>generate.ctp</code></strong></p> <pre><code>echo "&lt;xml&gt;&lt;data&gt;" . $array['contents'] . "&lt;/data&gt;"; </code></pre>
[ { "answer_id": 161854, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 1, "selected": true, "text": "<p>First of all you cannot send data from one view to another in the manner you are speaking. Each of those calls would be a separate request and this means that it goes out of the framework and then in again. This means that the framework will be built and tear down between calls, making impossible to pass the data between views.</p>\n\n<p>Now in regards to the array that has to be sent to your action, I'm utterly confused. I don't think you are looking at the problem the right way. If that action needs an array of data and then produce XML so the Flash Object can get it, then it makes even less sense. Are you sure that the Flash Object isn't the one responsible to sending that array of data to the Param you mentioned?</p>\n\n<p>Well, even if all you are saying has to be done quite like that, I'll suggest you drop that array on the file system and then pick it up when the action is called by the Flash.</p>\n\n<p>Or another suggestion would be to use AJAX to send that array to the action.</p>\n\n<p>Both suggestions imply my utter \"cluelessness\" on your predicate.</p>\n\n<p>I still have to ask, isn't the Flash Object gonna do something in all this?</p>\n" }, { "answer_id": 163979, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 1, "selected": false, "text": "<p>Save the array in the session then in the next request to the XML generator action, read it back from the session.</p>\n\n<p>my_controller.php</p>\n\n<pre><code>function player() {\n $this-&gt;Session-&gt;write('key', $array);\n}\n</code></pre>\n\n<p>xml_controller.php</p>\n\n<pre><code>public function generate() {\n $array = $this-&gt;Session-&gt;read('key');\n}\n</code></pre>\n\n<p>However, I have heard of some problems where flash sometimes doesn't send session cookies, in which case, append the session id to the url of the action:</p>\n\n<pre><code>so.addVariable('file','/xml/generate/&lt;?php echo $session-&gt;id(); ?&gt;');\n</code></pre>\n\n<p>and to get the session back:</p>\n\n<pre><code>public function generate($sessionId) {\n CakeSession::id($sessionId);\n $array = $this-&gt;Session-&gt;read('key');\n}\n</code></pre>\n" }, { "answer_id": 164000, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 2, "selected": false, "text": "<p>If the array is small enough, serialize then urlencode it and add it as a paramter to the url to your generate action:</p>\n\n<p>player.ctp</p>\n\n<pre><code>so.addVariable('file','/xml/generate/&lt;?php echo urlencode(serialize($array)); ?&gt;');\n</code></pre>\n\n<p>then read it back:</p>\n\n<pre><code>public function generate($array) {\n $array = unserialize($array);\n}\n</code></pre>\n" }, { "answer_id": 9646309, "author": "Vincent", "author_id": 1260980, "author_profile": "https://Stackoverflow.com/users/1260980", "pm_score": 0, "selected": false, "text": "<p>You can send an array with data from a view to a controller in CakePHP like this.</p>\n\n<p>To the link you can pass arguments:</p>\n\n<pre><code>www.site.com/model/action/param1:foo/param2:test\n</code></pre>\n\n<p>You can then retrieve them in the controller action in the following way:</p>\n\n<pre><code>$yourarray = $this-&gt;params['named'];\n</code></pre>\n\n<p>Of course the array shouldn't be too large then.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I am not sure if I formulated the question right, but still ... I have a view that shows a flash embed and this flash take as parameter a `/controller/action` URL that generates a XML. I nee to send, from this view, an array to the XML generator action. How is the best way ? Is there some `helper->set()` method like or I have to create an specific URL to send this array to that action ? Here goes my structure: **`my_controller.php`** ``` function player() {} ``` **`player.ctp`** ``` <div id="myDiv">Here it Goes</div> <script type="text/javascript"> var so = new SWFObject('player.swf','test','50','50','8'); so.addVariable('file','/xml/generate'); // need to pass an array here so.write('myDiv'); </script> ``` **`xml_controller.php`** ``` public function generate() { // I need to read an array here } ``` **`generate.ctp`** ``` echo "<xml><data>" . $array['contents'] . "</data>"; ```
First of all you cannot send data from one view to another in the manner you are speaking. Each of those calls would be a separate request and this means that it goes out of the framework and then in again. This means that the framework will be built and tear down between calls, making impossible to pass the data between views. Now in regards to the array that has to be sent to your action, I'm utterly confused. I don't think you are looking at the problem the right way. If that action needs an array of data and then produce XML so the Flash Object can get it, then it makes even less sense. Are you sure that the Flash Object isn't the one responsible to sending that array of data to the Param you mentioned? Well, even if all you are saying has to be done quite like that, I'll suggest you drop that array on the file system and then pick it up when the action is called by the Flash. Or another suggestion would be to use AJAX to send that array to the action. Both suggestions imply my utter "cluelessness" on your predicate. I still have to ask, isn't the Flash Object gonna do something in all this?
161,813
<p>How do I resolve merge conflicts in my Git repository?</p>
[ { "answer_id": 162056, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 9, "selected": false, "text": "<ol>\n<li><p>Identify which files are in conflict (Git should tell you this).</p></li>\n<li><p>Open each file and examine the diffs; Git demarcates them. Hopefully it will be obvious which version of each block to keep. You may need to discuss it with fellow developers who committed the code.</p></li>\n<li><p>Once you've resolved the conflict in a file <code>git add the_file</code>.</p></li>\n<li><p>Once you've resolved <strong>all</strong> conflicts, do <code>git rebase --continue</code> or whatever command \nGit said to do when you completed.</p></li>\n</ol>\n" }, { "answer_id": 163234, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 6, "selected": false, "text": "<p>If you're making frequent small commits, then start by looking at the commit comments with <code>git log --merge</code>. Then <code>git diff</code> will show you the conflicts.</p>\n\n<p>For conflicts that involve more than a few lines, it's easier to see what's going on in an external GUI tool. I like opendiff -- Git also supports vimdiff, gvimdiff, kdiff3, tkdiff, meld, xxdiff, emerge out of the box and you can install others: <code>git config merge.tool \"your.tool\"</code> will set your chosen tool and then <code>git mergetool</code> after a failed merge will show you the diffs in context.</p>\n\n<p>Each time you edit a file to resolve a conflict, <code>git add filename</code> will update the index and your diff will no longer show it. When all the conflicts are handled and their files have been <code>git add</code>-ed, <code>git commit</code> will complete your merge.</p>\n" }, { "answer_id": 163659, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 13, "selected": true, "text": "<p>Try:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git mergetool\n</code></pre>\n<p>It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly.</p>\n<hr />\n<p>As per <a href=\"https://stackoverflow.com/questions/161813/how-to-resolve-merge-conflicts-in-git-repository#comment6881558_163659\">Josh Glover's comment</a>:</p>\n<blockquote>\n<p>[This command]\ndoesn't necessarily open a GUI unless you install one. Running <code>git mergetool</code> for me resulted in <code>vimdiff</code> being used. You can install\none of the following tools to use it instead: <code>meld</code>, <code>opendiff</code>,\n<code>kdiff3</code>, <code>tkdiff</code>, <code>xxdiff</code>, <code>tortoisemerge</code>, <code>gvimdiff</code>, <code>diffuse</code>,\n<code>ecmerge</code>, <code>p4merge</code>, <code>araxis</code>, <code>vimdiff</code>, <code>emerge</code>.</p>\n</blockquote>\n<hr />\n<p>Below is a sample procedure using <code>vimdiff</code> to resolve merge conflicts, based on <a href=\"http://www.rosipov.com/blog/use-vimdiff-as-git-mergetool/#fromHistor\" rel=\"noreferrer\">this link</a>.</p>\n<ol>\n<li><p>Run the following commands in your terminal</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git config merge.tool vimdiff\ngit config merge.conflictstyle diff3\ngit config mergetool.prompt false\n</code></pre>\n<p>This will set <code>vimdiff</code> as the default merge tool.</p>\n</li>\n<li><p>Run the following command in your terminal</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git mergetool\n</code></pre>\n</li>\n<li><p>You will see a <code>vimdiff</code> display in the following format:</p>\n<pre class=\"lang-none prettyprint-override\"><code> ╔═══════╦══════╦════════╗\n ║ ║ ║ ║\n ║ LOCAL ║ BASE ║ REMOTE ║\n ║ ║ ║ ║\n ╠═══════╩══════╩════════╣\n ║ ║\n ║ MERGED ║\n ║ ║\n ╚═══════════════════════╝\n</code></pre>\n<p>These 4 views are</p>\n<ul>\n<li><strong>LOCAL:</strong> this is the file from the current branch</li>\n<li><strong>BASE:</strong> the common ancestor, how this file looked before both changes</li>\n<li><strong>REMOTE:</strong> the file you are merging into your branch</li>\n<li><strong>MERGED:</strong> the merge result; this is what gets saved in the merge commit and used in the future</li>\n</ul>\n<p>You can navigate among these views using <kbd>ctrl</kbd>+<kbd>w</kbd>. You can directly reach the MERGED view using <kbd>ctrl</kbd>+<kbd>w</kbd> followed by <kbd>j</kbd>.</p>\n<p>More information about <code>vimdiff</code> navigation is <a href=\"https://stackoverflow.com/questions/4556184/vim-move-window-left-right\">here</a> and <a href=\"https://stackoverflow.com/questions/27151456/how-do-i-jump-to-the-next-prev-diff-in-git-difftool\">here</a>.</p>\n</li>\n<li><p>You can edit the MERGED view like this:</p>\n<ul>\n<li><p>If you want to get changes from REMOTE</p>\n<pre><code>:diffg RE\n</code></pre>\n</li>\n<li><p>If you want to get changes from BASE</p>\n<pre><code>:diffg BA\n</code></pre>\n</li>\n<li><p>If you want to get changes from LOCAL</p>\n<pre><code>:diffg LO\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Save, Exit, Commit, and Clean up</p>\n<p><code>:wqa</code> save and exit from vi</p>\n<p><code>git commit -m &quot;message&quot;</code></p>\n<p><code>git clean</code> Remove extra files (e.g. <code>*.orig</code>). <strong>Warning:</strong> It will remove all untracked files, if you won't pass any arguments.</p>\n</li>\n</ol>\n" }, { "answer_id": 167365, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 7, "selected": false, "text": "<p>Check out the answers in Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/101752/aborting-a-merge-in-git\">Aborting a merge in Git</a></em>, especially <a href=\"https://stackoverflow.com/questions/101752/aborting-a-merge-in-git#107860\">Charles Bailey's answer</a> which shows how to view the different versions of the file with problems, for example, </p>\n\n<pre class=\"lang-bash prettyprint-override\"><code># Common base version of the file.\ngit show :1:some_file.cpp\n\n# 'Ours' version of the file.\ngit show :2:some_file.cpp\n\n# 'Theirs' version of the file.\ngit show :3:some_file.cpp\n</code></pre>\n" }, { "answer_id": 3407920, "author": "coolaj86", "author_id": 151312, "author_profile": "https://Stackoverflow.com/users/151312", "pm_score": 11, "selected": false, "text": "<p>Here's a probable use case, from the top:</p>\n<p>You're going to pull some changes, but oops, you're not up to date:</p>\n<pre><code>git fetch origin\ngit pull origin master\n\nFrom ssh://[email protected]:22/projectname\n * branch master -&gt; FETCH_HEAD\nUpdating a030c3a..ee25213\nerror: Entry 'filename.c' not uptodate. Cannot merge.\n</code></pre>\n<p>So you get up-to-date and try again, but have a conflict:</p>\n<pre><code>git add filename.c\ngit commit -m &quot;made some wild and crazy changes&quot;\ngit pull origin master\n\nFrom ssh://[email protected]:22/projectname\n * branch master -&gt; FETCH_HEAD\nAuto-merging filename.c\nCONFLICT (content): Merge conflict in filename.c\nAutomatic merge failed; fix conflicts and then commit the result.\n</code></pre>\n<p>So you decide to take a look at the changes:</p>\n<pre><code>git mergetool\n</code></pre>\n<p>Oh my, oh my, upstream changed some things, but just to use my changes...no...their changes...</p>\n<pre><code>git checkout --ours filename.c\ngit checkout --theirs filename.c\ngit add filename.c\ngit commit -m &quot;using theirs&quot;\n</code></pre>\n<p>And then we try a final time</p>\n<pre><code>git pull origin master\n\nFrom ssh://[email protected]:22/projectname\n * branch master -&gt; FETCH_HEAD\nAlready up-to-date.\n</code></pre>\n<p>Ta-da!</p>\n" }, { "answer_id": 7589612, "author": "Mark E. Haase", "author_id": 122763, "author_profile": "https://Stackoverflow.com/users/122763", "pm_score": 10, "selected": false, "text": "<p>I find merge tools rarely help me understand the conflict or the resolution. I'm usually more successful looking at the conflict markers in a text editor and using git log as a supplement.</p>\n\n<p>Here are a few tips:</p>\n\n<h1>Tip One</h1>\n\n<p>The best thing I have found is to use the \"diff3\" merge conflict style:</p>\n\n<p><code>git config merge.conflictstyle diff3</code></p>\n\n<p>This produces conflict markers like this:</p>\n\n<pre><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nChanges made on the branch that is being merged into. In most cases,\nthis is the branch that I have currently checked out (i.e. HEAD).\n|||||||\nThe common ancestor version.\n=======\nChanges made on the branch that is being merged in. This is often a \nfeature/topic branch.\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n</code></pre>\n\n<p>The middle section is what the common ancestor looked like. This is useful because you can compare it to the top and bottom versions to get a better sense of what was changed on each branch, which gives you a better idea for what the purpose of each change was.</p>\n\n<p>If the conflict is only a few lines, this generally makes the conflict very obvious. (Knowing how to fix a conflict is very different; you need to be aware of what other people are working on. If you're confused, it's probably best to just call that person into your room so they can see what you're looking at.)</p>\n\n<p>If the conflict is longer, then I will cut and paste each of the three sections into three separate files, such as \"mine\", \"common\" and \"theirs\".</p>\n\n<p>Then I can run the following commands to see the two diff hunks that caused the conflict:</p>\n\n<pre><code>diff common mine\ndiff common theirs\n</code></pre>\n\n<p>This is not the same as using a merge tool, since a merge tool will include all of the non-conflicting diff hunks too. I find that to be distracting.</p>\n\n<h1>Tip Two</h1>\n\n<p>Somebody already mentioned this, but understanding the intention behind each diff hunk is generally very helpful for understanding where a conflict came from and how to handle it.</p>\n\n<pre><code>git log --merge -p &lt;name of file&gt;\n</code></pre>\n\n<p>This shows all of the commits that touched that file in between the common ancestor and the two heads you are merging. (So it doesn't include commits that already exist in both branches before merging.) This helps you ignore diff hunks that clearly are not a factor in your current conflict.</p>\n\n<h1>Tip Three</h1>\n\n<p>Verify your changes with automated tools.</p>\n\n<p>If you have automated tests, run those. If you have a <a href=\"https://en.wikipedia.org/wiki/Lint_%28software%29\">lint</a>, run that. If it's a buildable project, then build it before you commit, etc. In all cases, you need to do a bit of testing to make sure your changes didn't break anything. (Heck, even a merge without conflicts can break working code.)</p>\n\n<h1>Tip Four</h1>\n\n<p>Plan ahead; communicate with co-workers.</p>\n\n<p>Planning ahead and being aware of what others are working on can help prevent merge conflicts and/or help resolve them earlier -- while the details are still fresh in mind. </p>\n\n<p>For example, if you know that you and another person are both working on different refactoring that will both affect the same set of files, you should talk to each other ahead of time and get a better sense for what types of changes each of you is making. You might save considerable time and effort if you conduct your planned changes serially rather than in parallel. </p>\n\n<p>For major refactorings that cut across a large swath of code, you should strongly consider working serially: everybody stops working on that area of the code while one person performs the complete refactoring.</p>\n\n<p>If you can't work serially (due to time pressure, maybe), then communicating about expected merge conflicts at least helps you solve the problems sooner while the details are still fresh in mind. For example, if a co-worker is making a disruptive series of commits over the course of a one-week period, you may choose to merge/rebase on that co-workers branch once or twice each day during that week. That way, if you do find merge/rebase conflicts, you can solve them more quickly than if you wait a few weeks to merge everything together in one big lump.</p>\n\n<h1>Tip Five</h1>\n\n<p>If you're unsure of a merge, don't force it.</p>\n\n<p>Merging can feel overwhelming, especially when there are a lot of conflicting files and the conflict markers cover hundreds of lines. Often times when estimating software projects we don't include enough time for overhead items like handling a gnarly merge, so it feels like a real drag to spend several hours dissecting each conflict.</p>\n\n<p>In the long run, planning ahead and being aware of what others are working on are the best tools for anticipating merge conflicts and prepare yourself to resolve them correctly in less time.</p>\n" }, { "answer_id": 15034682, "author": "eci", "author_id": 535192, "author_profile": "https://Stackoverflow.com/users/535192", "pm_score": 5, "selected": false, "text": "<p>For <a href=\"http://en.wikipedia.org/wiki/Emacs\" rel=\"noreferrer\">Emacs</a> users which want to resolve merge conflicts semi-manually:</p>\n\n<pre><code>git diff --name-status --diff-filter=U\n</code></pre>\n\n<p>shows all files which require conflict resolution.</p>\n\n<p>Open each of those files one by one, or all at once by:</p>\n\n<pre><code>emacs $(git diff --name-only --diff-filter=U)\n</code></pre>\n\n<p>When visiting a buffer requiring edits in Emacs, type</p>\n\n<pre><code>ALT+x vc-resolve-conflicts\n</code></pre>\n\n<p>This will open three buffers (mine, theirs, and the output buffer). Navigate by pressing 'n' (next region), 'p' (prevision region). Press 'a' and 'b' to copy mine or theirs region to the output buffer, respectively. And/or edit the output buffer directly.</p>\n\n<p>When finished: Press 'q'. Emacs asks you if you want to save this buffer: yes.\nAfter finishing a buffer mark it as resolved by running from the teriminal:</p>\n\n<pre><code>git add FILENAME\n</code></pre>\n\n<p>When finished with all buffers type</p>\n\n<pre><code>git commit\n</code></pre>\n\n<p>to finish the merge.</p>\n" }, { "answer_id": 16095649, "author": "Michael Durrant", "author_id": 631619, "author_profile": "https://Stackoverflow.com/users/631619", "pm_score": 5, "selected": false, "text": "<p>You could fix merge conflicts in a number of ways as other have detailed.</p>\n\n<p>I think the real key is knowing how changes flow with local and remote repositories. The key to this is understanding tracking branches. I have found that I think of the tracking branch as the 'missing piece in the middle' between me my local, actual files directory and the remote defined as origin. </p>\n\n<p>I've personally got into the habit of 2 things to help avoid this.</p>\n\n<p>Instead of:</p>\n\n<pre><code>git add .\ngit commit -m\"some msg\"\n</code></pre>\n\n<p>Which has two drawbacks - </p>\n\n<p>a) All new/changed files get added and that might include some unwanted changes.<br>\nb) You don't get to review the file list first.</p>\n\n<p>So instead I do:</p>\n\n<pre><code>git add file,file2,file3...\ngit commit # Then type the files in the editor and save-quit.\n</code></pre>\n\n<p>This way you are more deliberate about which files get added and you also get to review the list and think a bit more while using the editor for the message. I find it also improves my commit messages when I use a full screen editor rather than the <code>-m</code> option.</p>\n\n<p>[Update - as time has passed I've switched more to:</p>\n\n<pre><code>git status # Make sure I know whats going on\ngit add .\ngit commit # Then use the editor\n</code></pre>\n\n<p>]</p>\n\n<p>Also (and more relevant to your situation), I try to avoid:</p>\n\n<pre><code>git pull\n</code></pre>\n\n<p>or</p>\n\n<pre><code>git pull origin master.\n</code></pre>\n\n<p>because pull implies a merge and if you have changes locally that you didn't want merged you can easily end up with merged code and/or merge conflicts for code that shouldn't have been merged.</p>\n\n<p>Instead I try to do</p>\n\n<pre><code>git checkout master\ngit fetch \ngit rebase --hard origin/master # or whatever branch I want.\n</code></pre>\n\n<p>You may also find this helpful:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3329943/git-branch-fork-fetch-merge-rebase-and-clone-what-are-the-differences/9204499#9204499\">git branch, fork, fetch, merge, rebase and clone, what are the differences?</a></p>\n" }, { "answer_id": 17642404, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>See <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-merge.html#_how_conflicts_are_presented\" rel=\"noreferrer\">How Conflicts Are Presented</a> or, in Git, the <code>git merge</code> documentation to understand what merge conflict markers are.</p>\n<p>Also, the <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-merge.html#_how_to_resolve_conflicts\" rel=\"noreferrer\">How to Resolve Conflicts</a> section explains how to resolve the conflicts:</p>\n<blockquote>\n<p>After seeing a conflict, you can do two things:</p>\n<ul>\n<li><p>Decide not to merge. The only clean-ups you need are to reset the index file to the <code>HEAD</code> commit to reverse 2. and to clean up working tree changes made by 2. and 3.; <code>git merge --abort</code> can be used for this.</p>\n</li>\n<li><p>Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and <code>git add</code> them to the index. Use <code>git commit</code> to seal the deal.</p>\n</li>\n</ul>\n<p>You can work through the conflict with a number of tools:</p>\n<ul>\n<li><p>Use a mergetool. <code>git mergetool</code> to launch a graphical mergetool which will work you through the merge.</p>\n</li>\n<li><p>Look at the diffs. <code>git diff</code> will show a three-way diff, highlighting changes from both the <code>HEAD</code> and <code>MERGE_HEAD</code> versions.</p>\n</li>\n<li><p>Look at the diffs from each branch. <code>git log --merge -p &lt;path&gt;</code> will show diffs first for the <code>HEAD</code> version and then the <code>MERGE_HEAD</code> version.</p>\n</li>\n<li><p>Look at the originals. <code>git show :1:filename</code> shows the common ancestor, <code>git show :2:filename</code> shows the <code>HEAD</code> version, and <code>git show :3:filename</code> shows the <code>MERGE_HEAD</code> version.</p>\n</li>\n</ul>\n</blockquote>\n<p>You can also read about merge conflict markers and how to resolve them in the <a href=\"http://git-scm.com/book\" rel=\"noreferrer\">Pro Git</a> book section <a href=\"http://git-scm.com/book/ch3-2.html#Basic-Merge-Conflicts\" rel=\"noreferrer\">Basic Merge Conflicts</a>.</p>\n" }, { "answer_id": 21352966, "author": "iankit", "author_id": 1620792, "author_profile": "https://Stackoverflow.com/users/1620792", "pm_score": 5, "selected": false, "text": "<p>CoolAJ86's answer sums up pretty much everything. In case you have changes in both branches in the same piece of code you will have to do a manual merge. Open the file in conflict in any text editor and you should see following structure.</p>\n\n<pre><code>(Code not in Conflict)\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n(first alternative for conflict starts here)\nMultiple code lines here\n===========\n(second alternative for conflict starts here)\nMultiple code lines here too \n&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n(Code not in conflict here)\n</code></pre>\n\n<p>Choose one of the alternatives or a combination of both in a way that you want new code to be, while removing equal signs and angle brackets. </p>\n\n<pre><code>git commit -a -m \"commit message\"\ngit push origin master\n</code></pre>\n" }, { "answer_id": 24135969, "author": "trai bui", "author_id": 2285933, "author_profile": "https://Stackoverflow.com/users/2285933", "pm_score": -1, "selected": false, "text": "<p>If you do not use a tool to merge, first copy your code outside:</p>\n\n<pre><code>- `checkout master`\n- `git pull` / get new commit\n- `git checkout` to your branch\n- `git rebase master`\n</code></pre>\n\n<p>It resolve conflict and you can copy your code.</p>\n" }, { "answer_id": 25370867, "author": "Haimei", "author_id": 2730862, "author_profile": "https://Stackoverflow.com/users/2730862", "pm_score": 5, "selected": false, "text": "<p>If you want to merge from branch <code>test</code> to <code>master</code>, you can follow these steps:</p>\n<p><strong>Step 1</strong>: Go to the branch</p>\n<pre><code>git checkout test\n</code></pre>\n<p><strong>Step 2</strong>:</p>\n<pre><code>git pull --rebase origin master\n</code></pre>\n<p><strong>Step 3</strong>: If there are some conflicts, go to these files to modify it.</p>\n<p><strong>Step 4</strong>: Add these changes</p>\n<pre><code>git add #your_changes_files\n</code></pre>\n<p><strong>Step 5</strong>:</p>\n<pre><code>git rebase --continue\n</code></pre>\n<p><strong>Step 6</strong>: If there is still conflict, go back to step 3 again. If there is no conflict, do following:</p>\n<pre><code>git push origin +test\n</code></pre>\n<p><strong>Step 7</strong>: And then there is no conflict between test and master. You can use merge directly.</p>\n" }, { "answer_id": 27426207, "author": "Brian Di Palma", "author_id": 1927079, "author_profile": "https://Stackoverflow.com/users/1927079", "pm_score": 4, "selected": false, "text": "<pre><code>git log --merge -p [[--] path]\n</code></pre>\n\n<p>Does not seem to always work for me and usually ends up displaying every commit that was different between the two branches, this happens even when using <code>--</code> to separate the path from the command.</p>\n\n<p>What I do to work around this issue is open up two command lines and in one run</p>\n\n<pre><code>git log ..$MERGED_IN_BRANCH --pretty=full -p [path]\n</code></pre>\n\n<p>and in the other</p>\n\n<pre><code>git log $MERGED_IN_BRANCH.. --pretty=full -p [path]\n</code></pre>\n\n<p>Replacing <code>$MERGED_IN_BRANCH</code> with the branch I merged in and <code>[path]</code> with the file that is conflicting. This command will log all the commits, in patch form, between (<code>..</code>) two commits. If you leave one side empty like in the commands above git will automatically use <code>HEAD</code> (the branch you are merging into in this case).</p>\n\n<p>This will allow you to see what commits went into the file in the two branches after they diverged. It usually makes it much easier to solve conflicts.</p>\n" }, { "answer_id": 28469286, "author": "Chetan", "author_id": 2486083, "author_profile": "https://Stackoverflow.com/users/2486083", "pm_score": 4, "selected": false, "text": "<p>I always follow the below steps to avoid conflicts.</p>\n<ul>\n<li><code>git checkout master</code> (Come to the master branch)</li>\n<li><code>git pull</code> (Update your master to get the latest code)</li>\n<li><code>git checkout -b mybranch</code> (Check out a new a branch and start working on that branch so that your master always remains top of trunk.)</li>\n<li><code>git add .</code> <em>and</em> <code>git commit</code> <em>and</em> <em>git push</em> (on your local branch after your changes)</li>\n<li><code>git checkout master</code> (Come back to your master)</li>\n</ul>\n<p>Now you can do the same and maintain as many local branches you want and work simultaneous by just doing a <code>git checkout</code> to your branch whenever necessary.</p>\n" }, { "answer_id": 29667555, "author": "Chhabilal", "author_id": 2554162, "author_profile": "https://Stackoverflow.com/users/2554162", "pm_score": 5, "selected": false, "text": "<p>Please follow the following steps to fix merge conflicts in Git:</p>\n\n<ol>\n<li><p>Check the Git status:\n<strong><em>git status</em></strong></p></li>\n<li><p>Get the patchset:\n<strong><em>git fetch</em></strong> (checkout the right patch from your Git commit)</p></li>\n<li><p>Checkout a local branch (temp1 in my example here):\n<strong><em>git checkout -b temp1</em></strong></p></li>\n<li><p>Pull the recent contents from master:\n<strong><em>git pull --rebase origin master</em></strong></p></li>\n<li><p>Start the mergetool and check the conflicts and fix them...and check the changes in the remote branch with your current branch:\n<strong><em>git mergetool</em></strong></p></li>\n<li><p>Check the status again:\n <strong><em>git status</em></strong></p></li>\n<li><p>Delete the unwanted files locally created by mergetool, usually mergetool creates extra file with *.orig extension. Please delete that file as that is just the duplicate and fix changes locally and add the correct version of your files.\n<strong><em>git add #your_changed_correct_files</em></strong></p></li>\n<li><p>Check the status again:\n<strong><em>git status</em></strong></p></li>\n<li><p>Commit the changes to the same commit id (this avoids a new separate patch set):\n<strong><em>git commit --amend</em></strong></p></li>\n<li><p>Push to the master branch:\n<strong><em>git push</em></strong> (to your Git repository)</p></li>\n</ol>\n" }, { "answer_id": 31835412, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 7, "selected": false, "text": "<p>Merge conflicts happens when changes are made to a file at the same time. Here is how to solve it.</p>\n\n<h2><code>git</code> CLI</h2>\n\n<p>Here are simple steps what to do when you get into conflicted state:</p>\n\n<ol>\n<li>Note the list of conflicted files with: <code>git status</code> (under <code>Unmerged paths</code> section).</li>\n<li><p>Solve the conflicts separately for each file by one of the following approaches:</p>\n\n<ul>\n<li><p>Use GUI to solve the conflicts: <code>git mergetool</code> (the easiest way).</p></li>\n<li><p>To accept remote/other version, use: <code>git checkout --theirs path/file</code>. This will reject any local changes you did for that file.</p></li>\n<li><p>To accept local/our version, use: <code>git checkout --ours path/file</code></p>\n\n<p><sup>However you've to be careful, as remote changes that conflicts were done for some reason.</sup></p>\n\n<p>Related: <a href=\"https://stackoverflow.com/q/25576415/55075\">What is the precise meaning of &quot;ours&quot; and &quot;theirs&quot; in git?</a></p></li>\n<li><p>Edit the conflicted files manually and look for the code block between <code>&lt;&lt;&lt;&lt;&lt;</code>/<code>&gt;&gt;&gt;&gt;&gt;</code> then choose the version either from above or below <code>=====</code>. See: <a href=\"http://git-scm.com/docs/git-merge#_how_conflicts_are_presented\" rel=\"noreferrer\">How conflicts are presented</a>.</p></li>\n<li><p>Path and filename conflicts can be solved by <code>git add</code>/<code>git rm</code>.</p></li>\n</ul></li>\n<li><p>Finally, review the files ready for commit using: <code>git status</code>.</p>\n\n<p>If you still have any files under <code>Unmerged paths</code>, and you did solve the conflict manually, then let Git know that you solved it by: <code>git add path/file</code>.</p></li>\n<li><p>If all conflicts were solved successfully, commit the changes by: <code>git commit -a</code> and push to remote as usual.</p></li>\n</ol>\n\n<p>See also: <a href=\"https://help.github.com/articles/resolving-a-merge-conflict-from-the-command-line/\" rel=\"noreferrer\">Resolving a merge conflict from the command line</a> at GitHub</p>\n\n<p>For practical tutorial, check: <a href=\"https://www.katacoda.com/courses/git/5\" rel=\"noreferrer\">Scenario 5 - Fixing Merge Conflicts by Katacoda</a>.</p>\n\n<h2>DiffMerge</h2>\n\n<p>I've successfully used <a href=\"https://sourcegear.com/diffmerge/\" rel=\"noreferrer\">DiffMerge</a> which can visually compare and merge files on Windows, macOS and Linux/Unix.</p>\n\n<p>It graphically can show the changes between 3 files and it allows automatic merging (when safe to do so) and full control over editing the resulting file.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tAURE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tAURE.png\" alt=\"DiffMerge\"></a></p>\n\n<p><sup>Image source: <a href=\"https://sourcegear.com/diffmerge/\" rel=\"noreferrer\">DiffMerge</a> (Linux screenshot)</sup></p>\n\n<p>Simply download it and run in repo as:</p>\n\n<pre><code>git mergetool -t diffmerge .\n</code></pre>\n\n<hr>\n\n<h3>macOS</h3>\n\n<p>On macOS you can install via:</p>\n\n<pre><code>brew install caskroom/cask/brew-cask\nbrew cask install diffmerge\n</code></pre>\n\n<p>And probably (if not provided) you need the following extra simple wrapper placed in your PATH (e.g. <code>/usr/bin</code>):</p>\n\n<pre><code>#!/bin/sh\nDIFFMERGE_PATH=/Applications/DiffMerge.app\nDIFFMERGE_EXE=${DIFFMERGE_PATH}/Contents/MacOS/DiffMerge\nexec ${DIFFMERGE_EXE} --nosplash \"$@\"\n</code></pre>\n\n<p>Then you can use the following keyboard shortcuts:</p>\n\n<ul>\n<li><kbd>⌘</kbd>-<kbd>Alt</kbd>-<kbd>Up</kbd>/<kbd>Down</kbd> to jump to previous/next changes.</li>\n<li><kbd>⌘</kbd>-<kbd>Alt</kbd>-<kbd>Left</kbd>/<kbd>Right</kbd> to accept change from left or right</li>\n</ul>\n\n<p>Alternatively you can use <a href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/opendiff.1.html\" rel=\"noreferrer\">opendiff</a> (part of Xcode Tools) which lets you merge two files or directories together to create a third file or directory.</p>\n" }, { "answer_id": 34464046, "author": "Sazzad Hissain Khan", "author_id": 1084174, "author_profile": "https://Stackoverflow.com/users/1084174", "pm_score": 5, "selected": false, "text": "<h3>Bonus:</h3>\n<p>In speaking of pull/fetch/merge in the previous answers, I would like to share an interesting and productive trick,</p>\n<h1><strong><code>git pull --rebase</code></strong></h1>\n<p>This above command is the most useful command in my Git life which saved a lot of time.</p>\n<p>Before pushing your newly committed change to remote server, try <code>git pull --rebase</code> rather <code>git pull</code> and manual <code>merge</code> and it will automatically sync the latest remote server changes (with a fetch + merge) and will put your local latest commit at the top in the Git log. No need to worry about manual pull/merge.</p>\n<p>In case of a conflict, just use</p>\n<pre><code>git mergetool\ngit add conflict_file\ngit rebase --continue\n</code></pre>\n<p>Find details at: <em><a href=\"http://gitolite.com/git-pull--rebase\" rel=\"nofollow noreferrer\">What does “git pull –rebase” do?</a></em></p>\n" }, { "answer_id": 35020326, "author": "Mohamed Ali", "author_id": 4356754, "author_profile": "https://Stackoverflow.com/users/4356754", "pm_score": 5, "selected": false, "text": "<p>Simply, if you know well that changes in one of the repositories is not important, and want to resolve all changes in favor of the other one, use:</p>\n\n<pre><code>git checkout . --ours\n</code></pre>\n\n<p>to resolve changes in the favor of <strong>your repository</strong>, or</p>\n\n<pre><code>git checkout . --theirs\n</code></pre>\n\n<p>to resolve changes in favor of the <strong>other or the main repository</strong>.</p>\n\n<p>Or else you will have to use a GUI merge tool to step through files one by one, say the merge tool is <code>p4merge</code>, or write any one's name you've already installed</p>\n\n<pre><code>git mergetool -t p4merge\n</code></pre>\n\n<p>and after finishing a file, you will have to save and close, so the next one will open.</p>\n" }, { "answer_id": 37893577, "author": "akardon", "author_id": 3795379, "author_profile": "https://Stackoverflow.com/users/3795379", "pm_score": 4, "selected": false, "text": "<p>Merge conflicts could occur in different situations:</p>\n<ul>\n<li>When running <code>git fetch</code> and then <code>git merge</code></li>\n<li>When running <code>git fetch</code> and then <code>git rebase</code></li>\n<li>When running <code>git pull</code> (which is actually equal to one of the above-mentioned conditions)</li>\n<li>When running <code>git stash pop</code></li>\n<li>When you're applying git patches (commits that are exported to files to be transferred, for example, by email)</li>\n</ul>\n<p>You need to install a merge tool which is compatible with Git to resolve the conflicts. I personally use <a href=\"http://kdiff3.sourceforge.net/\" rel=\"nofollow noreferrer\">KDiff3</a>, and I've found it nice and handy. You can download its Windows version here:</p>\n<p><a href=\"https://sourceforge.net/projects/kdiff3/files/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/kdiff3/files/</a></p>\n<p>BTW, if you install Git Extensions there is an option in its setup wizard to install Kdiff3.</p>\n<p>Then setup the Git configuration to use KDiff3 as its mergetool:</p>\n<pre><code>$ git config --global --add merge.tool kdiff3\n$ git config --global --add mergetool.kdiff3.path &quot;C:/Program Files/KDiff3/kdiff3.exe&quot;\n$ git config --global --add mergetool.kdiff3.trustExitCode false\n\n$ git config --global --add diff.guitool kdiff3\n$ git config --global --add difftool.kdiff3.path &quot;C:/Program Files/KDiff3/kdiff3.exe&quot;\n$ git config --global --add difftool.kdiff3.trustExitCode false\n</code></pre>\n<p>(Remember to replace the path with the actual path of the KDiff3 EXE file.)</p>\n<p>Then every time you come across a merge conflict, you just need to run this command:</p>\n<pre><code>$ git mergetool\n</code></pre>\n<p>Then it opens Kdiff3, and first tries to resolve the merge conflicts automatically. Most of the conflicts would be resolved spontaneously and you need to fix the rest manually.</p>\n<p>Here's what Kdiff3 looks like:</p>\n<p><a href=\"https://i.stack.imgur.com/Xw3nw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xw3nw.png\" alt=\"Enter image description here\" /></a></p>\n<p>Then once you're done, save the file and it goes to the next file with a conflict and you do the same thing again until all the conflicts are resolved.</p>\n<p>To check if everything is merged successfully, just run the mergetool command again. You should get this result:</p>\n<pre><code>$ git mergetool\nNo files need merging\n</code></pre>\n" }, { "answer_id": 39771096, "author": "Noidea", "author_id": 6822575, "author_profile": "https://Stackoverflow.com/users/6822575", "pm_score": 6, "selected": false, "text": "<p>I either want my or their version in full, or want to review individual changes and decide for each of them.</p>\n\n<p><strong>Fully accept my or theirs version</strong>:</p>\n\n<p>Accept my version (local, ours):</p>\n\n<pre><code>git checkout --ours -- &lt;filename&gt;\ngit add &lt;filename&gt; # Marks conflict as resolved\ngit commit -m \"merged bla bla\" # An \"empty\" commit\n</code></pre>\n\n<p>Accept their version (remote, theirs):</p>\n\n<pre><code>git checkout --theirs -- &lt;filename&gt;\ngit add &lt;filename&gt;\ngit commit -m \"merged bla bla\"\n</code></pre>\n\n<p>If you want to do <strong>for all conflict files</strong> run:</p>\n\n<pre><code>git merge --strategy-option ours\n</code></pre>\n\n<p>or</p>\n\n<pre><code>git merge --strategy-option theirs\n</code></pre>\n\n<p><strong>Review all changes and accept them individually</strong></p>\n\n<ol>\n<li><code>git mergetool</code></li>\n<li>Review changes and accept either version for each of them.</li>\n<li><code>git add &lt;filename&gt;</code></li>\n<li><code>git commit -m \"merged bla bla\"</code></li>\n</ol>\n\n<p>Default <code>mergetool</code> works in <strong>command line</strong>. How to use a command line mergetool should be a separate question.</p>\n\n<p>You can also install <strong>visual tool</strong> for this, e.g. <code>meld</code> and run</p>\n\n<pre><code>git mergetool -t meld\n</code></pre>\n\n<p>It will open local version (ours), \"base\" or \"merged\" version (the current result of the merge) and remote version (theirs). Save the merged version when you are finished, run <code>git mergetool -t meld</code> again until you get \"No files need merging\", then go to Steps 3. and 4.</p>\n" }, { "answer_id": 40896972, "author": "Conchylicultor", "author_id": 4172685, "author_profile": "https://Stackoverflow.com/users/4172685", "pm_score": 4, "selected": false, "text": "<h3>Using <code>patience</code></h3>\n<p>For a big merge conflict, using <code>patience</code> provided good results for me. It will try to match blocks rather than individual lines.</p>\n<p>If you change the indentation of your program for instance, the default Git merge strategy sometimes matches single braces <code>{</code> which belongs to different functions. This is avoided with <code>patience</code>:</p>\n<pre><code>git merge -s recursive -X patience other-branch\n</code></pre>\n<p>From the documentation:</p>\n<pre><code>With this option, merge-recursive spends a little extra time to avoid \nmismerges that sometimes occur due to unimportant matching lines \n(e.g., braces from distinct functions). Use this when the branches to \nbe merged have diverged wildly.\n</code></pre>\n<h3>Comparison with the common ancestor</h3>\n<p>If you have a merge conflict and want to see what others had in mind when modifying their branch, it's sometimes easier to compare their branch directly with the common ancestor (instead of our branch). For that you can use <code>merge-base</code>:</p>\n<pre><code>git diff $(git merge-base &lt;our-branch&gt; &lt;their-branch&gt;) &lt;their-branch&gt;\n</code></pre>\n<p>Usually, you only want to see the changes for a particular file:</p>\n<pre><code>git diff $(git merge-base &lt;our-branch&gt; &lt;their-branch&gt;) &lt;their-branch&gt; &lt;file&gt;\n</code></pre>\n" }, { "answer_id": 41383833, "author": "yairchu", "author_id": 40916, "author_profile": "https://Stackoverflow.com/users/40916", "pm_score": 2, "selected": false, "text": "<p>A safer way to resolve conflicts is to use <a href=\"https://github.com/Peaker/git-mediate\" rel=\"nofollow noreferrer\">git-mediate</a> (the common solutions suggested here are quite error prone imho).</p>\n\n<p>See <a href=\"https://medium.com/@yairchu/how-git-mediate-made-me-stop-fearing-merge-conflicts-and-start-treating-them-like-an-easy-game-of-a2c71b919984\" rel=\"nofollow noreferrer\">this post</a> for a quick intro on how to use it.</p>\n" }, { "answer_id": 41555708, "author": "maxwell", "author_id": 3175905, "author_profile": "https://Stackoverflow.com/users/3175905", "pm_score": 4, "selected": false, "text": "<p>As of December 12th 2016, you can merge branches and <strong>resolve conflicts on github.com</strong></p>\n\n<p>Thus, if you don't want to use the command-line or <em>any 3rd party tools that are offered here from older answers</em>, go with GitHub's native tool.</p>\n\n<p><a href=\"https://github.com/blog/2293-resolve-simple-merge-conflicts-on-github\" rel=\"noreferrer\">This blog post</a> explains in detail, but the basics are that upon 'merging' two branches via the UI, you will now see a 'resolve conflicts' option that will take you to an editor allowing you to deal with these merge conflicts.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1YX5P.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1YX5P.gif\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 44724095, "author": "Qijun Liu", "author_id": 5771924, "author_profile": "https://Stackoverflow.com/users/5771924", "pm_score": 5, "selected": false, "text": "<p>There are three steps:</p>\n<ol>\n<li><p>Find which files cause conflicts by the command</p>\n<pre><code> git status\n</code></pre>\n</li>\n<li><p>Check the files, in which you would find the conflicts marked like</p>\n<pre><code> &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;head\n blablabla\n</code></pre>\n</li>\n<li><p>Change it to the way you want it, and then commit with the commands</p>\n<pre><code> git add solved_conflicts_files\n git commit -m 'merge msg'\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 44927577, "author": "Baini.Marouane", "author_id": 6204104, "author_profile": "https://Stackoverflow.com/users/6204104", "pm_score": 3, "selected": false, "text": "<pre><code>git fetch &lt;br&gt;\ngit checkout **your branch**&lt;br&gt;\ngit rebase master&lt;br&gt;\n</code></pre>\n<p>In this step you will try to fix the conflict using your preferred IDE.</p>\n<p>You can follow <a href=\"https://help.github.com/articles/resolving-a-merge-conflict-using-the-command-line/\" rel=\"nofollow noreferrer\">this link</a> to check how to fix the conflict in the file.</p>\n<pre><code>git add&lt;br&gt;\ngit rebase --continue&lt;br&gt;\ngit commit --amend&lt;br&gt;\ngit push origin HEAD:refs/drafts/master (push like a drafts)&lt;br&gt;\n</code></pre>\n<p>Now everything is fine and you will find your commit in <a href=\"https://en.wikipedia.org/wiki/Gerrit_(software)\" rel=\"nofollow noreferrer\">Gerrit</a>.</p>\n" }, { "answer_id": 45021055, "author": "Miguel", "author_id": 416255, "author_profile": "https://Stackoverflow.com/users/416255", "pm_score": 2, "selected": false, "text": "<p>For those who are using Visual Studio (<a href=\"https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2015\" rel=\"nofollow noreferrer\">Visual Studio 2015</a> in my case)</p>\n<ol>\n<li><p>Close your project in Visual Studio. Especially in big projects, Visual Studio tends to freak out when merging using the UI.</p>\n</li>\n<li><p>Do the merge in a command prompt.</p>\n<p>git checkout target_branch</p>\n<p>git merge source_branch</p>\n</li>\n<li><p>Then open the project in Visual Studio and go to Team Explorer → <em>Branch</em>. Now there is a message that says <em>Merge is pending</em> and conflicting files are listed right below the message.</p>\n</li>\n<li><p>Click the conflicting file and you will have the option to <em>Merge</em>, <em>Compare</em>, <em>Take Source</em>, and <em>Take Target</em>. The merge tool in Visual Studio is very easy to use.</p>\n</li>\n</ol>\n" }, { "answer_id": 45039920, "author": "AJC", "author_id": 6292652, "author_profile": "https://Stackoverflow.com/users/6292652", "pm_score": 2, "selected": false, "text": "<p>If you are using <a href=\"https://en.wikipedia.org/wiki/IntelliJ_IDEA\" rel=\"nofollow noreferrer\">IntelliJ IDEA</a> as the IDE, try to merge the parent to your branch by:</p>\n<pre><code>git checkout &lt;localbranch&gt;\ngit merge origin/&lt;remotebranch&gt;\n</code></pre>\n<p>It will show all conflicts like this:</p>\n<blockquote>\n<p>A_MBPro:test anu$ git merge origin/ Auto-merging\nsrc/test/java/com/.../TestClass.java CONFLICT\n(content): Merge conflict in\nsrc/test/java/com/.../TestClass.java</p>\n</blockquote>\n<p>Now note that the file TestClass.java is shown in red in IntelliJ IDEA.</p>\n<p>Also <code>git status</code> will show:</p>\n<pre><code>Unmerged paths:\n(use &quot;git add &lt;file&gt;...&quot; to mark resolution)\nboth modified: src/test/java/com/.../TestClass.java\n</code></pre>\n<p>Open the file in IntelliJ IDEA. It will have sections with</p>\n<pre><code> &lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD\n public void testMethod() {\n }\n =======\n public void testMethod() { ...\n }\n &gt;&gt;&gt;&gt;&gt;&gt;&gt; origin/&lt;remotebranch&gt;\n</code></pre>\n<p>where HEAD is changes on your local branch and origin/&lt;remotebranch&gt; is changes from the remote branch. Here keep the stuff that you need and remove the stuff you don't need. After that, the normal steps should do. That is</p>\n<pre><code> git add TestClass.java\n git commit -m &quot;commit message&quot;\n git push\n</code></pre>\n" }, { "answer_id": 46738478, "author": "Aniruddha Das", "author_id": 537647, "author_profile": "https://Stackoverflow.com/users/537647", "pm_score": 1, "selected": false, "text": "<p>I follow the below process.</p>\n<p>The process to fix a merge conflict:</p>\n<ol>\n<li><p>First, pull the latest from the destination branch to which you want to merge <code>git pull origin develop</code></p>\n</li>\n<li><p>As you get the latest from the destination, now resolve the conflict manually in an IDE by deleting those extra characters.</p>\n</li>\n<li><p>Do a <code>git add</code> to add these edited files to the Git queue so that it can be <code>commit</code> and <code>push</code> to the same branch you are working on.</p>\n</li>\n<li><p>As <code>git add</code> is done, do a <code>git commit</code> to commit the changes.</p>\n</li>\n<li><p>Now push the changes to your working branch by <code>git push origin HEAD</code></p>\n</li>\n</ol>\n<p>This is it and you will see it resolved in your pull request if you are using Bitbucket or GitHub.</p>\n" }, { "answer_id": 46763813, "author": "Vicente Bolea", "author_id": 2420872, "author_profile": "https://Stackoverflow.com/users/2420872", "pm_score": 3, "selected": false, "text": "<p>This answer is to add an alternative for those Vim users like me that prefers to do everything within the editor.</p>\n<hr />\n<h3>TL;DR</h3>\n<p><a href=\"https://i.stack.imgur.com/iW2iC.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iW2iC.gif\" alt=\"Enter image description here\" /></a></p>\n<hr />\n<p><em>Tpope</em> came up with this great plugin for Vim called <a href=\"https://github.com/tpope/vim-fugitive\" rel=\"nofollow noreferrer\">fugitive</a>. Once installed, you can run <code>:Gstatus</code> to check the files that have conflict and <code>:Gdiff</code> to open Git in a three-way merge.</p>\n<p>Once in the three-way merge, <em>fugitive</em> will let you get the changes of any of the branches you are merging in the following fashion:</p>\n<ul>\n<li><code>:diffget //2</code>, get changes from original (<em>HEAD</em>) branch:</li>\n<li><code>:diffget //3</code>, get changes from merging branch:</li>\n</ul>\n<p>Once you are finished merging the file, type <code>:Gwrite</code> in the merged buffer.</p>\n<p>Vimcasts released <a href=\"http://vimcasts.org/episodes/fugitive-vim-resolving-merge-conflicts-with-vimdiff/\" rel=\"nofollow noreferrer\">a great video</a> explaining these steps in detail.</p>\n" }, { "answer_id": 49314436, "author": "Kailash Bhalaki", "author_id": 8253389, "author_profile": "https://Stackoverflow.com/users/8253389", "pm_score": 2, "selected": false, "text": "<p>Try Visual Studio Code for editing if you aren't already.</p>\n<p>After you try merging (and land up in merge conflicts), Visual Studio Code automatically detects the merge conflicts.</p>\n<p>It can help you very well by showing the changes made to the original one and if you should accept <code>incoming</code> or</p>\n<p><code>current change</code> (meaning original one before merging)'.</p>\n<p>It helped me and it can work for you too!</p>\n<p>PS: It will work only if you've configured Git with with your code and Visual Studio Code.</p>\n" }, { "answer_id": 54055025, "author": "Ilyas karim", "author_id": 5247564, "author_profile": "https://Stackoverflow.com/users/5247564", "pm_score": 4, "selected": false, "text": "<h2>GitLens for Visual Studio Code</h2>\n<p>You can try <a href=\"https://github.com/eamodio/vscode-gitlens\" rel=\"nofollow noreferrer\">GitLens</a> for Visual Studio Code. The key features are:</p>\n<h3>3. Easily resolve conflicts</h3>\n<p>I already like this feature:</p>\n<p><a href=\"https://i.stack.imgur.com/4YBdY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4YBdY.png\" alt=\"Enter image description here\" /></a></p>\n<h3>2. Current Line Blame.</h3>\n<p><a href=\"https://i.stack.imgur.com/LuqoC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LuqoC.png\" alt=\"Enter image description here\" /></a></p>\n<h3>3. Gutter Blame</h3>\n<p><a href=\"https://i.stack.imgur.com/giS9K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/giS9K.png\" alt=\"Enter image description here\" /></a></p>\n<h3>4. Status Bar Blame</h3>\n<p><a href=\"https://i.stack.imgur.com/ZO7pm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZO7pm.png\" alt=\"Enter image description here\" /></a></p>\n<p>And there are many features. You can check them <a href=\"https://github.com/eamodio/vscode-gitlens\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 58196522, "author": "Ammar Mujeeb", "author_id": 1586606, "author_profile": "https://Stackoverflow.com/users/1586606", "pm_score": 3, "selected": false, "text": "<p>I am using Microsoft's Visual Studio Code for resolving conflicts. It's very simple to use. I keep my project open in the workspace. It detects and highlights conflicts. Moreover, it gives GUI options to select whatever change I want to keep from HEAD or incoming.</p>\n<p><a href=\"https://i.stack.imgur.com/RXgnQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RXgnQ.png\" alt=\"Enter image description here\" /></a></p>\n" }, { "answer_id": 62220397, "author": "Friedrich", "author_id": 11769765, "author_profile": "https://Stackoverflow.com/users/11769765", "pm_score": -1, "selected": false, "text": "<p>If you simply want to restore the remote master, then</p>\n\n<pre><code>git reset --hard origin/master\n</code></pre>\n\n<p><strong>WARNING</strong>: All local changes will be lost,\nsee <a href=\"https://stackoverflow.com/a/8476004/11769765\">https://stackoverflow.com/a/8476004/11769765</a>.</p>\n" }, { "answer_id": 63048815, "author": "Allan F", "author_id": 5315581, "author_profile": "https://Stackoverflow.com/users/5315581", "pm_score": 0, "selected": false, "text": "<p>I like using <a href=\"https://en.wikipedia.org/wiki/WinMerge\" rel=\"nofollow noreferrer\">WinMerge</a> (free tool) that does both full entire directory tree comparison/merge and also individual file(s) comparison/merge of the full directory tree compare.</p>\n<p>The Git merge conflict is telling you that your pull request will undo/lose/overwrite a coworker's changes, typically because your copy of the content wasn't recent enough.</p>\n<p>Steps to resolve can be:</p>\n<ul>\n<li>Take another new clone of the source to a newly named folder,</li>\n<li>Use WinMerge to compare your content and the most recent content to understand the conflict,</li>\n<li>For the file(s) changed by both yourself and your coworker that are causing the Git Merge conflict, look at the lines that your co-worker has added/changed/deleted as per compared to the code lines that you have added/changed/deleted.</li>\n<li>Use the WinMerge left / right code section move arrows to ensure your coworker's work is in your copy of the file and you aren't clobbering their work.</li>\n</ul>\n<p>I.e., no magic way to resolve Git merge conflicts other than manually looking at what each person has done to the same source file(s).</p>\n<p>That is what I'm thinking.</p>\n<p>Note: WinMerge creates .bak files .. and you don't want them copied to source control AzOps, TFS, etc., so if you are sure you have done the edit correctly, remove the .bak files.</p>\n" }, { "answer_id": 63326192, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well, all the answers already given seem to explain which tools you can use to detect merge conflicts or how to initiate a merge request...</p>\n<p>The answer to your question however is both simple and frustrating. Merge conflicts are almost always to solve by hand manually. If you use a tool like e.g. GitLab, the GUI might help you to find differences in two code versions, but at the end of the day, you have to decide which line should be kept and which should be erased.</p>\n<p>A simple example: Programmer A and programmer B both push the same - differently modified - file to a remote repository. Programmer A opens a merge request and GitLab highlights several lines of code where conflicts occur between the two versions. Now it is up to Programmer A and B to decide, who wrote better code in these specific lines. They have to make compromises.</p>\n" }, { "answer_id": 66118061, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 4, "selected": false, "text": "<p>I understood what a merge conflict was, but when I saw the output of <code>git diff</code>, it looked like nonsense to me at first:</p>\n<pre><code>git diff\n++&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD\n + display full last name boolean in star table\n++=======\n+ users viewer.id/star.id, and conversation uses user.id\n+\n++&gt;&gt;&gt;&gt;&gt;&gt;&gt; feat/rspec-tests-for-cancancan\n</code></pre>\n<p>But <a href=\"https://www.youtube.com/watch?v=JtIX3HJKwfo#t=3m45s\" rel=\"noreferrer\">here</a> is what helped me:</p>\n<ul>\n<li><p><strong>Everything between <code>&lt;&lt;&lt;&lt;&lt;&lt;&lt;</code> and <code>=======</code> is what was in one file</strong>, and</p>\n</li>\n<li><p><strong>Everything between <code>=======</code> and <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;</code> is what was in the other file</strong></p>\n</li>\n<li><p>So literally all you have to do is open the file with the merge conflicts and remove those lines from either branch (or just make them the same), and the <code>merge</code> will immediately succeed. Problem solved!</p>\n</li>\n</ul>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
How do I resolve merge conflicts in my Git repository?
Try: ```bash git mergetool ``` It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly. --- As per [Josh Glover's comment](https://stackoverflow.com/questions/161813/how-to-resolve-merge-conflicts-in-git-repository#comment6881558_163659): > > [This command] > doesn't necessarily open a GUI unless you install one. Running `git mergetool` for me resulted in `vimdiff` being used. You can install > one of the following tools to use it instead: `meld`, `opendiff`, > `kdiff3`, `tkdiff`, `xxdiff`, `tortoisemerge`, `gvimdiff`, `diffuse`, > `ecmerge`, `p4merge`, `araxis`, `vimdiff`, `emerge`. > > > --- Below is a sample procedure using `vimdiff` to resolve merge conflicts, based on [this link](http://www.rosipov.com/blog/use-vimdiff-as-git-mergetool/#fromHistor). 1. Run the following commands in your terminal ```bash git config merge.tool vimdiff git config merge.conflictstyle diff3 git config mergetool.prompt false ``` This will set `vimdiff` as the default merge tool. 2. Run the following command in your terminal ```bash git mergetool ``` 3. You will see a `vimdiff` display in the following format: ```none ╔═══════╦══════╦════════╗ ║ ║ ║ ║ ║ LOCAL ║ BASE ║ REMOTE ║ ║ ║ ║ ║ ╠═══════╩══════╩════════╣ ║ ║ ║ MERGED ║ ║ ║ ╚═══════════════════════╝ ``` These 4 views are * **LOCAL:** this is the file from the current branch * **BASE:** the common ancestor, how this file looked before both changes * **REMOTE:** the file you are merging into your branch * **MERGED:** the merge result; this is what gets saved in the merge commit and used in the futureYou can navigate among these views using `ctrl`+`w`. You can directly reach the MERGED view using `ctrl`+`w` followed by `j`. More information about `vimdiff` navigation is [here](https://stackoverflow.com/questions/4556184/vim-move-window-left-right) and [here](https://stackoverflow.com/questions/27151456/how-do-i-jump-to-the-next-prev-diff-in-git-difftool). 4. You can edit the MERGED view like this: * If you want to get changes from REMOTE ``` :diffg RE ``` * If you want to get changes from BASE ``` :diffg BA ``` * If you want to get changes from LOCAL ``` :diffg LO ``` 5. Save, Exit, Commit, and Clean up `:wqa` save and exit from vi `git commit -m "message"` `git clean` Remove extra files (e.g. `*.orig`). **Warning:** It will remove all untracked files, if you won't pass any arguments.
161,819
<p>What are the main/best Maven repositories to use that will include the majority of your open source Java package dependencies.</p> <p>Also in what order should these be included? Does it matter?</p>
[ { "answer_id": 161846, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": false, "text": "<p>This is the current setup in the project we are building:</p>\n\n<ul>\n<li>MavenCentral</li>\n<li>ObjectWeb</li>\n<li>JBoss Maven2</li>\n<li><p>and some snapshots (see below)</p>\n\n<pre><code>&lt;repository&gt;\n &lt;id&gt;MavenCentral&lt;/id&gt;\n &lt;name&gt;Maven repository&lt;/name&gt;\n &lt;url&gt;http://repo1.maven.org/maven2&lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;objectweb&lt;/id&gt;\n &lt;name&gt;Objectweb repository&lt;/name&gt;\n &lt;url&gt;http://maven.objectweb.org/maven2&lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;jboss&lt;/id&gt;\n &lt;name&gt;JBoss Maven2 repository&lt;/name&gt;\n &lt;url&gt;http://repository.jboss.com/maven2/&lt;/url&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;glassfish&lt;/id&gt;\n &lt;name&gt;Glassfish repository&lt;/name&gt;\n &lt;url&gt;http://download.java.net/maven/1&lt;/url&gt;\n &lt;layout&gt;legacy&lt;/layout&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;apache.snapshots&lt;/id&gt;\n &lt;name&gt;Apache Snapshot Repository&lt;/name&gt;\n &lt;url&gt;\n http://people.apache.org/repo/m2-snapshot-repository\n &lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/snapshots&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;ops4j.repository&lt;/id&gt;\n &lt;name&gt;OPS4J Repository&lt;/name&gt;\n &lt;url&gt;http://repository.ops4j.org/maven2&lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n&lt;/repository&gt;\n&lt;repository&gt;\n &lt;id&gt;Codehaus Snapshots&lt;/id&gt;\n &lt;url&gt;http://snapshots.repository.codehaus.org/&lt;/url&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/snapshots&gt;\n &lt;releases&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/releases&gt;\n&lt;/repository&gt;\n</code></pre></li>\n</ul>\n" }, { "answer_id": 163034, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "<p>I would suggest using a Maven proxy like Archiva, Artifactory or Nexus and defining your repo list on the server side. The order matters only to the extent that the proxy server tries the proxied repos one by one and specifying a fringe repository as first will slow down the resolution of uncached artifacts (Artifactory allows you to specify whitelist and blacklist expressions for each proxied repo, which solves this problem)</p>\n\n<p>Overall using your own repo gives you more control and reliable builds ('central' is often painfully slow). It also gives you a place to put your own artifacts and any non-free 3rd party artifacts. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17719/" ]
What are the main/best Maven repositories to use that will include the majority of your open source Java package dependencies. Also in what order should these be included? Does it matter?
This is the current setup in the project we are building: * MavenCentral * ObjectWeb * JBoss Maven2 * and some snapshots (see below) ``` <repository> <id>MavenCentral</id> <name>Maven repository</name> <url>http://repo1.maven.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>objectweb</id> <name>Objectweb repository</name> <url>http://maven.objectweb.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>jboss</id> <name>JBoss Maven2 repository</name> <url>http://repository.jboss.com/maven2/</url> <snapshots> <enabled>false</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </repository> <repository> <id>glassfish</id> <name>Glassfish repository</name> <url>http://download.java.net/maven/1</url> <layout>legacy</layout> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>apache.snapshots</id> <name>Apache Snapshot Repository</name> <url> http://people.apache.org/repo/m2-snapshot-repository </url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>ops4j.repository</id> <name>OPS4J Repository</name> <url>http://repository.ops4j.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>Codehaus Snapshots</id> <url>http://snapshots.repository.codehaus.org/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </repository> ```
161,822
<p>I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there.</p> <p>Ideally I would like the methods to 'look' similar; one solution could be to define them as </p> <pre><code>public Point CalculatePoint(... out Boolean boSuccess); public List&lt;Point&gt; CalculateListOfPoints(... out Boolean boSuccess); </code></pre> <p>or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.</p> <p>Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...</p> <p>What is best practice? </p> <p>Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.</p>
[ { "answer_id": 161827, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>I would say best practice is a return value means success, and an <a href=\"http://www.c-sharpcorner.com/UploadFile/rajeshvs/ExceptionHandlinginCSharp11282005051444AM/ExceptionHandlinginCSharp.aspx\" rel=\"nofollow noreferrer\">exception</a> means failure. </p>\n\n<p>I see no reason in the examples you provided that you shouldn't be using <a href=\"http://www.c-sharpcorner.com/UploadFile/rajeshvs/ExceptionHandlinginCSharp11282005051444AM/ExceptionHandlinginCSharp.aspx\" rel=\"nofollow noreferrer\">exceptions</a> in the event of a failure.</p>\n" }, { "answer_id": 161834, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 6, "selected": true, "text": "<p>Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not</p>\n\n<p><code>public bool CalculatePoint(... out Point result);</code></p>\n\n<p>I am not a fan of using exception for \"normal\" behaviors (if you expect the function not to work for some entries).</p>\n" }, { "answer_id": 161835, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": false, "text": "<p>Another alternative is to throw an exception. However, you generally only want to throw exceptions in \"exceptional cases\".</p>\n\n<p>If the failure cases are common (and not exceptional), then you've already listed out your two options. <strong>EDIT</strong>: There may be a convention in your project as how to handle such non-exceptional cases (whether one should return success or the object). If there is no existing convention, then I agree with lucasbfr and suggest you return success (which agrees with how TryParse(...) is designed).</p>\n" }, { "answer_id": 161840, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 0, "selected": false, "text": "<p>Using an exception is a bad idea in some cases (especially when writing a server). You would need two flavors of the method. Also look at the dictionary class for an indication of what you should do.</p>\n\n<pre><code>// NB: A bool is the return value. \n// This makes it possible to put this beast in if statements.\npublic bool TryCalculatePoint(... out Point result) { }\n\npublic Point CalculatePoint(...)\n{\n Point result;\n if(!TryCalculatePoint(... out result))\n throw new BogusPointException();\n return result;\n}\n</code></pre>\n\n<p>Best of both worlds!</p>\n" }, { "answer_id": 161844, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 0, "selected": false, "text": "<p>The bool TrySomething() is at least a practice, which works ok for .net's parse methods, but I don't think I like it in general.</p>\n\n<p>Throwing an exception is often a good thing, though it should not be used for situations you would expect to happen in many normal situations, and it has an associated performance cost.</p>\n\n<p>Returning null when possible is in most cases ok, when you don't want an exception. </p>\n\n<p><strong><em>However</em></strong> - your approach is a bit procedural - what about creating something like a PointCalculator class - taking the required data as parameters in the constructor? Then you call CalculatePoint on it, and access the result through properties (separate properties for Point and for Success).</p>\n" }, { "answer_id": 161849, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 1, "selected": false, "text": "<p>The model I've used is the same one MS uses with the TryParse methods of various classes.</p>\n\n<p>Your original code:<br>\npublic Point CalculatePoint(... out Boolean boSuccess);<br>\npublic List CalculateListOfPoints(... out Boolean boSuccess); </p>\n\n<p>Would turn into \npublic bool CalculatePoint(... out (or ref) Point CalculatedValue);<br>\npublic bool CalculateListOfPoints(... out (or ref) List CalculatedValues); </p>\n\n<p>Basically you make the success/failure the return value.</p>\n" }, { "answer_id": 161853, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>You don't want to be throwing exceptions when there is something expected happening, as @Kevin stated exceptions are for exceptional cases.</p>\n\n<p>You should return something that is expected for the 'failure', generally null is my choice of bad return.</p>\n\n<p>The documentation for your method should inform the users of what to expect when the data <em>does not compute</em>.</p>\n" }, { "answer_id": 161865, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 1, "selected": false, "text": "<p>To summarise there are a couple of approaches you can take:</p>\n\n<ol>\n<li>When the return type is a value-type, like Point, use the Nullable feature of C# and return a Point? (aka Nullable), that way you can still return null on a failure</li>\n<li>Throw an exception when there's a failure. The whole argument/discussion regarding what is and isn't \"exceptional\" is a moot point, it's your API, you decide what's exceptional behaviour.</li>\n<li>Adopt a model similar to that implemented by Microsoft in the base types like Int32, provide a CalculatePoint and TryCalculatePoint (int32.Parse and int32.TryParse) and have one throw and one return a bool.</li>\n<li>Return a generic struct from your methods that has two properties, bool Success and GenericType Value.</li>\n</ol>\n\n<p>Dependent on the scenario I tend to use a combination of returning null or throwing an exception as they seem \"cleanest\" to me and fit best with the existing codebase at the company I work for. So my personal best practice would be approaches 1 and 2.</p>\n" }, { "answer_id": 161867, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "<p>It mostly depends on the behavior of your methods and their usage.</p>\n\n<p>If failure is common and non-critical, then have your methods return a boolean indicating their success and use an out parameter to convey the result. Looking up a key in a hash, attempting to read data on a non-blocking socket when no data is available, all these examples fall in that category.</p>\n\n<p>If failure is unexpected, return directly the result and convey errors with exceptions. Opening a file read-only, connecting to a TCP server, are good candidates.</p>\n\n<p>And sometimes both ways make sense...</p>\n" }, { "answer_id": 161871, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Why would they fail? If it's because of something the caller has done (i.e. the arguments provided) then throwing ArgumentException is entirely appropriate. A Try[...] method which avoids the exception is fine.</p>\n\n<p>I think it's a good idea to provide the version which throws an exception though, so that callers who expect that they will always provide good data will receive a suitably strong message (i.e. an exception) if they're ever wrong.</p>\n" }, { "answer_id": 161876, "author": "Kepboy", "author_id": 21429, "author_profile": "https://Stackoverflow.com/users/21429", "pm_score": 2, "selected": false, "text": "<p>If the failure is for a specific reason then I think its ok to return null, or bool and have an out parameter. If however you return null regardless of the failure then I don't recommend it. Exceptions provide a rich set of information including the reason WHY something failed, if all you get back is a null then how do you know if its because the data is wrong, you've ran out of memory or some other weird behavior.</p>\n\n<p>Even in .net the TryParse has a Parse brother so that you can get the exception if you want to.</p>\n\n<p>If I provided a TrySomething method I would also provide a Something method that threw an exception in the event of failure. Then it's up to the caller.</p>\n" }, { "answer_id": 161919, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<p>We once wrote an entire Framework where all the public methods either returned true (executed successfully) or false (an error occurred). If we needed to return a value we used output parameters. Contrary to popular belief, this way of programming actually simplified a lot of our code.</p>\n" }, { "answer_id": 162023, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 0, "selected": false, "text": "<p>Well with Point, you can send back Point.Empty as a return value in case of failure. Now all this really does is return a point with 0 for the X and Y value, so if that can be a valid return value, I'd stay away from that, but if your method will never return a (0,0) point, then you can use that.</p>\n" }, { "answer_id": 162151, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 1, "selected": false, "text": "<p>Return <strong>Point.Empty</strong>. It's a .NET design patter to return a special field when you want to check if structure creation was successful. Avoid <em>out</em> parameters when you can.</p>\n\n<pre><code>public static readonly Point Empty\n</code></pre>\n" }, { "answer_id": 162237, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 1, "selected": false, "text": "<p>A pattern that I'm experimenting with is returning a <em>Maybe</em>. It has the semantics of the <em>TryParse</em> pattern, but a similar signature to the null-return-on-error pattern.</p>\n\n<p>I'm not yet convinced one way or the other, but I offer it for your collective consideration. It does have the benefit of not requiring a variable to defined before the method call to hold the out parameter at the call site of the method. It could also be extended with an <em>Errors</em> or <em>Messages</em> collection to indicate the reason for the failure.</p>\n\n<p>The Maybe class looks something like this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Represents the return value from an operation that might fail\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\npublic struct Maybe&lt;T&gt;\n{\n T _value;\n bool _hasValue;\n\n\n public Maybe(T value)\n {\n _value = value;\n _hasValue = true;\n }\n\n public Maybe()\n {\n _hasValue = false;\n _value = default(T);\n }\n\n\n public bool Success\n {\n get { return _hasValue; }\n }\n\n\n public T Value\n {\n get \n { // could throw an exception if _hasValue is false\n return _value; \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 182148, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 0, "selected": false, "text": "<p>Sorry, I just remembered the Nullable type, you should look at that. I am not too sure what the overhead is though.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ]
I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there. Ideally I would like the methods to 'look' similar; one solution could be to define them as ``` public Point CalculatePoint(... out Boolean boSuccess); public List<Point> CalculateListOfPoints(... out Boolean boSuccess); ``` or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive. Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something... What is best practice? Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.
Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not `public bool CalculatePoint(... out Point result);` I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).
161,828
<p>I need to control the data type when reading XML data in SAS. The XML data are written and accessed using the XML libname engine in SAS.</p> <p>SAS seems to guess the data type based on the contents of a column: If I write "20081002" to my XML data in a character column, it will be read back in as a numerical variable.</p> <p>An example:</p> <pre><code>filename my_xml '/tmp/my.xml'; * Yes, I use SAS on Unix *; libname my_xml XML; data my_xml.data_type_test; text_char="This is obviously text"; date_char="20081002"; num_char="42"; genuine_num=42; run; proc copy inlib=my_xml outlib=WORK; run; libname my_xml; filename my_xml CLEAR; </code></pre> <p>Only the last column is defined as numerical data type in the XML data, but when I copy it into my WORK library, only the column <em>text_char</em> is character. The other 3 are now numeric.</p> <p>How can I control the data type when reading XML data in SAS?</p>
[ { "answer_id": 162067, "author": "jilles de wit", "author_id": 7531, "author_profile": "https://Stackoverflow.com/users/7531", "pm_score": 1, "selected": false, "text": "<p>I think you need to define some xml specific options whith your libname XML statement for export go:</p>\n\n<pre><code>libname my_xml_out XML XMLMETA=SCHEMADATA;\n</code></pre>\n\n<p>To include the data schema. Also, you might want to save the XML schema to a separate file for later import:</p>\n\n<pre><code>libname my_xml_in XML XMLSCHEMA='external-file'\n</code></pre>\n\n<p>after you exported the schema using <code>XMLMETA=SCHEMA</code> of course.\nI think <a href=\"http://support.sas.com/documentation/cdl/en/engxml/59528/HTML/default/a002484784.htm#a002994559\" rel=\"nofollow noreferrer\">this is the documentation you need</a>.</p>\n\n<p>Apart from that liberal use of format statements on original dataset creation is recommended.</p>\n" }, { "answer_id": 536786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Take a look at the SAS XML Mapper.\nIt allows you to create a map to read (and wrte in 9.2) XML files and specifying column attributes.</p>\n\n<p>If this is your XML file:</p>\n\n\n\n \n This is obviously text \n 20081002 \n 42 \n 42 \n \n\n\n\nYou could create a MAP like this:\n\n\n\n<p></p>\n\n<pre><code>&lt;!-- ############################################################ --&gt;\n&lt;TABLE name=\"DATA_TYPE_TEST\"&gt;\n &lt;TABLE-PATH syntax=\"XPath\"&gt;/TABLE/DATA_TYPE_TEST&lt;/TABLE-PATH&gt;\n\n &lt;COLUMN name=\"text_char\"&gt;\n &lt;PATH syntax=\"XPath\"&gt;/TABLE/DATA_TYPE_TEST/text_char&lt;/PATH&gt;\n &lt;TYPE&gt;character&lt;/TYPE&gt;\n &lt;DATATYPE&gt;string&lt;/DATATYPE&gt;\n &lt;LENGTH&gt;22&lt;/LENGTH&gt;\n &lt;/COLUMN&gt;\n\n &lt;COLUMN name=\"date_char\"&gt;\n &lt;PATH syntax=\"XPath\"&gt;/TABLE/DATA_TYPE_TEST/date_char&lt;/PATH&gt;\n &lt;TYPE&gt;numeric&lt;/TYPE&gt;\n &lt;DATATYPE&gt;integer&lt;/DATATYPE&gt;\n &lt;FORMAT width=\"9\"&gt;DATE&lt;/FORMAT&gt;\n &lt;INFORMAT width=\"8\"&gt;ND8601DA&lt;/INFORMAT&gt;\n &lt;/COLUMN&gt;\n\n &lt;COLUMN name=\"num_char\"&gt;\n &lt;PATH syntax=\"XPath\"&gt;/TABLE/DATA_TYPE_TEST/num_char&lt;/PATH&gt;\n &lt;TYPE&gt;character&lt;/TYPE&gt;\n &lt;DATATYPE&gt;string&lt;/DATATYPE&gt;\n &lt;LENGTH&gt;2&lt;/LENGTH&gt;\n &lt;/COLUMN&gt;\n\n &lt;COLUMN name=\"genuine_num\"&gt;\n &lt;PATH syntax=\"XPath\"&gt;/TABLE/DATA_TYPE_TEST/genuine_num&lt;/PATH&gt;\n &lt;TYPE&gt;numeric&lt;/TYPE&gt;\n &lt;DATATYPE&gt;integer&lt;/DATATYPE&gt;\n &lt;/COLUMN&gt;\n\n&lt;/TABLE&gt;\n</code></pre>\n\n<p></p>\n\n<p>And then read the XML file:</p>\n\n<pre><code>filename my 'C:\\temp\\my.xml';\nfilename SXLEMAP 'C:\\temp\\MyMap.map';\nlibname my xml xmlmap=SXLEMAP access=READONLY;\n\ntitle 'Table DATA_TYPE_TEST';\nproc contents data=my.DATA_TYPE_TEST varnum; \nrun;\nproc print data=my.DATA_TYPE_TEST(obs=10); \nrun;\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Table DATA_TYPE_TEST\n\nThe CONTENTS Procedure\n\nData Set Name MY.DATA_TYPE_TEST Observations \nMember Type DATA Variables 4 \nEngine XML Indexes 0 \nCreated . Observation Length 0 \nLast Modified . Deleted Observations 0 \nProtection Compressed NO\nData Set Type Sorted NO\nLabel \nData Representation Default \nEncoding Default \n\n\nVariables in Creation Order\n\n# Variable Type Len Format Informat Label\n\n1 text_char Char 22 $22. $22. text_char \n2 date_char Num 8 DATE9. ND8601DA8. date_char \n3 num_char Char 2 $2. $2. num_char \n4 genuine_num Num 8 F8. F8. genuine_num\n\nTable DATA_TYPE_TEST\n\n genuine_\n Obs text_char date_char num_char num\n\n 1 This is obviously text 02OCT2008 42 42\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18968/" ]
I need to control the data type when reading XML data in SAS. The XML data are written and accessed using the XML libname engine in SAS. SAS seems to guess the data type based on the contents of a column: If I write "20081002" to my XML data in a character column, it will be read back in as a numerical variable. An example: ``` filename my_xml '/tmp/my.xml'; * Yes, I use SAS on Unix *; libname my_xml XML; data my_xml.data_type_test; text_char="This is obviously text"; date_char="20081002"; num_char="42"; genuine_num=42; run; proc copy inlib=my_xml outlib=WORK; run; libname my_xml; filename my_xml CLEAR; ``` Only the last column is defined as numerical data type in the XML data, but when I copy it into my WORK library, only the column *text\_char* is character. The other 3 are now numeric. How can I control the data type when reading XML data in SAS?
Take a look at the SAS XML Mapper. It allows you to create a map to read (and wrte in 9.2) XML files and specifying column attributes. If this is your XML file: This is obviously text 20081002 42 42 You could create a MAP like this: ``` <!-- ############################################################ --> <TABLE name="DATA_TYPE_TEST"> <TABLE-PATH syntax="XPath">/TABLE/DATA_TYPE_TEST</TABLE-PATH> <COLUMN name="text_char"> <PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/text_char</PATH> <TYPE>character</TYPE> <DATATYPE>string</DATATYPE> <LENGTH>22</LENGTH> </COLUMN> <COLUMN name="date_char"> <PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/date_char</PATH> <TYPE>numeric</TYPE> <DATATYPE>integer</DATATYPE> <FORMAT width="9">DATE</FORMAT> <INFORMAT width="8">ND8601DA</INFORMAT> </COLUMN> <COLUMN name="num_char"> <PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/num_char</PATH> <TYPE>character</TYPE> <DATATYPE>string</DATATYPE> <LENGTH>2</LENGTH> </COLUMN> <COLUMN name="genuine_num"> <PATH syntax="XPath">/TABLE/DATA_TYPE_TEST/genuine_num</PATH> <TYPE>numeric</TYPE> <DATATYPE>integer</DATATYPE> </COLUMN> </TABLE> ``` And then read the XML file: ``` filename my 'C:\temp\my.xml'; filename SXLEMAP 'C:\temp\MyMap.map'; libname my xml xmlmap=SXLEMAP access=READONLY; title 'Table DATA_TYPE_TEST'; proc contents data=my.DATA_TYPE_TEST varnum; run; proc print data=my.DATA_TYPE_TEST(obs=10); run; ``` Result: ``` Table DATA_TYPE_TEST The CONTENTS Procedure Data Set Name MY.DATA_TYPE_TEST Observations Member Type DATA Variables 4 Engine XML Indexes 0 Created . Observation Length 0 Last Modified . Deleted Observations 0 Protection Compressed NO Data Set Type Sorted NO Label Data Representation Default Encoding Default Variables in Creation Order # Variable Type Len Format Informat Label 1 text_char Char 22 $22. $22. text_char 2 date_char Num 8 DATE9. ND8601DA8. date_char 3 num_char Char 2 $2. $2. num_char 4 genuine_num Num 8 F8. F8. genuine_num Table DATA_TYPE_TEST genuine_ Obs text_char date_char num_char num 1 This is obviously text 02OCT2008 42 42 ```
161,838
<p>Is it possible to unlisten on a socket after you have called listen(fd, backlog)? </p> <p>Edit: My mistake for not making myself clear. I'd like to be able to temporarily unlisten on the socket. Calling close() will leave the socket in the M2LS state and prevent me from reopening it (or worse, some nefarious program could bind to that socket)</p> <p>Temporarily unlistening would be a way (maybe not the best way) to signal to an upstream load balancer that this app couldn't accept any more requests for the moment</p>
[ { "answer_id": 161841, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "<p>Close it. As I recall;</p>\n\n<pre><code>close(fd);\n</code></pre>\n" }, { "answer_id": 161896, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 1, "selected": false, "text": "<p>There is no explicit method to unlisten!</p>\n\n<p>You can either <code>close(fd)</code> or <code>shutdown(fd, how)</code></p>\n\n<pre><code>fd is the socket file descriptor you want to shutdown, and how is one of the following:\n\n0 Further receives are disallowed\n\n1 Further sends are disallowed\n\n2 Further sends and receives are disallowed (like close())\n</code></pre>\n" }, { "answer_id": 161924, "author": "gx.", "author_id": 21580, "author_profile": "https://Stackoverflow.com/users/21580", "pm_score": 3, "selected": false, "text": "<p>After closing the socket, your programs may still tell you that the socket is \"in use\", this is because of some weirdiness I don't know exactly about. But the manpage about sockets shows you there is a flag to re-use the same socket, lazily called: \"SO_REUSEADDR\". Set it using \"setsockopt()\".</p>\n" }, { "answer_id": 164682, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 0, "selected": false, "text": "<p>At a basic level, sockets are either open or closed (we'll ignore the niceties of the TCP/IP state diagram here). </p>\n\n<p>If your socket is closed, then nothing can send data to it. If it's open, then incoming data will be accepted and acknowledged by the TCP/IP stack until it's buffering algorithm cries \"enough!\". At that point, further data will not be acknowledged. </p>\n\n<p>You have two choices that I can see. Either close() the socket when you want to \"unlisten\", and reopen it later - Use setsockopt() with the SO_REUSEADDR flag to allow you to rebind to the well-known port before TIME_WAIT2 expires. </p>\n\n<p>The other choice is to keep the socket open but simply not accept() from it while you're 'busy'. Assuming you have an application-level acknowledge to requests, You load balancer would realise it's not getting a response and act accordingly.</p>\n" }, { "answer_id": 164734, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 2, "selected": false, "text": "<p>Based on your edited version of the question, I'm not sure you have to \"unlisten\" or close(). Two options come to mind:</p>\n\n<p>1) After you invoke listen(), connections are not actually accepted until (logically enough) you call accept(). You can \"unlisten\" by simply ignoring socket activity and deferring any accept()'s until you are ready for them. Any inbound connection attempts backlog onto the queue that was created when the port was opened in listen mode. Once the backlog queue is full in the stack, further connection attempts are simply dropped on the floor. When you resume with accepts(), you'll quickly dequeue the backlog and be ready for more connections.</p>\n\n<p>2) If you really want the port to appear completely closed temporarily, you might dynamically apply the kernel level packet filter to the port to prevent the inbound connection attempts from reaching the network stack. For example, you could use Berkeley Packet Filter (BPF) on most *nix platforms. That is you want to drop inbound packets coming in to the port of interest using the platform's firewall features. This, of course, varies by platform, but is a possible approach.</p>\n" }, { "answer_id": 168139, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 0, "selected": false, "text": "<p>Here's a rather ugly approach based on your edited question:</p>\n\n<p>Open a socket for listening with a normal backlog. Proceed.</p>\n\n<p>When you want to \"shut down\", open a 2nd one with a backlog of 1 and SO_REUSEADDR. Close the first one. When ready to resume, do another socket juggle to one with a normal backlog.</p>\n\n<p>Picky details around draining the accept queue from the socket that you're closing will be the killer here. Probably enough of a killer to make this approach nonviable.</p>\n" }, { "answer_id": 169005, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 4, "selected": true, "text": "<p>Some socket libraries allow you to specifically reject incoming connections. For example: <a href=\"ftp://ftp.tu-clausthal.de/pub/mirror/gnu/www/software/commoncpp/docs/refman/html/class_t_c_p_socket.html\" rel=\"nofollow noreferrer\">GNU's CommonC++: TCPsocket Class</a> has a <a href=\"ftp://ftp.tu-clausthal.de/pub/mirror/gnu/www/software/commoncpp/docs/refman/html/class_t_c_p_socket.html#a2\" rel=\"nofollow noreferrer\"><em>reject</em></a> method.</p>\n\n<p>BSD Sockets doesn't have this functionality. You can <em>accept</em> the connection and then immediately <em>close</em> it, while leaving the socket open:</p>\n\n<pre><code>while (running) {\n\n int i32ConnectFD = accept(i32SocketFD, NULL, NULL);\n while (noConnectionsPlease) {\n shutdown(i32ConnectFD, 2);\n close(i32ConnectFD);\n break;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1101735, "author": "Dan", "author_id": 95559, "author_profile": "https://Stackoverflow.com/users/95559", "pm_score": 0, "selected": false, "text": "<p>I don't necessarily think this is a good idea, but...</p>\n\n<p>You might be able to call listen a second time. The POSIX spec doesn't say not to. Perhaps you could call it a second time with a backlog parameter of 0 when you want to \"unlisten\".</p>\n\n<p>What happens when listen is called with a backlog of 0 seems to be implementation defined. The POSIX spec says it <strong>may</strong> allow connections to be accepted, which implies some implementations may choose to reject all connections if the backlog parameter is 0. More likely though, your implementation will choose some positive value when you pass in 0 (probably either 1 or SOMAXCONN).</p>\n" }, { "answer_id": 3478549, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>I don't think it's a good way to signal an upstream load-balancer. It would have to actually send some connections to your server before the message got through - those connections would probably get rejected.</p>\n\n<p>Likewise, any connections which were pending when you closed the listening socket will get closed with no data.</p>\n\n<p>If you want to signal the upstream load balancer, you should have a protocol for doing that. Don't try to abuse TCP to do it.</p>\n\n<p>Fortunately if the clients are normal web browsers, you can get away with an awful lot - simply closing sockets generally results in them retrying transparently to the user (to a point).</p>\n" }, { "answer_id": 3867013, "author": "Andrew", "author_id": 379428, "author_profile": "https://Stackoverflow.com/users/379428", "pm_score": 0, "selected": false, "text": "<p>The question didn't say what kind of socket. If it is a unix socket, you can stop and start listening with rename(2). You can also permanently stop listening with unlink(2), and since the socket remains open you can continue to service your backlog. This approach seems quite handy, though I have not seen used before and am just exploring it myself.</p>\n" }, { "answer_id": 12325036, "author": "eckes", "author_id": 13189, "author_profile": "https://Stackoverflow.com/users/13189", "pm_score": 0, "selected": false, "text": "<p>You already got some answers on the impossibility to do this via the socket API.</p>\n\n<p>You can use other OS methods (i.e. Host firwewall/iptables/ipfilter) to set up a temporary reject rule.</p>\n\n<p>I found that most load balancers are a bit limited in the possibilities they offer to recognize connection problems (most of them recognize a RST only in the connect probe, not as answer to a legit connection attempt.)</p>\n\n<p>Anyway, if you are limited by the probes detecting the inavailability, you set up an application level probe which does a HTTP request or FTP login or similiar things it will recognize if you simply close after accept. It could even interpret error messages like \"500 service not available\", which seems cleaner to me anyway. With SNMP some load balancers can also use the result as a load hint.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6449/" ]
Is it possible to unlisten on a socket after you have called listen(fd, backlog)? Edit: My mistake for not making myself clear. I'd like to be able to temporarily unlisten on the socket. Calling close() will leave the socket in the M2LS state and prevent me from reopening it (or worse, some nefarious program could bind to that socket) Temporarily unlistening would be a way (maybe not the best way) to signal to an upstream load balancer that this app couldn't accept any more requests for the moment
Some socket libraries allow you to specifically reject incoming connections. For example: [GNU's CommonC++: TCPsocket Class](ftp://ftp.tu-clausthal.de/pub/mirror/gnu/www/software/commoncpp/docs/refman/html/class_t_c_p_socket.html) has a [*reject*](ftp://ftp.tu-clausthal.de/pub/mirror/gnu/www/software/commoncpp/docs/refman/html/class_t_c_p_socket.html#a2) method. BSD Sockets doesn't have this functionality. You can *accept* the connection and then immediately *close* it, while leaving the socket open: ``` while (running) { int i32ConnectFD = accept(i32SocketFD, NULL, NULL); while (noConnectionsPlease) { shutdown(i32ConnectFD, 2); close(i32ConnectFD); break; } } ```
161,852
<p>I have a slight problem reading data from file. I want to be able to read wstring's, aswell as a chunk of raw data of arbitrary size (size is in bytes). </p> <pre><code>std::wfstream stream(file.c_str()); std::wstring comType; stream &gt;&gt; comType; int comSize; stream &gt;&gt; comSize; char *comData = new char[comSize]; memset(comData, 0, comSize); stream.read(comData, comSize); //error C2664 : 'std::basic_istream&lt;_Elem,_Traits&gt;::read' // : cannot convert parameter 1 from 'char *' to 'wchar_t *' </code></pre> <p>Perhaps I am using wrong streams, or something along those lines. Basically, I want to read a wstring, size of the data followed (which could be any number of bytes), followed by that many bytes of component data. Obviously, I can't read char's because the template assumes wchar_t's.</p> <p>I can read wchar_t's but then I have to make sure the data is stored as aligned by sizeof(wchar_t). Otherwise, I could end up corrupting the stream. A scenario would be when the data is 15 bytes. I would have to read 16 bytes, then mask the unwanted byte, seek the stream to 15 bytes offset (if possible with wchar_t templated?) to be able to read the next data chunk.</p> <p>Clearly, there <em>should</em> be a nicer way of achieving what I am trying to do.</p>
[ { "answer_id": 161878, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 1, "selected": false, "text": "<p>Considering your requirements I do not think wfstream is the way to go. Considerer using something like the following code snippet.</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n std::wstring str(L\"hello\");\n size_t size1 = str.length();\n char data[] = { 0x10, 0x20, 0x30 };\n size_t size2 = 3;\n\n FILE* output = NULL;\n if (_wfopen_s(&amp;output, L\"c:\\\\test.bin\", L\"wb\") == 0) {\n fwrite(&amp;size1, sizeof(size_t), 1, output);\n fwrite(str.c_str(), size1 * sizeof(wchar_t), 1, output);\n fwrite(&amp;size2, sizeof(size_t), 1, output);\n fwrite(data, size2, 1, output);\n\n fclose(output);\n }\n\n FILE* input = NULL;\n if (_wfopen_s(&amp;input, L\"c:\\\\test.bin\", L\"rb\") == 0) {\n fread(&amp;size1, sizeof(size_t), 1, input);\n wchar_t* wstr = new wchar_t[size1 + 1];\n fread(wstr, size1 * sizeof(wchar_t), 1, input);\n std::wstring str(wstr, size1);\n delete[] wstr;\n fread(&amp;size2, sizeof(size_t), 1, input);\n char* data1 = new char[size2];\n fread(data1, size2, 1, input);\n\n std::wcout &lt;&lt; str.c_str() &lt;&lt; std::endl;\n for (size_t i = 0; i &lt; size2; ++i) {\n std::wcout &lt;&lt; std::hex &lt;&lt; \"0x\" &lt;&lt; int(data1[i]) &lt;&lt; std::endl;\n }\n\n delete[] data1;\n\n fclose(input);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>hello\n0x10\n0x20\n0x30\n</code></pre>\n" }, { "answer_id": 162108, "author": "Fionn", "author_id": 21566, "author_profile": "https://Stackoverflow.com/users/21566", "pm_score": 2, "selected": false, "text": "<p>the problem with the stream.read is that it uses wchar_t as \"character unit\" with wfstream. If you use fstream it uses char as \"character unit\".</p>\n\n<p>This would work if you want to read wide characters:</p>\n\n<pre><code>wchar_t *comData = new wchar_t[comSize];\nstream.read(comData, comSize);\n</code></pre>\n\n<p>Also 15 bytes of data can't be read with a wide stream, because the smallest unit is at least 2bytes (see below), so you can only read chunks of sizwof(wchar_t) * n.</p>\n\n<p>But if you are concerned about portability of the application wfstream/wchar_t is maybe not the best solution because there is no standard how wide wchar_t is (e.g. on windows wchar_t is 16bit on many unix/linux systems it is 32bit).</p>\n\n<p>The second problem with storing text as wide characters is endianess, i would suggest to use UTF-8 for text storage.</p>\n" }, { "answer_id": 21128284, "author": "Jac08in", "author_id": 887061, "author_profile": "https://Stackoverflow.com/users/887061", "pm_score": 0, "selected": false, "text": "<pre><code># ifdef UNICODE\n# define tfstream wfstream\n# else\n# define tfstream fstream\n# endif\n\ntfstream fs( _T(\"filename.bin\"), tfstream::binary );\nbyte buffer[1023];\nfs.read( buffer, sizeof(buffer) )\n</code></pre>\n\n<p>I think, the _T(\"filename.bin\") and tfstream are the UI expression; the buffer and the read() is DATA LOGIC expression. wfstream must NOT restrict the buffer to the type wchar_t. The UI must NOT mix with DATA LOGIC ! wfstream do the wrong thing here</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166173/" ]
I have a slight problem reading data from file. I want to be able to read wstring's, aswell as a chunk of raw data of arbitrary size (size is in bytes). ``` std::wfstream stream(file.c_str()); std::wstring comType; stream >> comType; int comSize; stream >> comSize; char *comData = new char[comSize]; memset(comData, 0, comSize); stream.read(comData, comSize); //error C2664 : 'std::basic_istream<_Elem,_Traits>::read' // : cannot convert parameter 1 from 'char *' to 'wchar_t *' ``` Perhaps I am using wrong streams, or something along those lines. Basically, I want to read a wstring, size of the data followed (which could be any number of bytes), followed by that many bytes of component data. Obviously, I can't read char's because the template assumes wchar\_t's. I can read wchar\_t's but then I have to make sure the data is stored as aligned by sizeof(wchar\_t). Otherwise, I could end up corrupting the stream. A scenario would be when the data is 15 bytes. I would have to read 16 bytes, then mask the unwanted byte, seek the stream to 15 bytes offset (if possible with wchar\_t templated?) to be able to read the next data chunk. Clearly, there *should* be a nicer way of achieving what I am trying to do.
the problem with the stream.read is that it uses wchar\_t as "character unit" with wfstream. If you use fstream it uses char as "character unit". This would work if you want to read wide characters: ``` wchar_t *comData = new wchar_t[comSize]; stream.read(comData, comSize); ``` Also 15 bytes of data can't be read with a wide stream, because the smallest unit is at least 2bytes (see below), so you can only read chunks of sizwof(wchar\_t) \* n. But if you are concerned about portability of the application wfstream/wchar\_t is maybe not the best solution because there is no standard how wide wchar\_t is (e.g. on windows wchar\_t is 16bit on many unix/linux systems it is 32bit). The second problem with storing text as wide characters is endianess, i would suggest to use UTF-8 for text storage.
161,859
<p>I'd like to invoke bash using a string as input. Something like:</p> <pre><code>sh -l -c "./foo" </code></pre> <p>I'd like to do this from Java. Unfortunately, when I try to invoke the command using <code>getRuntime().exec</code>, I get the following error: </p> <pre><code> foo": -c: line 0: unexpected EOF while looking for matching `"' foo": -c: line 1: syntax error: unexpected end of file </code></pre> <p>It seems to be related to my string not being terminated with an EOF. </p> <p>Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ?</p>
[ { "answer_id": 161863, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 2, "selected": false, "text": "<p>EOF is NOT a character, so there's no way to write an EOF. \nYou've forgotten to close a quoted string.</p>\n" }, { "answer_id": 161866, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The cause for this error is most likely a missing syntax token that bash expects but the string you pass ends before bash encountered it. Look for ifs, fors etc. that have no closing fi or done.</p>\n" }, { "answer_id": 161888, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>Runtime.getRuntime().exec(new String[] {\"sh\", \"-l\", \"-c\", \"./foo\"});\n</code></pre>\n\n<p>Main point: don't put the double quotes in. That's only used when writing a command-line in the shell!</p>\n\n<p>e.g., <code>echo \"Hello, world!\"</code> (as typed in the shell) gets translated to:</p>\n\n<pre><code>Runtime.getRuntime().exec(new String[] {\"echo\", \"Hello, world!\"});\n</code></pre>\n\n<p>(Just forget for the moment that the shell normally has a builtin for <code>echo</code>, and is calling <code>/bin/echo</code> instead. :-))</p>\n" }, { "answer_id": 161931, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 0, "selected": false, "text": "<p>Quotes need to be escaped when inside a string.\nInstead of writing \" write \\\".</p>\n\n<p>E.g.</p>\n\n<p>strcpy(c, \"This is a string \\\"with\\\" quotes\");</p>\n" }, { "answer_id": 162577, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "<p>Windows command lines behave differently from UNIX, Mac OS X and GNU/Linux.</p>\n\n<p>On Windows the process receives the input text verbatim after the executable name (and space). It's then up to the program to parse the command line (which is usually done implicitly, the programmer is often clueless about the process).</p>\n\n<p>In GNU/Linux the shell processes the command line, guaranteeing the familiar array of strings passed to C's <code>main</code> function. You don't have that shell. The best approach (even on Windows) is to <strong>use one of the form of exec where you pass each command line argument individually in its own <code>String</code></strong>.</p>\n\n<pre><code>Process exec​(String[] cmdarray) \nProcess exec​(String[] cmdarray, String[] envp) \nProcess exec​(String[] cmdarray, String[] envp, File dir)\n</code></pre>\n\n<p><strong>Or better, <code>java.lang.ProcessBuilder</code>.</strong></p>\n\n<p>You can get a shell to do the parsing for you if you really want. This would make your example look something like (untested):</p>\n\n<pre><code>Runtime.getRuntime().exec(new String[] {\n \"sh\", \"-c\", \"sh -l -c \\\"echo foo; echo bar;\\\"\"\n});\n</code></pre>\n" }, { "answer_id": 162721, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>if I were you, I would write the contents of the string to a temp bashfile and see if bash executes that without any error. If that executes without an error, then I would consider debugging further;</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20426/" ]
I'd like to invoke bash using a string as input. Something like: ``` sh -l -c "./foo" ``` I'd like to do this from Java. Unfortunately, when I try to invoke the command using `getRuntime().exec`, I get the following error: ``` foo": -c: line 0: unexpected EOF while looking for matching `"' foo": -c: line 1: syntax error: unexpected end of file ``` It seems to be related to my string not being terminated with an EOF. Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ?
Use this: ``` Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"}); ``` Main point: don't put the double quotes in. That's only used when writing a command-line in the shell! e.g., `echo "Hello, world!"` (as typed in the shell) gets translated to: ``` Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"}); ``` (Just forget for the moment that the shell normally has a builtin for `echo`, and is calling `/bin/echo` instead. :-))
161,872
<p>What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?</p> <p>Guidelines:</p> <ul> <li>Try to limit answers to the Perl core and not CPAN</li> <li>Please give an example and a short description</li> </ul> <hr> <h2>Hidden Features also found in other languages' Hidden Features:</h2> <p>(These are all from <a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257">Corion's answer</a>)</p> <ul> <li><a href="https://stackoverflow.com/questions/132241/hidden-features-of-c#">C</a> <ul> <li>Duff's Device</li> <li>Portability and Standardness</li> </ul></li> <li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">C#</a> <ul> <li>Quotes for whitespace delimited lists and strings</li> <li>Aliasable namespaces</li> </ul></li> <li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Java</a> <ul> <li>Static Initalizers</li> </ul></li> <li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">JavaScript</a> <ul> <li>Functions are First Class citizens</li> <li>Block scope and closure</li> <li>Calling methods and accessors indirectly through a variable</li> </ul></li> <li><a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby">Ruby</a> <ul> <li>Defining methods through code</li> </ul></li> <li><a href="https://stackoverflow.com/questions/61401/hidden-features-of-php">PHP</a> <ul> <li>Pervasive online documentation</li> <li>Magic methods</li> <li>Symbolic references</li> </ul></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Python</a> <ul> <li>One line value swapping</li> <li>Ability to replace even core functions with your own functionality</li> </ul></li> </ul> <h2>Other Hidden Features:</h2> <p>Operators:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094">The bool quasi-operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058">The flip-flop operator</a> <ul> <li>Also used for <a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627">list construction</a></li> </ul></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004">The <code>++</code> and unary <code>-</code> operators work on strings</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075">The repetition operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943">The spaceship operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239">The || operator (and // operator) to select from a set of choices</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152">The diamond operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249">Special cases of the <code>m//</code> operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060">The tilde-tilde "operator"</a></li> </ul> <p>Quoting constructs:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416">The qw operator</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094">Letters can be used as quote delimiters in q{}-like constructs</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374">Quoting mechanisms</a></li> </ul> <p>Syntax and Names:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094">There can be a space after a sigil</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094">You can give subs numeric names with symbolic references</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416">Legal trailing commas</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601">Grouped Integer Literals</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925">hash slices</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254">Populating keys of a hash from an array</a></li> </ul> <p>Modules, Pragmas, and command-line options:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440">use strict and use warnings</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440">Taint checking</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085">Esoteric use of -n and -p</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541">CPAN</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601"><code>overload::constant</code></a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255">IO::Handle module</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725">Safe compartments</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083">Attributes</a></li> </ul> <p>Variables:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357">Autovivification</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985">The <code>$[</code> variable</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947">tie</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118">Dynamic Scoping</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627">Variable swapping with a single statement</a></li> </ul> <p>Loops and flow control:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440">Magic goto</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481"><code>for</code> on a single variable</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592">continue clause</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104">Desperation mode</a></li> </ul> <p>Regular expressions:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565">The <code>\G</code> anchor</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976"><code>(?{})</code> and '(??{})` in regexes</a></li> </ul> <p>Other features:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440">The debugger</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206">Special code blocks such as BEGIN, CHECK, and END</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700">The <code>DATA</code> block</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601">New Block Operations</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601">Source Filters</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601">Signal Hooks</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309">map</a> (<a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809">twice</a>)</li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842">Wrapping built-in functions</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883">The <code>eof</code> function</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796">The <code>dbmopen</code> function</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104">Turning warnings into errors</a></li> </ul> <p>Other tricks, and meta-answers:</p> <ul> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532">cat files, decompressing gzips if needed</a></li> <li><a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271">Perl Tips</a></li> </ul> <hr> <p><strong>See Also:</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/132241/hidden-features-of-c">Hidden features of C</a></li> <li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden features of C#</a></li> <li><a href="https://stackoverflow.com/questions/75538/hidden-features-of-c">Hidden features of C++</a></li> <li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li> <li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden features of JavaScript</a></li> <li><a href="https://stackoverflow.com/questions/63998/hidden-features-of-ruby">Hidden features of Ruby</a></li> <li><a href="https://stackoverflow.com/questions/61401/hidden-features-of-php">Hidden features of PHP</a></li> <li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li> <li><a href="https://stackoverflow.com/questions/2493996/hidden-features-of-clojure">Hidden features of Clojure</a></li> </ul>
[ { "answer_id": 161943, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 4, "selected": false, "text": "<p>Let's start easy with the <a href=\"http://en.wikipedia.org/wiki/Spaceship_operator\" rel=\"nofollow noreferrer\">Spaceship Operator</a>.</p>\n\n<pre><code>$a = 5 &lt;=&gt; 7; # $a is set to -1\n$a = 7 &lt;=&gt; 5; # $a is set to 1\n$a = 6 &lt;=&gt; 6; # $a is set to 0\n</code></pre>\n" }, { "answer_id": 161976, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>My vote would go for the (?{}) and (??{}) groups in Perl's regular expressions. The first executes Perl code, ignoring the return value, the second executes code, using the return value as a regular expression.</p>\n" }, { "answer_id": 161985, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 3, "selected": false, "text": "<p>There also is $[ the variable which decides at which index an array starts.\nDefault is 0 so an array is starting at 0. \nBy setting </p>\n\n<pre><code>$[=1;\n</code></pre>\n\n<p>You can make Perl behave more like <a href=\"http://en.wikipedia.org/wiki/AWK\" rel=\"nofollow noreferrer\">AWK</a> (or Fortran) if you really want to.</p>\n" }, { "answer_id": 162004, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 5, "selected": false, "text": "<p>The operators ++ and unary - don't only work on numbers, but also on strings. </p>\n\n<pre><code>my $_ = \"a\"\nprint -$_\n</code></pre>\n\n<p>prints <em>-a</em></p>\n\n<pre><code>print ++$_\n</code></pre>\n\n<p>prints <em>b</em></p>\n\n<pre><code>$_ = 'z'\nprint ++$_\n</code></pre>\n\n<p>prints <em>aa</em></p>\n" }, { "answer_id": 162058, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 6, "selected": false, "text": "<p>The flip-flop operator is useful for skipping the first iteration when looping through the records (usually lines) returned by a file handle, without using a flag variable:</p>\n\n<pre><code>while(&lt;$fh&gt;)\n{\n next if 1..1; # skip first record\n ...\n}\n</code></pre>\n\n<p>Run <code>perldoc perlop</code> and search for \"flip-flop\" for more information and examples.</p>\n" }, { "answer_id": 162060, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 3, "selected": false, "text": "<p>A bit obscure is the tilde-tilde \"operator\" which forces scalar context.</p>\n\n<pre><code>print ~~ localtime;\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>print scalar localtime;\n</code></pre>\n\n<p>and different from</p>\n\n<pre><code>print localtime;\n</code></pre>\n" }, { "answer_id": 162075, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": false, "text": "<p>Binary \"x\" is the <a href=\"http://perldoc.perl.org/perlop.html#Multiplicative-Operators\" rel=\"nofollow noreferrer\">repetition operator</a>:</p>\n\n<pre><code>print '-' x 80; # print row of dashes\n</code></pre>\n\n<p>It also works with lists:</p>\n\n<pre><code>print for (1, 4, 9) x 3; # print 149149149\n</code></pre>\n" }, { "answer_id": 162085, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 5, "selected": false, "text": "<p>Based on the way the <code>\"-n\"</code> and <code>\"-p\"</code> switches are implemented in Perl 5, you can write a seemingly incorrect program including <code>}{</code>:</p>\n\n<pre><code>ls |perl -lne 'print $_; }{ print \"$. Files\"'\n</code></pre>\n\n<p>which is converted internally to this code:</p>\n\n<pre><code>LINE: while (defined($_ = &lt;ARGV&gt;)) {\n print $_; }{ print \"$. Files\";\n}\n</code></pre>\n" }, { "answer_id": 162094, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 6, "selected": false, "text": "<p>There are many non-obvious features in Perl.</p>\n\n<p>For example, did you know that there can be a space after a sigil?</p>\n\n<pre><code> $ perl -wle 'my $x = 3; print $ x'\n 3\n</code></pre>\n\n<p>Or that you can give subs numeric names if you use symbolic references?</p>\n\n<pre><code>$ perl -lwe '*4 = sub { print \"yes\" }; 4-&gt;()' \nyes\n</code></pre>\n\n<p>There's also the \"bool\" quasi operator, that return 1 for true expressions and the empty string for false:</p>\n\n<pre><code>$ perl -wle 'print !!4'\n1\n$ perl -wle 'print !!\"0 but true\"'\n1\n$ perl -wle 'print !!0'\n(empty line)\n</code></pre>\n\n<p>Other interesting stuff: with <code>use overload</code> you can overload string literals and numbers (and for example make them BigInts or whatever).</p>\n\n<p>Many of these things are actually documented somewhere, or follow logically from the documented features, but nonetheless some are not very well known.</p>\n\n<p><em>Update</em>: Another nice one. Below the <code>q{...}</code> quoting constructs were mentioned, but did you know that you can use letters as delimiters?</p>\n\n<pre><code>$ perl -Mstrict -wle 'print q bJet another perl hacker.b'\nJet another perl hacker.\n</code></pre>\n\n<p>Likewise you can write regular expressions:</p>\n\n<pre><code>m xabcx\n# same as m/abc/\n</code></pre>\n" }, { "answer_id": 162152, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 4, "selected": false, "text": "<p>The null filehandle <a href=\"http://perldoc.perl.org/perlop.html#I%2fO-Operators\" rel=\"nofollow noreferrer\">diamond operator</a> <code>&lt;&gt;</code> has its place in building command line tools. It acts like <code>&lt;FH&gt;</code> to read from a handle, except that it magically selects whichever is found first: command line filenames or STDIN. Taken from perlop:</p>\n\n<pre><code>while (&lt;&gt;) {\n... # code for each line\n}\n</code></pre>\n" }, { "answer_id": 162206, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://perldoc.perl.org/perlmod.html#BEGIN%2c-UNITCHECK%2c-CHECK%2c-INIT-and-END\" rel=\"nofollow noreferrer\">Special code blocks</a> such as <code>BEGIN</code>, <code>CHECK</code> and <code>END</code>. They come from Awk, but work differently in Perl, because it is not record-based.</p>\n\n<p>The <code>BEGIN</code> block can be used to specify some code for the parsing phase; it is also executed when you do the syntax-and-variable-check <code>perl -c</code>. For example, to load in configuration variables:</p>\n\n<pre><code>BEGIN {\n eval {\n require 'config.local.pl';\n };\n if ($@) {\n require 'config.default.pl';\n }\n}\n</code></pre>\n" }, { "answer_id": 162239, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 5, "selected": false, "text": "<p>One of my favourite features in Perl is using the boolean <code>||</code> operator to select between a set of choices.</p>\n\n<pre><code> $x = $a || $b;\n\n # $x = $a, if $a is true.\n # $x = $b, otherwise\n</code></pre>\n\n<p>This means one can write:</p>\n\n<pre><code> $x = $a || $b || $c || 0;\n</code></pre>\n\n<p>to take the first true value from <code>$a</code>, <code>$b</code>, and <code>$c</code>, or a default of <code>0</code> otherwise.</p>\n\n<p>In Perl 5.10, there's also the <code>//</code> operator, which returns the left hand side if it's defined, and the right hand side otherwise. The following selects the first <em>defined</em> value from <code>$a</code>, <code>$b</code>, <code>$c</code>, or <code>0</code> otherwise:</p>\n\n<pre>\n$x = $a // $b // $c // 0;\n</pre>\n\n<p>These can also be used with their short-hand forms, which are very useful for providing defaults:</p>\n\n<pre>\n$x ||= 0; # If $x was false, it now has a value of 0.\n\n$x //= 0; # If $x was undefined, it now has a value of zero.\n</pre>\n\n<p>Cheerio,</p>\n\n<p><em>Paul</em></p>\n" }, { "answer_id": 162249, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 4, "selected": false, "text": "<p>The <code>m//</code> operator has some obscure special cases:</p>\n\n<ul>\n<li>If you use <code>?</code> as the delimiter it only matches once unless you call <code>reset</code>.</li>\n<li>If you use <code>'</code> as the delimiter the pattern is not interpolated.</li>\n<li>If the pattern is empty it uses the pattern from the last successful match.</li>\n</ul>\n" }, { "answer_id": 162257, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 5, "selected": false, "text": "<p>As Perl has almost all \"esoteric\" parts from the other lists, I'll tell you the one thing that Perl can't:</p>\n\n<p><strike>The one thing Perl can't do is have bare arbitrary URLs in your code, because the <code>//</code> operator is used for regular expressions.</strike></p>\n\n<p>Just in case it wasn't obvious to you what features Perl offers, here's a selective list of the maybe not totally obvious entries:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/132241/hidden-features-of-c#132274\">Duff's Device</a> - <a href=\"http://perlmonks.org/?node=388976\" rel=\"nofollow noreferrer\">in Perl</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/132241/hidden-features-of-c#132269\">Portability and Standardness</a> - <a href=\"http://activestate.com\" rel=\"nofollow noreferrer\">There are likely more computers with Perl than with a C compiler</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c#9401\">A file/path manipulation class</a> - <a href=\"http://search.cpan.org/perldoc?File::Find\" rel=\"nofollow noreferrer\">File::Find works on even more operating systems than .Net does</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c#9406\">Quotes for whitespace delimited lists</a> <a href=\"https://stackoverflow.com/questions/9033/hidden-features-of-c#9114\">and strings</a> - <a href=\"http://perldoc.org/perlop.html\" rel=\"nofollow noreferrer\">Perl allows you to choose almost arbitrary quotes for your list and string delimiters</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/75538/hidden-features-of-c#78484\">Aliasable namespaces</a> - Perl has these through glob assignments: </p>\n\n<pre><code>*My::Namespace:: = \\%Your::Namespace\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/15496/hidden-features-of-java#47493\">Static initializers</a> - Perl can run code in almost every phase of compilation and object instantiation, from <code>BEGIN</code> (code parse) to <code>CHECK</code> (after code parse) to <code>import</code> (at module import) to <code>new</code> (object instantiation) to <code>DESTROY</code> (object destruction) to <code>END</code> (program exit)</p>\n\n<p><a href=\"https://stackoverflow.com/questions/61088/hidden-features-of-javascript#61094\">Functions are First Class citizens</a> - just like in Perl</p>\n\n<p><a href=\"https://stackoverflow.com/questions/61088/hidden-features-of-javascript#61173\">Block scope and closure</a> - Perl has both</p>\n\n<p><a href=\"https://stackoverflow.com/questions/61088/hidden-features-of-javascript#61125\">Calling methods and accessors indirectly through a variable</a> - Perl does that too:</p>\n\n<pre><code>my $method = 'foo';\nmy $obj = My::Class-&gt;new();\n$obj-&gt;$method( 'baz' ); # calls $obj-&gt;foo( 'baz' )\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/63998/hidden-features-of-ruby#64080\">Defining methods through code</a> - <a href=\"http://perldoc.perl.org/functions/sub.html\" rel=\"nofollow noreferrer\">Perl allows that too</a>:</p>\n\n<pre><code>*foo = sub { print \"Hello world\" };\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/61401/hidden-features-of-php#61491\">Pervasive online documentation</a> - <a href=\"http://perldoc.com/\" rel=\"nofollow noreferrer\">Perl documentation is online and likely on your system too</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/61401/hidden-features-of-php#61482\">Magic methods</a> that get called whenever you call a \"nonexisting\" function - Perl implements that in the AUTOLOAD function</p>\n\n<p><a href=\"https://stackoverflow.com/questions/61401/hidden-features-of-php#62525\">Symbolic references</a> - you are well advised to stay away from these. <a href=\"http://perl.plover.com/varvarname.html\" rel=\"nofollow noreferrer\">They will eat your children.</a> But of course, Perl allows you to offer your children to blood-thirsty demons.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python#102037\">One line value swapping</a> - Perl allows list assignment</p>\n\n<p><a href=\"https://stackoverflow.com/questions/101268/hidden-features-of-python#101744\">Ability to replace even core functions with your own functionality</a></p>\n\n<pre><code>use subs 'unlink'; \nsub unlink { print 'No.' }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>BEGIN{\n *CORE::GLOBAL::unlink = sub {print 'no'}\n};\n\nunlink($_) for @ARGV\n</code></pre>\n" }, { "answer_id": 162271, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 4, "selected": false, "text": "<p>This is a meta-answer, but the <a href=\"http://perltraining.com.au/tips/\" rel=\"nofollow noreferrer\">Perl Tips</a> archives contain all sorts of interesting tricks that can be done with Perl. The archive of previous tips is on-line for browsing, and can be subscribed to via mailing list or atom feed.</p>\n\n<p>Some of my favourite tips include <a href=\"http://perltraining.com.au/tips/2008-05-23.html\" rel=\"nofollow noreferrer\">building executables with PAR</a>, <a href=\"http://perltraining.com.au/tips/2008-08-20.html\" rel=\"nofollow noreferrer\">using autodie to throw exceptions automatically</a>, and the use of the <a href=\"http://perltraining.com.au/tips/2008-03-12.html\" rel=\"nofollow noreferrer\">switch</a> and <a href=\"http://perltraining.com.au/tips/2008-04-18.html\" rel=\"nofollow noreferrer\">smart-match</a> constructs in Perl 5.10.</p>\n\n<p><em>Disclosure:</em> I'm one of the authors and maintainers of Perl Tips, so I obviously think very highly of them. ;)</p>\n" }, { "answer_id": 162357, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Autovivification\" rel=\"nofollow noreferrer\">Autovivification</a>. AFAIK <strong>no other language has it</strong>.</p>\n" }, { "answer_id": 162565, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 4, "selected": false, "text": "<pre><code>while(/\\G(\\b\\w*\\b)/g) {\n print \"$1\\n\";\n}\n</code></pre>\n\n<p>the \\G anchor. It's <strong>hot</strong>.</p>\n" }, { "answer_id": 162601, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": false, "text": "<h3>New Block Operations</h3>\n\n<p>I'd say the ability to expand the language, creating pseudo block operations is one.</p>\n\n<ol>\n<li><p>You declare the prototype for a sub indicating that it takes a code reference first:</p>\n\n<pre><code>sub do_stuff_with_a_hash (&amp;\\%) {\n my ( $block_of_code, $hash_ref ) = @_;\n while ( my ( $k, $v ) = each %$hash_ref ) { \n $block_of_code-&gt;( $k, $v );\n }\n}\n</code></pre></li>\n<li><p>You can then call it in the body like so </p>\n\n<pre><code>use Data::Dumper;\n\ndo_stuff_with_a_hash {\n local $Data::Dumper::Terse = 1;\n my ( $k, $v ) = @_;\n say qq(Hey, the key is \"$k\"!);\n say sprintf qq(Hey, the value is \"%v\"!), Dumper( $v );\n\n} %stuff_for\n;\n</code></pre></li>\n</ol>\n\n<p>(<code>Data::Dumper::Dumper</code> is another semi-hidden gem.) Notice how you don't need the <code>sub</code> keyword in front of the block, or the comma before the hash. It ends up looking a lot like: <code>map { } @list</code></p>\n\n<h3>Source Filters</h3>\n\n<p>Also, there are source filters. Where Perl will pass you the code so you can manipulate it. Both this, and the block operations, are pretty much don't-try-this-at-home type of things. </p>\n\n<p>I have done some neat things with source filters, for example like creating a very simple language to check the time, allowing short Perl one-liners for some decision making:</p>\n\n<pre><code>perl -MLib::DB -MLib::TL -e 'run_expensive_database_delete() if $hour_of_day &lt; AM_7';\n</code></pre>\n\n<p><code>Lib::TL</code> would just scan for both the \"variables\" and the constants, create them and substitute them as needed. </p>\n\n<p>Again, source filters can be messy, but are powerful. But they can mess debuggers up something terrible--and even warnings can be printed with the wrong line numbers. I stopped using Damian's <a href=\"http://search.cpan.org/perldoc?Switch\" rel=\"nofollow noreferrer\">Switch</a> because the debugger would lose all ability to tell me where I really was. But I've found that you can minimize the damage by modifying small sections of code, keeping them on the same line. </p>\n\n<h3>Signal Hooks</h3>\n\n<p>It's often enough done, but it's not all that obvious. Here's a die handler that piggy backs on the old one. </p>\n\n<pre><code>my $old_die_handler = $SIG{__DIE__};\n$SIG{__DIE__} \n = sub { say q(Hey! I'm DYIN' over here!); goto &amp;$old_die_handler; }\n ;\n</code></pre>\n\n<p>That means whenever some other module in the code wants to die, they gotta come to you (unless someone else does a destructive overwrite on <code>$SIG{__DIE__}</code>). And you can be notified that somebody things something is an error. </p>\n\n<p>Of course, for enough things you can just use an <code>END { }</code> block, if all you want to do is clean up. </p>\n\n<h3><code>overload::constant</code></h3>\n\n<p>You can inspect literals of a certain type in packages that include your module. For example, if you use this in your <code>import</code> sub:</p>\n\n<pre><code>overload::constant \n integer =&gt; sub { \n my $lit = shift;\n return $lit &gt; 2_000_000_000 ? Math::BigInt-&gt;new( $lit ) : $lit \n };\n</code></pre>\n\n<p>it will mean that every integer greater than 2 billion in the calling packages will get changed to a <code>Math::BigInt</code> object. (See <a href=\"http://search.cpan.org/perldoc?overload#Overloading_constants\" rel=\"nofollow noreferrer\">overload::constant</a>).</p>\n\n<h3>Grouped Integer Literals</h3>\n\n<p>While we're at it. Perl allows you to break up large numbers into groups of three digits and still get a parsable integer out of it. Note <code>2_000_000_000</code> above for 2 billion. </p>\n" }, { "answer_id": 162842, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "<p>Axeman reminded me of how easy it is to wrap some of the built-in functions.</p>\n\n<p>Before Perl 5.10 Perl didn't have a pretty print(say) like Python.</p>\n\n<p>So in your local program you could do something like:</p>\n\n<pre><code>sub print {\n print @_, \"\\n\";\n}\n</code></pre>\n\n<p>or add in some debug.</p>\n\n<pre><code>sub print {\n exists $ENV{DEVELOPER} ?\n print Dumper(@_) :\n print @_;\n}\n</code></pre>\n" }, { "answer_id": 163374, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 5, "selected": false, "text": "<p>It's simple to quote almost any kind of strange string in Perl.</p>\n\n<pre><code>my $url = q{http://my.url.com/any/arbitrary/path/in/the/url.html};\n</code></pre>\n\n<p>In fact, the various quoting mechanisms in Perl are quite interesting. The Perl regex-like quoting mechanisms allow you to quote anything, specifying the delimiters. You can use almost any special character like #, /, or open/close characters like (), [], or {}. Examples:</p>\n\n<pre><code>my $var = q#some string where the pound is the final escape.#;\nmy $var2 = q{A more pleasant way of escaping.};\nmy $var3 = q(Others prefer parens as the quote mechanism.);\n</code></pre>\n\n<p>Quoting mechanisms:</p>\n\n<p>q : literal quote; only character that needs to be escaped is the end character.\nqq : an interpreted quote; processes variables and escape characters. Great for strings that you need to quote:</p>\n\n<pre><code>my $var4 = qq{This \"$mechanism\" is broken. Please inform \"$user\" at \"$email\" about it.};\n</code></pre>\n\n<p>qx : Works like qq, but then executes it as a system command, non interactively. Returns all the text generated from the standard out. (Redirection, if supported in the OS, also comes out) Also done with back quotes (the ` character).</p>\n\n<pre><code>my $output = qx{type \"$path\"}; # get just the output\nmy $moreout = qx{type \"$path\" 2&gt;&amp;1}; # get stuff on stderr too\n</code></pre>\n\n<p>qr : Interprets like qq, but then compiles it as a regular expression. Works with the various options on the regex as well. You can now pass the regex around as a variable:</p>\n\n<pre><code>sub MyRegexCheck {\n my ($string, $regex) = @_;\n if ($string)\n {\n return ($string =~ $regex);\n }\n return; # returns 'null' or 'empty' in every context\n}\n\nmy $regex = qr{http://[\\w]\\.com/([\\w]+/)+};\n@results = MyRegexCheck(q{http://myurl.com/subpath1/subpath2/}, $regex);\n</code></pre>\n\n<p>qw : A very, very useful quote operator. Turns a quoted set of whitespace separated words into a list. Great for filling in data in a unit test.</p>\n\n<pre><code>\n my @allowed = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z { });\n my @badwords = qw(WORD1 word2 word3 word4);\n my @numbers = qw(one two three four 5 six seven); # works with numbers too\n my @list = ('string with space', qw(eight nine), \"a $var\"); # works in other lists\n my $arrayref = [ qw(and it works in arrays too) ]; \n</code></pre>\n\n<p>They're great to use them whenever it makes things clearer. For qx, qq, and q, I most likely use the {} operators. The most common habit of people using qw is usually the () operator, but sometimes you also see qw//.</p>\n" }, { "answer_id": 163416, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 5, "selected": false, "text": "<p>The quoteword operator is one of my favourite things. Compare:</p>\n\n<pre><code>my @list = ('abc', 'def', 'ghi', 'jkl');\n</code></pre>\n\n<p>and</p>\n\n<pre><code>my @list = qw(abc def ghi jkl);\n</code></pre>\n\n<p>Much less noise, easier on the eye. Another really nice thing about Perl, that one really misses when writing SQL, is that a trailing comma is legal:</p>\n\n<pre><code>print 1, 2, 3, ;\n</code></pre>\n\n<p>That looks odd, but not if you indent the code another way:</p>\n\n<pre><code>print\n results_of_foo(),\n results_of_xyzzy(),\n results_of_quux(),\n ;\n</code></pre>\n\n<p>Adding an additional argument to the function call does not require you to fiddle around with commas on previous or trailing lines. The single line change has no impact on its surrounding lines.</p>\n\n<p>This makes it very pleasant to work with variadic functions. This is perhaps one of the most under-rated features of Perl.</p>\n" }, { "answer_id": 163440, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": false, "text": "<p>Taint checking. With taint checking enabled, perl will die (or warn, with <code>-t</code>) if you try to pass tainted data (roughly speaking, data from outside the program) to an unsafe function (opening a file, running an external command, etc.). It is very helpful when writing setuid scripts or CGIs or anything where the script has greater privileges than the person feeding it data.</p>\n\n<p>Magic goto. <code>goto &amp;sub</code> does an optimized tail call.</p>\n\n<p>The debugger.</p>\n\n<p><code>use strict</code> and <code>use warnings</code>. These can save you from a bunch of typos.</p>\n" }, { "answer_id": 163481, "author": "timkay", "author_id": 24558, "author_profile": "https://Stackoverflow.com/users/24558", "pm_score": 5, "selected": false, "text": "<p>The \"for\" statement can be used the same way \"with\" is used in Pascal:</p>\n\n<pre><code>for ($item)\n{\n s/&amp;‎nbsp;/ /g;\n s/&lt;.*?&gt;/ /g;\n $_ = join(\" \", split(\" \", $_));\n}\n</code></pre>\n\n<p>You can apply a sequence of s/// operations, etc. to the same variable without having to repeat the variable name.</p>\n\n<p>NOTE: the non-breaking space above (&amp;‎nbsp;) has hidden Unicode in it to circumvent the Markdown. Don't copy paste it :)</p>\n" }, { "answer_id": 163488, "author": "timkay", "author_id": 24558, "author_profile": "https://Stackoverflow.com/users/24558", "pm_score": 4, "selected": false, "text": "<pre><code>rename(\"$_.part\", $_) for \"data.txt\";\n</code></pre>\n\n<p>renames data.txt.part to data.txt without having to repeat myself.</p>\n" }, { "answer_id": 163498, "author": "timkay", "author_id": 24558, "author_profile": "https://Stackoverflow.com/users/24558", "pm_score": 3, "selected": false, "text": "<pre><code>sub load_file\n{\n local(@ARGV, $/) = shift;\n &lt;&gt;;\n}\n</code></pre>\n\n<p>and a version that returns an array as appropriate:</p>\n\n<pre><code>sub load_file\n{\n local @ARGV = shift;\n local $/ = wantarray? $/: undef;\n &lt;&gt;;\n}\n</code></pre>\n" }, { "answer_id": 163532, "author": "timkay", "author_id": 24558, "author_profile": "https://Stackoverflow.com/users/24558", "pm_score": 6, "selected": false, "text": "<p>Add support for compressed files via <em>magic ARGV</em>:</p>\n\n<pre><code>s{ \n ^ # make sure to get whole filename\n ( \n [^'] + # at least one non-quote\n \\. # extension dot\n (?: # now either suffix\n gz\n | Z \n )\n )\n \\z # through the end\n}{gzcat '$1' |}xs for @ARGV;\n</code></pre>\n\n<p><em>(quotes around $_ necessary to handle filenames with shell metacharacters in)</em></p>\n\n<p>Now the <code>&lt;&gt;</code> feature will decompress any <code>@ARGV</code> files that end with \".gz\" or \".Z\":</p>\n\n<pre><code>while (&lt;&gt;) {\n print;\n}\n</code></pre>\n" }, { "answer_id": 163541, "author": "mpeters", "author_id": 12094, "author_profile": "https://Stackoverflow.com/users/12094", "pm_score": 5, "selected": false, "text": "<p>Not really hidden, but many every day Perl programmers don't know about <a href=\"http://search.cpan.org\" rel=\"nofollow noreferrer\">CPAN</a>. This especially applies to people who aren't full time programmers or don't program in Perl full time.</p>\n" }, { "answer_id": 163700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>The ability to parse data directly pasted into a <strong>DATA</strong> block. No need to save to a test file to be opened in the program or similar. For example:</p>\n\n<pre><code>my @lines = &lt;DATA&gt;;\nfor (@lines) {\n print if /bad/;\n}\n\n__DATA__\nsome good data\nsome bad data\nmore good data \nmore good data \n</code></pre>\n" }, { "answer_id": 163725, "author": "melo", "author_id": 24579, "author_profile": "https://Stackoverflow.com/users/24579", "pm_score": 2, "selected": false, "text": "<p>Safe compartments.</p>\n\n<p>With the Safe module you can build your own sandbox-style environment using nothing but perl. You would then be able to load perl scripts into the sandbox.</p>\n\n<p>Best regards,</p>\n" }, { "answer_id": 164217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>@Corion - Bare URLs in Perl? Of course you can, even in interpolated strings. The only time it would matter is in a string that you were actually USING as a regular expression.</p>\n" }, { "answer_id": 164255, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 2, "selected": false, "text": "<p>Core <a href=\"http://search.cpan.org/perldoc?IO::Handle\" rel=\"nofollow noreferrer\"><code>IO::Handle</code></a> module. Most important thing for me is that it allows autoflush on filehandles. Example:</p>\n\n<pre><code>use IO::Handle; \n$log-&gt;autoflush(1);\n</code></pre>\n" }, { "answer_id": 166230, "author": "Tomasz", "author_id": 10523, "author_profile": "https://Stackoverflow.com/users/10523", "pm_score": 0, "selected": false, "text": "<p>Showing progress in the script by printing on the same line:</p>\n\n<pre><code>$| = 1; # flush the buffer on the next output \n\nfor $i(1..100) {\n print \"Progress $i %\\r\"\n}\n</code></pre>\n" }, { "answer_id": 167309, "author": "brunorc", "author_id": 24853, "author_profile": "https://Stackoverflow.com/users/24853", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://perldoc.perl.org/functions/map.html\" rel=\"nofollow noreferrer\">map</a> - not only because it makes one's code more expressive, but because it gave me an impulse to read a little bit more about this \"functional programming\".</p>\n" }, { "answer_id": 167809, "author": "talexb", "author_id": 5649, "author_profile": "https://Stackoverflow.com/users/5649", "pm_score": 2, "selected": false, "text": "<p>How about the ability to use</p>\n\n<p><pre><code>my @symbols = map { +{ 'key' => $_ } } @things;</code></pre></p>\n\n<p>to generate an array of hashrefs from an array -- the + in front of the hashref disambiguates the block so the interpreter knows that it's a hashref and not a code block. Awesome.</p>\n\n<p>(Thanks to Dave Doyle for explaining this to me at the last Toronto Perlmongers meeting.)</p>\n" }, { "answer_id": 168925, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I don't know how esoteric it is, but one of my favorites is the <a href=\"http://www.webquills.net/scroll/2008/05/perl-5-hash-slices-can-replace.html\" rel=\"nofollow noreferrer\">hash slice</a>. I use it for all kinds of things. For example to merge two hashes:</p>\n\n<pre>\nmy %number_for = (one => 1, two => 2, three => 3);\nmy %your_numbers = (two => 2, four => 4, six => 6);\n@number_for{keys %your_numbers} = values %your_numbers;\nprint sort values %number_for; # 12346\n</pre>\n" }, { "answer_id": 168947, "author": "davidnicol", "author_id": 7420, "author_profile": "https://Stackoverflow.com/users/7420", "pm_score": 3, "selected": false, "text": "<p>tie, the variable tying interface.</p>\n" }, { "answer_id": 169592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>The continue clause on loops. It will be executed at the bottom of every loop, even those which are next'ed.</p>\n\n<pre><code>while( &lt;&gt; ){\n print \"top of loop\\n\";\n chomp;\n\n next if /next/i;\n last if /last/i;\n\n print \"bottom of loop\\n\";\n}continue{\n print \"continue\\n\";\n}\n</code></pre>\n" }, { "answer_id": 172118, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "<p>All right. Here is another. <a href=\"http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping\" rel=\"nofollow noreferrer\">Dynamic Scoping</a>. It was talked about a little in a different post, but I didn't see it here on the hidden features. </p>\n\n<p>Dynamic Scoping like Autovivification has a very limited amount of languages that use it. <strong>Perl and Common Lisp are the only two I know of that use Dynamic Scoping.</strong></p>\n" }, { "answer_id": 189883, "author": "Telemachus", "author_id": 26702, "author_profile": "https://Stackoverflow.com/users/26702", "pm_score": 2, "selected": false, "text": "<p>My favorite semi-hidden feature of Perl is the <code>eof</code> function. Here's an example pretty much directly from <code>perldoc -f eof</code> that shows how you can use it to reset the file name and <code>$.</code> (the current line number) easily across multiple files loaded up at the command line: </p>\n\n<pre><code>while (&lt;&gt;) {\n print \"$ARGV:$.\\t$_\";\n} \ncontinue {\n close ARGV if eof\n}\n</code></pre>\n" }, { "answer_id": 194796, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 1, "selected": false, "text": "<p>I'm a bit late to the party, but a vote for the built-in tied-hash function <code>dbmopen()</code> -- it's helped me a lot. It's not exactly a database, but if you need to save data to disk it takes away a lot of the problems and Just Works. It helped me get started when I didn't have a database, didn't understand Storable.pm, but I knew I wanted to progress beyond reading and writing to text files.</p>\n" }, { "answer_id": 205104, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "<p>The \"desperation mode\" of Perl's loop control constructs which causes them to look up the stack to find a matching label allows some curious behaviors which Test::More takes advantage of, for better or worse.</p>\n\n<pre><code>SKIP: {\n skip() if $something;\n\n print \"Never printed\";\n}\n\nsub skip {\n no warnings \"exiting\";\n last SKIP;\n}\n</code></pre>\n\n<p>There's the little known .pmc file. \"use Foo\" will look for Foo.pmc in @INC before Foo.pm. This was intended to allow compiled bytecode to be loaded first, but <a href=\"http://search.cpan.org/dist/Module-Compile\" rel=\"nofollow noreferrer\">Module::Compile</a> takes advantage of this to cache source filtered modules for faster load times and easier debugging.</p>\n\n<p>The ability to turn warnings into errors.</p>\n\n<pre><code>local $SIG{__WARN__} = sub { die @_ };\n$num = \"two\";\n$sum = 1 + $num;\nprint \"Never reached\";\n</code></pre>\n\n<p>That's what I can think of off the top of my head that hasn't been mentioned.</p>\n" }, { "answer_id": 205627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>($x, $y) = ($y, $x) is what made me want to learn Perl.</p>\n\n<p>The list constructor 1..99 or 'a'..'zz' is also very nice.</p>\n" }, { "answer_id": 243146, "author": "Guillaume Gervais", "author_id": 10687, "author_profile": "https://Stackoverflow.com/users/10687", "pm_score": 2, "selected": false, "text": "<p>You can replace the delimiter in regexes and strings with just about anything else. This is particularly useful for \"leaning toothpick syndrome\", exemplified here:</p>\n\n<pre><code>$url =~ /http:\\/\\/www\\.stackoverflow\\.com\\//;\n</code></pre>\n\n<p>You can eliminate most of the back-whacking by changing the delimiter. <code>/bar/</code> is shorthand for <code>m/bar/</code> which is the same as <code>m!bar!</code>.</p>\n\n<pre><code>$url =~ m!http://www\\.stackoverflow\\.com/!;\n</code></pre>\n\n<p>You can even use balanced delimiters like {} and []. I personally love these. <code>q{foo}</code> is the same as <code>'foo'</code>.</p>\n\n<pre><code>$code = q{\n if( this is awesome ) {\n print \"Look ma, no escaping!\";\n }\n};\n</code></pre>\n\n<p>To confuse your friends (and your syntax highlighter) try this:</p>\n\n<pre><code>$string = qq'You owe me $1,000 dollars!';\n</code></pre>\n" }, { "answer_id": 302384, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Use lvalues to make your code really confusing:</p>\n\n<pre><code>my $foo = undef ;\nsub bar:lvalue{ return $foo ;}\n\n# Then later\n\nbar = 5 ;\nprint bar ;\n</code></pre>\n" }, { "answer_id": 310083, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 2, "selected": false, "text": "<p>Very late to the party, but: attributes.</p>\n\n<p>Attributes essentially let you define arbitrary code to be associated with the declaration of a variable or subroutine. The best way to use these is with <a href=\"http://search.cpan.org/perldoc?Attribute::Handlers\" rel=\"nofollow noreferrer\">Attribute::Handlers</a>; this makes it easy to define attributes (in terms of, what else, attributes!).</p>\n\n<p>I did a presentation on using them to declaratively assemble a pluggable class and its plugins at YAPC::2006, online <a href=\"http://www.ibiblio.org/mcmahon/talks/designing4pluggability/\" rel=\"nofollow noreferrer\">here</a>. This is a pretty unique feature.</p>\n" }, { "answer_id": 479046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One more...</p>\n\n<p>Perl cache:</p>\n\n<pre><code>my $processed_input = $records || process_inputs($records_file);\n</code></pre>\n\n<p>On Elpeleg\nOpen Source, Perl CMS\n<a href=\"http://www.web-app.net/\" rel=\"nofollow noreferrer\">http://www.web-app.net/</a></p>\n" }, { "answer_id": 530460, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "<p>This one isn't particularly useful, but it's extremely esoteric. I stumbled on this while digging around in the Perl parser.</p>\n\n<p>Before there was POD, perl4 had a trick to allow you to embed the man page, as nroff, straight into your program so it wouldn't get lost. perl4 used a program called <a href=\"http://www.cpan.org/scripts/nutshell/ch6/wrapman\" rel=\"nofollow noreferrer\">wrapman</a> (see Pink Camel page 319 for some details) to cleverly embed an nroff man page into your script.</p>\n\n<p>It worked by telling nroff to ignore all the code, and then put the meat of the man page after an <strong>END</strong> tag which tells Perl to stop processing code. Looked something like this:</p>\n\n<pre><code>#!/usr/bin/perl\n'di';\n'ig00';\n\n...Perl code goes here, ignored by nroff...\n\n.00; # finish .ig\n\n'di \\\" finish the diversion\n.nr nl 0-1 \\\" fake up transition to first page\n.nr % 0 \\\" start at page 1\n'; __END__\n\n...man page goes here, ignored by Perl...\n</code></pre>\n\n<p>The details of the roff magic escape me, but you'll notice that the roff commands are strings or numbers in void context. Normally a constant in void context produces a warning. There are special exceptions in <code>op.c</code> to allow void context strings which start with certain roff commands.</p>\n\n<pre><code> /* perl4's way of mixing documentation and code\n (before the invention of POD) was based on a\n trick to mix nroff and perl code. The trick was\n built upon these three nroff macros being used in\n void context. The pink camel has the details in\n the script wrapman near page 319. */\n const char * const maybe_macro = SvPVX_const(sv);\n if (strnEQ(maybe_macro, \"di\", 2) ||\n strnEQ(maybe_macro, \"ds\", 2) ||\n strnEQ(maybe_macro, \"ig\", 2))\n useless = NULL;\n</code></pre>\n\n<p>This means that <code>'di';</code> doesn't produce a warning, but neither does <code>'die';</code> <code>'did you get that thing I sentcha?';</code> or <code>'ignore this line';</code>.</p>\n\n<p>In addition, there are exceptions for the numeric constants <code>0</code> and <code>1</code> which allows the bare <code>.00;</code>. The code claims this was for more general purposes.</p>\n\n<pre><code> /* the constants 0 and 1 are permitted as they are\n conventionally used as dummies in constructs like\n 1 while some_condition_with_side_effects; */\n else if (SvNIOK(sv) &amp;&amp; (SvNV(sv) == 0.0 || SvNV(sv) == 1.0))\n useless = NULL;\n</code></pre>\n\n<p>And what do you know, <code>2 while condition</code> does warn!</p>\n" }, { "answer_id": 530538, "author": "Chris Lutz", "author_id": 60777, "author_profile": "https://Stackoverflow.com/users/60777", "pm_score": 2, "selected": false, "text": "<p>I personally love the /e modifier to the s/// operation:</p>\n\n<pre><code>while(&lt;&gt;) {\n s/(\\w{0,4})/reverse($1);/e; # reverses all words between 0 and 4 letters\n print;\n}\n</code></pre>\n\n<p>Input:</p>\n\n<pre><code>This is a test of regular expressions\n^D\n</code></pre>\n\n<p>Output (I think):</p>\n\n<pre><code>sihT si a tset fo regular expressions\n</code></pre>\n" }, { "answer_id": 547210, "author": "timkay", "author_id": 24558, "author_profile": "https://Stackoverflow.com/users/24558", "pm_score": 1, "selected": false, "text": "<p>You might think you can do this to save memory:</p>\n\n<pre><code>@is_month{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = undef;\n\nprint \"It's a month\" if exists $is_month{lc $mon};\n</code></pre>\n\n<p>but it doesn't do that. Perl still assigns a different scalar value to each key. <a href=\"http://search.cpan.org/perldoc?Devel::Peek\" rel=\"nofollow noreferrer\">Devel::Peek</a> shows this. <code>PVHV</code> is the hash. <code>Elt</code> is a key and the <code>SV</code> that follows is its value. Note that each SV has a different memory address indicating they're not being shared.</p>\n\n<pre><code>Dump \\%is_month, 12;\n\nSV = RV(0x81c1bc) at 0x81c1b0\n REFCNT = 1\n FLAGS = (TEMP,ROK)\n RV = 0x812480\n SV = PVHV(0x80917c) at 0x812480\n REFCNT = 2\n FLAGS = (SHAREKEYS)\n ARRAY = 0x206f20 (0:8, 1:4, 2:4)\n hash quality = 101.2%\n KEYS = 12\n FILL = 8\n MAX = 15\n RITER = -1\n EITER = 0x0\n Elt \"feb\" HASH = 0xeb0d8580\n SV = NULL(0x0) at 0x804b40\n REFCNT = 1\n FLAGS = ()\n Elt \"may\" HASH = 0xf2290c53\n SV = NULL(0x0) at 0x812420\n REFCNT = 1\n FLAGS = ()\n</code></pre>\n\n<p>An undef scalar takes as much memory as an integer scalar, so you might ask well just assign them all to 1 and avoid the trap of forgetting to check with <code>exists</code>.</p>\n\n<pre><code>my %is_month = map { $_ =&gt; 1 } qw(jan feb mar apr may jun jul aug sep oct nov dec);\n\nprint \"It's a month\" if $is_month{lc $mon});\n</code></pre>\n" }, { "answer_id": 686725, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 3, "selected": false, "text": "<pre><code>use diagnostics;\n</code></pre>\n\n<p>If you are starting to work with Perl and have never done so before, this module will save you tons of time and hassle. For almost every basic error message you can get, this module will give you a lengthy explanation as to why your code is breaking, including some helpful hints as to how to fix it. For example:</p>\n\n<pre><code>use strict;\nuse diagnostics;\n\n$var = \"foo\";\n</code></pre>\n\n<p>gives you this helpful message:</p>\n\n<pre>\nGlobal symbol \"$var\" requires explicit package name at - line 4.\nExecution of - aborted due to compilation errors (#1)\n (F) You've said \"use strict vars\", which indicates that all variables\n must either be lexically scoped (using \"my\"), declared beforehand using\n \"our\", or explicitly qualified to say which package the global variable\n is in (using \"::\").\n\nUncaught exception from user code:\n Global symbol \"$var\" requires explicit package name at - line 4.\nExecution of - aborted due to compilation errors.\n at - line 5\n</pre>\n\n<pre><code>use diagnostics;\nuse strict;\n\nsub myname {\n print { \" Some Error \" };\n};\n</code></pre>\n\n<p>you get this large, helpful chunk of text:</p>\n\n<pre>\nsyntax error at - line 5, near \"};\"\nExecution of - aborted due to compilation errors (#1)\n(F) Probably means you had a syntax error. Common reasons include:\n\n A keyword is misspelled.\n A semicolon is missing.\n A comma is missing.\n An opening or closing parenthesis is missing.\n An opening or closing brace is missing.\n A closing quote is missing.\n\nOften there will be another error message associated with the syntax\nerror giving more information. (Sometimes it helps to turn on -w.)\nThe error message itself often tells you where it was in the line when\nit decided to give up. Sometimes the actual error is several tokens\nbefore this, because Perl is good at understanding random input.\nOccasionally the line number may be misleading, and once in a blue moon\nthe only way to figure out what's triggering the error is to call\nperl -c repeatedly, chopping away half the program each time to see\nif the error went away. Sort of the cybernetic version of S.\n\nUncaught exception from user code:\n syntax error at - line 5, near \"};\"\nExecution of - aborted due to compilation errors.\nat - line 7\n</pre>\n\n<p>From there you can go about deducing what might be wrong with your program (in this case, print is formatted entirely wrong). There's a large number of known errors with diagnostics. Now, while this would not be a good thing to use in production, it can serve as a great learning aid for those who are new to Perl.</p>\n" }, { "answer_id": 931133, "author": "user105090", "author_id": 105090, "author_profile": "https://Stackoverflow.com/users/105090", "pm_score": 3, "selected": false, "text": "<p>You can use @{[...]} to get an interpolated result of complex perl expressions</p>\n\n<pre><code>$a = 3;\n$b = 4;\n\nprint \"$a * $b = @{[$a * $b]}\";\n</code></pre>\n\n<p>prints: <code>3 * 4 = 12</code></p>\n" }, { "answer_id": 931169, "author": "Chas. Owens", "author_id": 78259, "author_profile": "https://Stackoverflow.com/users/78259", "pm_score": 3, "selected": false, "text": "<p>The goatse operator<code>*</code>:</p>\n\n<pre><code>$_ = \"foo bar\";\nmy $count =()= /[aeiou]/g; #3\n</code></pre>\n\n<p>or </p>\n\n<pre><code>sub foo {\n return @_;\n}\n\n$count =()= foo(qw/a b c d/); #4\n</code></pre>\n\n<p>It works because list assignment in scalar context yields the number of elements in the list being assigned.</p>\n\n<p><code>*</code> Note, not really an operator</p>\n" }, { "answer_id": 1026982, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The input record separator can be set to a reference to a number to read fixed length records:</p>\n\n<pre><code>$/ = \\3; print $_,\"\\n\" while &lt;&gt;; # output three chars on each line\n</code></pre>\n" }, { "answer_id": 1059420, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following are just as short but more meaningful than \"~~\" since they indicate what is returned, and there's no confusion with the smart match operator:</p>\n\n<pre><code>print \"\".localtime; # Request a string\n\nprint 0+@array; # Request a number\n</code></pre>\n" }, { "answer_id": 1105711, "author": "Dario", "author_id": 105459, "author_profile": "https://Stackoverflow.com/users/105459", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~dconway/Quantum-Superpositions-1.03/lib/Quantum/Superpositions.pm\" rel=\"nofollow noreferrer\"><code>Quantum::Superpositions</code></a></p>\n\n<pre><code>use Quantum::Superpositions;\n\nif ($x == any($a, $b, $c)) { ... }\n</code></pre>\n" }, { "answer_id": 1270366, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"nofollow noreferrer\">Schwartzian Transform</a> is a technique that allows you to efficiently sort by a computed, secondary index. Let's say that you wanted to sort a list of strings by their md5 sum. The comments below are best read backwards (that's the order I always end up writing these anyways):</p>\n\n<pre><code>my @strings = ('one', 'two', 'three', 'four');\n\nmy $md5sorted_strings = \n map { $_-&gt;[0] } # 4) map back to the original value\n sort { $a-&gt;[1] cmp $b-&gt;[1] } # 3) sort by the correct element of the list\n map { [$_, md5sum_func($_)] } # 2) create a list of anonymous lists\n @strings # 1) take strings\n</code></pre>\n\n<p>This way, you only have to do the expensive md5 computation N times, rather than N log N times.</p>\n" }, { "answer_id": 1380565, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 0, "selected": false, "text": "<p>$0 is the name of the perl script being executed. It can be used to get the context from which a module is being run.</p>\n\n<pre><code># MyUsefulRoutines.pl\n\nsub doSomethingUseful {\n my @args = @_;\n # ...\n}\n\nif ($0 =~ /MyUsefulRoutines.pl/) {\n # someone is running perl MyUsefulRoutines.pl [args] from the command line\n &amp;doSomethingUseful (@ARGV);\n} else {\n # someone is calling require \"MyUsefulRoutines.pl\" from another script\n 1;\n}\n</code></pre>\n\n<p>This idiom is helpful for treating a standalone script with some useful subroutines into a library that can be imported into other scripts. Python has similar functionality with the <code>object.__name__ == \"__main__\"</code> idiom.</p>\n" }, { "answer_id": 1548716, "author": "Kiffin", "author_id": 178045, "author_profile": "https://Stackoverflow.com/users/178045", "pm_score": 1, "selected": false, "text": "<p>The expression <code>defined &amp;DB::DB</code> returns true if the program is running from within the debugger.</p>\n" }, { "answer_id": 1653812, "author": "Eric Strom", "author_id": 189416, "author_profile": "https://Stackoverflow.com/users/189416", "pm_score": 2, "selected": false, "text": "<p>One useful composite operator for conditionally adding strings or lists into other lists is the <code>x!!</code>operator:</p>\n\n<pre><code> print 'the meaning of ', join ' ' =&gt; \n 'life,' x!! $self-&gt;alive,\n 'the universe,' x!! ($location ~~ Universe),\n ('and', 'everything.') x!! 42; # this is added as a list\n</code></pre>\n\n<p>this operator allows for a reversed syntax similar to</p>\n\n<pre><code> do_something() if test();\n</code></pre>\n" }, { "answer_id": 1681732, "author": "Erick", "author_id": 12251, "author_profile": "https://Stackoverflow.com/users/12251", "pm_score": 1, "selected": false, "text": "<p>Interpolation of match regular expressions. A useful application of this is when matching on a blacklist. Without using interpolation it is written like so:</p>\n\n<pre><code>#detecting blacklist words in the current line\n/foo|bar|baz/;\n</code></pre>\n\n<p>Can instead be written</p>\n\n<pre><code>@blacklistWords = (\"foo\", \"bar\", \"baz\");\n$anyOfBlacklist = join \"|\", (@blacklistWords);\n/$anyOfBlacklist/;\n</code></pre>\n\n<p>This is more verbose, but allows for population from a datafile. Also if the list is maintained in the source for whatever reason, it is easier to maintain the array then the RegExp.</p>\n" }, { "answer_id": 1762916, "author": "Nick Dixon", "author_id": 52958, "author_profile": "https://Stackoverflow.com/users/52958", "pm_score": 1, "selected": false, "text": "<p>Using hashes (where keys are unique) to obtain the unique elements of a list:</p>\n\n<pre><code>my %unique = map { $_ =&gt; 1 } @list;\nmy @unique = keys %unique;\n</code></pre>\n" }, { "answer_id": 2062632, "author": "Eric Strom", "author_id": 189416, "author_profile": "https://Stackoverflow.com/users/189416", "pm_score": 0, "selected": false, "text": "<p>using bare blocks with <code>redo</code> or other control words to create custom looping constructs.</p>\n\n<p>traverse a linked list of objects returning the first <code>-&gt;can('print')</code> method:</p>\n\n<pre><code>sub get_printer {\n my $self = shift;\n {$self-&gt;can('print') or $self = $self-&gt;next and redo}\n}\n</code></pre>\n" }, { "answer_id": 2136296, "author": "Peter", "author_id": 227491, "author_profile": "https://Stackoverflow.com/users/227491", "pm_score": 1, "selected": false, "text": "<p>Add one for the unpack() and pack() functions, which are great if you need to import and/or export data in a format which is used by other programs.</p>\n\n<p>Of course these days most programs will allow you to export data in XML, and many commonly used proprietary document formats have associated Perl modules written for them. But this is one of those features that is incredibly useful when you need it, and pack()/unpack() are probably the <em>reason</em> that people have been able to write CPAN modules for so many proprietary data formats.</p>\n" }, { "answer_id": 2628795, "author": "Alexey", "author_id": 281140, "author_profile": "https://Stackoverflow.com/users/281140", "pm_score": 2, "selected": false, "text": "<p>There is a more powerful way to check program for syntax errors:</p>\n\n<pre><code>perl -w -MO=Lint,no-context myscript.pl\n</code></pre>\n\n<p>The most important thing that it can do is reporting for 'unexistant subroutine' errors.</p>\n" }, { "answer_id": 2655810, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 2, "selected": false, "text": "<p><code>use re debug</code><br>\n<a href=\"http://perldoc.perl.org/re.html\" rel=\"nofollow noreferrer\">Doc on use re debug</a></p>\n\n<p>and </p>\n\n<p><code>perl -MO=Concise[,OPTIONS]</code><br>\n<a href=\"http://perldoc.perl.org/B/Concise.html\" rel=\"nofollow noreferrer\">Doc on Concise</a></p>\n\n<p>Besides being exquisitely flexible, expressive and amenable to programing in the style of C, Pascal, Python and other languages, there are several pragmas command switches that make Perl my 'goto' language for initial kanoodling on an algorithm, regex, or quick problems that needs to be solved. These two are unique to Perl I believe, and are among my favorites. </p>\n\n<p><code>use re debug</code>:\nMost modern flavors of regular expressions owe their current form and function to Perl. While there are many Perl forms of regex that cannot be expressed in other languages, there are almost no forms of other languages' flavor of regex that cannot be expressed in Perl. Additionally, Perl has a wonderful regex debugger built in to show how the regex engine is interpreting your regex and matching against the target string. </p>\n\n<p>Example: I recently was trying to write a simple CSV routine. (Yes, yes, I know, I should have been using <a href=\"http://search.cpan.org/~ALANCITT/Text-CSV-0.01/CSV.pm\" rel=\"nofollow noreferrer\">Text::CSV...</a>) but the CSV values were not quoted and simple. </p>\n\n<p>My first take was <code>/^(^(?:(.*?),){$i}/</code> to extract the i record on n CSV records. That works fine -- except for the last record or n of n. I could see that without the debugger.</p>\n\n<p>Next I tried <code>/^(?:(.*?),|$){$i}/</code> This did not work, and I could not see immediately why. I thought I was saying <code>(.*?)</code> followed by a comma or EOL. Then I added <code>use re debug</code> at the top of a small test script. Ahh yes, the alteration between <code>,|$</code> was not being interpreted that way; it was being interpreted as <code>((.*?),) | ($)</code> -- not what I wanted. </p>\n\n<p><a href=\"http://perldoc.perl.org/perlrequick.html#Grouping-things-and-hierarchical-matching\" rel=\"nofollow noreferrer\">A new grouping was needed</a>. So I arrived at the working <code>/^(?:(.*?)(?:,|$)){$i}/</code>. While I was in the regex debugger, I was surprised how many loops it took for a match towards the end of the string. It is the <code>.*?</code> term that is quite ambiguous and requires excessive backtracking to satisfy. So I tried <code>/^(?:(?:^|,)([^,]*)){$i}/</code> This does two things: 1) reduces backtracking because of the greedy match of all but a comma 2) allowed the regex optimizer to only use the alteration once on the first field. Using Benchmark, this is 35% faster than the first regex. The regex debugger is wonderful and few use it.</p>\n\n<p><code>perl -MO=Concise[,OPTIONS]</code>:\nThe B and Concise frameworks are tremendous tools to see how Perl is interpreting your masterpiece. Using the <code>-MO=Concise</code> prints the result of the Perl interpreters translation of your source code. There are many options to Concise and in B, you can write your own presentation of the OP codes. </p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/885908/while-1-vs-for-is-there-a-speed-difference/885951#885951\">in this post</a>, you can use Concise to compare different code structures. You can interleave your source lines with the OP codes those lines generate. Check it out.</p>\n" }, { "answer_id": 2911357, "author": "Danny Woods", "author_id": 350695, "author_profile": "https://Stackoverflow.com/users/350695", "pm_score": 2, "selected": false, "text": "<p>Two things that work well together: IO handles on in-core strings, and using function prototypes to enable you to write your own functions with grep/map-like syntax.</p>\n\n<pre><code>sub with_output_to_string(&amp;) { # allows compiler to accept \"yoursub {}\" syntax.\n my $function = shift;\n my $string = '';\n my $handle = IO::Handle-&gt;new();\n open($handle, '&gt;', \\$string) || die $!; # IO handle on a plain scalar string ref\n my $old_handle = select $handle;\n eval { $function-&gt;() };\n select $old_handle;\n die $@ if $@;\n return $string;\n}\n\nmy $greeting = with_output_to_string {\n print \"Hello, world!\";\n};\n\nprint $greeting, \"\\n\";\n</code></pre>\n" }, { "answer_id": 2911832, "author": "Terry", "author_id": 68338, "author_profile": "https://Stackoverflow.com/users/68338", "pm_score": 0, "selected": false, "text": "<p>Perl is great as a flexible awk/sed. </p>\n\n<p>For example lets use a simple replacement for <code>ls | xargs stat</code>, naively done like: </p>\n\n<pre><code>$ ls | perl -pe 'print \"stat \"' | sh \n</code></pre>\n\n<p>This doesn't work well when the input (filenames) have spaces or shell special characters like <code>|$\\</code>. So single quotes are frequently required in the Perl output.</p>\n\n<p>One complication with calling perl via the command line <code>-ne</code> is that the shell gets first nibble at your one-liner. This often leads to torturous escaping to satisfy it.</p>\n\n<p>One 'hidden' feature that I use all the time is <strong><code>\\x27</code></strong> to include a single quote instead of trying to use shell escaping <code>'\\''</code></p>\n\n<p>So:</p>\n\n<pre><code>$ ls | perl -nle 'chomp; print \"stat '\\''$_'\\''\"' | sh\n</code></pre>\n\n<p>can be more safely written:</p>\n\n<pre><code>$ ls | perl -pe 's/(.*)/stat \\x27$1\\x27/' | sh\n</code></pre>\n\n<p>That won't work with funny characters in the filenames, even quoted like that. But this will:</p>\n\n<pre><code>$ ls | perl -pe 's/\\n/\\0/' | xargs -0 stat\n</code></pre>\n" }, { "answer_id": 2911882, "author": "Mark Maunder", "author_id": 350768, "author_profile": "https://Stackoverflow.com/users/350768", "pm_score": 1, "selected": false, "text": "<p>Next time you're at a geek party pull out this one-liner in a bash shell and the women will swarm you and your friends will worship you:</p>\n\n<p>find . -name \"*.txt\"|xargs perl -pi -e 's/1:(\\S+)/uc($1)/ge'</p>\n\n<p>Process all *.txt files and do an in-place find and replace using perl's regex. This one converts text after a '1:' to upper case and removes the '1:'. Uses Perl's 'e' modifier to treat the second part of the find/replace regex as executable code. Instant one-line template system. Using xargs lets you process a huge number of files without running into bash's command line length limit. </p>\n" }, { "answer_id": 2912104, "author": "Jauder Ho", "author_id": 26366, "author_profile": "https://Stackoverflow.com/users/26366", "pm_score": 2, "selected": false, "text": "<p>The ability to use a hash as a seen filter in a loop. I have yet to see something quite as nice in a different language. For example, I have not been able to duplicate this in python.</p>\n\n<p>For example, I want to print a line if it has not been seen before. </p>\n\n<pre><code>my %seen;\n\nfor (&lt;LINE&gt;) {\n print $_ unless $seen{$_}++;\n}\n</code></pre>\n" }, { "answer_id": 2912459, "author": "knb", "author_id": 202553, "author_profile": "https://Stackoverflow.com/users/202553", "pm_score": 2, "selected": false, "text": "<p>The new -E option on the command line: </p>\n\n<pre><code>&gt; perl -e \"say 'hello\"\" # does not work \n\nString found where operator expected at -e line 1, near \"say 'hello'\"\n (Do you need to predeclare say?)\nsyntax error at -e line 1, near \"say 'hello'\"\nExecution of -e aborted due to compilation errors.\n\n&gt; perl -E \"say 'hello'\" \nhello\n</code></pre>\n" }, { "answer_id": 2913535, "author": "trapd00r", "author_id": 227697, "author_profile": "https://Stackoverflow.com/users/227697", "pm_score": 2, "selected": false, "text": "<p>You can expand function calls in a string, for example;</p>\n\n<pre><code>print my $foo = \"foo @{[scalar(localtime)]} bar\";\n</code></pre>\n\n<blockquote>\n <p>foo Wed May 26 15:50:30 2010 bar</p>\n</blockquote>\n" }, { "answer_id": 2913693, "author": "Justin", "author_id": 201853, "author_profile": "https://Stackoverflow.com/users/201853", "pm_score": 2, "selected": false, "text": "<p>You can use different quotes on HEREDOCS to get different behaviors.</p>\n\n<pre><code>my $interpolation = \"We will interpolated variables\";\nprint &lt;&lt;\"END\";\nWith double quotes, $interpolation, just like normal HEREDOCS.\nEND\n\nprint &lt;&lt;'END';\nWith single quotes, the variable $foo will *not* be interpolated.\n(You have probably seen this in other languages.)\nEND\n\n## this is the fun and \"hidden\" one\nmy $shell_output = &lt;&lt;`END`;\necho With backticks, these commands will be executed in shell.\necho The output is returned.\nls | wc -l\nEND\n\nprint \"shell output: $shell_output\\n\";\n</code></pre>\n" }, { "answer_id": 3526979, "author": "wolverian", "author_id": 245704, "author_profile": "https://Stackoverflow.com/users/245704", "pm_score": 3, "selected": false, "text": "<p>@Schwern mentioned turning warnings into errors by localizing <code>$SIG{__WARN__}</code>. You can do also do this (lexically) with <code>use warnings FATAL =&gt; \"all\";</code>. See <code>perldoc lexwarn</code>.</p>\n\n<p>On that note, since Perl 5.12, you've been able to say <code>perldoc foo</code> instead of the full <code>perldoc perlfoo</code>. Finally! :)</p>\n" }, { "answer_id": 3653228, "author": "Jet", "author_id": 348008, "author_profile": "https://Stackoverflow.com/users/348008", "pm_score": 0, "selected": false, "text": "<p>\"now\"</p>\n\n<pre><code>sub _now { \n my ($now) = localtime() =~ /([:\\d]{8})/;\n return $now;\n}\n\nprint _now(), \"\\n\"; # 15:10:33\n</code></pre>\n" }, { "answer_id": 5630109, "author": "gdey", "author_id": 73494, "author_profile": "https://Stackoverflow.com/users/73494", "pm_score": 2, "selected": false, "text": "<p>The feature I like the best is statement modifiers.</p>\n\n<p>Don't know how many times I've wanted to do:</p>\n\n<pre><code>say 'This will output' if 1;\nsay 'This will not output' unless 1;\nsay 'Will say this 3 times. The first Time: '.$_ for 1..3;\n</code></pre>\n\n<p>in other languages.\netc...</p>\n\n<p>The 'etc' reminded me of another 5.12 feature, the Yada Yada operator.</p>\n\n<p>This is great, for the times when you just want a place holder.</p>\n\n<pre><code>sub something_really_important_to_implement_later {\n ...\n} \n</code></pre>\n\n<p>Check it out: <a href=\"http://perldoc.perl.org/perlop.html#The-Triple-Dot-Operator\" rel=\"nofollow\">Perl Docs on Yada Yada Operator</a>.</p>\n" }, { "answer_id": 6244313, "author": "maasha", "author_id": 764601, "author_profile": "https://Stackoverflow.com/users/764601", "pm_score": 2, "selected": false, "text": "<p>This one-liner illustrates how to use glob to generate all word combinations of an alphabet (A, T, C, and G -> DNA) for words of a specified length (4):</p>\n\n<pre><code>perl -MData::Dumper -e '@CONV = glob( \"{A,T,C,G}\" x 4 ); print Dumper( \\@CONV )'\n</code></pre>\n" }, { "answer_id": 6631997, "author": "Balbir Singh", "author_id": 812536, "author_profile": "https://Stackoverflow.com/users/812536", "pm_score": -1, "selected": false, "text": "<p>I like the way we can insert a element in any place in the array, such as</p>\n\n<p>=> Insert $x in position $i in array @a</p>\n\n<pre><code>@a = ( 11, 22, 33, 44, 55, 66, 77 );\n$x = 10;\n$i = 3;\n\n@a = ( @a[0..$i-1], $x, @a[$i..$#a] );\n</code></pre>\n" }, { "answer_id": 8842278, "author": "Prakash K", "author_id": 159470, "author_profile": "https://Stackoverflow.com/users/159470", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~flora/perl-5.14.2/dist/B-Deparse/Deparse.pm\" rel=\"nofollow\">B::Deparse</a> - Perl compiler backend to produce perl code. Not something you'd use in your daily Perl coding, but could be useful in special circumstances.</p>\n\n<p>If you come across some piece of code that is obfuscated, or a complex expression, pass it through <code>Deparse</code>. Useful to figure out a JAPH or a Perl code that is golfed.</p>\n\n<pre><code>$ perl -e '$\"=$,;*{;qq{@{[(A..Z)[qq[0020191411140003]=~m[..]g]]}}}=*_=sub{print/::(.*)/};$\\=$/;q&lt;Just another Perl Hacker&gt;-&gt;();'\nJust another Perl Hacker\n\n$ perl -MO=Deparse -e '$\"=$,;*{;qq{@{[(A..Z)[qq[0020191411140003]=~m[..]g]]}}}=*_=sub{print/::(.*)/};$\\=$/;q&lt;Just another Perl Hacker&gt;-&gt;();'\n$\" = $,;\n*{\"@{[('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')['0020191411140003' =~ /../g]];}\";} = *_ = sub {\n print /::(.*)/;\n}\n;\n$\\ = $/;\n'Just another Perl Hacker'-&gt;();\n-e syntax OK\n</code></pre>\n\n<p>A more useful example is to use deparse to find out the code behind a coderef, that you might have received from another module, or</p>\n\n<pre><code>use B::Deparse;\nmy $deparse = B::Deparse-&gt;new;\n$code = $deparse-&gt;coderef2text($coderef);\nprint $code;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ]
What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work? Guidelines: * Try to limit answers to the Perl core and not CPAN * Please give an example and a short description --- Hidden Features also found in other languages' Hidden Features: --------------------------------------------------------------- (These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257)) * [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#) + Duff's Device + Portability and Standardness * [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) + Quotes for whitespace delimited lists and strings + Aliasable namespaces * [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java) + Static Initalizers * [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript) + Functions are First Class citizens + Block scope and closure + Calling methods and accessors indirectly through a variable * [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby) + Defining methods through code * [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php) + Pervasive online documentation + Magic methods + Symbolic references * [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python) + One line value swapping + Ability to replace even core functions with your own functionality Other Hidden Features: ---------------------- Operators: * [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094) * [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058) + Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627) * [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004) * [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075) * [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943) * [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239) * [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152) * [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249) * [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060) Quoting constructs: * [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416) * [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094) * [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374) Syntax and Names: * [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094) * [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094) * [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416) * [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601) * [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925) * [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254) Modules, Pragmas, and command-line options: * [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440) * [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440) * [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085) * [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541) * [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601) * [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255) * [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725) * [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083) Variables: * [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357) * [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985) * [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947) * [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118) * [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627) Loops and flow control: * [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440) * [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481) * [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592) * [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104) Regular expressions: * [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565) * [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976) Other features: * [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440) * [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206) * [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700) * [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601) * [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601) * [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601) * [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809)) * [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842) * [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883) * [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796) * [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104) Other tricks, and meta-answers: * [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532) * [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271) --- **See Also:** * [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c) * [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) * [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c) * [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java) * [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript) * [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby) * [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php) * [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python) * [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure)
The flip-flop operator is useful for skipping the first iteration when looping through the records (usually lines) returned by a file handle, without using a flag variable: ``` while(<$fh>) { next if 1..1; # skip first record ... } ``` Run `perldoc perlop` and search for "flip-flop" for more information and examples.
161,873
<p>I'm working on the K&amp;R book. I've read farther ahead than I've done exercises, mostly for lack of time. I'm catching up, and have done almost all the exercises from chapter 1, which is the tutorial.</p> <p>My issue was exercise 1-18. The exercise is to:</p> <blockquote> <p>Write a program to remove trailing blanks and tabs from line of input, and to delete entirely blank lines</p> </blockquote> <p>My code (below) does that, and works. My problem with it is the trim method I implemented. It feels ... wrong ... somehow. Like if I saw similar code in C# in a code review, I'd probably go nuts. (C# being one of my specialties.)</p> <p>Can anyone offer some advice on cleaning this up -- with the catch that said advice has to only use knowledge from Chapter 1 of K &amp; R. (I know there are a zillion ways to clean this up using the full C library; we're just talking Chapter 1 and basic stdio.h here.) Also, when giving the advice, can you explain why it will help? (I am, after all, trying to learn! And who better to learn from than the experts here?)</p> <pre><code>#include &lt;stdio.h&gt; #define MAXLINE 1000 int getline(char line[], int max); void trim(char line[], char ret[]); int main() { char line[MAXLINE]; char out[MAXLINE]; int length; while ((length = getline(line, MAXLINE)) &gt; 0) { trim(line, out); printf("%s", out); } return 0; } int getline(char line[], int max) { int c, i; for (i = 0; i &lt; max - 1 &amp;&amp; (c = getchar()) != EOF &amp;&amp; c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i; } void trim(char line[], char ret[]) { int i = 0; while ((ret[i] = line[i]) != '\0') ++i; if (i == 1) { // Special case to remove entirely blank line ret[0] = '\0'; return; } for ( ; i &gt;= 0; --i) { if (ret[i] == ' ' || ret[i] == '\t') ret[i] = '\0'; else if (ret[i] != '\0' &amp;&amp; ret[i] != '\r' &amp;&amp; ret[i] != '\n') break; } for (i = 0; i &lt; MAXLINE; ++i) { if (ret[i] == '\n') { break; } else if (ret[i] == '\0') { ret[i] = '\n'; ret[i + 1] = '\0'; break; } } } </code></pre> <p>EDIT: I appreciate all the helpful tips I'm seeing here. I would like to remind folks that I'm still a n00b with C, and specifically haven't gotten up to pointers yet. (Remember the bit about Ch.1 of K&amp;R -- Ch.1 doesn't do pointers.) I "kinda" get some of those solutions, but they're still a touch advanced for where I'm at ... </p> <p>And most of what I'm looking for is the trim method itself -- specifically the fact that I'm looping through <strong>3</strong> times (which feels so dirty). I feel like if I were just a touch more clever (even without the advanced knowledge of C), this could have been cleaner.</p>
[ { "answer_id": 161895, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": false, "text": "<p>If you are sticking with chapter 1, that looks pretty good to me. Here's what I would recommend from a code-review standpoint:</p>\n\n<p>When checking equality in C, always put the constant first</p>\n\n<pre><code>if (1 == myvar)\n</code></pre>\n\n<p>That way you will never accidentally do something like this:</p>\n\n<pre><code>if (myvar = 1)\n</code></pre>\n\n<p>You can't get away with that in C#, but it compiles fine in C and can be a real devil to debug.</p>\n" }, { "answer_id": 161935, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": true, "text": "<p>There is no reason to have two buffers, you can trim the input line in place</p>\n\n<pre><code>int trim(char line[])\n{\n int len = 0;\n for (len = 0; line[len] != 0; ++len)\n ;\n\n while (len &gt; 0 &amp;&amp;\n line[len-1] == ' ' &amp;&amp; line[len-1] == '\\t' &amp;&amp; line[len-1] == '\\n')\n line[--len] = 0;\n\n return len;\n}\n</code></pre>\n\n<p>By returning the line length, you can eliminate blank lines by testing for non-zero length lines</p>\n\n<pre><code>if (trim(line) != 0)\n printf(\"%s\\n\", line);\n</code></pre>\n\n<p>EDIT: You can make the while loop even simpler, assuming ASCII encoding.</p>\n\n<pre><code>while (len &gt; 0 &amp;&amp; line[len-1] &lt;= ' ')\n line[--len] = 0;\n</code></pre>\n" }, { "answer_id": 161974, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 1, "selected": false, "text": "<p>Personally for while constructs:</p>\n\n<p>I prefer the following:</p>\n\n<pre><code>while( (ret[i] = line[i]) )\n i++;\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>while ((ret[i] = line[i]) != '\\0')\n ++i;\n</code></pre>\n\n<p>They both check against != 0 but the first looks a little cleaner. If the char is anything other thah 0, then the loop body will execute else it will break out of the loop.</p>\n\n<p>Also for 'for' statements, whilst being syntatically valid, I find that the following:</p>\n\n<pre><code>for ( ; i &gt;= 0; --i)\n</code></pre>\n\n<p>just looks 'odd' to me and indeed is a potential nightmare solution for potential bugs. If I was reviewing this code, it would be like a glowing red warning like. Typically you want to use for loops for iterating a known number of times, otherwise cosider a while loop. (as always there are exceptions to the rule but Ive found that this generally holds true). The above for statement could become:</p>\n\n<pre><code>while (i)\n{\n if (ret[i] == ' ' || ret[i] == '\\t')\n {\n ret[i--] = '\\0';\n }\n else if (ret[i] != '\\0' &amp;&amp; ret[i] != '\\r' &amp;&amp; ret[i] != '\\n')\n {\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 162002, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "<p>First of all:</p>\n\n<blockquote>\n <p>int main(void)</p>\n</blockquote>\n\n<p>You know the parameters to main(). They're nothing. (Or argc&amp;argv, but I don't think that's Chapter 1 material.)</p>\n\n<p>Stylewise, you might want to try K&amp;R-style brackets. They're much easier on the vertical space:</p>\n\n<pre><code>void trim(char line[], char ret[])\n{\n int i = 0;\n\n while ((ret[i] = line[i]) != '\\0')\n ++i;\n\n if (i == 1) { // Special case to remove entirely blank line\n ret[0] = '\\0';\n return;\n }\n\n for (; i&gt;=0; --i) { //continue backwards from the end of the line\n if ((ret[i] == ' ') || (ret[i] == '\\t')) //remove trailing whitespace\n ret[i] = '\\0';\n\n else if ((ret[i] != '\\0') &amp;&amp; (ret[i] != '\\r') &amp;&amp; (ret[i] != '\\n')) //...until we hit a word character\n break;\n }\n\n for (i=0; i&lt;MAXLINE-1; ++i) { //-1 because we might need to add a character to the line\n if (ret[i] == '\\n') //break on newline\n break;\n\n if (ret[i] == '\\0') { //line doesn't have a \\n -- add it\n ret[i] = '\\n';\n ret[i+1] = '\\0';\n break;\n }\n }\n}\n</code></pre>\n\n<p>(Also added comments and fixed one bug.)</p>\n\n<p>A big issue is the usage of the MAXLINE constant -- main() exclusively uses it for the <em>line</em> and <em>out</em> variables; trim(), which is only working on them doesn't need to use the constant. You should pass the size(s) as a parameter just like you did in getline().</p>\n" }, { "answer_id": 162047, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p>trim() is too big.</p>\n\n<p>What I think you need is a strlen-ish function (go ahead and write it int stringlength(const char *s)).</p>\n\n<p>Then you need a function called int scanback(const char *s, const char *matches, int start) which starts at start, goes down to z as long as the character being scanned at s id contained in matches, return the last index where a match is found.</p>\n\n<p>Then you need a function called int scanfront(const char *s, const char *matches) which starts at 0 and scans forward as long as the character being scanned at s is contained in matches, returning the last index where a match is found.</p>\n\n<p>Then you need a function called int charinstring(char c, const char *s) which returns non-zero if c is contained in s, 0 otherwise.</p>\n\n<p>You should be able to write trim in terms of these.</p>\n" }, { "answer_id": 162226, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 0, "selected": false, "text": "<p>Here's my stab at the exercise without knowing what is in Chapter 1 or K &amp; R. I assume pointers?</p>\n\n<pre><code>#include \"stdio.h\"\n\nsize_t StrLen(const char* s)\n{\n // this will crash if you pass NULL\n size_t l = 0;\n const char* p = s;\n while(*p)\n {\n l++;\n ++p;\n }\n return l;\n}\n\nconst char* Trim(char* s)\n{\n size_t l = StrLen(s);\n if(l &lt; 1)\n return 0;\n\n char* end = s + l -1;\n while(s &lt; end &amp;&amp; (*end == ' ' || *end == '\\t'))\n {\n *end = 0;\n --end;\n }\n\n return s;\n}\n\nint Getline(char* out, size_t max)\n{\n size_t l = 0;\n char c;\n while(c = getchar())\n {\n ++l;\n\n if(c == EOF) return 0;\n if(c == '\\n') break;\n\n if(l &lt; max-1)\n {\n out[l-1] = c;\n out[l] = 0;\n }\n }\n\n return l;\n}\n\n#define MAXLINE 1024\n\nint main (int argc, char * const argv[]) \n{\n char line[MAXLINE];\n while (Getline(line, MAXLINE) &gt; 0)\n {\n const char* trimmed = Trim(line);\n if(trimmed)\n printf(\"|%s|\\n\", trimmed);\n\n line[0] = 0;\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 162266, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<p>Personally I'd put code like this:</p>\n\n<pre><code>ret[i] != '\\0' &amp;&amp; ret[i] != '\\r' &amp;&amp; ret[i] != '\\n'\n</code></pre>\n\n<p>into a separate function (or even a define macro)</p>\n" }, { "answer_id": 162329, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ol>\n<li>trim should indeed use 1 buffer only (as @Ferruccio says). </li>\n<li>trim needs to be broken up, as @plinth says</li>\n<li>trim needs not return any value (if you want to check for empty string, test line[0] == 0)</li>\n<li>for extra C flavor, use pointers rather than indexes</li>\n</ol>\n\n<p>-go to end of line (terminating 0;\n-while not at the start of line and current character is space, replace it with 0.\n-back off one char</p>\n\n<pre><code>char *findEndOfString(char *string) {\n while (*string) ++string;\n return string; // string is now pointing to the terminating 0\n}\n\nvoid trim(char *line) {\n char *end = findEndOfString(line);\n // note that we start at the first real character, not at terminating 0\n for (end = end-1; end &gt;= line; end--) {\n if (isWhitespace(*end)) *end = 0;\n else return;\n }\n}\n</code></pre>\n" }, { "answer_id": 164006, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Another example of doing the same thing. Did some minor violation by using C99-specific stuff. that will not be found in K&amp;R. also used the assert() function which is part of the starndard library, but is probably not covered in chapter one of K&amp;R.</p>\n\n<pre><code>#include &lt;stdbool.h&gt; /* needed when using bool, false and true. C99 specific. */\n#include &lt;assert.h&gt; /* needed for calling assert() */\n\ntypedef enum {\n TAB = '\\t',\n BLANK = ' '\n} WhiteSpace_e;\n\ntypedef enum {\n ENDOFLINE = '\\n',\n ENDOFSTRING = '\\0'\n} EndofLine_e;\n\nbool isWhiteSpace(\n char character\n) {\n if ( (BLANK == character) || (TAB == character ) ) {\n return true;\n } else {\n return false;\n }\n}\n\nbool isEndOfLine( \n char character\n) {\n if ( (ENDOFLINE == character) || (ENDOFSTRING == character ) ) {\n return true;\n } else {\n return false;\n }\n} \n\n/* remove blanks and tabs (i.e. whitespace) from line-string */\nvoid removeWhiteSpace(\n char string[]\n) {\n int i;\n int indexOutput;\n\n /* copy all non-whitespace character in sequential order from the first to the last.\n whitespace characters are not copied */\n i = 0;\n indexOutput = 0;\n while ( false == isEndOfLine( string[i] ) ) {\n if ( false == isWhiteSpace( string[i] ) ) {\n assert ( indexOutput &lt;= i );\n string[ indexOutput ] = string[ i ];\n indexOutput++;\n }\n i++; /* proceed to next character in the input string */\n }\n\n assert( isEndOfLine( string[ i ] ) );\n string[ indexOutput ] = ENDOFSTRING;\n\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
I'm working on the K&R book. I've read farther ahead than I've done exercises, mostly for lack of time. I'm catching up, and have done almost all the exercises from chapter 1, which is the tutorial. My issue was exercise 1-18. The exercise is to: > > Write a program to remove trailing blanks and > tabs from line of input, and to delete entirely blank lines > > > My code (below) does that, and works. My problem with it is the trim method I implemented. It feels ... wrong ... somehow. Like if I saw similar code in C# in a code review, I'd probably go nuts. (C# being one of my specialties.) Can anyone offer some advice on cleaning this up -- with the catch that said advice has to only use knowledge from Chapter 1 of K & R. (I know there are a zillion ways to clean this up using the full C library; we're just talking Chapter 1 and basic stdio.h here.) Also, when giving the advice, can you explain why it will help? (I am, after all, trying to learn! And who better to learn from than the experts here?) ``` #include <stdio.h> #define MAXLINE 1000 int getline(char line[], int max); void trim(char line[], char ret[]); int main() { char line[MAXLINE]; char out[MAXLINE]; int length; while ((length = getline(line, MAXLINE)) > 0) { trim(line, out); printf("%s", out); } return 0; } int getline(char line[], int max) { int c, i; for (i = 0; i < max - 1 && (c = getchar()) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i; } void trim(char line[], char ret[]) { int i = 0; while ((ret[i] = line[i]) != '\0') ++i; if (i == 1) { // Special case to remove entirely blank line ret[0] = '\0'; return; } for ( ; i >= 0; --i) { if (ret[i] == ' ' || ret[i] == '\t') ret[i] = '\0'; else if (ret[i] != '\0' && ret[i] != '\r' && ret[i] != '\n') break; } for (i = 0; i < MAXLINE; ++i) { if (ret[i] == '\n') { break; } else if (ret[i] == '\0') { ret[i] = '\n'; ret[i + 1] = '\0'; break; } } } ``` EDIT: I appreciate all the helpful tips I'm seeing here. I would like to remind folks that I'm still a n00b with C, and specifically haven't gotten up to pointers yet. (Remember the bit about Ch.1 of K&R -- Ch.1 doesn't do pointers.) I "kinda" get some of those solutions, but they're still a touch advanced for where I'm at ... And most of what I'm looking for is the trim method itself -- specifically the fact that I'm looping through **3** times (which feels so dirty). I feel like if I were just a touch more clever (even without the advanced knowledge of C), this could have been cleaner.
There is no reason to have two buffers, you can trim the input line in place ``` int trim(char line[]) { int len = 0; for (len = 0; line[len] != 0; ++len) ; while (len > 0 && line[len-1] == ' ' && line[len-1] == '\t' && line[len-1] == '\n') line[--len] = 0; return len; } ``` By returning the line length, you can eliminate blank lines by testing for non-zero length lines ``` if (trim(line) != 0) printf("%s\n", line); ``` EDIT: You can make the while loop even simpler, assuming ASCII encoding. ``` while (len > 0 && line[len-1] <= ' ') line[--len] = 0; ```
161,879
<p>Quite often in ANSI C code I can see parenthesis sorrounding a single return value. </p> <p>Like this:-</p> <pre><code>int foo(int x) { if (x) return (-1); else return (0); } </code></pre> <p>Why use () around the return value in those cases? Any ideas? I can see no reason for that.</p>
[ { "answer_id": 161894, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "<p>As often the case when using parenthesis, I think that's just for readability (e.g., Ruby supports method calls w/o parenthesis enclosing the arguments but recent books and articles advise otherwise).</p>\n" }, { "answer_id": 161899, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 7, "selected": true, "text": "<p>There really isn't a reason...it's just old convention.</p>\n\n<p>To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this:</p>\n\n<pre><code>return (x+i*2);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>int y = x+i*2;\nreturn y;\n</code></pre>\n\n<p>The parenthesis became a habit and it stuck.</p>\n" }, { "answer_id": 161992, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 5, "selected": false, "text": "<p>My personal style is to use parentheses if there is a complex expression; e.g.,</p>\n\n<pre><code>return (a + b);\n</code></pre>\n\n<p>but to not use them if the expression is a simple term</p>\n\n<pre><code>return a;\n</code></pre>\n\n<p>I can't say why I do it that way; just something I picked up long ago.</p>\n\n<p>By the way, I think that making it look like a function call, like this:</p>\n\n<pre><code>return(a); // ugh\n</code></pre>\n\n<p>is incredibly ugly and just wrong.</p>\n" }, { "answer_id": 162636, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 4, "selected": false, "text": "<p>There are a few reasons:</p>\n\n<ol>\n<li><p>if/while/for/etc. are all control keywords which must have parens. So it often seems natural to always put them on return too.</p></li>\n<li><p>sizeof is the only other keyword that can either have them or not, except that in some cases you <em>must</em> use parens. So it's easier to get into the habit of always using parens. for sizeof, which implies a logic of: if you can, always do.</p></li>\n<li><p>case/goto are the only keywords where you never use parens. ... and people tend to think of those as special cases (and like them both to stand out from other control keywords, esp. goto).</p></li>\n</ol>\n" }, { "answer_id": 164112, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 6, "selected": false, "text": "<p>A practical, but unlikely, motive is if you put parenthesis around the value, you can define return as a macro, and then insert some logging code to watch all your returns.</p>\n" }, { "answer_id": 164410, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "<p>I've worked with at least one programmer who thought return <em>was</em> some special sort of function call, and was suprised when he saw that my code complied without the parens.</p>\n" }, { "answer_id": 182760, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 3, "selected": false, "text": "<p>When returning -1 as in your excample, I think it's more readable with the parenthesis because the minus is more visible:</p>\n\n<pre><code>return 1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return -1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return (-1)\n</code></pre>\n" }, { "answer_id": 4762785, "author": "TonyK", "author_id": 428857, "author_profile": "https://Stackoverflow.com/users/428857", "pm_score": -1, "selected": false, "text": "<p>Using parentheses in a return statement shows a deficient grasp of <code>C/C++</code> syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:</p>\n\n<pre><code>int foo(int x) {\n if (x) {\n return (-1);\n }\n else {\n return (0);\n }\n}\n</code></pre>\n\n<p>So many programmers do this. If one of you reads this, perhaps you might like to explain.</p>\n" }, { "answer_id": 23298415, "author": "James Jones", "author_id": 1503446, "author_profile": "https://Stackoverflow.com/users/1503446", "pm_score": 3, "selected": false, "text": "<p>Perhaps it's custom--after all, the folks who brought us Unix and C came from the Multics project. Multics was written in PL/I, and in PL/I the parentheses are mandatory.</p>\n" }, { "answer_id": 36232426, "author": "Diogenes", "author_id": 6116674, "author_profile": "https://Stackoverflow.com/users/6116674", "pm_score": -1, "selected": false, "text": "<p>The Parenthesis in a return statement indicate to the compiler that you intend for this value to be returned on the stack instead of in memory.</p>\n\n<p>In the old days this was rigorously enforced(typically), but today most compilers only take it as a hint.</p>\n\n<p>This is something I do frequently, since an error could corrupt anything being returned via a memory reference, but typically wont effect a variable being returned on the stack.</p>\n\n<p>Using the stack for transient variables also cuts down on memory usage and typically makes the function call/return quicker because that's what the stack is designed for, transient data/variables.</p>\n" }, { "answer_id": 46867785, "author": "rakslice", "author_id": 60422, "author_profile": "https://Stackoverflow.com/users/60422", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://www.bell-labs.com/usr/dmr/www/cman.pdf#page=14\" rel=\"noreferrer\">In the original C specification, parentheses were required around the return value.</a> While modern C compilers and the ANSI C standard do not require them, the presence of parentheses does not affect the return value, and programmers sometimes still include them out of habit, unfamiliarity with the standards, for consistency with a stylistic convention that requires them, or possibly for backward compatibility.</p>\n\n<p>I should add, for people that are thinking about C++: <em>This</em> question is about C and C is not C++; these are two different languages with different standards, capabilities, levels of difficulty, and different styles of usage that emerge -- whatever they have in common, it is wise to treat them as two totally separate things. For a similar question that covers C++, see <a href=\"https://stackoverflow.com/questions/4762662/are-parentheses-around-the-result-significant-in-a-return-statement/25615981#25615981\">Are parentheses around the result significant in a return statement?</a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23864/" ]
Quite often in ANSI C code I can see parenthesis sorrounding a single return value. Like this:- ``` int foo(int x) { if (x) return (-1); else return (0); } ``` Why use () around the return value in those cases? Any ideas? I can see no reason for that.
There really isn't a reason...it's just old convention. To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this: ``` return (x+i*2); ``` instead of ``` int y = x+i*2; return y; ``` The parenthesis became a habit and it stuck.
161,884
<p>For those of you that like puzzles: I had this problem recently and am sure there must be a nicer solution.</p> <p>Consider :</p> <ul> <li>an ObservableCollection of <strong>Foo</strong> objects called <em>foos</em>.</li> <li><strong>Foo</strong> contains a string ID field</li> <li>I have no control over <em>foos</em></li> <li><em>foos</em> will be changing</li> </ul> <p>Then:</p> <ul> <li>I have another collection called <em>sortLikeThis</em></li> <li><em>sortListThis</em> contains strings</li> <li>The strings are the IDs in the order in which the <em>foos</em> are to be shown</li> </ul> <p>Plus:</p> <ul> <li>There may be objects in <em>foos</em> with an ID that is not in <em>sortLikeThis</em>. These need to go at the end.</li> <li>Likewise, there may be strings in <em>sortLikeThis</em> that do not appear in <em>foos</em>.</li> </ul> <p>Is there a nice way to bind to and show in wpf the <strong>Foo</strong> objects in <em>foos</em> in the order defined by IDs in <em>sortLikeThis</em> ?</p>
[ { "answer_id": 161894, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "<p>As often the case when using parenthesis, I think that's just for readability (e.g., Ruby supports method calls w/o parenthesis enclosing the arguments but recent books and articles advise otherwise).</p>\n" }, { "answer_id": 161899, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 7, "selected": true, "text": "<p>There really isn't a reason...it's just old convention.</p>\n\n<p>To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this:</p>\n\n<pre><code>return (x+i*2);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>int y = x+i*2;\nreturn y;\n</code></pre>\n\n<p>The parenthesis became a habit and it stuck.</p>\n" }, { "answer_id": 161992, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 5, "selected": false, "text": "<p>My personal style is to use parentheses if there is a complex expression; e.g.,</p>\n\n<pre><code>return (a + b);\n</code></pre>\n\n<p>but to not use them if the expression is a simple term</p>\n\n<pre><code>return a;\n</code></pre>\n\n<p>I can't say why I do it that way; just something I picked up long ago.</p>\n\n<p>By the way, I think that making it look like a function call, like this:</p>\n\n<pre><code>return(a); // ugh\n</code></pre>\n\n<p>is incredibly ugly and just wrong.</p>\n" }, { "answer_id": 162636, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 4, "selected": false, "text": "<p>There are a few reasons:</p>\n\n<ol>\n<li><p>if/while/for/etc. are all control keywords which must have parens. So it often seems natural to always put them on return too.</p></li>\n<li><p>sizeof is the only other keyword that can either have them or not, except that in some cases you <em>must</em> use parens. So it's easier to get into the habit of always using parens. for sizeof, which implies a logic of: if you can, always do.</p></li>\n<li><p>case/goto are the only keywords where you never use parens. ... and people tend to think of those as special cases (and like them both to stand out from other control keywords, esp. goto).</p></li>\n</ol>\n" }, { "answer_id": 164112, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 6, "selected": false, "text": "<p>A practical, but unlikely, motive is if you put parenthesis around the value, you can define return as a macro, and then insert some logging code to watch all your returns.</p>\n" }, { "answer_id": 164410, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "<p>I've worked with at least one programmer who thought return <em>was</em> some special sort of function call, and was suprised when he saw that my code complied without the parens.</p>\n" }, { "answer_id": 182760, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 3, "selected": false, "text": "<p>When returning -1 as in your excample, I think it's more readable with the parenthesis because the minus is more visible:</p>\n\n<pre><code>return 1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return -1\n</code></pre>\n\n<p>or</p>\n\n<pre><code>return (-1)\n</code></pre>\n" }, { "answer_id": 4762785, "author": "TonyK", "author_id": 428857, "author_profile": "https://Stackoverflow.com/users/428857", "pm_score": -1, "selected": false, "text": "<p>Using parentheses in a return statement shows a deficient grasp of <code>C/C++</code> syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:</p>\n\n<pre><code>int foo(int x) {\n if (x) {\n return (-1);\n }\n else {\n return (0);\n }\n}\n</code></pre>\n\n<p>So many programmers do this. If one of you reads this, perhaps you might like to explain.</p>\n" }, { "answer_id": 23298415, "author": "James Jones", "author_id": 1503446, "author_profile": "https://Stackoverflow.com/users/1503446", "pm_score": 3, "selected": false, "text": "<p>Perhaps it's custom--after all, the folks who brought us Unix and C came from the Multics project. Multics was written in PL/I, and in PL/I the parentheses are mandatory.</p>\n" }, { "answer_id": 36232426, "author": "Diogenes", "author_id": 6116674, "author_profile": "https://Stackoverflow.com/users/6116674", "pm_score": -1, "selected": false, "text": "<p>The Parenthesis in a return statement indicate to the compiler that you intend for this value to be returned on the stack instead of in memory.</p>\n\n<p>In the old days this was rigorously enforced(typically), but today most compilers only take it as a hint.</p>\n\n<p>This is something I do frequently, since an error could corrupt anything being returned via a memory reference, but typically wont effect a variable being returned on the stack.</p>\n\n<p>Using the stack for transient variables also cuts down on memory usage and typically makes the function call/return quicker because that's what the stack is designed for, transient data/variables.</p>\n" }, { "answer_id": 46867785, "author": "rakslice", "author_id": 60422, "author_profile": "https://Stackoverflow.com/users/60422", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://www.bell-labs.com/usr/dmr/www/cman.pdf#page=14\" rel=\"noreferrer\">In the original C specification, parentheses were required around the return value.</a> While modern C compilers and the ANSI C standard do not require them, the presence of parentheses does not affect the return value, and programmers sometimes still include them out of habit, unfamiliarity with the standards, for consistency with a stylistic convention that requires them, or possibly for backward compatibility.</p>\n\n<p>I should add, for people that are thinking about C++: <em>This</em> question is about C and C is not C++; these are two different languages with different standards, capabilities, levels of difficulty, and different styles of usage that emerge -- whatever they have in common, it is wise to treat them as two totally separate things. For a similar question that covers C++, see <a href=\"https://stackoverflow.com/questions/4762662/are-parentheses-around-the-result-significant-in-a-return-statement/25615981#25615981\">Are parentheses around the result significant in a return statement?</a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20508/" ]
For those of you that like puzzles: I had this problem recently and am sure there must be a nicer solution. Consider : * an ObservableCollection of **Foo** objects called *foos*. * **Foo** contains a string ID field * I have no control over *foos* * *foos* will be changing Then: * I have another collection called *sortLikeThis* * *sortListThis* contains strings * The strings are the IDs in the order in which the *foos* are to be shown Plus: * There may be objects in *foos* with an ID that is not in *sortLikeThis*. These need to go at the end. * Likewise, there may be strings in *sortLikeThis* that do not appear in *foos*. Is there a nice way to bind to and show in wpf the **Foo** objects in *foos* in the order defined by IDs in *sortLikeThis* ?
There really isn't a reason...it's just old convention. To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this: ``` return (x+i*2); ``` instead of ``` int y = x+i*2; return y; ``` The parenthesis became a habit and it stuck.
161,885
<p>When running performance tests file system cache hit or miss can significantly influence test results. Therefore generally before running such tests used files are evicted from system cache. How to do that on Linux?</p> <p><strong>Clarification:</strong> If possible, the solution should not require root privileges.</p>
[ { "answer_id": 162041, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 4, "selected": false, "text": "<p>As a superuser you can do the following:</p>\n\n<p>To free pagecache:</p>\n\n<ul>\n<li>echo 1 > /proc/sys/vm/drop_caches</li>\n</ul>\n\n<p>To free dentries and inodes:</p>\n\n<ul>\n<li>echo 2 > /proc/sys/vm/drop_caches</li>\n</ul>\n\n<p>To free pagecache, dentries and inodes:</p>\n\n<ul>\n<li>echo 3 > /proc/sys/vm/drop_caches</li>\n</ul>\n\n<p>This operation will not \"lose\" any data (caches are written out to disk before their data is dropped), however, to really make sure all cache is cleaned, you should sync first. E.g. all caches should be cleared if you run</p>\n\n<pre><code>sync; echo 3 &gt; /proc/sys/vm/drop_caches\n</code></pre>\n\n<p>As I said, only a superuser (root) may do so.</p>\n" }, { "answer_id": 162393, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "<p>Regarding use of O_DIRECT: that would perturb the results in another way. The kernel will attempt to DMA the filesystem data directly into your read() buffer, so it can be handed up to your application without any additional copy being done. Without O_DIRECT the kernel DMAs the file data into the page cache, and copies it from the page cache to your read() buffer.</p>\n\n<p>This is fine if your app is really going to use O_DIRECT in production. If you run performance tests with O_DIRECT and then remove O_DIRECT for production, your performance test will be unrealistic.</p>\n" }, { "answer_id": 162792, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 4, "selected": true, "text": "<p>Ha, I have the answer:</p>\n\n<pre><code>#include &lt;unistd.h&gt;\n#include &lt;fcntl.h&gt;\nint main(int argc, char *argv[]) {\n int fd;\n fd = open(argv[1], O_RDONLY);\n fdatasync(fd);\n posix_fadvise(fd, 0,0,POSIX_FADV_DONTNEED);\n close(fd);\n return 0;\n}\n</code></pre>\n\n<p>This is from <a href=\"http://insights.oetiker.ch/linux/fadvise.html\" rel=\"noreferrer\">http://insights.oetiker.ch/linux/fadvise.html</a></p>\n" }, { "answer_id": 195372, "author": "James", "author_id": 27193, "author_profile": "https://Stackoverflow.com/users/27193", "pm_score": -1, "selected": false, "text": "<p>If you can put the test data in a separate filesystem then mounting the filesystem afresh for the test will give you empty caches.</p>\n\n<p>If you list the test fileystem in /etc/fstab with the \"user\" option then you can mount it for the test without being superuser</p>\n" }, { "answer_id": 1167957, "author": "user143174", "author_id": 143174, "author_profile": "https://Stackoverflow.com/users/143174", "pm_score": 3, "selected": false, "text": "<p>There is a command line utility by Eric Wong that makes it easy to invoke posix_fadvise:</p>\n\n<p><a href=\"http://git.bogomips.org/cgit/pcu.git/tree/README\" rel=\"noreferrer\">http://git.bogomips.org/cgit/pcu.git/tree/README</a></p>\n\n<p>It's then as simple as</p>\n\n<pre><code>$ pcu-fadvise -a dontneed filename-to-evict\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
When running performance tests file system cache hit or miss can significantly influence test results. Therefore generally before running such tests used files are evicted from system cache. How to do that on Linux? **Clarification:** If possible, the solution should not require root privileges.
Ha, I have the answer: ``` #include <unistd.h> #include <fcntl.h> int main(int argc, char *argv[]) { int fd; fd = open(argv[1], O_RDONLY); fdatasync(fd); posix_fadvise(fd, 0,0,POSIX_FADV_DONTNEED); close(fd); return 0; } ``` This is from <http://insights.oetiker.ch/linux/fadvise.html>
161,913
<p>I would like to draw a diagram in HTML. The positioning structure looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id='hostDiv'&gt; &lt;div id='backgroundDiv'&gt; ... drawing the background ... &lt;/div&gt; &lt;div id='foregroundDiv' style='position: absolute;'&gt; ... drawing the foreground ... &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The foreground contains a Table element that is dynamically populated with text, hence the row heights might alter depending on the amount of text going into a cell. How can I predict the final height of the Table element in the foregroun? I need this information to set the correct height of the background. Is there a way to pre-render the Table from Javascript and read out its height? Or some other trick?</p> <p>PS. The size of the hostDiv may vary as the browser resizes.</p>
[ { "answer_id": 161923, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>There isn't any way to predict the height without actually rendering it in the target browser.</p>\n\n<p>Once you do that, you can use (for example) <a href=\"http://docs.jquery.com/\" rel=\"noreferrer\"><strong>jQuery</strong></a> to get the height of the element:</p>\n\n<pre><code>var height = $('#myTable').height();\n</code></pre>\n" }, { "answer_id": 161934, "author": "gx.", "author_id": 21580, "author_profile": "https://Stackoverflow.com/users/21580", "pm_score": 2, "selected": false, "text": "<p>While using jquery, you can actually find out the height of the table <em>before</em> it is rendered to the user. Use a construct like this (liberally borrowing code from the person above me):</p>\n\n<pre><code>$(document).ready(function () { var height = $('#myTable').height(); });\n</code></pre>\n" }, { "answer_id": 161947, "author": "japollock", "author_id": 1210318, "author_profile": "https://Stackoverflow.com/users/1210318", "pm_score": 1, "selected": false, "text": "<p>You can't predict the overall height of the element until after load as the browser will render and position elements depending on the adjacent elements and the size of the viewing window.</p>\n\n<p>That said, you can use most any js library to find what you are looking for. In Prototype, it's:</p>\n\n<pre><code>$('navlist-main').offsetHeight\n</code></pre>\n\n<p>This will recursively add up the rendered height (not just the styled height) for each child element and any associated margin and padding and return an accurate figure for element height.</p>\n" }, { "answer_id": 161951, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 1, "selected": false, "text": "<p>If you simply don't want to display the table before resizing the foregorund div:<br>\nSet style.visibility=\"hidden\" on the table. Unlike display:none, this does not remove the div from the document flow and so the foreground div will still be properly sized (the table will simply not be visible).</p>\n\n<p>Of course, if acceptable, you could move foregroundDiv into backgroundDiv and remove absolute positioning. backgroundDiv will then automatically resize to contain foregroundDiv (and the table).</p>\n" }, { "answer_id": 5100073, "author": "Alvin T", "author_id": 472482, "author_profile": "https://Stackoverflow.com/users/472482", "pm_score": 0, "selected": false, "text": "<p>I think you can use one of DOM attributes: clientHeight, offsetHeight, and scrollHeight as defined in w3 <a href=\"http://www.w3.org/TR/cssom-view/#extensions-to-the-element-interface\" rel=\"nofollow\">here</a></p>\n\n<p>This is the usage of clientHeight:</p>\n\n<pre><code>document.getElementById(\"#Table\").clientHeight;\ndocument.getElementById(\"#Table\").clientWidth;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24451/" ]
I would like to draw a diagram in HTML. The positioning structure looks like this: ```html <div id='hostDiv'> <div id='backgroundDiv'> ... drawing the background ... </div> <div id='foregroundDiv' style='position: absolute;'> ... drawing the foreground ... </div> </div> ``` The foreground contains a Table element that is dynamically populated with text, hence the row heights might alter depending on the amount of text going into a cell. How can I predict the final height of the Table element in the foregroun? I need this information to set the correct height of the background. Is there a way to pre-render the Table from Javascript and read out its height? Or some other trick? PS. The size of the hostDiv may vary as the browser resizes.
There isn't any way to predict the height without actually rendering it in the target browser. Once you do that, you can use (for example) [**jQuery**](http://docs.jquery.com/) to get the height of the element: ``` var height = $('#myTable').height(); ```
161,915
<p>I'm trying to have two inputs (one textbox, one drop down) to have the same width. You can set the width through css, but for some reason, the select box is always a few pixels smaller. It seems this only happens with the xhtml 1.0 strict doctype Any suggestions/ideas about the reason/work around?</p> <p>Having the following HTML</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&gt; &lt;head&gt; &lt;style&gt; .searchInput{ width: 1000px; overflow: hidden; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="theAction" method="post" class="searchForm" &gt; &lt;fieldset&gt; &lt;legend&gt;Search&lt;/legend&gt; &lt;p&gt; &lt;!--&lt;label for="name"&gt;Product name&lt;/label&gt;--&gt; &lt;input class="searchInput" type="text" name="name" id="name" value="" /&gt; &lt;/p&gt; &lt;p&gt; &lt;!--&lt;label for="ml2"&gt;Product Group&lt;/label&gt;--&gt; &lt;select class="searchInput" name="ml2" id="ml2"&gt; &lt;option value="158"&gt;INDUSTRIAL PRIMERS/FILLERS&lt;/option&gt; &lt;option value="168"&gt;CV CLEAR COATS&lt;/option&gt; &lt;option value="171"&gt;CV PRIMERS/FILLERS&lt;/option&gt; &lt;option value="" selected="selected"&gt;All&lt;/option&gt; &lt;/select&gt; &lt;/p&gt; &lt;input type="submit" class="search" value="Show" name="Show" id="Show" /&gt; &lt;input type="reset" value="Reset" name="reset" id="reset" class="reset"/&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/body &lt;/html&gt; </code></pre>
[ { "answer_id": 161940, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 0, "selected": false, "text": "<p>You're right, there is a 4px difference. The <code>input</code> is coming out at 103px wide, while the <code>select</code> is coming at 99px wide. I have no idea why this occurs, but you could work around it like this:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n .searchInput {\n overflow: hidden;\n }\n select.searchInput {\n width: 101px;\n }\n input.searchInput {\n width: 97px;\n }\n&lt;/style&gt;\n</code></pre>\n\n<p>It's really quite silly, and I would be really interested if someone knew why this was happening, and a way to prevent it.</p>\n\n<p>The work-around works on Webkit and Firefox. The pixel difference is different in IE.</p>\n\n<p>The funny thing is, they would normally be the same size using an HTML doctype.</p>\n" }, { "answer_id": 161946, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>I had this issue in Firefox 2, but it seems to be resolved in Firefox 3 and IE7. </p>\n\n<p>My fix was to add the missing pixels to a seperate width for <code>select</code>.</p>\n" }, { "answer_id": 162008, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": -1, "selected": false, "text": "<p>It seems only with the doctype added this happens.\nCorrected the example.</p>\n" }, { "answer_id": 162278, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 0, "selected": false, "text": "<p>Browsers tend to do their own thing with regard to form elements and styles. The CSS standard doesn’t specify how browsers should display form widgets, nor which CSS properties it should let users change. It varies between browsers, and between different form widgets in the same browser.</p>\n\n<p>You could try adjusting the padding and borders to help different form widgets match up.</p>\n" }, { "answer_id": 163296, "author": "Allen Hardy", "author_id": 11394, "author_profile": "https://Stackoverflow.com/users/11394", "pm_score": 0, "selected": false, "text": "<p>@Paul D. Waite - Got to agree with you there</p>\n\n<p>This isn't what CSS is meant for. Look at input boxes in Safari, for example. They're elliptical. CSS properties just don't apply in some cases.</p>\n\n<p>Pad around your elements to line them up.</p>\n" }, { "answer_id": 167288, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 3, "selected": false, "text": "<p>You could try resetting the margins, padding and borders to see if that helps:</p>\n\n<pre><code>.searchInput {\n margin:0;\n padding:0;\n border-width:1px;\n width:1000px;\n}\n</code></pre>\n" }, { "answer_id": 169007, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 2, "selected": false, "text": "<p>This seems to have something to do with the box model. More specifically, it seems to have something to do with the border. If you're using firebug, check out the layout tab...</p>\n\n<p>The select shows a 2px border, 0 padding and a width of 996px and height of 18px.<br>\nThe input shows a 2px border, 1px 0 padding and a width of 1000px and height of 16px.</p>\n\n<p>If you set the border to zero (and give them a background color), you can see they'll be the same size, which shows them both with a width of 1000px in the layout tab.</p>\n\n<pre><code> .searchInput{\n width: 1000px;\n border: 0;\n background-color: #CCC;\n overflow: hidden;\n }\n</code></pre>\n" }, { "answer_id": 573033, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It is ndeed due to the Box Model that #IE supports when it finds the \"strict\" in the doctype. If u change it to \"traditional\" doctype everything behaves normally...but not normally as per CSS standard.</p>\n\n<p>CSS Box Model states that in the width/height of an element the padding and border withs are not included. So they are additional on top of the mentioned width of the element, and thus are bigger than desired actually.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
I'm trying to have two inputs (one textbox, one drop down) to have the same width. You can set the width through css, but for some reason, the select box is always a few pixels smaller. It seems this only happens with the xhtml 1.0 strict doctype Any suggestions/ideas about the reason/work around? Having the following HTML ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <style> .searchInput{ width: 1000px; overflow: hidden; } </style> </head> <body> <form action="theAction" method="post" class="searchForm" > <fieldset> <legend>Search</legend> <p> <!--<label for="name">Product name</label>--> <input class="searchInput" type="text" name="name" id="name" value="" /> </p> <p> <!--<label for="ml2">Product Group</label>--> <select class="searchInput" name="ml2" id="ml2"> <option value="158">INDUSTRIAL PRIMERS/FILLERS</option> <option value="168">CV CLEAR COATS</option> <option value="171">CV PRIMERS/FILLERS</option> <option value="" selected="selected">All</option> </select> </p> <input type="submit" class="search" value="Show" name="Show" id="Show" /> <input type="reset" value="Reset" name="reset" id="reset" class="reset"/> </fieldset> </form> </body </html> ```
You could try resetting the margins, padding and borders to see if that helps: ``` .searchInput { margin:0; padding:0; border-width:1px; width:1000px; } ```
161,937
<p>I understand there is a HTTP response header directive to disable page caching:</p> <pre><code>Cache-Control:no-cache </code></pre> <p>I can modify the header by "hand":</p> <pre><code> &lt;%response.addHeader("Cache-Control","no-cache");%&gt; </code></pre> <p>But is there a "nice" way to make the JSP interpreter return this header line in the server response?</p> <p>(I checked the &lt;%@page ...%> directive. It seems there is nothing like that.)</p>
[ { "answer_id": 161952, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "<p>If you were using a servlet, then I believe what you posted in the question would be the correct approach. I'm not aware of any way to do this in the JSP.</p>\n" }, { "answer_id": 162096, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" version=\"2.0\"&gt; \n &lt;jsp:scriptlet&gt;&lt;![CDATA[\n response.setHeader(\"Cache-Control\", \"no-cache\");\n ]]&gt;&lt;/jsp:scriptlet&gt;\n&lt;/jsp:root&gt;\n</code></pre>\n\n<p>You must put the response header inside <code>&lt;jsp:root /&gt;</code>. Also, I would instead recommend it sending this from your servlet instead of JSP page. </p>\n" }, { "answer_id": 162118, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "<p>IIRC some browsers may ignore the cache control settings in some contexts. The 'safe' workaround for this was to always get a page (even an AJAX chunk) with a new query string variable (like the time.)</p>\n" }, { "answer_id": 169831, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 3, "selected": true, "text": "<p>Also add </p>\n\n<pre>\nresponse.addHeader(\"Expires\",\"-1\");\nresponse.addHeader(\"Pragma\",\"no-cache\");\n</pre>\n\n<p>to your headers and give that a shot. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17428/" ]
I understand there is a HTTP response header directive to disable page caching: ``` Cache-Control:no-cache ``` I can modify the header by "hand": ``` <%response.addHeader("Cache-Control","no-cache");%> ``` But is there a "nice" way to make the JSP interpreter return this header line in the server response? (I checked the <%@page ...%> directive. It seems there is nothing like that.)
Also add ``` response.addHeader("Expires","-1"); response.addHeader("Pragma","no-cache"); ``` to your headers and give that a shot.
161,960
<p>A query that is used to loop through <b>17 millions records to remove duplicates</b> has been running now for about <b>16 hours</b> and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize the deletes or rolls back?</p> <p>I have found that when I do a </p> <pre><code> select count(*) from myTable </code></pre> <p>That the rows that it returns (while doing this query) is about 5 less than what the starting row count was. Obviously the server resources are extremely poor, so does that mean that this process has taken 16 hours to find 5 duplicates (when there are actually thousands), and this could be running for days?</p> <p>This query took 6 seconds on 2000 rows of test data, and it works great on that set of data, so I figured it would take 15 hours for the complete set.</p> <p>Any ideas?</p> <p>Below is the query:</p> <pre><code>--Declare the looping variable DECLARE @LoopVar char(10) DECLARE --Set private variables that will be used throughout @long DECIMAL, @lat DECIMAL, @phoneNumber char(10), @businessname varchar(64), @winner char(10) SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable) WHILE @LoopVar is not null BEGIN --initialize the private variables (essentially this is a .ctor) SELECT @long = null, @lat = null, @businessname = null, @phoneNumber = null, @winner = null -- load data from the row declared when setting @LoopVar SELECT @long = longitude, @lat = latitude, @businessname = BusinessName, @phoneNumber = Phone FROM MyTable WHERE RecordID = @LoopVar --find the winning row with that data. The winning row means SELECT top 1 @Winner = RecordID FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone ORDER BY CASE WHEN webAddress is not null THEN 1 ELSE 2 END, CASE WHEN caption1 is not null THEN 1 ELSE 2 END, CASE WHEN caption2 is not null THEN 1 ELSE 2 END, RecordID --delete any losers. DELETE FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone AND @winner != RecordID -- prep the next loop value to go ahead and perform the next duplicate query. SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable WHERE @LoopVar &lt; RecordID) END </code></pre>
[ { "answer_id": 161990, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": -1, "selected": false, "text": "<p>I'm pretty sure that is a negatory. Otherwise what would the point of transactions be?</p>\n" }, { "answer_id": 162021, "author": "jwanagel", "author_id": 15118, "author_profile": "https://Stackoverflow.com/users/15118", "pm_score": 3, "selected": false, "text": "<p>Your query is not wrapped in a transaction, so it won't rollback the changes already made by the individual delete statements.</p>\n\n<p>I specifically tested this myself on my own SQL Server using the following query, and the ApplicationLog table was empty even though I cancelled the query:</p>\n\n<pre><code>declare @count int\nselect @count = 5\nWHILE @count &gt; 0\nBEGIN\n print @count\n delete from applicationlog;\n waitfor time '20:00';\n select @count = @count -1\nEND\n</code></pre>\n\n<p>However your query is likely to take many days or weeks, much longer then 15 hours. Your estimate that you can process 2000 records every 6 seconds is wrong because each iteration in your while loop will take significantly longer with 17 million rows then it does with 2000 rows. So unless your query takes significantly less then a second for 2000 rows, it will take days for all 17 million.</p>\n\n<p>You should ask a new question on how you can delete duplicate rows efficiently.</p>\n" }, { "answer_id": 162035, "author": "user10635", "author_id": 10635, "author_profile": "https://Stackoverflow.com/users/10635", "pm_score": 6, "selected": true, "text": "<p>no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql.</p>\n\n<p>with sql server it will not roll back unless you are specifically running in the context of a transaction and you rollback that transaction, or the connection closes without the transaction having been committed. but i don't see a transaction context in your above query.</p>\n\n<p>you could also try re-structuring your query to make the deletes a little more efficient, but essentially if the specs of your box are not up to snuff then you might be stuck waiting it out.</p>\n\n<p>going forward, you should create a unique index on the table to keep yourself from having to go through this again. </p>\n" }, { "answer_id": 162039, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 0, "selected": false, "text": "<p>As a loop your query will struggle to scale well, even with appropriate indexes. The query should be rewritten to a single statement, as per the suggestions in <a href=\"https://stackoverflow.com/questions/150891/sql-query-remove-duplicates-with-caveats\">your previous question</a> on this.</p>\n\n<p>If you're not running it explicitly within a transaction it will only roll back the executing statement.</p>\n" }, { "answer_id": 162050, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>If you don't do anything explicit about transactions then the connection will be in <a href=\"http://msdn.microsoft.com/en-us/library/ms187878.aspx\" rel=\"nofollow noreferrer\">autocommit transactions</a> mode. In this mode every SQL statement is considered a transaction.</p>\n\n<p>The question is whether this means the individual SQL statements are transactions and are therefore being committed as you go, or whether the outer WHILE loop counts as a transaction.</p>\n\n<p>There doesn't seem to be any discussion of this in the description of the WHILE construct on <a href=\"http://msdn.microsoft.com/en-us/library/ms178642.aspx\" rel=\"nofollow noreferrer\">MSDN</a>. However, since a WHILE statement can't directly modify the database it would seem logical that it <strong>doesn't</strong> start an auto-commit transaction.</p>\n" }, { "answer_id": 162070, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>I inherited a system which had logic something like yours implemented in SQL. In our case, we were trying to link together rows using fuzzy matching that had similar names/addresses, etc, and that logic was done purely in SQL. At the time I inherited it we had about 300,000 rows in the table and according to the timings, we calculated it would take A YEAR to match them all.</p>\n\n<p>As an experiment to see how much faster I could do it outside of SQL, I wrote a program to dump the db table into flat files, read the flat files into a C++ program, build my own indexes, and do the fuzzy logic there, then reimport the flat files into the database. What took A YEAR in SQL took about 30 seconds in the C++ app.</p>\n\n<p>So, my advice is, don't even try what you are doing in SQL. Export, process, re-import.</p>\n" }, { "answer_id": 162178, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 0, "selected": false, "text": "<p>I think this query would be much more efficient if it was re-written using a single-pass algorithm using a cursor. You would order you cursor table by longitude,latitude,BusinessName AND @phoneNumber. You’d step through the rows one at a time. If a row has the same longitude, latitude, businessname, and phonenumber as the previous row, then delete it. </p>\n" }, { "answer_id": 162277, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>DELETES that have been performed up to this point will not be rolled back.</p>\n\n<hr>\n\n<p>As the original author of the <a href=\"https://stackoverflow.com/questions/150891/sql-query-remove-duplicates-with-caveats#150967\">code in question</a>, and having issued the caveat that performance will be dependant on indexes, I would propose the following items to speed this up.</p>\n\n<p>RecordId better be PRIMARY KEY. I don't mean IDENTITY, I mean PRIMARY KEY. Confirm this using sp_help</p>\n\n<p>Some index should be used in evaluating this query. Figure out which of these four columns has the least repeats and index that...</p>\n\n<pre><code>SELECT *\nFROM MyTable\nWHERE @long = longitude\n AND @lat = latitude\n AND @businessname = BusinessName\n AND @phoneNumber = Phone\n</code></pre>\n\n<p>Before and After adding this index, check the query plan to see if index scanning has been added.</p>\n" }, { "answer_id": 165659, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 2, "selected": false, "text": "<h2>Implicit transactions</h2>\n\n<p><strong>If no 'Implicit transactions' has been set, then each iteration in your loop committed the changes.</strong></p>\n\n<p>It is possible for any SQL Server to be set with 'Implicit transactions'. This is a database setting (by default is OFF). You can also have implicit transactions in the properties of a particular query inside of Management Studio (right click in query pane>options), by default settings in the client, or a SET statement.</p>\n\n<pre><code>SET IMPLICIT_TRANSACTIONS ON;\n</code></pre>\n\n<p>Either way, if this was the case, you would still need to execute an explicit COMMIT/ROLLBACK regardless of interruption of the query execution.</p>\n\n<hr>\n\n<p><strong>Implicit transactions reference:</strong></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188317.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms188317.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190230.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms190230.aspx</a></p>\n" }, { "answer_id": 1177803, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>I think you need to seriously consider your methodolology. \n You need to start thinking in sets (although for performance you may need batch processing, but not row by row against a 17 million record table.)</p>\n\n<p>First do all of your records have duplicates? I suspect not, so the first thing you wan to do is limit your processing to only those records which have duplicates. Since this is a large table and you may need to do the deletes in batches over time depending on what other processing is going on, you first pull the records you want to deal with into a table of their own that you then index. You can also use a temp table if you are going to be able to do this all at the same time without ever stopping it other wise create a table in your database and drop at the end.</p>\n\n<p>Something like (Note I didn't write the create index statments, I figure you can look that up yourself):</p>\n\n<pre><code>SELECT min(m.RecordID), m.longitude, m.latitude, m.businessname, m.phone \n into #RecordsToKeep \nFROM MyTable m\njoin \n(select longitude, latitude, businessname, phone\nfrom MyTable\ngroup by longitude, latitude, businessname, phone\nhaving count(*) &gt;1) a \non a.longitude = m.longitude and a.latitude = m.latitude and\na.businessname = b.businessname and a.phone = b.phone \ngroup by m.longitude, m.latitude, m.businessname, m.phone \nORDER BY CASE WHEN m.webAddress is not null THEN 1 ELSE 2 END, \n CASE WHEN m.caption1 is not null THEN 1 ELSE 2 END, \n CASE WHEN m.caption2 is not null THEN 1 ELSE 2 END\n\n\n\nwhile (select count(*) from #RecordsToKeep) &gt; 0\nbegin\nselect top 1000 * \ninto #Batch\nfrom #RecordsToKeep\n\nDelete m\nfrom mytable m\njoin #Batch b \n on b.longitude = m.longitude and b.latitude = m.latitude and\n b.businessname = b.businessname and b.phone = b.phone \nwhere r.recordid &lt;&gt; b.recordID\n\nDelete r\nfrom #RecordsToKeep r\njoin #Batch b on r.recordid = b.recordid\n\nend\n\nDelete m\nfrom mytable m\njoin #RecordsToKeep r \n on r.longitude = m.longitude and r.latitude = m.latitude and\n r.businessname = b.businessname and r.phone = b.phone \nwhere r.recordid &lt;&gt; m.recordID\n</code></pre>\n" }, { "answer_id": 4646461, "author": "endo64", "author_id": 333153, "author_profile": "https://Stackoverflow.com/users/333153", "pm_score": 0, "selected": false, "text": "<p>Also try thinking another method to remove duplicate rows:</p>\n\n<pre><code>delete t1 from table1 as t1 where exists (\n select * from table1 as t2 where\n t1.column1=t2.column1 and\n t1.column2=t2.column2 and\n t1.column3=t2.column3 and\n --add other colums if any\n t1.id&gt;t2.id\n)\n</code></pre>\n\n<p>I suppose that you have an integer id column in your table.</p>\n" }, { "answer_id": 19576621, "author": "user2917618", "author_id": 2917618, "author_profile": "https://Stackoverflow.com/users/2917618", "pm_score": 0, "selected": false, "text": "<p>If your machine doesn't have very advanced hardware then it may take sql server a very long time to complete that command. I don't know for sure how this operation is performed under the hood but based on my experience this could be done more efficiently by bringing the records out of the database and into memory for a program that uses a tree structure with a remove duplicate rule for insertion. Try reading the entirety of the table in chuncks (say 10000 rows at a time) into a C++ program using ODBC. Once in the C++ program use and std::map where key is the unique key and struct is a struct that holds the rest of the data in variables. Loop over all the records and perform insertion into the map. The map insert function will handle removing the duplicates. Since search inside a map is lg(n) time far less time to find duplicates than using your while loop. You can then delete the entire table and add the tuples back into the database from the map by forming insert queries and executing them via odbc or building a text file script and running it in management studio.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
A query that is used to loop through **17 millions records to remove duplicates** has been running now for about **16 hours** and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize the deletes or rolls back? I have found that when I do a ``` select count(*) from myTable ``` That the rows that it returns (while doing this query) is about 5 less than what the starting row count was. Obviously the server resources are extremely poor, so does that mean that this process has taken 16 hours to find 5 duplicates (when there are actually thousands), and this could be running for days? This query took 6 seconds on 2000 rows of test data, and it works great on that set of data, so I figured it would take 15 hours for the complete set. Any ideas? Below is the query: ``` --Declare the looping variable DECLARE @LoopVar char(10) DECLARE --Set private variables that will be used throughout @long DECIMAL, @lat DECIMAL, @phoneNumber char(10), @businessname varchar(64), @winner char(10) SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable) WHILE @LoopVar is not null BEGIN --initialize the private variables (essentially this is a .ctor) SELECT @long = null, @lat = null, @businessname = null, @phoneNumber = null, @winner = null -- load data from the row declared when setting @LoopVar SELECT @long = longitude, @lat = latitude, @businessname = BusinessName, @phoneNumber = Phone FROM MyTable WHERE RecordID = @LoopVar --find the winning row with that data. The winning row means SELECT top 1 @Winner = RecordID FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone ORDER BY CASE WHEN webAddress is not null THEN 1 ELSE 2 END, CASE WHEN caption1 is not null THEN 1 ELSE 2 END, CASE WHEN caption2 is not null THEN 1 ELSE 2 END, RecordID --delete any losers. DELETE FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone AND @winner != RecordID -- prep the next loop value to go ahead and perform the next duplicate query. SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable WHERE @LoopVar < RecordID) END ```
no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql. with sql server it will not roll back unless you are specifically running in the context of a transaction and you rollback that transaction, or the connection closes without the transaction having been committed. but i don't see a transaction context in your above query. you could also try re-structuring your query to make the deletes a little more efficient, but essentially if the specs of your box are not up to snuff then you might be stuck waiting it out. going forward, you should create a unique index on the table to keep yourself from having to go through this again.
161,984
<p>Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests?</p> <p><strong>The full story:</strong> I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic. </p>
[ { "answer_id": 162107, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 7, "selected": true, "text": "<p>First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages.</p>\n\n<p>Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters.\nYou should be able to type a random number into a text field, for example:</p>\n\n<pre><code>type fieldName javascript{Math.floor(Math.random()*11)}\n</code></pre>\n\n<p><strong>Update:</strong> You can define helper functions in a file called \"user-extensions.js\". See the <a href=\"http://seleniumhq.org/docs/08_user_extensions.html#using-user-extensions-with-selenium-ide\" rel=\"noreferrer\">Selenium Reference</a>.</p>\n" }, { "answer_id": 2709476, "author": "RajendraChary", "author_id": 325509, "author_profile": "https://Stackoverflow.com/users/325509", "pm_score": 5, "selected": false, "text": "<p>You can add user exentions.js to get the random values .</p>\n\n<p>Copy the below code and save it as .js extension (randomgenerator.js) and add it to the Selenium core extensions (SeleniumIDE-->Options--->general tab)</p>\n\n<pre><code>Selenium.prototype.doRandomString = function( options, varName ) {\n\n var length = 8;\n var type = 'alphanumeric';\n var o = options.split( '|' );\n for ( var i = 0 ; i &lt; 2 ; i ++ ) {\n if ( o[i] &amp;&amp; o[i].match( /^\\d+$/ ) )\n length = o[i];\n\n if ( o[i] &amp;&amp; o[i].match( /^(?:alpha)?(?:numeric)?$/ ) )\n type = o[i];\n }\n\n switch( type ) {\n case 'alpha' : storedVars[ varName ] = randomAlpha( length ); break;\n case 'numeric' : storedVars[ varName ] = randomNumeric( length ); break;\n case 'alphanumeric' : storedVars[ varName ] = randomAlphaNumeric( length ); break;\n default : storedVars[ varName ] = randomAlphaNumeric( length );\n };\n};\n\nfunction randomNumeric ( length ) {\n return generateRandomString( length, '0123456789'.split( '' ) );\n}\n\nfunction randomAlpha ( length ) {\n var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );\n return generateRandomString( length, alpha );\n}\n\nfunction randomAlphaNumeric ( length ) {\n var alphanumeric = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split( '' );\n return generateRandomString( length, alphanumeric );\n}\n\nfunction generateRandomString( length, chars ) {\n var string = '';\n for ( var i = 0 ; i &lt; length ; i++ )\n string += chars[ Math.floor( Math.random() * chars.length ) ];\n return string;\n}\n</code></pre>\n\n<p>Way to use </p>\n\n<pre><code>Command Target Value\n----------- --------- ----------\nrandomString 6 x\ntype username ${x}\n</code></pre>\n\n<p>Above code generates 6 charactes string and it assign to the variable x</p>\n\n<p>Code in HTML format looks like below:</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td&gt;randomString&lt;/td&gt;\n &lt;td&gt;6&lt;/td&gt;\n &lt;td&gt;x&lt;/td&gt;\n&lt;/tr&gt;\n&lt;tr&gt;\n &lt;td&gt;type&lt;/td&gt;\n &lt;td&gt;username&lt;/td&gt;\n &lt;td&gt;${x}&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 3616176, "author": "corbacho", "author_id": 436732, "author_profile": "https://Stackoverflow.com/users/436732", "pm_score": 5, "selected": false, "text": "<p><em>(Based on Thilo answer)</em>\nYou can mix literals and random numbers like this:</p>\n\n<pre><code>javascript{\"joe+\" + Math.floor(Math.random()*11111) + \"@gmail.com\";}\n</code></pre>\n\n<p>Gmail makes possible that automatically everything that use aliases, for example, <code>[email protected]</code> will go to your address <code>[email protected]</code></p>\n\n<p>Multiplying *11111 to give you more random values than 1 to 9 (in Thilo example)</p>\n" }, { "answer_id": 4959178, "author": "afternoon", "author_id": 26201, "author_profile": "https://Stackoverflow.com/users/26201", "pm_score": 3, "selected": false, "text": "<p>Here's a one-line solution to generating a random string of letters in JS:</p>\n\n<pre><code>\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\").filter(function(e, i, a) { return Math.random() &gt; 0.8 }).join(\"\")\n</code></pre>\n\n<p>Useful for pasting into Selenium IDE.</p>\n" }, { "answer_id": 5500921, "author": "TomG", "author_id": 6315, "author_profile": "https://Stackoverflow.com/users/6315", "pm_score": 2, "selected": false, "text": "<p>A one-liner for randomly choosing from a small set of alternatives:</p>\n\n<pre><code>javascript{['brie','cheddar','swiss'][Math.floor(Math.random()*3)]}\n</code></pre>\n" }, { "answer_id": 5619276, "author": "bast", "author_id": 701873, "author_profile": "https://Stackoverflow.com/users/701873", "pm_score": 1, "selected": false, "text": "<p>I made a little improvment to the function generateRandomString.\nWhen FF crashes, it's good to be able to use the same random number again.</p>\n\n<p>Basically, it will ask you to enter a string yourself. If you don't enter anything, it will generate it.</p>\n\n<p><code>function generateRandomString( length, chars ) {\nvar string=prompt(\"Please today's random string\",'');\nif (string == '')\n {for ( var i = 0 ; i &lt; length ; i++ )\n string += chars[ Math.floor( Math.random() * chars.length ) ];\n return string;}\n else\n {\n return string;}\n}\n</code></p>\n" }, { "answer_id": 9708548, "author": "lhoess", "author_id": 398403, "author_profile": "https://Stackoverflow.com/users/398403", "pm_score": 0, "selected": false, "text": "<p>Here another variation on the gmail example:</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td&gt;runScript&lt;/td&gt;\n &lt;td&gt;emailRandom=document.getElementById('email');console.log(emailRandom.value);emailRandom.value=&amp;quot;myEmail+&amp;quot; + Math.floor(Math.random()*11111)+ &amp;quot;@gmail.com&amp;quot;;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 10651611, "author": "CuongHuyTo", "author_id": 487785, "author_profile": "https://Stackoverflow.com/users/487785", "pm_score": 0, "selected": false, "text": "<p>Selenium RC gives you much more freedom than Selenium IDE, in that you can:</p>\n\n<ul>\n<li>(1) Enter any value to a certain field</li>\n<li>(2) Choose any field to test in a certain HTML form</li>\n<li>(3) Choose any execution order/step to test a certain set of fields.</li>\n</ul>\n\n<p>You asked how to enter some random value in a field using Selenium IDE, other people have answered you how to generate and enter random values in a field using Selenium RC. That falls into the testing phase (1): \"Enter any value to a certain field\".</p>\n\n<p>Using Selenium RC you could easily do the phase (2) and (3): testing any field under any execution step by doing some programming in a supported language like Java, PHP, CSharp, Ruby, Perl, Python.</p>\n\n<p>Following is the steps to do phase (2) and (3):</p>\n\n<ul>\n<li>Create list of your HTML fields so that you could easily iterate through them</li>\n<li>Create a random variable to control the step, say RAND_STEP</li>\n<li>Create a random variable to control the field, say RAND_FIELD</li>\n<li>[Eventually, create a random variable to control the value entered into a certain field, say RAND_VALUE, if you want to do phase (1)]</li>\n<li>Now, inside your fuzzing algorithm, iterate first through the values of RAND_STEP, then with each such iteration, iterate through RAND_FIELD, then finally iterate through RAND_VALUE.</li>\n</ul>\n\n<p>See <a href=\"https://stackoverflow.com/questions/10650990/how-to-do-fuzzing-testing-with-selenium\">my other answer</a> about fuzzing test, Selenium and white/black box testing</p>\n" }, { "answer_id": 10863468, "author": "agileadam", "author_id": 1023773, "author_profile": "https://Stackoverflow.com/users/1023773", "pm_score": 1, "selected": false, "text": "<p>While making sense of RajendraChary's post above, I spent some time writing a new Selenium IDE extension. </p>\n\n<p>My extension will let the user populate a variable with lorem ipsum text. There are a number of configurable options and it's turned into a nice little command. You can do things like \"5 words|wordcaps|nomarks\" to generate 5 lorem ipsum words, all capitalized, without punctuation.</p>\n\n<p>I've thoroughly explained installation and usage as well as provided the <a href=\"https://github.com/agileadam/selenium-lipsumtext\" rel=\"nofollow\">full codebase here</a></p>\n\n<p>If you take a peek at the code you'll get an idea of how to build similar functionality.</p>\n" }, { "answer_id": 16658108, "author": "djangofan", "author_id": 118228, "author_profile": "https://Stackoverflow.com/users/118228", "pm_score": 0, "selected": false, "text": "<p>Math.random may be \"good enough\" but, in practice, the <strong>Random class</strong> is often preferable to Math.random(). Using Math.random , the numbers you get may not actually be completely random. The book \"Effective Java Second Edition\" covers this in Item #47. </p>\n" }, { "answer_id": 29807393, "author": "Jonathan Conibeer", "author_id": 4821205, "author_profile": "https://Stackoverflow.com/users/4821205", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;tr&gt;\n&lt;td&gt;store&lt;/td&gt;\n &lt;td&gt;javascript{Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8)}&lt;/td&gt;\n&lt;td&gt;myRandomString&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 41010108, "author": "andrew lorien", "author_id": 4920725, "author_profile": "https://Stackoverflow.com/users/4920725", "pm_score": 0, "selected": false, "text": "<p>One more solution, which I've copied and pasted into hundreds of tests :</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td&gt;store&lt;/td&gt;\n &lt;td&gt;javascript{var myDate = new Date(); myDate.getFullYear()+&amp;quot;-&amp;quot;+(myDate.getMonth()+1)+&amp;quot;-&amp;quot;+myDate.getDate()+&amp;quot;-&amp;quot;+myDate.getHours()+myDate.getMinutes()+myDate.getSeconds()+myDate.getMilliseconds();}&lt;/td&gt;\n &lt;td&gt;S_Unique&lt;/td&gt;\n&lt;/tr&gt;\n&lt;tr&gt;\n &lt;td&gt;store&lt;/td&gt;\n &lt;td&gt;Selenium Test InternalRefID-${S_Unique}&lt;/td&gt;\n &lt;td&gt;UniqueInternalRefID&lt;/td&gt;\n&lt;/tr&gt;\n&lt;tr&gt;\n &lt;td&gt;store&lt;/td&gt;\n &lt;td&gt;Selenium Test Title-${S_Unique}&lt;/td&gt;\n &lt;td&gt;UniqueTitle&lt;/td&gt;\n&lt;/tr&gt;\n&lt;tr&gt;\n &lt;td&gt;store&lt;/td&gt;\n &lt;td&gt;SeleniumEmail-${G_Unique}@myURL.com&lt;/td&gt;\n &lt;td&gt;UniqueEmailAddress&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>Each test suite begins by setting a series of variables (if it's a big suite, use a separate file like Set_Variables.html). Those variables can then be used throughout your suite to set, test, and delete test data. And since the variables use the date rather than a random number, you can debug your test suite by looking for the objects which share a date.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14971/" ]
Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests? **The full story:** I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic.
First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages. Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters. You should be able to type a random number into a text field, for example: ``` type fieldName javascript{Math.floor(Math.random()*11)} ``` **Update:** You can define helper functions in a file called "user-extensions.js". See the [Selenium Reference](http://seleniumhq.org/docs/08_user_extensions.html#using-user-extensions-with-selenium-ide).
161,988
<p>I'm reading data from a table( from a MySQL Database) with Hibernate SQL Query. The thing is, the table contains a colum that is mapped to a char in Hibernate Model, and sometimes this column is empty. And I suppose this is where my exception comes from. How can I map a colum of char to my hibernate model without getting this error ? Thanks for your answers !</p> <hr> <p>Thank you for your answer ! My column is not nullable (I 'm using MySQL and this column is NOT NULL) Then, I don't think that </p> <pre><code>if (str == null) { </code></pre> <p>is appropriate.</p> <p>the error is : </p> <pre><code>15:30:35,289 INFO CharacterType:178 - could not read column value from result set: LSFUS11_20_; String index out of range: 0 </code></pre> <p>which results in the following exception :</p> <pre><code>java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:558) </code></pre> <p>I think I may try your solution, but with : </p> <pre><code>if (str == "") { </code></pre> <p>since it can't be null, it's just an empty String.</p> <p>Thanks for your piece code, I'm going to try that !</p>
[ { "answer_id": 162145, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 3, "selected": true, "text": "<p>I am assuming from your question that you're mapping this to a primitive character. Next time, please post the stacktrace that you receive (you may leave out where you call it, you could only include the hibernate stuff if your project is too sensitive).</p>\n\n<p>If you do map to a primitive character, and it is null, you will get an exception, because primitives cannot have null assigned to them. </p>\n\n<p>This class will mitigate this, the \"null\" character is returned as a character representing \"0\". You can customize this to your liking:</p>\n\n<pre><code>import java.sql.ResultSet;\nimport java.sql.SQLException;\n\nimport org.hibernate.type.CharacterType;\n\npublic class NullCharacterType extends CharacterType {\n\n /**\n * Serializable ID generated by Eclipse\n */\n private static final long serialVersionUID = 1L;\n\n public NullCharacterType() {\n super();\n }\n\n public Object get(final ResultSet rs, final String name)\n throws SQLException {\n final String str = rs.getString(name);\n if (str == null || str.length() == 0) {\n return new Character((char) 0);\n } else {\n return new Character(str.charAt(0));\n }\n }\n}\n</code></pre>\n\n<p>To use this new type, in your hibernate mapping, before you had something like:</p>\n\n<pre><code>&lt;property name=\"theChar\" type=\"character\"&gt;\n</code></pre>\n\n<p>Now, you just specify the class name as your type:</p>\n\n<pre><code>&lt;property name=\"theChar\" type=\"yourpackage.NullCharacterType\"&gt;\n</code></pre>\n\n<p>However, the best practice is to not use primitive types for database mapping. If at all possible, use Character instead of char, because that way you won't have an issue with null (null can be assigned to the wrapper types).</p>\n" }, { "answer_id": 3280869, "author": "srinivas", "author_id": 395796, "author_profile": "https://Stackoverflow.com/users/395796", "pm_score": 0, "selected": false, "text": "<p>Search your JBoss (server) whether <code>mysql.jar</code> (mysql-connector-java-5.1.7-bin) is present in lib files or not.\nEven I faced the same problem, after adding the <code>mysql.jar</code> file it is working fine.</p>\n" }, { "answer_id": 5408552, "author": "jmpeace", "author_id": 53415, "author_profile": "https://Stackoverflow.com/users/53415", "pm_score": 0, "selected": false, "text": "<p>use native function LEFT or RIGHT to change the column datatype in origin </p>\n\n<p>let's suppose this was the SQL query giving the error\nselect username from Users</p>\n\n<p>change it with:\nselect <strong>LEFT</strong>(username,<strong>100</strong>) from Users</p>\n\n<p>the number should be equal to the size of the field</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24069/" ]
I'm reading data from a table( from a MySQL Database) with Hibernate SQL Query. The thing is, the table contains a colum that is mapped to a char in Hibernate Model, and sometimes this column is empty. And I suppose this is where my exception comes from. How can I map a colum of char to my hibernate model without getting this error ? Thanks for your answers ! --- Thank you for your answer ! My column is not nullable (I 'm using MySQL and this column is NOT NULL) Then, I don't think that ``` if (str == null) { ``` is appropriate. the error is : ``` 15:30:35,289 INFO CharacterType:178 - could not read column value from result set: LSFUS11_20_; String index out of range: 0 ``` which results in the following exception : ``` java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:558) ``` I think I may try your solution, but with : ``` if (str == "") { ``` since it can't be null, it's just an empty String. Thanks for your piece code, I'm going to try that !
I am assuming from your question that you're mapping this to a primitive character. Next time, please post the stacktrace that you receive (you may leave out where you call it, you could only include the hibernate stuff if your project is too sensitive). If you do map to a primitive character, and it is null, you will get an exception, because primitives cannot have null assigned to them. This class will mitigate this, the "null" character is returned as a character representing "0". You can customize this to your liking: ``` import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.type.CharacterType; public class NullCharacterType extends CharacterType { /** * Serializable ID generated by Eclipse */ private static final long serialVersionUID = 1L; public NullCharacterType() { super(); } public Object get(final ResultSet rs, final String name) throws SQLException { final String str = rs.getString(name); if (str == null || str.length() == 0) { return new Character((char) 0); } else { return new Character(str.charAt(0)); } } } ``` To use this new type, in your hibernate mapping, before you had something like: ``` <property name="theChar" type="character"> ``` Now, you just specify the class name as your type: ``` <property name="theChar" type="yourpackage.NullCharacterType"> ``` However, the best practice is to not use primitive types for database mapping. If at all possible, use Character instead of char, because that way you won't have an issue with null (null can be assigned to the wrapper types).
162,007
<p>I have an object of the type System.Drawing.Image and want to make every pixel which has some specific color, for example black, transparent (that is, set alpha to 0 for this pixel).</p> <p>What is the best way to do this?</p>
[ { "answer_id": 162017, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Do you only know that it's an Image? If it's a Bitmap, you could call LockBits, check/fix every pixel and then unlock the bits again.</p>\n" }, { "answer_id": 162030, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 2, "selected": false, "text": "<p>Construct a Bitmap from the Image, and then call MakeTransparent() on that Bitmap. It allows you to specify a colour that should be rendered as transparent.</p>\n" }, { "answer_id": 162063, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 4, "selected": true, "text": "<p>One good approach is to use the <strong>ImageAttributes</strong> class to setup a list of colors to remap when drawing takes place. The advantage of this is good performance as well as allowing you to alter the remapping colors very easily. Try something like this code...</p>\n\n<pre><code>ImageAttributes attribs = new ImageAttributes();\nList&lt;ColorMap&gt; colorMaps = new List&lt;ColorMap&gt;();\n//\n// Remap black top be transparent\nColorMap remap = new ColorMap();\nremap.OldColor = Color.Black;\nremap.NewColor = Color.Transparent;\ncolorMaps.Add(remap);\n//\n// ...add additional remapping entries here...\n//\nattribs.SetRemapTable(colorMaps.ToArray(), ColorAdjustType.Bitmap);\ncontext.Graphics.DrawImage(image, imageRect, 0, 0, \n imageRect.Width, imageRect.Height, \n GraphicsUnit.Pixel, attribs);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7559/" ]
I have an object of the type System.Drawing.Image and want to make every pixel which has some specific color, for example black, transparent (that is, set alpha to 0 for this pixel). What is the best way to do this?
One good approach is to use the **ImageAttributes** class to setup a list of colors to remap when drawing takes place. The advantage of this is good performance as well as allowing you to alter the remapping colors very easily. Try something like this code... ``` ImageAttributes attribs = new ImageAttributes(); List<ColorMap> colorMaps = new List<ColorMap>(); // // Remap black top be transparent ColorMap remap = new ColorMap(); remap.OldColor = Color.Black; remap.NewColor = Color.Transparent; colorMaps.Add(remap); // // ...add additional remapping entries here... // attribs.SetRemapTable(colorMaps.ToArray(), ColorAdjustType.Bitmap); context.Graphics.DrawImage(image, imageRect, 0, 0, imageRect.Width, imageRect.Height, GraphicsUnit.Pixel, attribs); ```
162,011
<p>I have a Nant build file which executes NUnit after compiling the dll's. I am executing the NAnt build file with a task in CruiseControl. So NAnt is running the tests not CruiseControl.</p> <p>How do I configure it so that the CruiseControl web dashboard can be used to view the NUnit output ?</p> <hr> <p>This fixed it:</p> <pre><code>&lt;publishers&gt; &lt;merge&gt; &lt;files&gt; &lt;file&gt;build\*.test-result.xml&lt;/file&gt; &lt;/files&gt; &lt;/merge&gt; &lt;xmllogger /&gt; &lt;/publishers&gt; </code></pre>
[ { "answer_id": 162055, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 4, "selected": true, "text": "<p>You want to use the merge capabilities of CruiseControl to grab your NUnit XML output. This is the situation my company has going, and it seems to work fairly well. Here is a config snippet (This goes in the &lt;publishers&gt; element in CCNet.config):</p>\n<pre><code> &lt;merge&gt;\n &lt;files&gt;\n &lt;file&gt;&lt;path to XML output&gt;\\*.xml&lt;/file&gt;\n &lt;/files&gt;\n &lt;/merge&gt;\n</code></pre>\n<p>Hope this works for you.</p>\n" }, { "answer_id": 162062, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": 0, "selected": false, "text": "<p>Make sure that in the the dashboard.config file you have a valid xsl file in the section we run nunit with ncover and use this xsl\\NCoverExplorer.xsl\nI think that the xsl file we took from the ncover install somewhere.</p>\n\n<p>also make sure that this line is correct:\n </p>\n\n<p>Then make sure in the ccnet.config file that under the section you have the xml output from the nunit test listed.</p>\n\n<p>Also make sure you put the xsl file in the xsl folder under webdashboard.</p>\n" }, { "answer_id": 2237994, "author": "ScottD", "author_id": 111506, "author_profile": "https://Stackoverflow.com/users/111506", "pm_score": 2, "selected": false, "text": "<p>FWIW I had the same problem (CC.Net fires off Nant which does the compile and NUnit work) and my NUnit output was not appearing on CC.Net either. I already had the <code>&lt;merge&gt;</code> task inside my <code>&lt;publisher&gt;</code> task (and before the <code>&lt;xmllogger&gt;</code> task) and still nothing.</p>\n\n<p>The one thing that I did <em>not</em> have, b/c I didn't explicitly need it, was a <code>&lt;workingDirectory&gt;</code> node in my <code>&lt;project&gt;</code>. As soon as I added that my NUnit output appeared immediately. Looks as if there's a dependency there for whatever reason. Hope this helps some of you.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083160/" ]
I have a Nant build file which executes NUnit after compiling the dll's. I am executing the NAnt build file with a task in CruiseControl. So NAnt is running the tests not CruiseControl. How do I configure it so that the CruiseControl web dashboard can be used to view the NUnit output ? --- This fixed it: ``` <publishers> <merge> <files> <file>build\*.test-result.xml</file> </files> </merge> <xmllogger /> </publishers> ```
You want to use the merge capabilities of CruiseControl to grab your NUnit XML output. This is the situation my company has going, and it seems to work fairly well. Here is a config snippet (This goes in the <publishers> element in CCNet.config): ``` <merge> <files> <file><path to XML output>\*.xml</file> </files> </merge> ``` Hope this works for you.
162,032
<p>I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.</p> <p>Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?</p> <pre><code>$mapped_array = mapkeys($array_with_keys, $array_with_values); </code></pre>
[ { "answer_id": 162040, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 7, "selected": true, "text": "<p>See <a href=\"http://php.net/array_combine\" rel=\"noreferrer\"><code>array_combine()</code></a> on PHP.net.</p>\n" }, { "answer_id": 163069, "author": "Christopher Lightfoot", "author_id": 24525, "author_profile": "https://Stackoverflow.com/users/24525", "pm_score": 4, "selected": false, "text": "<p>(from the docs for easy reading)</p>\n\n<p>array_combine — Creates an array by using one array for keys and another for its values</p>\n\n<p><strong>Description</strong></p>\n\n<p><code>array array_combine ( array $keys , array $values )</code></p>\n\n<p>Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.</p>\n\n<p><strong>Parameters</strong></p>\n\n<p>keys - Array of keys to be used. Illegal values for key will be converted to string.</p>\n\n<p>values - Array of values to be used</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>&lt;?php\n$a = array('green', 'red', 'yellow');\n$b = array('avocado', 'apple', 'banana');\n$c = array_combine($a, $b);\n\nprint_r($c);\n?&gt;\n</code></pre>\n\n<p>The above example will output:</p>\n\n<pre><code>Array\n(\n [green] =&gt; avocado\n [red] =&gt; apple\n [yellow] =&gt; banana\n)\n</code></pre>\n" }, { "answer_id": 1923763, "author": "Mathias", "author_id": 234034, "author_profile": "https://Stackoverflow.com/users/234034", "pm_score": 3, "selected": false, "text": "<p>This should do the trick</p>\n\n<pre><code>function array_merge_keys($ray1, $ray2) {\n $keys = array_merge(array_keys($ray1), array_keys($ray2));\n $vals = array_merge($ray1, $ray2);\n return array_combine($keys, $vals);\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other. Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines? ``` $mapped_array = mapkeys($array_with_keys, $array_with_values); ```
See [`array_combine()`](http://php.net/array_combine) on PHP.net.
162,037
<p>My Outlook add-in handles NewInspector event of the Inspector object, in order to display a custom form for the mail item.</p> <p>I can get EntryID of the CurrentItem of the Inspector object which is passed as a parameter of the event. But, the problem is that the EntryID of the current mail item is shorter than it should be, and is unknown. I know every EntryID of every mail item that was created, and I can see that specific mail item has a wrong EntryID.</p> <p>What is wrong?</p>
[ { "answer_id": 162585, "author": "Nenad Dobrilovic", "author_id": 22062, "author_profile": "https://Stackoverflow.com/users/22062", "pm_score": 3, "selected": true, "text": "<p>The idea is to remember every EntryID of the MailItem that was created by an add-in, so that it can be treated differently later. Problem was that EntryID of the item opened by an Inspector was the short one, and not in the list of remembered ids, although it should be.</p>\n\n<p>Few lines of code where I was creating mail item were:</p>\n\n<pre><code>item.Save();\nitem.Move(some_folder);\nitems_list.Add(item.EntryID);\n</code></pre>\n\n<p>Folder 'some_folder' is inside of external non-default PST, so mail item gets new EntryID. I changed those lines to:</p>\n\n<pre><code>item.Save();\nitem = (Outlook.MailItem)item.Move(some_folder);\nitems_list.Add(item.EntryID);\n</code></pre>\n\n<p>Now, item has a new EntryID, which can be found later.</p>\n" }, { "answer_id": 58498283, "author": "dotNET", "author_id": 1137199, "author_profile": "https://Stackoverflow.com/users/1137199", "pm_score": 0, "selected": false, "text": "<p>Just in case this helps anyone, all I needed to do is to call <code>MailItem.Save()</code> before fetching <code>EntryID</code>. A newly created <code>MailItem</code> doesn't have any <code>EntryID</code> till it is saved (in <code>Drafts</code> folder in my case).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22062/" ]
My Outlook add-in handles NewInspector event of the Inspector object, in order to display a custom form for the mail item. I can get EntryID of the CurrentItem of the Inspector object which is passed as a parameter of the event. But, the problem is that the EntryID of the current mail item is shorter than it should be, and is unknown. I know every EntryID of every mail item that was created, and I can see that specific mail item has a wrong EntryID. What is wrong?
The idea is to remember every EntryID of the MailItem that was created by an add-in, so that it can be treated differently later. Problem was that EntryID of the item opened by an Inspector was the short one, and not in the list of remembered ids, although it should be. Few lines of code where I was creating mail item were: ``` item.Save(); item.Move(some_folder); items_list.Add(item.EntryID); ``` Folder 'some\_folder' is inside of external non-default PST, so mail item gets new EntryID. I changed those lines to: ``` item.Save(); item = (Outlook.MailItem)item.Move(some_folder); items_list.Add(item.EntryID); ``` Now, item has a new EntryID, which can be found later.
162,057
<p>I'm building a Thunderbird extension and would like to add my own header to all outgoing email (e.g. &lt;myext-version: 1.0&gt; ). Any idea how to do this? I know it's possible since this is done in the OpenPGP Enigmail extension. Thanks!</p>
[ { "answer_id": 229559, "author": "Colin Pickard", "author_id": 12744, "author_profile": "https://Stackoverflow.com/users/12744", "pm_score": 1, "selected": false, "text": "<p>I don't know the answer but just some thoughts...</p>\n\n<p>I think thunderbird extensions are usually just xul and js. From the enigmail site:</p>\n\n<blockquote>\n <p>Unlike most Mozilla AddOns, Enigmail\n contains platform dependent parts: it\n depends on the CPU, the compiler,\n libraries of the operating system and\n the email application it shall\n integrate into.</p>\n</blockquote>\n\n<p>Looking at the Enigmail source code, <a href=\"http://www.mozdev.org/source/browse/enigmail/src/src/mimehdrs2.cpp?rev=1.3;content-type=text%2Fx-cvsweb-markup\" rel=\"nofollow noreferrer\">this might be the relevant section</a> (written in c++)</p>\n\n<p>So you might need to either translate what they've done into js(!) or keep looking for a different example.</p>\n\n<p><a href=\"http://email.about.com/cs/mozillatips/qt/et030604.htm\" rel=\"nofollow noreferrer\">Here's another link that might be helpful</a></p>\n" }, { "answer_id": 686118, "author": "gerhard", "author_id": 83151, "author_profile": "https://Stackoverflow.com/users/83151", "pm_score": 2, "selected": false, "text": "<p>Here is the code from one extension I'm working on:</p>\n\n<pre><code>function SendObserver() {\n this.register();\n}\n\nSendObserver.prototype = {\n observe: function(subject, topic, data) {\n\n /* thunderbird sends a notification even when it's only saving the message as a draft.\n * We examine the caller chain to check for valid send notifications \n */\n var f = this.observe;\n while (f) {\n if(/Save/.test(f.name)) {\n print(\"Ignoring send notification because we're probably autosaving or saving as a draft/template\");\n return;\n }\n f = f.caller;\n }\n\n // add your headers here, separated by \\r\\n\n subject.gMsgCompose.compFields.otherRandomHeaders += \"x-test: test\\r\\n\"; \n }\n\n },\n register: function() {\n var observerService = Components.classes[\"@mozilla.org/observer-service;1\"]\n .getService(Components.interfaces.nsIObserverService);\n observerService.addObserver(this, \"mail:composeOnSend\", false);\n },\n unregister: function() {\n var observerService = Components.classes[\"@mozilla.org/observer-service;1\"]\n .getService(Components.interfaces.nsIObserverService);\n observerService.removeObserver(this, \"mail:composeOnSend\");\n }\n};\n\n\n/*\n * Register observer for send events. Check for event target to ensure that the \n * compose window is loaded/unloaded (and not the content of the editor).\n * \n * Unregister to prevent memory leaks (as per MDC documentation).\n */\nvar sendObserver;\nwindow.addEventListener('load', function (e) {if (e.target == document) sendObserver = new SendObserver(); }, true);\nwindow.addEventListener('unload', function (e) { if (e.target == document) sendObserver.unregister();}, true);\n</code></pre>\n\n<p>Put this inside a .js file that is loaded by the compose window (for example by overlaying <code>chrome://messenger/content/messengercompose/messengercompose.xul)</code>.</p>\n\n<p>The check in SendObserver.observe was necessary in my case because I wanted to do a user interaction, but you could probably leave it out.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24473/" ]
I'm building a Thunderbird extension and would like to add my own header to all outgoing email (e.g. <myext-version: 1.0> ). Any idea how to do this? I know it's possible since this is done in the OpenPGP Enigmail extension. Thanks!
Here is the code from one extension I'm working on: ``` function SendObserver() { this.register(); } SendObserver.prototype = { observe: function(subject, topic, data) { /* thunderbird sends a notification even when it's only saving the message as a draft. * We examine the caller chain to check for valid send notifications */ var f = this.observe; while (f) { if(/Save/.test(f.name)) { print("Ignoring send notification because we're probably autosaving or saving as a draft/template"); return; } f = f.caller; } // add your headers here, separated by \r\n subject.gMsgCompose.compFields.otherRandomHeaders += "x-test: test\r\n"; } }, register: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "mail:composeOnSend", false); }, unregister: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.removeObserver(this, "mail:composeOnSend"); } }; /* * Register observer for send events. Check for event target to ensure that the * compose window is loaded/unloaded (and not the content of the editor). * * Unregister to prevent memory leaks (as per MDC documentation). */ var sendObserver; window.addEventListener('load', function (e) {if (e.target == document) sendObserver = new SendObserver(); }, true); window.addEventListener('unload', function (e) { if (e.target == document) sendObserver.unregister();}, true); ``` Put this inside a .js file that is loaded by the compose window (for example by overlaying `chrome://messenger/content/messengercompose/messengercompose.xul)`. The check in SendObserver.observe was necessary in my case because I wanted to do a user interaction, but you could probably leave it out.
162,064
<p>I am using a textbox in a .NET 2 winforms app that is setup with a custom AutoCompleteSource. Is there anyway through code that I can increase the width of the list that appears containing the auto complete suggestions? </p> <p>Ideally I would like to do this without increasing the width of the textbox as I am short for space in the UI.</p>
[ { "answer_id": 162222, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Hmmm, there's no direct way really. You'd probably have to resort to subclassing (in the Windows API sense) the TextBox to do that, and even then there'd be a lot of guessing to do.</p>\n" }, { "answer_id": 162547, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 1, "selected": false, "text": "<p>Not that I know of, but you can auto-size the Textbox so that it is only wide when it needs to be, rather than always as wide as the longest text.</p>\n\n<p>Example from <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3311429&amp;SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3311429&amp;SiteID=1</a></p>\n\n<pre><code>Public Class Form1\nPrivate WithEvents T As TextBox\nPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n T = New TextBox\n T.SetBounds(20, 20, 100, 30)\n T.Font = New Font(\"Arial\", 12, FontStyle.Regular)\n T.Multiline = True\n T.Text = \"Type Here\"\n T.SelectAll()\n Controls.Add(T)\nEnd Sub\nPrivate Sub T_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles T.TextChanged\n Dim Width As Integer = TextRenderer.MeasureText(T.Text, T.Font).Width + 10\n Dim Height As Integer = TextRenderer.MeasureText(T.Text, T.Font).Height + 10\n T.Width = Width\n T.Height = Height\nEnd Sub\n</code></pre>\n\n<p>End Class</p>\n" }, { "answer_id": 164989, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 0, "selected": false, "text": "<p>As far as I know the TextBox class wraps the complete AutoComplete API that comes with Windows. Alas, this fact is not \"portable\" to other parts of the .NET framework.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6165/" ]
I am using a textbox in a .NET 2 winforms app that is setup with a custom AutoCompleteSource. Is there anyway through code that I can increase the width of the list that appears containing the auto complete suggestions? Ideally I would like to do this without increasing the width of the textbox as I am short for space in the UI.
Not that I know of, but you can auto-size the Textbox so that it is only wide when it needs to be, rather than always as wide as the longest text. Example from <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3311429&SiteID=1> ``` Public Class Form1 Private WithEvents T As TextBox Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load T = New TextBox T.SetBounds(20, 20, 100, 30) T.Font = New Font("Arial", 12, FontStyle.Regular) T.Multiline = True T.Text = "Type Here" T.SelectAll() Controls.Add(T) End Sub Private Sub T_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles T.TextChanged Dim Width As Integer = TextRenderer.MeasureText(T.Text, T.Font).Width + 10 Dim Height As Integer = TextRenderer.MeasureText(T.Text, T.Font).Height + 10 T.Width = Width T.Height = Height End Sub ``` End Class
162,079
<p>We have the usual <strong>web.xml</strong> for our web application which includes some jsp and jsp tag files. I want to switch to using pre-compiled jsp's. I have the pre-compilation happening in the build ok, and it generates the web.xml fragment and now I want to merge the fragment into the main web.xml.</p> <p>Is there an <strong>include</strong> type directive for <strong>web.xml</strong> that will let me include the fragment. </p> <p>Ideally I will leave things as is for DEV- as its useful to change jsp's on the fly and see the changes immediately but then for UAT/PROD, the jsp's will be pre-compiled and thus work faster.</p>
[ { "answer_id": 162186, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 2, "selected": false, "text": "<p>Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml - <strong>addWebXmlMappings</strong></p>\n\n<pre><code> &lt;jasper2\n validateXml=\"false\"\n uriroot=\"${web.dir}\"\n addWebXmlMappings=\"true\"\n webXmlFragment=\"${web.dir}/WEB-INF/classes/jasper_generated_web.xml\"\n outputDir=\"${web.dir}/WEB-INF/jsp-src\" /&gt;\n</code></pre>\n\n<p>I wonder how good the merge is...</p>\n\n<p>Annoyingly you need to generate the fragment still, even though its not needed after this task.</p>\n" }, { "answer_id": 171192, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 3, "selected": true, "text": "<p>I use the <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html\" rel=\"nofollow noreferrer\">Tomcat jasper ANT tasks</a> in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml.</p>\n\n<pre><code> &lt;?xml version=\"1.0\"?&gt;\n&lt;project name=\"jspc\" basedir=\".\" default=\"all\"&gt;\n &lt;import file=\"${build.appserver.home}/bin/catalina-tasks.xml\"/&gt;\n\n &lt;target name=\"all\" depends=\"jspc,compile\"&gt;&lt;/target&gt;\n\n &lt;target name=\"jspc\"&gt;\n &lt;jasper\n validateXml=\"false\"\n uriroot=\"${build.war.dir}\"\n webXmlFragment=\"${build.war.dir}/WEB-INF/generated_web.xml\"\n addWebXmlMappings=\"true\"\n outputDir=\"${build.src.dir}\" /&gt;\n &lt;/target&gt;\n\n &lt;target name=\"compile\"&gt;\n &lt;javac destdir=\"${build.dir}/classes\"\n srcdir=\"${build.src.dir}\"\n optimize=\"on\"\n debug=\"off\"\n failonerror=\"true\"\n source=\"1.5\"\n target=\"1.5\"\n excludes=\"**/*.smap\"&gt;\n &lt;classpath&gt;\n &lt;fileset dir=\"${build.war.dir}/WEB-INF/classes\"&gt;\n &lt;include name=\"*.class\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${build.war.lib.dir}\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${build.appserver.home}/lib\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt; \n &lt;fileset dir=\"${build.appserver.home}/bin\"&gt;\n &lt;include name=\"*.jar\"/&gt;\n &lt;/fileset&gt;\n &lt;/classpath&gt;\n &lt;include name=\"**\" /&gt;\n &lt;exclude name=\"tags/**\"/&gt;\n &lt;/javac&gt;\n &lt;/target&gt;\n\n &lt;target name=\"clean\"&gt;\n &lt;delete&gt;\n &lt;fileset dir=\"${build.src.dir}\"/&gt;\n &lt;fileset dir=\"${build.dir}/classes/org/apache/jsp\"/&gt;\n &lt;/delete&gt;\n &lt;/target&gt;\n&lt;/project&gt;\n</code></pre>\n\n<p>If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.</p>\n" }, { "answer_id": 1532580, "author": "Alexander Pogrebnyak", "author_id": 185722, "author_profile": "https://Stackoverflow.com/users/185722", "pm_score": 2, "selected": false, "text": "<p>Because the generated fragment is not a valid XML file ( it's a fragment after all ), it is not possible to use XSLT directly. On the other hand you don't have to. Here is a simple trick that will give you exactly what you need.</p>\n\n<p>In your web.xml file insert XML comment <code>&lt;!-- @JSPS_MAP@ --&gt;</code> between <code>&lt;servlet&gt;</code> and <code>&lt;servlet-mapping&gt;</code> elements, e.g.</p>\n\n<pre><code> &lt;servlet&gt;\n &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt;\n &lt;servlet-class&gt;my.servlets.MyServlet&lt;/servlet-class&gt;\n &lt;servlet&gt;\n\n &lt;!-- @JSPS_MAP@ --&gt;\n\n &lt;servlet-mapping&gt;\n &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/my-servlet&lt;/url-pattern&gt;\n &lt;/servlet-mapping&gt;\n</code></pre>\n\n<p>Then use a token filter to replace <code>@JSPS_MAP@</code> tag with generated content.</p>\n\n<pre><code>&lt;loadfile\n property=\"generated.web.xml.fragment\"\n srcFile=\"${generated.fragment.file}\"\n/&gt;\n\n&lt;copy file=\"${orig-web-content.dir}/WEB-INF/web.xml\"\n toFile=\"${generated-web-content.dir}/WEB-INF/web.xml\"\n&gt;\n &lt;filterset&gt;\n &lt;filter token=\"JSPS_MAP\"\n value=\" --&amp;gt; ${generated.web.xml.fragment} &amp;lt;!-- \"\n /&gt;\n &lt;/filterset&gt;\n&lt;/copy&gt;\n</code></pre>\n\n<p>This approach has an advantage that the original web.xml file is completely valid (a tag is hidden in the comment), but gives you total control of where and when the generated fragment will be inserted.</p>\n\n<p>So for DEV build, just copy <code>${orig-web-content.dir}/WEB-INF/web.xml</code> to <code>${generated-web-content.dir}/WEB-INF/web.xml</code> without filtering.</p>\n" }, { "answer_id": 1859394, "author": "JasonPlutext", "author_id": 1031689, "author_profile": "https://Stackoverflow.com/users/1031689", "pm_score": 1, "selected": false, "text": "<p>There is the <strong>jasper2</strong> ant task others have noted. I thought I'd mention a couple of other options I've found.</p>\n\n<p>One is cactus' <strong>webxmlmerge</strong> ant task, which uses org.codehaus.cargo.module.webapp.WebXmlMerger </p>\n\n<p>Another would be to use <strong>JAXB</strong> to manipulate the web.xml; Sebastien Dionne's <a href=\"http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator\" rel=\"nofollow noreferrer\">dtd-schemas-generator</a> demo does this. Not sure what the license is though.</p>\n\n<p>fwiw having considered these options i think I'm going to use the ant <strong>XSLT</strong> task.</p>\n" }, { "answer_id": 3151739, "author": "Rick Justesen", "author_id": 380346, "author_profile": "https://Stackoverflow.com/users/380346", "pm_score": 1, "selected": false, "text": "<p>In your web.xml file if you have tags to specify where the merge starts and ends the addWebXmlMappings flag will generate the file correctly for you. The tags are:\n&lt;!-- JSPC servlet mappings start -->\nand \n&lt;!-- JSPC servlet mappings end -->\nafter doing this to my web.xml everything worked like a charm! (I have to look at the code for org.apcahe.jasper.JspC to see how this was implemented)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48310/" ]
We have the usual **web.xml** for our web application which includes some jsp and jsp tag files. I want to switch to using pre-compiled jsp's. I have the pre-compilation happening in the build ok, and it generates the web.xml fragment and now I want to merge the fragment into the main web.xml. Is there an **include** type directive for **web.xml** that will let me include the fragment. Ideally I will leave things as is for DEV- as its useful to change jsp's on the fly and see the changes immediately but then for UAT/PROD, the jsp's will be pre-compiled and thus work faster.
I use the [Tomcat jasper ANT tasks](http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html) in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml. ``` <?xml version="1.0"?> <project name="jspc" basedir="." default="all"> <import file="${build.appserver.home}/bin/catalina-tasks.xml"/> <target name="all" depends="jspc,compile"></target> <target name="jspc"> <jasper validateXml="false" uriroot="${build.war.dir}" webXmlFragment="${build.war.dir}/WEB-INF/generated_web.xml" addWebXmlMappings="true" outputDir="${build.src.dir}" /> </target> <target name="compile"> <javac destdir="${build.dir}/classes" srcdir="${build.src.dir}" optimize="on" debug="off" failonerror="true" source="1.5" target="1.5" excludes="**/*.smap"> <classpath> <fileset dir="${build.war.dir}/WEB-INF/classes"> <include name="*.class" /> </fileset> <fileset dir="${build.war.lib.dir}"> <include name="*.jar" /> </fileset> <fileset dir="${build.appserver.home}/lib"> <include name="*.jar" /> </fileset> <fileset dir="${build.appserver.home}/bin"> <include name="*.jar"/> </fileset> </classpath> <include name="**" /> <exclude name="tags/**"/> </javac> </target> <target name="clean"> <delete> <fileset dir="${build.src.dir}"/> <fileset dir="${build.dir}/classes/org/apache/jsp"/> </delete> </target> </project> ``` If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.
162,086
<p>in web.xml i set my welcome file to a jsp within web.xml</p> <pre><code>&lt;welcome-file&gt;WEB-INF/index.jsp&lt;/welcome-file&gt; </code></pre> <p>inside index.jsp i then forward on to a servlet </p> <pre><code>&lt;% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %&gt; </code></pre> <p>however the application tries to find the servlet at the following path </p> <pre><code>applicationName/WEB-INF/myServlet </code></pre> <p>the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?</p>
[ { "answer_id": 162186, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 2, "selected": false, "text": "<p>Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml - <strong>addWebXmlMappings</strong></p>\n\n<pre><code> &lt;jasper2\n validateXml=\"false\"\n uriroot=\"${web.dir}\"\n addWebXmlMappings=\"true\"\n webXmlFragment=\"${web.dir}/WEB-INF/classes/jasper_generated_web.xml\"\n outputDir=\"${web.dir}/WEB-INF/jsp-src\" /&gt;\n</code></pre>\n\n<p>I wonder how good the merge is...</p>\n\n<p>Annoyingly you need to generate the fragment still, even though its not needed after this task.</p>\n" }, { "answer_id": 171192, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 3, "selected": true, "text": "<p>I use the <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html\" rel=\"nofollow noreferrer\">Tomcat jasper ANT tasks</a> in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml.</p>\n\n<pre><code> &lt;?xml version=\"1.0\"?&gt;\n&lt;project name=\"jspc\" basedir=\".\" default=\"all\"&gt;\n &lt;import file=\"${build.appserver.home}/bin/catalina-tasks.xml\"/&gt;\n\n &lt;target name=\"all\" depends=\"jspc,compile\"&gt;&lt;/target&gt;\n\n &lt;target name=\"jspc\"&gt;\n &lt;jasper\n validateXml=\"false\"\n uriroot=\"${build.war.dir}\"\n webXmlFragment=\"${build.war.dir}/WEB-INF/generated_web.xml\"\n addWebXmlMappings=\"true\"\n outputDir=\"${build.src.dir}\" /&gt;\n &lt;/target&gt;\n\n &lt;target name=\"compile\"&gt;\n &lt;javac destdir=\"${build.dir}/classes\"\n srcdir=\"${build.src.dir}\"\n optimize=\"on\"\n debug=\"off\"\n failonerror=\"true\"\n source=\"1.5\"\n target=\"1.5\"\n excludes=\"**/*.smap\"&gt;\n &lt;classpath&gt;\n &lt;fileset dir=\"${build.war.dir}/WEB-INF/classes\"&gt;\n &lt;include name=\"*.class\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${build.war.lib.dir}\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${build.appserver.home}/lib\"&gt;\n &lt;include name=\"*.jar\" /&gt;\n &lt;/fileset&gt; \n &lt;fileset dir=\"${build.appserver.home}/bin\"&gt;\n &lt;include name=\"*.jar\"/&gt;\n &lt;/fileset&gt;\n &lt;/classpath&gt;\n &lt;include name=\"**\" /&gt;\n &lt;exclude name=\"tags/**\"/&gt;\n &lt;/javac&gt;\n &lt;/target&gt;\n\n &lt;target name=\"clean\"&gt;\n &lt;delete&gt;\n &lt;fileset dir=\"${build.src.dir}\"/&gt;\n &lt;fileset dir=\"${build.dir}/classes/org/apache/jsp\"/&gt;\n &lt;/delete&gt;\n &lt;/target&gt;\n&lt;/project&gt;\n</code></pre>\n\n<p>If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.</p>\n" }, { "answer_id": 1532580, "author": "Alexander Pogrebnyak", "author_id": 185722, "author_profile": "https://Stackoverflow.com/users/185722", "pm_score": 2, "selected": false, "text": "<p>Because the generated fragment is not a valid XML file ( it's a fragment after all ), it is not possible to use XSLT directly. On the other hand you don't have to. Here is a simple trick that will give you exactly what you need.</p>\n\n<p>In your web.xml file insert XML comment <code>&lt;!-- @JSPS_MAP@ --&gt;</code> between <code>&lt;servlet&gt;</code> and <code>&lt;servlet-mapping&gt;</code> elements, e.g.</p>\n\n<pre><code> &lt;servlet&gt;\n &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt;\n &lt;servlet-class&gt;my.servlets.MyServlet&lt;/servlet-class&gt;\n &lt;servlet&gt;\n\n &lt;!-- @JSPS_MAP@ --&gt;\n\n &lt;servlet-mapping&gt;\n &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt;\n &lt;url-pattern&gt;/my-servlet&lt;/url-pattern&gt;\n &lt;/servlet-mapping&gt;\n</code></pre>\n\n<p>Then use a token filter to replace <code>@JSPS_MAP@</code> tag with generated content.</p>\n\n<pre><code>&lt;loadfile\n property=\"generated.web.xml.fragment\"\n srcFile=\"${generated.fragment.file}\"\n/&gt;\n\n&lt;copy file=\"${orig-web-content.dir}/WEB-INF/web.xml\"\n toFile=\"${generated-web-content.dir}/WEB-INF/web.xml\"\n&gt;\n &lt;filterset&gt;\n &lt;filter token=\"JSPS_MAP\"\n value=\" --&amp;gt; ${generated.web.xml.fragment} &amp;lt;!-- \"\n /&gt;\n &lt;/filterset&gt;\n&lt;/copy&gt;\n</code></pre>\n\n<p>This approach has an advantage that the original web.xml file is completely valid (a tag is hidden in the comment), but gives you total control of where and when the generated fragment will be inserted.</p>\n\n<p>So for DEV build, just copy <code>${orig-web-content.dir}/WEB-INF/web.xml</code> to <code>${generated-web-content.dir}/WEB-INF/web.xml</code> without filtering.</p>\n" }, { "answer_id": 1859394, "author": "JasonPlutext", "author_id": 1031689, "author_profile": "https://Stackoverflow.com/users/1031689", "pm_score": 1, "selected": false, "text": "<p>There is the <strong>jasper2</strong> ant task others have noted. I thought I'd mention a couple of other options I've found.</p>\n\n<p>One is cactus' <strong>webxmlmerge</strong> ant task, which uses org.codehaus.cargo.module.webapp.WebXmlMerger </p>\n\n<p>Another would be to use <strong>JAXB</strong> to manipulate the web.xml; Sebastien Dionne's <a href=\"http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator\" rel=\"nofollow noreferrer\">dtd-schemas-generator</a> demo does this. Not sure what the license is though.</p>\n\n<p>fwiw having considered these options i think I'm going to use the ant <strong>XSLT</strong> task.</p>\n" }, { "answer_id": 3151739, "author": "Rick Justesen", "author_id": 380346, "author_profile": "https://Stackoverflow.com/users/380346", "pm_score": 1, "selected": false, "text": "<p>In your web.xml file if you have tags to specify where the merge starts and ends the addWebXmlMappings flag will generate the file correctly for you. The tags are:\n&lt;!-- JSPC servlet mappings start -->\nand \n&lt;!-- JSPC servlet mappings end -->\nafter doing this to my web.xml everything worked like a charm! (I have to look at the code for org.apcahe.jasper.JspC to see how this was implemented)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
in web.xml i set my welcome file to a jsp within web.xml ``` <welcome-file>WEB-INF/index.jsp</welcome-file> ``` inside index.jsp i then forward on to a servlet ``` <% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %> ``` however the application tries to find the servlet at the following path ``` applicationName/WEB-INF/myServlet ``` the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?
I use the [Tomcat jasper ANT tasks](http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html) in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml. ``` <?xml version="1.0"?> <project name="jspc" basedir="." default="all"> <import file="${build.appserver.home}/bin/catalina-tasks.xml"/> <target name="all" depends="jspc,compile"></target> <target name="jspc"> <jasper validateXml="false" uriroot="${build.war.dir}" webXmlFragment="${build.war.dir}/WEB-INF/generated_web.xml" addWebXmlMappings="true" outputDir="${build.src.dir}" /> </target> <target name="compile"> <javac destdir="${build.dir}/classes" srcdir="${build.src.dir}" optimize="on" debug="off" failonerror="true" source="1.5" target="1.5" excludes="**/*.smap"> <classpath> <fileset dir="${build.war.dir}/WEB-INF/classes"> <include name="*.class" /> </fileset> <fileset dir="${build.war.lib.dir}"> <include name="*.jar" /> </fileset> <fileset dir="${build.appserver.home}/lib"> <include name="*.jar" /> </fileset> <fileset dir="${build.appserver.home}/bin"> <include name="*.jar"/> </fileset> </classpath> <include name="**" /> <exclude name="tags/**"/> </javac> </target> <target name="clean"> <delete> <fileset dir="${build.src.dir}"/> <fileset dir="${build.dir}/classes/org/apache/jsp"/> </delete> </target> </project> ``` If you already have the JSP compilation working and just want to merge the web.xml files, a simple XSLT could be written to add selected elements(such as the servlet mappings) from the newly generated web,xml into your original.
162,088
<p>I use <code>serialize</code> in one <code>ActiveRecord</code> model to serialize an <code>Array</code> of simple Hashes into a text database field. I even use the second parameter to coerce deserialization into <code>Array</code>s.</p> <pre><code>class Shop &lt; ActiveRecord::Base serialize : recipients, Array end </code></pre> <p>It seems to work fine but, after a few requests, the content of <code>recipients</code> turns to <code>HashOfIndifferentAccess</code> hashes instead of arrays. This only happens after a few reloads of the models and I haven't been able to reproduce it in tests or the console, only in production environment.</p>
[ { "answer_id": 12409593, "author": "J_McCaffrey", "author_id": 318699, "author_profile": "https://Stackoverflow.com/users/318699", "pm_score": 1, "selected": false, "text": "<p>This seems like something you should be able to reproduce locally with enough testing.\nLook through your production db and logs and attempt to use the same data in your local tests.</p>\n\n<p>The hashwithindifferentaccess is coming from the controller. Perhaps you are taking data straight from the controller and not massaging it at all.</p>\n\n<p>Create a gist of your page, controller, and model saving code, and update this question.\nDepending on how deeply nested your hash, you can convert a HWIA hash to a regular one before saving.</p>\n\n<p>Shouldn't be too hard to debug and resolve.</p>\n" }, { "answer_id": 12501093, "author": "Jordan Sitkin", "author_id": 273987, "author_profile": "https://Stackoverflow.com/users/273987", "pm_score": 2, "selected": false, "text": "<p>I had the same problem with some serialized fields in one of my Rails 3.1 apps. After a lot of troubleshooting I narrowed it down to a character encoding issue. I wasn't able to reproduce it locally because I was using SQLite, while my production environment was on Postgres.</p>\n\n<p>Try applying <code>some_field.force_encoding(Encoding::UTF_8)</code> on all values before they are serialized and see what happens.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21702/" ]
I use `serialize` in one `ActiveRecord` model to serialize an `Array` of simple Hashes into a text database field. I even use the second parameter to coerce deserialization into `Array`s. ``` class Shop < ActiveRecord::Base serialize : recipients, Array end ``` It seems to work fine but, after a few requests, the content of `recipients` turns to `HashOfIndifferentAccess` hashes instead of arrays. This only happens after a few reloads of the models and I haven't been able to reproduce it in tests or the console, only in production environment.
I had the same problem with some serialized fields in one of my Rails 3.1 apps. After a lot of troubleshooting I narrowed it down to a character encoding issue. I wasn't able to reproduce it locally because I was using SQLite, while my production environment was on Postgres. Try applying `some_field.force_encoding(Encoding::UTF_8)` on all values before they are serialized and see what happens.
162,113
<p>I'm looking for an elegant, high performance solution to the following problem. </p> <p>There are 256 linked lists. </p> <ul> <li>Each list contains the same types of object that among other things holds a whole number that is used to define a sort order.</li> <li>All numbers across all lists are unique</li> <li>Each individual list is sorted in ascending order by these numbers</li> </ul> <p>How would you create a single ascending ordered list from all the objects from the 256 original linked lists? I'd prefer not to brute force it, and have a few other ideas, but this seems like one of those problems that there's a standard, optimal solution for.</p>
[ { "answer_id": 162131, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<p>You could use a priority queue that holds the “topmost” item of each of the 256 linked lists. This “topmost” item is the one that is scheduled to be inserted into the resulting list. This way, you can just take the smallest element from the priority queue, insert it into your resulting queue, and insert its next element into the priority queue:</p>\n\n<pre><code># Preprocessing:\nresult = list.new()\nqueue = priority_queue.new()\n\nforeach (list in lists):\n queue.push(list.first())\n\n# Main loop:\nwhile (not queue.empty()):\n node = queue.pop()\n result.insert(node)\n if (node.next() != null):\n queue.push(node.next())\n</code></pre>\n" }, { "answer_id": 162133, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 1, "selected": false, "text": "<p>if the individual lists are already sorted, then it's a direct application of the <a href=\"http://en.wikipedia.org/wiki/Merge_algorithm\" rel=\"nofollow noreferrer\">merge algorithm</a>. in short: compare all the heads and pick the smallest, take it out of its list and push into your output list. repeat until all source lists are empty.</p>\n\n<p>edit: Konrad's use of a priority queue (a <a href=\"http://en.wikipedia.org/wiki/Heap_(data_structure)\" rel=\"nofollow noreferrer\">heap</a>) is a far more elegant and scalable solution, but maybe 256 input lists are so few that a simple compare could be faster.</p>\n" }, { "answer_id": 237529, "author": "paperhorse", "author_id": 4498, "author_profile": "https://Stackoverflow.com/users/4498", "pm_score": 0, "selected": false, "text": "<p>Just merge each list with the list 128 above it. (resulting in 128 lists)<br>\nThen merge each list with the list 64 above it. (resulting in 64 lists)<br>\nThen merge each list with the list 32 above it. (resulting in 32 lists)<br>\nThen merge each list with the list 16 above it. (resulting in 16 lists)<br>\nThen merge each list with the list 8 above it. (resulting in 8 lists)<br>\nThen merge each list with the list 4 above it. (resulting in 4 lists)<br>\nThen merge each list with the list 2 above it. (resulting in 2 lists)<br>\nThen merge each list with the list 1 above it. (resulting in 1 list)<br>\n(You might use a loop for the above).</p>\n" }, { "answer_id": 237547, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>You don't say how long these lists are, but I assume they all fit in RAM at the same time. The first thing I would try is appending them all together, and calling my environment's builtin sort routine, and I'd see if that gave acceptable performance. It's easy to implement and wouldn't take long to test. If that didn't give acceptable performance, I'd go with the priority queue merge given by Konrad Rudolph.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7855/" ]
I'm looking for an elegant, high performance solution to the following problem. There are 256 linked lists. * Each list contains the same types of object that among other things holds a whole number that is used to define a sort order. * All numbers across all lists are unique * Each individual list is sorted in ascending order by these numbers How would you create a single ascending ordered list from all the objects from the 256 original linked lists? I'd prefer not to brute force it, and have a few other ideas, but this seems like one of those problems that there's a standard, optimal solution for.
You could use a priority queue that holds the “topmost” item of each of the 256 linked lists. This “topmost” item is the one that is scheduled to be inserted into the resulting list. This way, you can just take the smallest element from the priority queue, insert it into your resulting queue, and insert its next element into the priority queue: ``` # Preprocessing: result = list.new() queue = priority_queue.new() foreach (list in lists): queue.push(list.first()) # Main loop: while (not queue.empty()): node = queue.pop() result.insert(node) if (node.next() != null): queue.push(node.next()) ```
162,142
<p>Perforce allows people to check in unchanged files. Why any version control system would allow this is beyond me, but that's a topic for another question. I want to create a trigger that will deny the submission of unchanged files. However, I have no experience with Perforce triggers. From what I've read, I'm guessing this would be a "Change-content" trigger since the files being submitted would have to be diffed against the respective head revisions they are about to replace. I would need to iterate over the incoming files and make sure they had all indeed changed. The problem is, I have no idea how to go about it.</p> <p>Can anyone with Perforce trigger experience offer an example or at least point me in the right direction?</p>
[ { "answer_id": 162285, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 1, "selected": false, "text": "<p>If you look at the Triggers table in Perforce, you will see that triggers are nothing but scripts that get invoked when some kind of event happens. In your case, the change-content event is triggered.</p>\n\n<p>You have several options to write scripts that interact with Perforce. The <a href=\"http://www.perforce.com/perforce/loadsupp.html\" rel=\"nofollow noreferrer\">Perforce downloads page</a> has libraries and modules for many widely use languages. Any of this will help you and greatly simplify what you need to do. Also, check the <a href=\"http://www.perforce.com/perforce/technical.html\" rel=\"nofollow noreferrer\">Perforce Documentation page</a> and download the administrator's guide. It will explain how to create the trigger, etc.</p>\n\n<p>Basically, you need to write a script that will get the information from the change list that is being submitted and for each file in it run a \"diff\" command against the server. If you find a file that has not change, you need to invalidate the submission.</p>\n\n<p>The Perforce module on you favorite language and the administrators guide will give you all the answers you need.</p>\n" }, { "answer_id": 162570, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 3, "selected": false, "text": "<p>In recent version of perforce allow a client setting which prevents submitting unchanged files:</p>\n\n<pre><code> SubmitOptions: Flags to change submit behaviour.\n\n submitunchanged All open files are submitted\n submitunchanged+reopen (default).\n\n revertunchanged Files that have content or type\n revertunchanged+reopen changes are submitted. Unchanged\n files are reverted.\n\n leaveunchanged Files that have content or type\n leaveunchanged+reopen changes are submitted. Unchanged\n files are moved to the default\n changelist.\n\n +reopen appended to the submit option flag\n will cause submitted files to be\n reopened on the default changelist.\n</code></pre>\n\n<p>This might be an avenue to investigate if the user is just checking unchanged files due to apathy.</p>\n\n<p>EDIT:</p>\n\n<p>Given that you want to enforce the restriction regardless of the user's workspace settings, then you'll need a trigger as suggested in other answers.</p>\n\n<p>You'll need to look at <a href=\"http://www.perforce.com/perforce/doc.current/manuals/cmdref/triggers.html\" rel=\"nofollow noreferrer\">Perforce's documentation</a> to work out the details, but you'll need a change-content trigger.</p>\n\n<p>You'll probably want to pass in %user% as well as %change% plus possibly other variables, so that you can restrict the expensive operations to just the problem user.</p>\n" }, { "answer_id": 164925, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 1, "selected": false, "text": "<p>You'll want to write a change-content trigger. These triggers are run after files are transferred to the server, but before they are committed to the DB. As per the perforce documentation, you can use a command similar to the following</p>\n\n<pre><code>p4 diff //depot/path/...@=&lt;change&gt;\n</code></pre>\n\n<p>In the change-content trigger the @= (where change is the changelist number sent to the trigger) will get you the contents of the files that were submitted. If you are looking for a way to check against the server version, you might be able to do something like</p>\n\n<pre><code>p4 diff -sr //...@=&lt;change&gt;\n</code></pre>\n\n<p>The -sr command will report on files that open and are the same as the current depot contents. Since the files haven't been committed yet, I'm going to assume that you will actually get a list of files whose contents that have been transferred to the server are the same as the current head revision in the depot. If p4 diff -sr returns any files that are the same, return a non-zero exit code and the submit will be halted and the user will have to revert his unchanged files manually.</p>\n\n<p>I don't think that you want to actually modify the contents of the changelist by doing the revert for him. That sounds too dangerous.</p>\n\n<p>Note that you can write your trigger in any language that makes sense (as a previous poster suggested). I do think that this kind of trigger is going to be pretty heavyweight though. You will essentially be enforcing a diff on all contents submitted for all users in order to make one developer step in line. Maybe that's an okay price to pay, but depending on the number of users and the sizes of their changelist (and files), this kind of trigger might take a long time to run.</p>\n" }, { "answer_id": 250198, "author": "Toby Allen", "author_id": 6244, "author_profile": "https://Stackoverflow.com/users/6244", "pm_score": 1, "selected": false, "text": "<p>Rather than using a trigger, you can edit his workspaces (assuming you have the correct permissions ) to default to a submission strategy that avoids this. By default (again I dont know why) peforce will submit all selected files even if unchanged, but it is possible to change this behaviour. Open his workspaces, and set the SubmitOptions drop down to 'revertunchanged' which will revert any files in the changelist that have not changed, or 'leaveunchanged' which will keep them checked out but not submit them.</p>\n\n<p>It is also possible to do this on an individual changelist submit if he wishes just look at the On Submit Dropdown.</p>\n\n<p>We had this problem in our environment, but once I explained to the offenders what was happening and how easy it was to change the default behaviour they changed without any problems.</p>\n" }, { "answer_id": 8567383, "author": "Chance", "author_id": 382186, "author_profile": "https://Stackoverflow.com/users/382186", "pm_score": 0, "selected": false, "text": "<p>The script below is done in Linux using a perl script. I'm sure you can adapt it as necessary in Windows and using a scripting language other than Perl.</p>\n\n<p>As the admin user, type \n<code>p4 triggers</code>. </p>\n\n<p>Add this under the <code>Triggers:</code> line of your script.</p>\n\n<p><code>Trigger_name change-content //... \"/&lt;path_to_trigger_script&gt;/&lt;script_name&gt; %changelist% %serverhost% %serverport% %user%\"</code></p>\n\n<p>The <code>Trigger_name</code> is arbitrary. The <code>//...</code> means all of your versioned files, but you can modify this as needed. Anything surrounded by <code>%</code> is a special variable name unique to Perforce, and these will be the arguments to your script. These should be all you need. Note that anything surrounded by <code>&lt;&gt;</code> is variable and depends on your environment. </p>\n\n<p>Now, for the script itself. This is what I wrote. </p>\n\n<pre><code>#!/usr/bin/perl\n\n# ----- CHECK 1 : Make sure files NOT identical\n\n# get variables passed in through triggers call 'p4 triggers'\n$ChangeNum = $ARGV[0]; #change number\n$Server = $ARGV[1];\n$Port = $ARGV[2];\n$User = $ARGV[3];\n$p4 = \"&lt;path_to_p4_exec&gt;/p4 -p $Port \";\n# get list of files opened under the submitted changelist\n@files = `$p4 opened -a -c $ChangeNum | cut -f1 -d\"#\"`;\n\n# go through each file and compare to predecessor\n# although workspace should be configured to not submit unchanged files\n# this is an additional check\nforeach $file (@files)\n{\n chomp($file);\n # get sum of depot file, the #head version\n $depotSum = `$p4 print -q $file\\#head | sum`;\n # get sum of the recently submitted file, use @=$ChangeNum to do this\n $clientSum = `$p4 print -q $file\\@=$ChangeNum | sum`;\n\n chomp $depotSum;\n chomp $clientSum;\n # if 2 sums are same, issue error\n if ( $depotSum eq $clientSum )\n {\n # make sure this file is opened for edit and not for add/delete\n if ( `$p4 describe $ChangeNum | grep \"edit\"` )\n {\n printf \"\\nFile $file identical to predecessor!\";\n exit( 1 );\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 43927019, "author": "Jerry Nairn", "author_id": 8000060, "author_profile": "https://Stackoverflow.com/users/8000060", "pm_score": 0, "selected": false, "text": "<p>We have a trigger script which begins by checking the SubmitOptions of the client spec for submitunchanged. If that is not present, then the trigger script can exit, since the user could not have submitted an unchanged file. Otherwise, we check all files where the action is edit and the file type has not been changed. We compare such files against the previous revision.</p>\n" }, { "answer_id": 43927870, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "<p>Add this to your <code>triggers</code> table:</p>\n\n<pre><code>Triggers:\n myTrigger form-in client \"sed -i -e s/submitunchanged/leaveunchanged/ %formfile%\"\n</code></pre>\n\n<p>This will prevent anyone from saving a client with the <code>submitunchanged</code> option, which will in turn make it difficult for them to submit unchanged files.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
Perforce allows people to check in unchanged files. Why any version control system would allow this is beyond me, but that's a topic for another question. I want to create a trigger that will deny the submission of unchanged files. However, I have no experience with Perforce triggers. From what I've read, I'm guessing this would be a "Change-content" trigger since the files being submitted would have to be diffed against the respective head revisions they are about to replace. I would need to iterate over the incoming files and make sure they had all indeed changed. The problem is, I have no idea how to go about it. Can anyone with Perforce trigger experience offer an example or at least point me in the right direction?
In recent version of perforce allow a client setting which prevents submitting unchanged files: ``` SubmitOptions: Flags to change submit behaviour. submitunchanged All open files are submitted submitunchanged+reopen (default). revertunchanged Files that have content or type revertunchanged+reopen changes are submitted. Unchanged files are reverted. leaveunchanged Files that have content or type leaveunchanged+reopen changes are submitted. Unchanged files are moved to the default changelist. +reopen appended to the submit option flag will cause submitted files to be reopened on the default changelist. ``` This might be an avenue to investigate if the user is just checking unchanged files due to apathy. EDIT: Given that you want to enforce the restriction regardless of the user's workspace settings, then you'll need a trigger as suggested in other answers. You'll need to look at [Perforce's documentation](http://www.perforce.com/perforce/doc.current/manuals/cmdref/triggers.html) to work out the details, but you'll need a change-content trigger. You'll probably want to pass in %user% as well as %change% plus possibly other variables, so that you can restrict the expensive operations to just the problem user.
162,172
<p>I am trying to install xampp 1.6.7 in a Red Hat Enterprise Edition. I followed the installation instructions and after that I started the stack with the command </p> <pre><code>sudo /opt/lampp/lampp start </code></pre> <p>And I get te usual response</p> <pre><code>XAMPP: Starting Apache with SSL (and PHP5)... XAMPP: Starting MySQL... XAMPP: Starting ProFTPD... XAMPP for Linux started. </code></pre> <p>But when I check the status of the components of the stack MySQL is not running, and I get:</p> <pre><code>Version: XAMPP for Linux 1.5.5 Apache is running. MySQL is not running. ProFTPD is running. </code></pre> <p>This not always happens immediatly. Some times MySQL runs for a little while before crashing. I checked the logs and found nothing. </p> <p>Edit:</p> <p>the mysql log says</p> <pre><code>081002 10:41:22 mysqld started libgcc_s.so.1 must be installed for pthread_cancel to work 081002 10:41:24 mysqld ended </code></pre> <p>mysql status says:</p> <pre><code>[root@localhost lampp]# bin/mysql status ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/opt/lampp/var/mysql/mysql.sock' (2) </code></pre> <p>and ps -ef | grep mysql yields nothing</p>
[ { "answer_id": 162230, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>What do</p>\n\n<pre><code>mysql status\n</code></pre>\n\n<p>and</p>\n\n<pre><code>ps aux | grep mysql\n</code></pre>\n\n<p>say?</p>\n\n<p>Also a snippet of the logs might help as well.</p>\n" }, { "answer_id": 162275, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>When mysqld <em>crashes</em> (I think it just shuts down), you may need to configure <code>log-error</code> in <code>my.cnf</code> to see anything of real use. I am not sure how xampp is setup, but a simple <code>find / -name \"my.cnf\"</code> should point you to the location of that file.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>You want to install libgcc. It should be available as an RPM for your platform. Let me know if this helps.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9132/" ]
I am trying to install xampp 1.6.7 in a Red Hat Enterprise Edition. I followed the installation instructions and after that I started the stack with the command ``` sudo /opt/lampp/lampp start ``` And I get te usual response ``` XAMPP: Starting Apache with SSL (and PHP5)... XAMPP: Starting MySQL... XAMPP: Starting ProFTPD... XAMPP for Linux started. ``` But when I check the status of the components of the stack MySQL is not running, and I get: ``` Version: XAMPP for Linux 1.5.5 Apache is running. MySQL is not running. ProFTPD is running. ``` This not always happens immediatly. Some times MySQL runs for a little while before crashing. I checked the logs and found nothing. Edit: the mysql log says ``` 081002 10:41:22 mysqld started libgcc_s.so.1 must be installed for pthread_cancel to work 081002 10:41:24 mysqld ended ``` mysql status says: ``` [root@localhost lampp]# bin/mysql status ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/opt/lampp/var/mysql/mysql.sock' (2) ``` and ps -ef | grep mysql yields nothing
When mysqld *crashes* (I think it just shuts down), you may need to configure `log-error` in `my.cnf` to see anything of real use. I am not sure how xampp is setup, but a simple `find / -name "my.cnf"` should point you to the location of that file. **Edit** You want to install libgcc. It should be available as an RPM for your platform. Let me know if this helps.
162,176
<p><code>fopen</code> is failing when I try to read in a very moderately sized file in <code>PHP</code>. <code>A 6 meg file</code> makes it choke, though smaller files around <code>100k</code> are just fine. i've read that it is sometimes necessary to recompile <code>PHP</code> with the <code>-D_FILE_OFFSET_BITS=64</code> flag in order to read files over 20 gigs or something ridiculous, but shouldn't I have no problems with a 6 meg file? Eventually we'll want to read in files that are around 100 megs, and it would be nice be able to open them and then read through them line by line with fgets as I'm able to do with smaller files.</p> <p>What are your tricks/solutions for reading and doing operations on very large files in <code>PHP</code>?</p> <p>Update: Here's an example of a simple codeblock that fails on my 6 meg file - PHP doesn't seem to throw an error, it just returns false. Maybe I'm doing something extremely dumb?</p> <pre><code>$rawfile = "mediumfile.csv"; if($file = fopen($rawfile, "r")){ fclose($file); } else { echo "fail!"; } </code></pre> <p>Another update: Thanks all for your help, it did turn out to be something incredibly dumb - a permissions issue. My small file inexplicably had read permissions when the larger file didn't. Doh!</p>
[ { "answer_id": 162210, "author": "Fionn", "author_id": 21566, "author_profile": "https://Stackoverflow.com/users/21566", "pm_score": 1, "selected": false, "text": "<p>Well you could try to use the readfile function if you just want to output the file.</p>\n\n<p>If this is not the case - maybe you should think about the design of the application, why do you want to open such large files on web requests?</p>\n" }, { "answer_id": 162227, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": 1, "selected": false, "text": "<p>I used fopen to open video files for streaming, using a php script as a video streaming server, and I had no problem with files of size more than 50/60 MB.</p>\n" }, { "answer_id": 162262, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": -1, "selected": false, "text": "<p>Have you tried file() ?</p>\n\n<p><a href=\"http://is2.php.net/manual/en/function.file.php\" rel=\"nofollow noreferrer\">http://is2.php.net/manual/en/function.file.php</a></p>\n\n<p>Or file_ get_contents()</p>\n\n<p><a href=\"http://is2.php.net/manual/en/function.file-get-contents.php\" rel=\"nofollow noreferrer\">http://is2.php.net/manual/en/function.file-get-contents.php</a></p>\n" }, { "answer_id": 162263, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 7, "selected": true, "text": "<p>Are you sure that it's <code>fopen</code> that's failing and not your script's timeout setting? The default is usually around 30 seconds or so, and if your file is taking longer than that to read in, it may be tripping that up.</p>\n\n<p>Another thing to consider may be the memory limit on your script - reading the file into an array may trip over this, so check your error log for memory warnings.</p>\n\n<p>If neither of the above are your problem, you might look into using <a href=\"http://ie.php.net/fgets\" rel=\"noreferrer\"><code>fgets</code></a> to read the file in line-by-line, processing as you go.</p>\n\n<pre><code>$handle = fopen(\"/tmp/uploadfile.txt\", \"r\") or die(\"Couldn't get handle\");\nif ($handle) {\n while (!feof($handle)) {\n $buffer = fgets($handle, 4096);\n // Process buffer here..\n }\n fclose($handle);\n}\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<blockquote>\n <p>PHP doesn't seem to throw an error, it just returns false.</p>\n</blockquote>\n\n<p>Is the path to <code>$rawfile</code> correct relative to where the script is running? Perhaps try setting an absolute path here for the filename.</p>\n" }, { "answer_id": 162495, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": -1, "selected": false, "text": "<p>If the problem is caused by hitting the memory limit, you can try setting it a higher value (this could work or not depending on php's configuration).</p>\n\n<p>this sets the memory limit to 12 Mb</p>\n\n<pre><code>ini\\_set(\"memory_limit\",\"12M\");\n</code></pre>\n" }, { "answer_id": 25123395, "author": "RightClick", "author_id": 3621140, "author_profile": "https://Stackoverflow.com/users/3621140", "pm_score": 0, "selected": false, "text": "<p>for me, <code>fopen()</code> has been very slow with files over 1mb, <code>file()</code> is much faster.</p>\n\n<p>Just trying to read lines 100 at a time and create batch inserts, <code>fopen()</code> takes 37 seconds vs <code>file()</code> takes 4 seconds. Must be that <code>string-&gt;array</code> step built into <code>file()</code></p>\n\n<p>I'd try all of the file handling options to see which will work best in your application.</p>\n" }, { "answer_id": 33001695, "author": "Al-Punk", "author_id": 277861, "author_profile": "https://Stackoverflow.com/users/277861", "pm_score": 4, "selected": false, "text": "<p>Did 2 tests with a 1.3GB file and a 9.5GB File.</p>\n\n<p><strong>1.3 GB</strong></p>\n\n<p><strong>Using <code>fopen()</code></strong></p>\n\n<p>This process used 15555 ms for its computations.</p>\n\n<p>It spent 169 ms in system calls.</p>\n\n<p><strong>Using <code>file()</code></strong></p>\n\n<p>This process used 6983 ms for its computations.</p>\n\n<p>It spent 4469 ms in system calls.</p>\n\n<p><strong>9.5 GB</strong></p>\n\n<p><strong>Using <code>fopen()</code></strong></p>\n\n<p>This process used 113559 ms for its computations.</p>\n\n<p>It spent 2532 ms in system calls.</p>\n\n<p><strong>Using <code>file()</code></strong></p>\n\n<p>This process used 8221 ms for its computations.</p>\n\n<p>It spent 7998 ms in system calls.</p>\n\n<p>Seems <code>file()</code> is faster.</p>\n" }, { "answer_id": 54704668, "author": "Tinel Barb", "author_id": 7725536, "author_profile": "https://Stackoverflow.com/users/7725536", "pm_score": 3, "selected": false, "text": "<p>• The <code>fgets()</code> function is fine until the text files passed 20 MBytes and the parsing speed is greatly reduced.</p>\n<p>• The <code>file_ get_contents()</code> function give good results until 40 MBytes and acceptable results until 100 MBytes, but <strong><code>file_get_contents()</code> loads the entire file into memory</strong>, so it's not scalabile.</p>\n<p>• The <code>file()</code> function is disastrous with large files of text because this function creates an array containing each line of text, thus this array is stored in memory and the memory used is even larger.<br />\nActually, a 200 MB file I could only manage to parse with <code>memory_limit</code> set at 2 GB which was inappropriate for the 1+ GB files I intended to parse.</p>\n<p>When you have to parse files larger than 1 GB and the parsing time exceeded 15 seconds and you want to avoid to load the entire file into memory, you have to find another way.</p>\n<p>My solution was to <strong>parse data in arbitrary small chunks</strong>. The code is:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$filesize = get_file_size($file);\n$fp = @fopen($file, &quot;r&quot;);\n$chunk_size = (1&lt;&lt;24); // 16MB arbitrary\n$position = 0;\n\n// if handle $fp to file was created, go ahead\nif ($fp) {\n while(!feof($fp)){\n // move pointer to $position in file\n fseek($fp, $position);\n\n // take a slice of $chunk_size bytes\n $chunk = fread($fp,$chunk_size);\n\n // searching the end of last full text line (or get remaining chunk)\n if ( !($last_lf_pos = strrpos($chunk, &quot;\\n&quot;)) ) $last_lf_pos = mb_strlen($chunk);\n\n // $buffer will contain full lines of text\n // starting from $position to $last_lf_pos\n $buffer = mb_substr($chunk,0,$last_lf_pos);\n \n ////////////////////////////////////////////////////\n //// ... DO SOMETHING WITH THIS BUFFER HERE ... ////\n ////////////////////////////////////////////////////\n\n // Move $position\n $position += $last_lf_pos;\n\n // if remaining is less than $chunk_size, make $chunk_size equal remaining\n if(($position+$chunk_size) &gt; $filesize) $chunk_size = $filesize-$position;\n $buffer = NULL;\n }\n fclose($fp);\n}\n</code></pre>\n<p>The memory used is only the <code>$chunk_size</code> and the speed is slightly less than the one obtained with <code>file_ get_contents()</code>. I think PHP Group should use my approach in order to optimize it's parsing functions.</p>\n<p>*) <em>Find the <code>get_file_size()</code> function <a href=\"https://stackoverflow.com/a/54592081/7725536\">here</a>.</em></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`fopen` is failing when I try to read in a very moderately sized file in `PHP`. `A 6 meg file` makes it choke, though smaller files around `100k` are just fine. i've read that it is sometimes necessary to recompile `PHP` with the `-D_FILE_OFFSET_BITS=64` flag in order to read files over 20 gigs or something ridiculous, but shouldn't I have no problems with a 6 meg file? Eventually we'll want to read in files that are around 100 megs, and it would be nice be able to open them and then read through them line by line with fgets as I'm able to do with smaller files. What are your tricks/solutions for reading and doing operations on very large files in `PHP`? Update: Here's an example of a simple codeblock that fails on my 6 meg file - PHP doesn't seem to throw an error, it just returns false. Maybe I'm doing something extremely dumb? ``` $rawfile = "mediumfile.csv"; if($file = fopen($rawfile, "r")){ fclose($file); } else { echo "fail!"; } ``` Another update: Thanks all for your help, it did turn out to be something incredibly dumb - a permissions issue. My small file inexplicably had read permissions when the larger file didn't. Doh!
Are you sure that it's `fopen` that's failing and not your script's timeout setting? The default is usually around 30 seconds or so, and if your file is taking longer than that to read in, it may be tripping that up. Another thing to consider may be the memory limit on your script - reading the file into an array may trip over this, so check your error log for memory warnings. If neither of the above are your problem, you might look into using [`fgets`](http://ie.php.net/fgets) to read the file in line-by-line, processing as you go. ``` $handle = fopen("/tmp/uploadfile.txt", "r") or die("Couldn't get handle"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); // Process buffer here.. } fclose($handle); } ``` **Edit** > > PHP doesn't seem to throw an error, it just returns false. > > > Is the path to `$rawfile` correct relative to where the script is running? Perhaps try setting an absolute path here for the filename.
162,187
<p>When used like this:</p> <pre><code>import static com.showboy.Myclass; public class Anotherclass{} </code></pre> <p>what's the difference between <code>import static com.showboy.Myclass</code> and <code>import com.showboy.Myclass</code>?</p>
[ { "answer_id": 162195, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 10, "selected": true, "text": "<p>See <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html\" rel=\"noreferrer\">Documentation</a></p>\n\n<blockquote>\n <p>The static import declaration is\n analogous to the normal import\n declaration. Where the normal import\n declaration imports classes from\n packages, allowing them to be used\n without package qualification, the\n static import declaration imports\n static members from classes, allowing\n them to be used without class\n qualification.</p>\n \n <p>So when should you use static import?\n Very sparingly! Only use it when you'd\n otherwise be tempted to declare local\n copies of constants, or to abuse\n inheritance (the Constant Interface\n Antipattern). In other words, use it\n when you require frequent access to\n static members from one or two\n classes. If you overuse the static\n import feature, it can make your\n program unreadable and unmaintainable,\n polluting its namespace with all the\n static members you import. Readers of\n your code (including you, a few months\n after you wrote it) will not know\n which class a static member comes\n from. Importing all of the static\n members from a class can be\n particularly harmful to readability;\n if you need only one or two members,\n import them individually. Used\n appropriately, static import can make\n your program more readable, by\n removing the boilerplate of repetition\n of class names.</p>\n</blockquote>\n" }, { "answer_id": 162215, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 6, "selected": false, "text": "<p>Static import is used to import static fields / method of a class instead of:</p>\n\n<pre><code>package test;\n\nimport org.example.Foo;\n\nclass A {\n\n B b = Foo.B_INSTANCE;\n\n}\n</code></pre>\n\n<p>You can write :</p>\n\n<pre><code>package test;\n\nimport static org.example.Foo.B_INSTANCE;\n\nclass A {\n\n B b = B_INSTANCE;\n\n}\n</code></pre>\n\n<p>It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.</p>\n\n<p>Btw, in your example \"import static org.example.Myclass;\" won't work : import is for class, import static is for static members of a class.</p>\n" }, { "answer_id": 162328, "author": "Victor", "author_id": 3419, "author_profile": "https://Stackoverflow.com/users/3419", "pm_score": 8, "selected": false, "text": "<p>There is no difference between those two imports you state. You can, however, use the static import to allow unqualified access to static members of other classes. Where I used to have to do this:</p>\n\n<pre><code>import org.apache.commons.lang.StringUtils;\n .\n .\n .\nif (StringUtils.isBlank(aString)) {\n .\n .\n .\n</code></pre>\n\n<p>I can do this:</p>\n\n<pre><code>import static org.apache.commons.lang.StringUtils.isBlank;\n .\n .\n .\nif (isBlank(aString)) {\n .\n .\n .\n</code></pre>\n\n<p>You can see more in the <a href=\"https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html\" rel=\"noreferrer\">documentation</a>.</p>\n" }, { "answer_id": 1565597, "author": "user85421", "author_id": 85421, "author_profile": "https://Stackoverflow.com/users/85421", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>the difference between \"import static com.showboy.Myclass\" and \"import com.showboy.Myclass\"?</p>\n</blockquote>\n\n<p>The first should generate a compiler error since the static import only works for importing fields or member types. (assuming MyClass is not an inner class or member from showboy)</p>\n\n<p>I think you meant </p>\n\n<pre><code>import static com.showboy.MyClass.*;\n</code></pre>\n\n<p>which makes all static fields and members from MyClass available in the actual compilation unit without having to qualify them... as explained above</p>\n" }, { "answer_id": 12494839, "author": "Rahul Saxena", "author_id": 1682964, "author_profile": "https://Stackoverflow.com/users/1682964", "pm_score": 5, "selected": false, "text": "<p>The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.</p>\n\n<p>I will elaborate my point with example.</p>\n\n<pre><code>import java.lang.Math;\n\nclass WithoutStaticImports {\n\n public static void main(String [] args) {\n System.out.println(\"round \" + Math.round(1032.897));\n System.out.println(\"min \" + Math.min(60,102));\n }\n}\n</code></pre>\n\n<p>Same code, with static imports:</p>\n\n<pre><code>import static java.lang.System.out;\nimport static java.lang.Math.*;\n\nclass WithStaticImports {\n public static void main(String [] args) {\n out.println(\"round \" + round(1032.897));\n out.println(\"min \" + min(60,102));\n }\n}\n</code></pre>\n\n<p><strong>Note</strong>: static import can make your code confusing to read.</p>\n" }, { "answer_id": 34414886, "author": "Java Main", "author_id": 4537618, "author_profile": "https://Stackoverflow.com/users/4537618", "pm_score": 2, "selected": false, "text": "<p>Say you have static fields and methods inside a class called <code>MyClass</code> inside a package called <code>myPackage</code> and you want to access them directly by typing <code>myStaticField</code> or <code>myStaticMethod</code> without typing each time <code>MyClass.myStaticField</code> or <code>MyClass.myStaticMethod</code>.</p>\n\n<p>Note : you need to do an\n <code>import myPackage.MyClass</code> or <code>myPackage.*</code>\n for accessing the other resources </p>\n" }, { "answer_id": 35114747, "author": "roottraveller", "author_id": 5167682, "author_profile": "https://Stackoverflow.com/users/5167682", "pm_score": 4, "selected": false, "text": "<p>The <code>import</code> allows the java programmer to access classes of a package without package qualification. </p>\n\n<p>The <code>static import</code> feature allows to access the static members of a class without the class qualification. </p>\n\n<p>The <code>import</code> provides accessibility to classes and interface whereas <code>static import</code> provides accessibility to static members of the class.</p>\n\n<p><strong>Example :</strong></p>\n\n<p>With <strong><em>import</em></strong></p>\n\n<pre><code>import java.lang.System.*; \nclass StaticImportExample{ \n public static void main(String args[]){ \n\n System.out.println(\"Hello\");\n System.out.println(\"Java\"); \n\n } \n} \n</code></pre>\n\n<p>With <strong><em>static import</em></strong></p>\n\n<pre><code>import static java.lang.System.*; \nclass StaticImportExample{ \n public static void main(String args[]){ \n\n out.println(\"Hello\");//Now no need of System.out \n out.println(\"Java\"); \n\n } \n} \n</code></pre>\n\n<p>See also : <a href=\"http://javarevisited.blogspot.in/2012/10/what-is-static-import-in-java-5-example-tutorial.html\" rel=\"noreferrer\">What is static import in Java 5</a></p>\n" }, { "answer_id": 37723728, "author": "Rajeev", "author_id": 3821301, "author_profile": "https://Stackoverflow.com/users/3821301", "pm_score": 1, "selected": false, "text": "<p>The <code>static</code> modifier after <code>import</code> is for retrieving/using static fields of a class. One area in which I use <code>import static</code> is for retrieving constants from a class.\nWe can also apply <code>import static</code> on static methods. Make sure to type <code>import static</code> because <code>static import</code> is wrong. </p>\n\n<p><strong><a href=\"http://javarevisited.blogspot.com/2012/10/what-is-static-import-in-java-5-example-tutorial.html\" rel=\"nofollow noreferrer\">What is <code>static import</code> in Java - JavaRevisited</a></strong> - A very good resource to know more about <code>import static</code>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10927/" ]
When used like this: ``` import static com.showboy.Myclass; public class Anotherclass{} ``` what's the difference between `import static com.showboy.Myclass` and `import com.showboy.Myclass`?
See [Documentation](http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html) > > The static import declaration is > analogous to the normal import > declaration. Where the normal import > declaration imports classes from > packages, allowing them to be used > without package qualification, the > static import declaration imports > static members from classes, allowing > them to be used without class > qualification. > > > So when should you use static import? > Very sparingly! Only use it when you'd > otherwise be tempted to declare local > copies of constants, or to abuse > inheritance (the Constant Interface > Antipattern). In other words, use it > when you require frequent access to > static members from one or two > classes. If you overuse the static > import feature, it can make your > program unreadable and unmaintainable, > polluting its namespace with all the > static members you import. Readers of > your code (including you, a few months > after you wrote it) will not know > which class a static member comes > from. Importing all of the static > members from a class can be > particularly harmful to readability; > if you need only one or two members, > import them individually. Used > appropriately, static import can make > your program more readable, by > removing the boilerplate of repetition > of class names. > > >
162,225
<p>I've got an XML document containing news stories, and the body element of a news story contains p tags amongst the plain text. When I use XSL to retrieve the body, e.g.</p> <pre><code>&lt;xsl:value-of select="body" /&gt; </code></pre> <p>the p tags seem to get stripped out. I'm using Visual Studio 2005's implementation of XSL.</p> <p>Does anyone have any ideas how to avoid this? Thanks.</p>
[ { "answer_id": 162248, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 1, "selected": false, "text": "<p>If you have control over the input document, <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"nofollow noreferrer\">CDATA</a> is the right way to go.</p>\n" }, { "answer_id": 162250, "author": "Enrico Murru", "author_id": 68336, "author_profile": "https://Stackoverflow.com/users/68336", "pm_score": -1, "selected": false, "text": "<p>It is because the engine is interpreting the &lt;p&gt; tag (excluding it for the output). You need to specify you want the content \"as it is\", using the \"disable-output-escaping=yes|no\" attribute.</p>\n\n<pre><code>&lt;xsl:value-of select=\"body\" disable-output-escaping=\"yes\"/&gt;\n</code></pre>\n" }, { "answer_id": 162259, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 6, "selected": true, "text": "<p>Try to use</p>\n\n<pre><code>&lt;xsl:copy-of select=\"body\"/&gt;\n</code></pre>\n\n<p>instead. From <a href=\"http://www.w3schools.com/XSL/el_copy-of.asp\" rel=\"noreferrer\">w3schools' documentation on same</a>:</p>\n\n<blockquote>\n <p>The <code>&lt;xsl:copy-of&gt;</code> element creates a\n copy of the current node.</p>\n \n <p>Note: Namespace nodes, child nodes,\n and attributes of the current node are\n automatically copied as well!</p>\n</blockquote>\n" }, { "answer_id": 162274, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 3, "selected": false, "text": "<p>If you don't have control over the input document, copy-of should work:</p>\n\n<p>From <a href=\"http://www.xml.com/pub/a/2000/06/07/transforming/index.html\" rel=\"noreferrer\">http://www.xml.com/pub/a/2000/06/07/transforming/index.html</a></p>\n\n<p>\"The xsl:copy-of element, on the other hand, can copy the entire subtree of each node that the template selects. This includes attributes, if the xsl:copy-of element's select attribute has the appropriate value. In the following example, the template copies title element nodes and all of their descendant nodes -- in other words, the complete title elements, including their tags, subelements, and attributes:\"</p>\n\n<pre><code>&lt;xsl:template match=\"title\"&gt;\n &lt;xsl:copy-of select=\"*\"/&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 164160, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>The value of an XML element - this is true not just in XSLT but in DOM implementations - is the concatenation of all of its descendant text nodes. In XSLT, <code>value-of</code> emits an element's value, while <code>copy-of</code> emits a copy of the element.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
I've got an XML document containing news stories, and the body element of a news story contains p tags amongst the plain text. When I use XSL to retrieve the body, e.g. ``` <xsl:value-of select="body" /> ``` the p tags seem to get stripped out. I'm using Visual Studio 2005's implementation of XSL. Does anyone have any ideas how to avoid this? Thanks.
Try to use ``` <xsl:copy-of select="body"/> ``` instead. From [w3schools' documentation on same](http://www.w3schools.com/XSL/el_copy-of.asp): > > The `<xsl:copy-of>` element creates a > copy of the current node. > > > Note: Namespace nodes, child nodes, > and attributes of the current node are > automatically copied as well! > > >
162,255
<p>What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".</p>
[ { "answer_id": 162374, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 5, "selected": false, "text": "<p>I thought this would work, based on <a href=\"http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14237/dynviews_1144.htm\" rel=\"noreferrer\">this source</a>.</p>\n\n<pre><code>SELECT\n 'Currently, ' \n || (SELECT COUNT(*) FROM V$SESSION)\n || ' out of ' \n || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX) \n || ' connections are used.' AS USAGE_MESSAGE\nFROM \n V$LICENSE VL\n</code></pre>\n\n<p>However, Justin Cave is right. This query gives better results:</p>\n\n<pre><code>SELECT\n 'Currently, ' \n || (SELECT COUNT(*) FROM V$SESSION)\n || ' out of ' \n || VP.VALUE \n || ' connections are used.' AS USAGE_MESSAGE\nFROM \n V$PARAMETER VP\nWHERE VP.NAME = 'sessions'\n</code></pre>\n" }, { "answer_id": 162381, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 8, "selected": true, "text": "<p>There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.</p>\n\n<p>The number of sessions the database was configured to allow</p>\n\n<pre><code>SELECT name, value \n FROM v$parameter\n WHERE name = 'sessions'\n</code></pre>\n\n<p>The number of sessions currently active</p>\n\n<pre><code>SELECT COUNT(*)\n FROM v$session\n</code></pre>\n\n<p>As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.</p>\n" }, { "answer_id": 2977596, "author": "saris mohammad", "author_id": 358837, "author_profile": "https://Stackoverflow.com/users/358837", "pm_score": 1, "selected": false, "text": "<pre><code>select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'\n</code></pre>\n" }, { "answer_id": 24239149, "author": "botkop", "author_id": 478746, "author_profile": "https://Stackoverflow.com/users/478746", "pm_score": 3, "selected": false, "text": "<p>Note: this only answers part of the question.</p>\n\n<p>If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:</p>\n\n<pre><code>SQL&gt; show parameter sessions\n</code></pre>\n\n<p>This gives you an output like:</p>\n\n<pre><code> NAME TYPE VALUE\n------------------------------------ ----------- ------------------------------\njava_max_sessionspace_size integer 0\njava_soft_sessionspace_limit integer 0\nlicense_max_sessions integer 0\nlicense_sessions_warning integer 0\nsessions integer 248\nshared_server_sessions integer\n</code></pre>\n\n<p>The sessions parameter is the one what you want.</p>\n" }, { "answer_id": 26061422, "author": "FuePi", "author_id": 139378, "author_profile": "https://Stackoverflow.com/users/139378", "pm_score": 5, "selected": false, "text": "<p>The <strong>sessions</strong> parameter is derived from the <strong>processes</strong> parameter and changes accordingly when you change the number of max processes. See the <a href=\"http://docs.oracle.com/cd/B28359_01/server.111/b28320/initparams001.htm#i1124357\">Oracle docs</a> for further info.</p>\n\n<p>To get only the info about the sessions:</p>\n\n<pre><code> select current_utilization, limit_value \n from v$resource_limit \n where resource_name='sessions';\n</code></pre>\n\n<pre>\nCURRENT_UTILIZATION LIMIT_VALUE\n------------------- -----------\n 110 792\n</pre>\n\n<p>Try this to show info about both:</p>\n\n<pre><code> select resource_name, current_utilization, max_utilization, limit_value \n from v$resource_limit \n where resource_name in ('sessions', 'processes');\n</code></pre>\n\n<pre>\nRESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE\n------------- ------------------- --------------- -----------\nprocesses 96 309 500\nsessions 104 323 792\n</pre>\n" }, { "answer_id": 28351648, "author": "Tom", "author_id": 4534333, "author_profile": "https://Stackoverflow.com/users/4534333", "pm_score": 2, "selected": false, "text": "<p>Use gv$session for RAC, if you want get the total number of session across the cluster.</p>\n" }, { "answer_id": 46211522, "author": "fdominguez.bbdd", "author_id": 8607101, "author_profile": "https://Stackoverflow.com/users/8607101", "pm_score": 2, "selected": false, "text": "<p>v$resource_limit view is so interesting for me in order to glance oracle sessions,processes..:</p>\n\n<p><a href=\"https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html\" rel=\"nofollow noreferrer\">https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24495/" ]
What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e. The number of sessions the database was configured to allow ``` SELECT name, value FROM v$parameter WHERE name = 'sessions' ``` The number of sessions currently active ``` SELECT COUNT(*) FROM v$session ``` As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
162,276
<p>I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.</p> <p>Has anyone dealt with this that can give me some pointers?</p>
[ { "answer_id": 162317, "author": "Kevin Sheffield", "author_id": 590, "author_profile": "https://Stackoverflow.com/users/590", "pm_score": 3, "selected": true, "text": "<p>poking around the facebox.js I came across this line in the function init(settings)...</p>\n\n<pre><code>$('body').append($.facebox.settings.faceboxHtml)\n</code></pre>\n\n<p>I changed that to ...</p>\n\n<pre><code>$('#aspnetForm').append($.facebox.settings.faceboxHtml)\n</code></pre>\n\n<p>and it loads up in the form tag, not sure yet if there are any side effects</p>\n" }, { "answer_id": 395627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can use this code to register the PostBack event:</p>\n\n<pre><code>btn.OnClientClick = string.Format(\"{0}; $.facebox.close();\",ClientScript.GetPostBackEventReference(btn, null));\n</code></pre>\n\n<p>this will let the button fires a PostBack.</p>\n" }, { "answer_id": 2639975, "author": "Paul", "author_id": 314918, "author_profile": "https://Stackoverflow.com/users/314918", "pm_score": 0, "selected": false, "text": "<p>Even after the :\n$('#aspnetForm').append($.facebox.settings.faceboxHtml)</p>\n\n<p>change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).</p>\n\n<p>So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.</p>\n" }, { "answer_id": 2693050, "author": "Mustafa", "author_id": 323507, "author_profile": "https://Stackoverflow.com/users/323507", "pm_score": 0, "selected": false, "text": "<p>I modified facbox.js to do this. Maybe there is a better solution but this works like a charm</p>\n\n<p>Here what i did:</p>\n\n<ol>\n<li>add two lines on top of facbox.js before '(function($)'</li>\n</ol>\n\n<pre>var willremove = '';\nvar willremovehtml = '';\n</pre>\n\n<ol start=\"2\">\n<li>find \"reveal: function(data, klass) {\" and add this lines before the first line of function.</li>\n</ol>\n\n<pre>willremove = data.attr('id')\nwillremovehtml = $('#'+willremove).html()\n$('#'+willremove).html('')</pre>\n\n<ol start=\"3\">\n<li>find \"close: function() {\" and make it look like below.</li>\n</ol>\n\n<pre>close: function() {\n$(document).trigger('close.facebox')\n$('#'+willremove).html(willremovehtml)\nwillremovehtml = ''\nwillremove = ''\nreturn false\n}</pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590/" ]
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server. Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)... ``` $('body').append($.facebox.settings.faceboxHtml) ``` I changed that to ... ``` $('#aspnetForm').append($.facebox.settings.faceboxHtml) ``` and it loads up in the form tag, not sure yet if there are any side effects
162,291
<p>How can I check if an application is running from a batch (well cmd) file?</p> <p>I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.)</p> <p>Also the application could be running as any user.</p>
[ { "answer_id": 162302, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": -1, "selected": false, "text": "<p>You should check the parent process name, see <a href=\"http://en.wikipedia.org/wiki/The_Code_Project\" rel=\"nofollow noreferrer\">The Code Project</a> article about a <a href=\"http://www.codeproject.com/KB/cs/ParentProcWindow.aspx\" rel=\"nofollow noreferrer\">.NET based solution**</a>.</p>\n\n<p>A non-programmatic way to check:</p>\n\n<ol>\n<li>Launch Cmd.exe</li>\n<li>Launch an application (for instance, <code>c:\\windows\\notepad.exe</code>)</li>\n<li>Check properties of the Notepad.exe process in <a href=\"http://en.wikipedia.org/wiki/Process_Explorer\" rel=\"nofollow noreferrer\">Process&nbsp;Explorer</a> </li>\n<li>Check for parent process (This shows cmd.exe)</li>\n</ol>\n\n<p>The same can be checked by getting the parent process name.</p>\n" }, { "answer_id": 162306, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 0, "selected": false, "text": "<p>I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/hsgarch.mspx\" rel=\"nofollow noreferrer\">archives</a> for a lot of examples on how to use WMI from a script.</p>\n" }, { "answer_id": 162361, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 6, "selected": false, "text": "<p>Here's how I've worked it out:</p>\n\n<pre><code>tasklist /FI \"IMAGENAME eq notepad.exe\" /FO CSV &gt; search.log\n\nFOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end\n\nstart notepad.exe\n\n:end\n\ndel search.log\n</code></pre>\n\n<p>The above will open <a href=\"http://en.wikipedia.org/wiki/Notepad_%28software%29\" rel=\"noreferrer\">Notepad</a> if it is not already running.</p>\n\n<p>Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.</p>\n" }, { "answer_id": 162364, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "<p>I don't know how to do so with built in CMD but if you have <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\">grep</a> you can try the following:</p>\n\n<pre><code>tasklist /FI \"IMAGENAME eq myApp.exe\" | grep myApp.exe\nif ERRORLEVEL 1 echo \"myApp is not running\"\n</code></pre>\n" }, { "answer_id": 334954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I use PV.exe from <a href=\"http://www.teamcti.com/pview/prcview.htm\" rel=\"noreferrer\">http://www.teamcti.com/pview/prcview.htm</a> installed in Program Files\\PV with a batch file like this:</p>\n\n<pre><code>@echo off\nPATH=%PATH%;%PROGRAMFILES%\\PV;%PROGRAMFILES%\\YourProgram\nPV.EXE YourProgram.exe &gt;nul\nif ERRORLEVEL 1 goto Process_NotFound\n:Process_Found\necho YourProgram is running\ngoto END\n:Process_NotFound\necho YourProgram is not running\nYourProgram.exe\ngoto END\n:END\n</code></pre>\n" }, { "answer_id": 1329790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<p>Another possibility I came up with, which does not require to save a file, inspired by using <a href=\"http://en.wikipedia.org/wiki/Grep\" rel=\"noreferrer\">grep</a> is:</p>\n<pre><code>tasklist /fi &quot;ImageName eq MyApp.exe&quot; /fo csv 2&gt;NUL | find /I &quot;myapp.exe&quot;&gt;NUL\nif &quot;%ERRORLEVEL%&quot;==&quot;0&quot; echo Program is running\n</code></pre>\n<ul>\n<li><code>/fi &quot;&quot;</code> defines a filter of apps to find, in our case it's the *.exe name</li>\n<li><code>/fo csv</code> defines the output format, csv is required because by default the name of the executable may be truncated if it is too long and thus wouldn't be matched by <code>find</code> later.</li>\n<li><code>find /I</code> means case-insensitive matching and may be omitted</li>\n</ul>\n<p>See the man page of the <a href=\"https://learn.microsoft.com/de-de/windows-server/administration/windows-commands/tasklist#filter-names-operators-and-values\" rel=\"noreferrer\">tasklist</a> command for the whole syntax.</p>\n" }, { "answer_id": 3103301, "author": "Nin", "author_id": 374408, "author_profile": "https://Stackoverflow.com/users/374408", "pm_score": 0, "selected": false, "text": "<p>I used the <a href=\"https://stackoverflow.com/questions/162291/how-to-check-if-a-process-is-running-via-a-batch-script/162361#162361\">script provided by Matt</a> (2008-10-02). The only thing I had trouble with was that it wouldn't delete the <code>search.log</code> file. I expect because I had to <code>cd</code> to another location to start my program. I <code>cd</code>'d back to where the BAT file and <code>search.log</code> are, but it still wouldn't delete. So I resolved that by deleting the <code>search.log</code> file first instead of last.</p>\n\n<pre><code>del search.log\n\ntasklist /FI \"IMAGENAME eq myprog.exe\" /FO CSV &gt; search.log\n\nFOR /F %%A IN (search.log) DO IF %%-zA EQU 0 GOTO end\n\ncd \"C:\\Program Files\\MyLoc\\bin\"\n\nmyprog.exe myuser mypwd\n\n:end\n</code></pre>\n" }, { "answer_id": 4783062, "author": "vtrz", "author_id": 477371, "author_profile": "https://Stackoverflow.com/users/477371", "pm_score": 4, "selected": false, "text": "<p>Under Windows you can use Windows Management Instrumentation (WMI) to ensure that no apps with the specified command line is launched, for example:</p>\n\n<p><code>wmic process where (name=\"nmake.exe\") get commandline | findstr /i /c:\"/f load.mak\" /c:\"/f build.mak\" &gt; NUL &amp;&amp; (echo THE BUILD HAS BEEN STARTED ALREADY! &gt; %ALREADY_STARTED% &amp; exit /b 1)</code></p>\n" }, { "answer_id": 7007630, "author": "benmod", "author_id": 531709, "author_profile": "https://Stackoverflow.com/users/531709", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://stackoverflow.com/questions/162291/how-to-check-if-a-process-is-running-via-a-batch-script/162361#162361\">answer provided by Matt Lacey</a> works for Windows XP. However, in Windows Server 2003 the line </p>\n\n<pre><code> tasklist /FI \"IMAGENAME eq notepad.exe\" /FO CSV &gt; search.log\n</code></pre>\n\n<p>returns </p>\n\n<blockquote>\n <p>INFO: No tasks are running which match the specified criteria.</p>\n</blockquote>\n\n<p>which is then read as the process is running.</p>\n\n<p>I don't have a heap of batch scripting experience, so my soulution is to then search for the process name in the <code>search.log</code> file and pump the results into another file and search that for any output.</p>\n\n<pre><code>tasklist /FI \"IMAGENAME eq notepad.exe\" /FO CSV &gt; search.log\n\nFINDSTR notepad.exe search.log &gt; found.log\n\nFOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end\n\nstart notepad.exe\n\n:end\n\ndel search.log\ndel found.log\n</code></pre>\n\n<p>I hope this helps someone else.</p>\n" }, { "answer_id": 18873920, "author": "Calimo", "author_id": 333599, "author_profile": "https://Stackoverflow.com/users/333599", "pm_score": 0, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/a/4783062/333599\">vtrz's answer</a> and <a href=\"https://stackoverflow.com/a/334890/333599\">Samuel Renkert's answer on an other topic</a>, I came up with the following script that only runs <code>%EXEC_CMD%</code> if it isn't already running:</p>\n\n<pre><code>@echo off\nset EXEC_CMD=\"rsync.exe\"\nwmic process where (name=%EXEC_CMD%) get commandline | findstr /i %EXEC_CMD%&gt; NUL\nif errorlevel 1 (\n %EXEC_CMD% ...\n) else (\n @echo not starting %EXEC_CMD%: already running.\n)\n</code></pre>\n\n<p>As was said before, this requires administrative privileges.</p>\n" }, { "answer_id": 25041951, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 3, "selected": false, "text": "<p>I like the <code>WMIC</code> and <code>TASKLIST</code> tools but they are not available in home/basic editions of windows.Another way is to use <code>QPROCESS</code> command available on almost every windows machine (for the ones that have terminal services - I think only win XP without SP2 , so practialy every windows machine):</p>\n\n<pre><code>@echo off\n:check_process\nsetlocal\nif \"%~1\" equ \"\" echo pass the process name as forst argument &amp;&amp; exit /b 1\n:: first argument is the process you want to check if running\nset process_to_check=%~1\n:: QPROCESS can display only the first 12 symbols of the running process\n:: If other tool is used the line bellow could be deleted\nset process_to_check=%process_to_check:~0,12%\n\nQPROCESS * | find /i \"%process_to_check%\" &gt;nul 2&gt;&amp;1 &amp;&amp; (\n echo process %process_to_check% is running\n) || (\n echo process %process_to_check% is not running\n)\nendlocal\n</code></pre>\n\n<p><a href=\"http://ss64.com/nt/query-process.html\" rel=\"noreferrer\"><strong><code>QPROCESS</code></strong></a> command is not so powerful as <code>TASKLIST</code> and is limited in showing only 12 symbols of process name but should be taken into consideration if <code>TASKLIST</code> is not available.</p>\n\n<p>More simple usage where it uses the name if the process as an argument (the <code>.exe</code> suffix is mandatory in this case where you pass the executable name):</p>\n\n<pre><code>@echo off\n:check_process\nsetlocal\nif \"%~1\" equ \"\" echo pass the process name as forst argument &amp;&amp; exit /b 1\n:: first argument is the process you want to check if running\n:: .exe suffix is mandatory\nset \"process_to_check=%~1\"\n\n\nQPROCESS \"%process_to_check%\" &gt;nul 2&gt;&amp;1 &amp;&amp; (\n echo process %process_to_check% is running\n) || (\n echo process %process_to_check% is not running\n)\nendlocal\n</code></pre>\n\n<p>The difference between two ways of <code>QPROCESS</code> usage is that the <code>QPROCESS *</code> will list all processes while <code>QPROCESS some.exe</code> will filter only the processes for the current user.</p>\n\n<p>Using <code>WMI</code> objects through windows script host exe instead of <code>WMIC</code> is also an option.It should on run also on every windows machine (excluding the ones where the WSH is turned off but this is a rare case).Here bat file that lists all processes through WMI classes and can be used instead of <code>QPROCESS</code> in the script above (it is a jscript/bat hybrid and should be saved as <code>.bat</code>):</p>\n\n<pre><code>@if (@X)==(@Y) @end /* JSCRIPT COMMENT **\n\n\n@echo off\ncscript //E:JScript //nologo \"%~f0\"\nexit /b\n\n************** end of JSCRIPT COMMENT **/\n\n\nvar winmgmts = GetObject(\"winmgmts:\\\\\\\\.\\\\root\\\\cimv2\");\nvar colProcess = winmgmts.ExecQuery(\"Select * from Win32_Process\");\nvar processes = new Enumerator(colProcess);\nfor (;!processes.atEnd();processes.moveNext()) {\n var process=processes.item();\n WScript.Echo( process.processID + \" \" + process.Name );\n}\n</code></pre>\n\n<p>And a modification that will check if a process is running:</p>\n\n<pre><code>@if (@X)==(@Y) @end /* JSCRIPT COMMENT **\n\n\n@echo off\nif \"%~1\" equ \"\" echo pass the process name as forst argument &amp;&amp; exit /b 1\n:: first argument is the process you want to check if running\nset process_to_check=%~1\n\ncscript //E:JScript //nologo \"%~f0\" | find /i \"%process_to_check%\" &gt;nul 2&gt;&amp;1 &amp;&amp; (\n echo process %process_to_check% is running\n) || (\n echo process %process_to_check% is not running\n)\n\nexit /b\n\n************** end of JSCRIPT COMMENT **/\n\n\nvar winmgmts = GetObject(\"winmgmts:\\\\\\\\.\\\\root\\\\cimv2\");\nvar colProcess = winmgmts.ExecQuery(\"Select * from Win32_Process\");\nvar processes = new Enumerator(colProcess);\nfor (;!processes.atEnd();processes.moveNext()) {\n var process=processes.item();\n WScript.Echo( process.processID + \" \" + process.Name );\n}\n</code></pre>\n\n<p>The two options could be used on machines that have no <code>TASKLIST</code>. </p>\n\n<p>The ultimate technique is using <code>MSHTA</code> . This will run on every windows machine from XP and above and does not depend on windows script host settings. the call of <code>MSHTA</code> could reduce a little bit the performance though (again should be saved as bat):</p>\n\n<pre><code>@if (@X)==(@Y) @end /* JSCRIPT COMMENT **\n@echo off\n\nsetlocal\nif \"%~1\" equ \"\" echo pass the process name as forst argument &amp;&amp; exit /b 1\n:: first argument is the process you want to check if running\n\nset process_to_check=%~1\n\n\nmshta \"about:&lt;script language='javascript' src='file://%~dpnxf0'&gt;&lt;/script&gt;\" | find /i \"%process_to_check%\" &gt;nul 2&gt;&amp;1 &amp;&amp; (\n echo process %process_to_check% is running\n) || (\n echo process %process_to_check% is not running\n)\nendlocal\nexit /b\n************** end of JSCRIPT COMMENT **/\n\n\n var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);\n\n\n var winmgmts = GetObject(\"winmgmts:\\\\\\\\.\\\\root\\\\cimv2\");\n var colProcess = winmgmts.ExecQuery(\"Select * from Win32_Process\");\n var processes = new Enumerator(colProcess);\n for (;!processes.atEnd();processes.moveNext()) {\n var process=processes.item();\n fso.Write( process.processID + \" \" + process.Name + \"\\n\");\n }\n close();\n</code></pre>\n" }, { "answer_id": 25423791, "author": "TrueY", "author_id": 2156952, "author_profile": "https://Stackoverflow.com/users/2156952", "pm_score": 6, "selected": false, "text": "<p>I like Chaosmaster's solution! But I looked for a solution which does not start another external program (like <a href=\"https://technet.microsoft.com/en-us/library/bb490906.aspx\" rel=\"noreferrer\">find.exe</a> or <a href=\"https://technet.microsoft.com/en-us/library/bb490907.aspx\" rel=\"noreferrer\">findstr.exe</a>). So I added the idea from Matt Lacey's solution, which creates an also avoidable temp file. At the end I could find a fairly simple solution, so I share it...</p>\n<pre><code>SETLOCAL EnableExtensions\nset EXE=MyProg.exe\nFOR /F %%x IN ('tasklist /NH /FI &quot;IMAGENAME eq %EXE%&quot;') DO IF NOT %%x == %EXE% (\n echo %EXE% is Not Running\n)\n</code></pre>\n<p>This is working for me nicely...</p>\n<p>The above is an edit. The original code apparently had a GOTO in it, which someone in the comments thought uncouth.</p>\n<h3>Spaces</h3>\n<p>If you are concerned that the program name may have spaces in it then you need to complicate the code very slightly:</p>\n<pre><code>SETLOCAL EnableExtensions\nset EXE=My Prog.exe\nFOR /F %%x IN (&quot;%EXE%&quot;) do set EXE_=%%x\nFOR /F %%x IN ('tasklist /NH /FI &quot;IMAGENAME eq %EXE%&quot;') DO IF NOT %%x == %EXE_% (\n echo %EXE% is Not Running\n)\n</code></pre>\n<p>The original code will work fine whether or not <em>other</em> running processes have spaces in their names. The only concern is whether or not the process we are targeting has space(s).</p>\n<h3>ELSE</h3>\n<p>Keep in mind that if you add an ELSE clause then it will be executed once for <em>every instance</em> of the application that is already running. There is no guarantee that there be only a single instance running when you run this script.</p>\n<p>Should you want one anyway, either a GOTO or a flag variable is indicated.</p>\n<p>Ideally the targeted application should already mutex itself to prevent multiple instances, but that is a topic for another SO question and is not necessarily applicable to the subject of this question.</p>\n<h3>GOTO again</h3>\n<p>I do agree with the &quot;ELSE&quot; comment. The problem with the GOTO-less solution, that is may run the condition part (and the ELSE part) multiple times, so it is a bit messy as it has to quit the loop anyway. (Sorry, but I do not deal with the SPACE issue here, as it seems to be pretty rare and a solution is shown for it)</p>\n<pre><code>SETLOCAL EnableExtensions\nSET EXE=MyProg.exe\nREM for testing\nREM SET EXE=svchost.exe\nFOR /F %%x IN ('tasklist /NH /FI &quot;IMAGENAME eq %EXE%&quot;') DO IF NOT %%x == %EXE% (\n ECHO %EXE% is Not Running\n REM This GOTO may be not necessary\n GOTO notRunning\n) ELSE (\n ECHO %EXE is running\n GOTO Running\n)\n...\n:Running\nREM If Running label not exists, it will loop over all found tasks\n</code></pre>\n" }, { "answer_id": 26024028, "author": "kayleeFrye_onDeck", "author_id": 3543437, "author_profile": "https://Stackoverflow.com/users/3543437", "pm_score": 3, "selected": false, "text": "<p>TrueY's answer seemed the most elegant solution, however, I had to do some messing around because I didn't understand what exactly was going on. Let me clear things up to hopefully save some time for the next person.</p>\n\n<p>TrueY's modified Answer:</p>\n\n<pre><code>::Change the name of notepad.exe to the process .exe that you're trying to track\n::Process names are CASE SENSITIVE, so notepad.exe works but Notepad.exe does NOT\n::Do not change IMAGENAME\n::You can Copy and Paste this into an empty batch file and change the name of\n::notepad.exe to the process you'd like to track\n::Also, some large programs take a while to no longer show as not running, so\n::give this batch a few seconds timer to avoid a false result!!\n\n@echo off\nSETLOCAL EnableExtensions\n\nset EXE=notepad.exe\n\nFOR /F %%x IN ('tasklist /NH /FI \"IMAGENAME eq %EXE%\"') DO IF %%x == %EXE% goto ProcessFound\n\ngoto ProcessNotFound\n\n:ProcessFound\n\necho %EXE% is running\ngoto END\n:ProcessNotFound\necho %EXE% is not running\ngoto END\n:END\necho Finished!\n</code></pre>\n\n<p>Anyway, I hope that helps. I know sometimes reading batch/command-line can be kind of confusing sometimes if you're kind of a newbie, like me.</p>\n" }, { "answer_id": 41684126, "author": "Riccardo La Marca", "author_id": 7028122, "author_profile": "https://Stackoverflow.com/users/7028122", "pm_score": 5, "selected": false, "text": "<pre><code>TASKLIST | FINDSTR ProgramName || START \"\" \"Path\\ProgramName.exe\"\n</code></pre>\n" }, { "answer_id": 42947089, "author": "Rajeev Jayaswal", "author_id": 2155858, "author_profile": "https://Stackoverflow.com/users/2155858", "pm_score": -1, "selected": false, "text": "<p>I usually execute following command in cmd prompt to check if my program.exe is running or not:</p>\n\n<pre><code>tasklist | grep program\n</code></pre>\n" }, { "answer_id": 43922550, "author": "aldemarcalazans", "author_id": 4941815, "author_profile": "https://Stackoverflow.com/users/4941815", "pm_score": 5, "selected": false, "text": "<p>The suggestion of npocmaka to use QPROCESS instead of TASKLIST is great but, its answer is so big and complex that I feel obligated to post a quite simplified version of it which, I guess, will solve the problem of most non-advanced users:</p>\n\n<pre><code>QPROCESS \"myprocess.exe\"&gt;NUL\nIF %ERRORLEVEL% EQU 0 ECHO \"Process running\"\n</code></pre>\n\n<p>The code above was tested in Windows 7, with a user with administrator rigths.</p>\n" }, { "answer_id": 50299150, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "<p>Just mentioning, if your task name is really long then it won't appear in its entirety in the <code>tasklist</code> result, so it might be safer (other than localization) to check for the opposite.</p>\n\n<p>Variation of <a href=\"https://stackoverflow.com/a/1329790/1037948\">this answer</a>:</p>\n\n<pre><code>:: in case your task name is really long, check for the 'opposite' and find the message when it's not there\ntasklist /fi \"imagename eq yourreallylongtasknamethatwontfitinthelist.exe\" 2&gt;NUL | find /I /N \"no tasks are running\"&gt;NUL\nif \"%errorlevel%\"==\"0\" (\n echo Task Found\n) else (\n echo Not Found Task\n)\n</code></pre>\n" }, { "answer_id": 61414882, "author": "Patrick", "author_id": 10582249, "author_profile": "https://Stackoverflow.com/users/10582249", "pm_score": 1, "selected": false, "text": "<p>I needed a solution with a retry. This code will run until the process is found and then kill it. You can set a timeout or anything if you like.</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>The \".exe\" is mandatory</li>\n<li>You could make a file runnable with parameters, version below</li>\n</ul>\n\n<pre class=\"lang-vb prettyprint-override\"><code> :: Set programm you want to kill\n :: Fileextension is mandatory\n SET KillProg=explorer.exe\n\n :: Set waiting time between 2 requests in seconds\n SET /A \"_wait=3\"\n\n :ProcessNotFound\n tasklist /NH /FI \"IMAGENAME eq %KillProg%\" | FIND /I \"%KillProg%\"\n IF \"%ERRORLEVEL%\"==\"0\" (\n TASKKILL.EXE /F /T /IM %KillProg%\n ) ELSE (\n timeout /t %_wait%\n GOTO :ProcessNotFound\n )\n</code></pre>\n\n<p><code>taskkill.bat</code>:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> :: Get program name from argumentlist\n IF NOT \"%~1\"==\"\" (\n SET \"KillProg=%~1\"\n ) ELSE (\n ECHO Usage: \"%~nx0\" ProgramToKill.exe &amp; EXIT /B\n )\n\n :: Set waiting time between 2 requests in seconds\n SET /A \"_wait=3\"\n\n :ProcessNotFound\n tasklist /NH /FI \"IMAGENAME eq %KillProg%\" | FIND /I \"%KillProg%\"\n IF \"%ERRORLEVEL%\"==\"0\" (\n TASKKILL.EXE /F /T /IM %KillProg%\n ) ELSE (\n timeout /t %_wait%\n GOTO :ProcessNotFound\n )\n</code></pre>\n\n<p>Run with <code>.\\taskkill.bat ProgramToKill.exe</code></p>\n" }, { "answer_id": 67500084, "author": "arnold_w", "author_id": 2075678, "author_profile": "https://Stackoverflow.com/users/2075678", "pm_score": 2, "selected": false, "text": "<p>If you have more than one .exe-file with the same name and you only want to check one of them (e.g. you care about C:\\MyProject\\bin\\release\\MyApplication.exe but not C:\\MyProject\\bin\\debug\\MyApplication.exe) then you can use the following:</p>\n<pre><code>@echo off\n\nset &quot;workdir=C:\\MyProject\\bin\\release&quot;\nset &quot;workdir=%workdir:\\=\\\\%&quot;\n\nsetlocal enableDelayedExpansion\nfor /f &quot;usebackq tokens=* delims=&quot; %%a in (`\n wmic process where 'CommandLine like &quot;%%!workdir!%%&quot; and not CommandLine like &quot;%%RuntimeBroker%%&quot;' get CommandLine^,ProcessId /format:value\n`) do (\n for /f &quot;tokens=* delims=&quot; %%G in (&quot;%%a&quot;) do (\n if &quot;%%G&quot; neq &quot;&quot; (\nrem echo %%G\n set &quot;%%G&quot;\nrem echo !ProcessId!\n goto :TheApplicationIsRunning\n )\n )\n) \n\necho The application is not running\nexit /B\n\n:TheApplicationIsRunning\necho The application is running\nexit /B\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755/" ]
How can I check if an application is running from a batch (well cmd) file? I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.) Also the application could be running as any user.
Another possibility I came up with, which does not require to save a file, inspired by using [grep](http://en.wikipedia.org/wiki/Grep) is: ``` tasklist /fi "ImageName eq MyApp.exe" /fo csv 2>NUL | find /I "myapp.exe">NUL if "%ERRORLEVEL%"=="0" echo Program is running ``` * `/fi ""` defines a filter of apps to find, in our case it's the \*.exe name * `/fo csv` defines the output format, csv is required because by default the name of the executable may be truncated if it is too long and thus wouldn't be matched by `find` later. * `find /I` means case-insensitive matching and may be omitted See the man page of the [tasklist](https://learn.microsoft.com/de-de/windows-server/administration/windows-commands/tasklist#filter-names-operators-and-values) command for the whole syntax.
162,298
<p>I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value.</p> <p>How do i express this with </p> <pre><code>validates_presence_of </code></pre> <p>statements? For example:</p> <pre><code>validates_presence_of :main_file validates_presence_of :alt_file </code></pre> <p>i don't want an error to be generated if only one of them is empty, only if both are empty. </p>
[ { "answer_id": 162334, "author": "Bartosz Blimke", "author_id": 18715, "author_profile": "https://Stackoverflow.com/users/18715", "pm_score": 4, "selected": true, "text": "<pre><code>validates_presence_of :main_file, :if =&gt; Proc.new { |p| p.alt_file.blank? }\nvalidates_presence_of :alt_file, :if =&gt; Proc.new { |p| p.main_file.blank? }\n</code></pre>\n" }, { "answer_id": 162557, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 2, "selected": false, "text": "<p>changing .nil? to .blank? does the trick!</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value. How do i express this with ``` validates_presence_of ``` statements? For example: ``` validates_presence_of :main_file validates_presence_of :alt_file ``` i don't want an error to be generated if only one of them is empty, only if both are empty.
``` validates_presence_of :main_file, :if => Proc.new { |p| p.alt_file.blank? } validates_presence_of :alt_file, :if => Proc.new { |p| p.main_file.blank? } ```
162,309
<p>To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick:</p> <pre><code>ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE); </code></pre> <p>This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to <a href="http://msdn.microsoft.com/en-us/library/aa384235(VS.85).aspx" rel="noreferrer">registry reflection</a>.</p> <p>So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "*" suffix in the Task Manager)?</p>
[ { "answer_id": 162327, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>Have you considered creating a small \"helper\" application to make the registry update for you? If you compile it to 64bit and include a manifest that indicates it requires administrator rights, then it'll cover both bases for you.</p>\n\n<p>There are API's to detect the \"bitness\" of the OS you're running on so you could, conceivably, compile both RegistryUpdate32.exe and RegistryUpdate64.exe and call the relevant one.</p>\n" }, { "answer_id": 162360, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": false, "text": "<p>Whether a 32-bit or 64-bit native (unmanaged) program is run depends solely on the executable. There are two copies of <code>reg.exe</code>, in C:\\Windows\\System32 (64-bit) and C:\\Windows\\SysWOW64 (32-bit). Because you don't specify a path, you're getting whatever appears first in the <code>PATH</code> environment variable, which is the 32-bit version for a 32-bit process.</p>\n\n<p>You should really factor this function out into a separate program or COM object, and mark the program with a manifest, or launch the COM object using the <a href=\"http://msdn.microsoft.com/en-us/library/ms679687(VS.85).aspx\" rel=\"noreferrer\">COM elevation moniker</a>.</p>\n" }, { "answer_id": 2801958, "author": "akira", "author_id": 98653, "author_profile": "https://Stackoverflow.com/users/98653", "pm_score": 5, "selected": true, "text": "<p>try this (from a 32bit process):</p>\n\n<pre><code>&gt; %WINDIR%\\sysnative\\reg.exe query ...\n</code></pre>\n\n<p>(found that <a href=\"http://ovidiupl.spaces.live.com/blog/cns!1E8A6038167E4BE9!925.entry\" rel=\"noreferrer\">here</a>).</p>\n" }, { "answer_id": 8662289, "author": "ymerej", "author_id": 186034, "author_profile": "https://Stackoverflow.com/users/186034", "pm_score": 1, "selected": false, "text": "<p>One thing that I've done as a solution for myself is to PInvoke disabling redirection:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx</a></p>\n\n<p>You can always turn it right back on.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9744/" ]
To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick: ``` ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE); ``` This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to [registry reflection](http://msdn.microsoft.com/en-us/library/aa384235(VS.85).aspx). So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "\*" suffix in the Task Manager)?
try this (from a 32bit process): ``` > %WINDIR%\sysnative\reg.exe query ... ``` (found that [here](http://ovidiupl.spaces.live.com/blog/cns!1E8A6038167E4BE9!925.entry)).
162,325
<p>This has been an adventure. I started with the looping duplicate query located in <a href="https://stackoverflow.com/questions/161960">my previous question</a>, but each loop would go over all <strong>17 million records</strong>, <strong>meaning it would take weeks</strong> (just running <code>*select count * from MyTable*</code> takes my server 4:30 minutes using MSSQL 2005). I gleamed information from this site and at this <a href="http://weblogs.sqlteam.com/jeffs/archive/2007/03/28/60146.aspx" rel="nofollow noreferrer">post</a>.</p> <p>And have arrived at the query below. The question is, is this the correct type of query to run on 17 million records for any type of performance? If it isn't, what is?</p> <p>SQL QUERY:</p> <pre><code>DELETE tl_acxiomimport.dbo.tblacxiomlistings WHERE RecordID in (SELECT RecordID FROM tl_acxiomimport.dbo.tblacxiomlistings EXCEPT SELECT RecordID FROM ( SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank FROM tl_acxiomimport.dbo.tblacxiomlistings ) al WHERE Rank = 1) </code></pre>
[ { "answer_id": 162378, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Run this in query analyzer:</p>\n\n<pre><code>SET SHOWPLAN_TEXT ON\n</code></pre>\n\n<p>Then ask query analyzer to run your query. Instead of running the query, SQL Server will generate a query plan and put it in the result set.</p>\n\n<p>Show us the query plan.</p>\n" }, { "answer_id": 162439, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 0, "selected": false, "text": "<p>This looks fine but you might consider selecting your data into a temporary table and using that in your delete statement. I've noticed huge performance gains from doing this instead of doing it all in that one query.</p>\n" }, { "answer_id": 162443, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "<p>17 million records is nothing. If it takes 4:30 to just do a select count(*) then there is a serious problem, probably related to either lack of memory in the server or a really old processor.</p>\n\n<p>For performance, fix the machine. Pump it up to 2GB. RAM is so cheap these days that its cost is far less than your time.</p>\n\n<p>Is the processor or disk thrashing when that query is going? If not, then something is blocking the calls. In that case you might consider putting the database in single user mode for the amount of time it takes to run the cleanup.</p>\n" }, { "answer_id": 162447, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>So you're deleting all the records that aren't ranked first? It might be worth comparing a join against a top 1 sub query against (which might also work in 2000, as rank is 2005 and above only)</p>\n\n<p>Do you need to remove all the duplicates in a single operation? I assume that you're preforming some sort of housekeeping task, you might be able to do it piece-wise.</p>\n\n<p>Basically create a cursor that loops all the records (dirty read) and removes dupes for each. It'll be a lot slower overall, but each operation will be relatively minimal. Then your housekeeping becomes a constant background task rather than a nightly batch.</p>\n" }, { "answer_id": 162476, "author": "Mike Reedell", "author_id": 4897, "author_profile": "https://Stackoverflow.com/users/4897", "pm_score": 2, "selected": false, "text": "<p>Something's up with your DB, server, storage or some combination thereof. 4:30 for a select count * seems VERY high.</p>\n\n<p>Run a DBCC_SHOWCONTIG to see how fragmented your table is, this could cause a major performance hit over a table that size.</p>\n\n<p>Also, to add on to the comment by RyanKeeter, run the show plan and if there are any table scans create an index for the PK field on that table.</p>\n" }, { "answer_id": 162479, "author": "TrevorD", "author_id": 12492, "author_profile": "https://Stackoverflow.com/users/12492", "pm_score": 1, "selected": false, "text": "<p>The suggestion above to select into a temporary table first is your best bet. You could also use something like:</p>\n\n<pre><code>set rowcount 1000\n</code></pre>\n\n<p>before running your delete. It will stop running after it deletes the 1000 rows. Then run it again and again until you get 0 records deleted.</p>\n" }, { "answer_id": 162660, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": true, "text": "<p>Seeing the QueryPlan would help.</p>\n\n<p>Is this feasible?</p>\n\n<pre><code>SELECT m.*\ninto #temp\nFROM tl_acxiomimport.dbo.tblacxiomlistings m \ninner join (SELECT RecordID, \n Rank() over (Partition BY BusinessName, \n latitude, \n longitude, \n Phone \n ORDER BY webaddress DESC, \n caption1 DESC, \n caption2 DESC ) AS Rank\n FROM tl_acxiomimport.dbo.tblacxiomlistings\n ) al on (al.RecordID = m.RecordID and al.Rank = 1)\n\ntruncate table tl_acxiomimport.dbo.tblacxiomlistings\n\ninsert into tl_acxiomimport.dbo.tblacxiomlistings\n select * from #temp\n</code></pre>\n" }, { "answer_id": 162857, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 1, "selected": false, "text": "<p>if i get it correctly you query is the same as</p>\n\n<pre><code>DELETE tl_acxiomimport.dbo.tblacxiomlistings\nFROM\n tl_acxiomimport.dbo.tblacxiomlistings allRecords\n LEFT JOIN ( \n SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank\n FROM tl_acxiomimport.dbo.tblacxiomlistings\n WHERE Rank = 1) myExceptions\n ON allRecords.RecordID = myExceptions.RecordID\nWHERE\n myExceptions.RecordID IS NULL\n</code></pre>\n\n<p>I think that should run faster, I tend to avoid using \"IN\" clause in favor of JOINs where possible.</p>\n\n<p>You can actually test the speed and the results safely by simply calling <code>SELECT *</code> or <code>SELECT COUNT(*)</code> on the FROM part like e.g.</p>\n\n<pre><code>SELECT *\nFROM\n tl_acxiomimport.dbo.tblacxiomlistings allRecords\n LEFT JOIN ( \n SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank\n FROM tl_acxiomimport.dbo.tblacxiomlistings\n WHERE Rank = 1) myExceptions\n ON allRecords.RecordID = myExceptions.RecordID\nWHERE\n myExceptions.RecordID IS NULL\n</code></pre>\n\n<p>That is another reason why I would prefer the JOIN approach\nI hope that helps</p>\n" }, { "answer_id": 163274, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>Wouldn't it be more simple to do:</p>\n\n<pre><code>DELETE tl_acxiomimport.dbo.tblacxiomlistings\nWHERE RecordID in \n(SELECT RecordID\n FROM (\n SELECT RecordID,\n Rank() over (Partition BY BusinessName,\n latitude,\n longitude,\n Phone\n ORDER BY webaddress DESC,\n caption1 DESC,\n caption2 DESC) AS Rank\n FROM tl_acxiomimport.dbo.tblacxiomlistings\n )\n WHERE Rank &gt; 1\n )\n</code></pre>\n" }, { "answer_id": 164121, "author": "Chris", "author_id": 24356, "author_profile": "https://Stackoverflow.com/users/24356", "pm_score": -1, "selected": false, "text": "<p>Other than using truncate as suggested, I've had the best luck using this template for deleting lots of rows from a table. I don't remember off hand, but I think using the transaction helped to keep the log file from growing -- may have been another reason though -- not sure. And I usually switch the transaction logging method over to simple before doing something like this:</p>\n\n<pre>\nSET ROWCOUNT 5000\nWHILE 1 = 1\nBEGIN\n begin tran\n DELETE FROM ??? WHERE ???\n IF @@rowcount = 0\n BEGIN\n COMMIT\n BREAK\n END\n COMMIT\nEND\nSET ROWCOUNT 0\n</pre>\n" }, { "answer_id": 1178180, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>Remember when doing a large delete it is best to have a good backup first.(And I also usually copy the deleted records to another table just in case, I need to recover them right away. )</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
This has been an adventure. I started with the looping duplicate query located in [my previous question](https://stackoverflow.com/questions/161960), but each loop would go over all **17 million records**, **meaning it would take weeks** (just running `*select count * from MyTable*` takes my server 4:30 minutes using MSSQL 2005). I gleamed information from this site and at this [post](http://weblogs.sqlteam.com/jeffs/archive/2007/03/28/60146.aspx). And have arrived at the query below. The question is, is this the correct type of query to run on 17 million records for any type of performance? If it isn't, what is? SQL QUERY: ``` DELETE tl_acxiomimport.dbo.tblacxiomlistings WHERE RecordID in (SELECT RecordID FROM tl_acxiomimport.dbo.tblacxiomlistings EXCEPT SELECT RecordID FROM ( SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank FROM tl_acxiomimport.dbo.tblacxiomlistings ) al WHERE Rank = 1) ```
Seeing the QueryPlan would help. Is this feasible? ``` SELECT m.* into #temp FROM tl_acxiomimport.dbo.tblacxiomlistings m inner join (SELECT RecordID, Rank() over (Partition BY BusinessName, latitude, longitude, Phone ORDER BY webaddress DESC, caption1 DESC, caption2 DESC ) AS Rank FROM tl_acxiomimport.dbo.tblacxiomlistings ) al on (al.RecordID = m.RecordID and al.Rank = 1) truncate table tl_acxiomimport.dbo.tblacxiomlistings insert into tl_acxiomimport.dbo.tblacxiomlistings select * from #temp ```
162,326
<p>How to get the checked option in a group of radio inputs with JavaScript?</p>
[ { "answer_id": 162339, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.somacon.com/p143.php\" rel=\"nofollow noreferrer\">http://www.somacon.com/p143.php</a></p>\n" }, { "answer_id": 162408, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\"&gt;\n function testR(){\n var x = document.getElementsByName('r')\n for(var k=0;k&lt;x.length;k++)\n if(x[k].checked){\n alert('Option selected: ' + x[k].value)\n }\n\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;form&gt;\n &lt;input type=\"radio\" id=\"r1\" name=\"r\" value=\"1\"&gt;Yes&lt;/input&gt;\n &lt;input type=\"radio\" id=\"r2\" name=\"r\" value=\"2\"&gt;No&lt;/input&gt;\n &lt;input type=\"radio\" id=\"r3\" name=\"r\" value=\"3\"&gt;Don't Know&lt;/input&gt;\n &lt;br/&gt;\n &lt;input type=\"button\" name=\"check\" value=\"Test\" onclick=\"testR()\"/&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 162429, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>If you need the actual element and not just the selected value, try this:</p>\n\n<pre><code>function findSelected(){\n for (i=0;i&lt;document.formname.radioname.length;i++){\n if (document.formname.radioname[i].checked){\n return document.formname.radioname[i];\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 591978, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>generic functions (loosely based on yours )</p>\n\n<pre><code>function getRadioGroupSelectedElement(radioGroupName) {\n\n var radioGroup = document.getElementsByName(radioGroupName);\n var radioElement = radioGroup.length - 1;\n for(radioElement; radioElement &gt;= 0; radioElement--) {\n if(radioGroup[radioElement].checked){\n return radioGroup[radioElement];\n }\n }\n return false;\n}\n\n\n\nfunction getRadioGroupSelectedValue(radioGroupName) {\n\n var selectedRadio = getRadioGroupSelectedElement(radioGroupName);\n if (selectedRadio !== false) {\n return selectedRadio.value;\n }\n return false;\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
How to get the checked option in a group of radio inputs with JavaScript?
``` <html> <head> <script type="text/javascript"> function testR(){ var x = document.getElementsByName('r') for(var k=0;k<x.length;k++) if(x[k].checked){ alert('Option selected: ' + x[k].value) } } </script> </head> <body> <form> <input type="radio" id="r1" name="r" value="1">Yes</input> <input type="radio" id="r2" name="r" value="2">No</input> <input type="radio" id="r3" name="r" value="3">Don't Know</input> <br/> <input type="button" name="check" value="Test" onclick="testR()"/> </form> </body> </html> ```
162,331
<p>I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type.</p> <p>I know that, for example, if you just want to open a file using that application you can use something like:</p> <pre><code>System.Diagnostics.Process.Start( "C:\...\...\myfile.html" ); </code></pre> <p>to open an HTML document in the default browser, or</p> <pre><code>System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" ); </code></pre> <p>to open a text file in the default text editor.</p> <p>However, what I want to be able to do is to open files that don't necessarily have a <em>.txt</em> extension (for example), in the default text editor, so I need to be able to find out the default application for opening <em>.txt</em> files, which will allow me to invoke it directly.</p> <p>I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for. </p>
[ { "answer_id": 162351, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 5, "selected": true, "text": "<p>You can check under registry section <code>HKEY_CLASSES_ROOT</code> for the extension and action details. Documentation for this is <a href=\"http://msdn.microsoft.com/en-us/library/cc144148.aspx\" rel=\"noreferrer\">on MSDN</a>. Alternatively, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/bb761400.aspx\" rel=\"noreferrer\">IQueryAssociations</a> interface.</p>\n" }, { "answer_id": 162356, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://windevblog.blogspot.com/2008/09/get-default-application-in-windows-xp.html\" rel=\"noreferrer\">Here is a blog post with about this topic.</a> The code samples are in VB.net, but it should be easy to port them to C#.</p>\n" }, { "answer_id": 162369, "author": "Tom", "author_id": 24227, "author_profile": "https://Stackoverflow.com/users/24227", "pm_score": 2, "selected": false, "text": "<p>You can just query the registry. First get the Default entry under HKEY_CLASSES_ROOT\\.ext</p>\n\n<p>That will give you the classname. For example .txt has a default of txtfile</p>\n\n<p>Then open up HKEY_CLASSES_ROOT\\txtfile\\Shell\\Open\\Command</p>\n\n<p>That will give you the default command used.</p>\n" }, { "answer_id": 162371, "author": "Bart Read", "author_id": 17786, "author_profile": "https://Stackoverflow.com/users/17786", "pm_score": 3, "selected": false, "text": "<p>Doh! Of course.</p>\n\n<pre><code>HKEY_CLASSES_ROOT\\.txt\n</code></pre>\n\n<p>includes a reference to</p>\n\n<pre><code>HKEY_CLASSES_ROOT\\txtfile\n</code></pre>\n\n<p>which contains a subkey</p>\n\n<pre><code>HKEY_CLASSES_ROOT\\txtfile\\shell\\open\\command\n</code></pre>\n\n<p>which references Notepad.</p>\n\n<p>Sorted, many thanks!</p>\n\n<p>Bart</p>\n" }, { "answer_id": 17773402, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 6, "selected": false, "text": "<p>All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically <a href=\"http://msdn.microsoft.com/en-us/library/bb773471.aspx\" rel=\"noreferrer\">AssocQueryString</a>:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"Shlwapi.dll\", CharSet = CharSet.Unicode)]\npublic static extern uint AssocQueryString(\n AssocF flags, \n AssocStr str, \n string pszAssoc, \n string pszExtra, \n [Out] StringBuilder pszOut, \n ref uint pcchOut\n); \n\n[Flags]\npublic enum AssocF\n{\n None = 0,\n Init_NoRemapCLSID = 0x1,\n Init_ByExeName = 0x2,\n Open_ByExeName = 0x2,\n Init_DefaultToStar = 0x4,\n Init_DefaultToFolder = 0x8,\n NoUserSettings = 0x10,\n NoTruncate = 0x20,\n Verify = 0x40,\n RemapRunDll = 0x80,\n NoFixUps = 0x100,\n IgnoreBaseClass = 0x200,\n Init_IgnoreUnknown = 0x400,\n Init_Fixed_ProgId = 0x800,\n Is_Protocol = 0x1000,\n Init_For_File = 0x2000\n}\n\npublic enum AssocStr\n{\n Command = 1,\n Executable,\n FriendlyDocName,\n FriendlyAppName,\n NoOpen,\n ShellNewValue,\n DDECommand,\n DDEIfExec,\n DDEApplication,\n DDETopic,\n InfoTip,\n QuickTip,\n TileInfo,\n ContentType,\n DefaultIcon,\n ShellExtension,\n DropTarget,\n DelegateExecute,\n Supported_Uri_Protocols,\n ProgID,\n AppID,\n AppPublisher,\n AppIconReference,\n Max\n}\n</code></pre>\n\n<p><strong>Relevant documentation:</strong></p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/bb773471.aspx\" rel=\"noreferrer\">AssocQueryString</a></li>\n<li><a href=\"https://web.archive.org/web/20130217094323/https://msdn.microsoft.com/en-us/library/windows/desktop/bb762471(v=vs.85).aspx\" rel=\"noreferrer\">ASSOCF</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb762475(v=vs.85).aspx\" rel=\"noreferrer\">ASSOCSTR</a></li>\n</ul>\n\n<p><strong>Sample usage:</strong></p>\n\n<pre><code>static string AssocQueryString(AssocStr association, string extension)\n{\n const int S_OK = 0;\n const int S_FALSE = 1;\n\n uint length = 0;\n uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length);\n if (ret != S_FALSE)\n {\n throw new InvalidOperationException(\"Could not determine associated string\");\n }\n\n var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination\n ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length);\n if (ret != S_OK)\n {\n throw new InvalidOperationException(\"Could not determine associated string\"); \n }\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 33167069, "author": "Harald Coppoolse", "author_id": 2281790, "author_profile": "https://Stackoverflow.com/users/2281790", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>A late answer, but there is a good NUGET package that handles file associations: File Association</p>\n</blockquote>\n\n<p><a href=\"https://www.nuget.org/packages/FileAssociation/\" rel=\"nofollow\">Link NUGET File Association</a></p>\n\n<p>Usage is simple, for instance to add all allowed file extensions to a context menu:</p>\n\n<pre><code>private void OnMenuSourceFileOpening(object sender, ...)\n{ // open a context menu with the associated files + \".txt\" files\n if (File.Exists(this.SelectedFileName))\n {\n string fileExt = Path.GetExtension(this.SelectedFileNames);\n string[] allowedExtensions = new string[] { fileExt, \".txt\" };\n var fileAssociations = allowedExtensions\n .Select(ext =&gt; new FileAssociationInfo(ext));\n var progInfos = fileAssociations\n .Select(fileAssoc =&gt; new ProgramAssociationInfo (fileAssoc.ProgID));\n var toolstripItems = myProgInfos\n .Select(proginfo =&gt; new ToolStripLabel (proginfo.Description) { Tag = proginfo });\n // add also the prog info as Tag, for easy access\n // when the toolstrip item is selected\n // of course this can also be done in one long linq statement\n\n // fill the context menu:\n this.contextMenu1.Items.Clear();\n this.contextMenuOpenSourceFile.Items.AddRange (toolstripItems.ToArray());\n }\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17786/" ]
I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type. I know that, for example, if you just want to open a file using that application you can use something like: ``` System.Diagnostics.Process.Start( "C:\...\...\myfile.html" ); ``` to open an HTML document in the default browser, or ``` System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" ); ``` to open a text file in the default text editor. However, what I want to be able to do is to open files that don't necessarily have a *.txt* extension (for example), in the default text editor, so I need to be able to find out the default application for opening *.txt* files, which will allow me to invoke it directly. I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for.
You can check under registry section `HKEY_CLASSES_ROOT` for the extension and action details. Documentation for this is [on MSDN](http://msdn.microsoft.com/en-us/library/cc144148.aspx). Alternatively, you can use the [IQueryAssociations](http://msdn.microsoft.com/en-us/library/bb761400.aspx) interface.
162,399
<p>Hi why doesn't this work in SQL Server 2005?</p> <pre><code>select HALID, count(HALID) as CH from Outages.FaultsInOutages where CH &gt; 3 group by HALID </code></pre> <p>I get invalid column name 'CH'</p> <hr> <p>i think having was the right way to go but still receive the error: Invalid column name 'CH'.</p> <p>When running:</p> <p>select HALID, count(HALID) as CH from Outages.FaultsInOutages group by HALID having CH > 3</p>
[ { "answer_id": 162406, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<pre><code>select HALID, count(HALID) from Outages.FaultsInOutages \ngroup by HALID having count(HALID) &gt; 3\n</code></pre>\n\n<p>Your query has two errors:</p>\n\n<ul>\n<li>Using where an aggregate when grouping by, solved by using having</li>\n<li>Using an alias for an aggregate in the condition, not supported, solved by using the aggregate again</li>\n</ul>\n" }, { "answer_id": 162420, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>You can't use the alias in the where clause or having clause, as it isn't processed until AFTER the result set is generated, the proper syntax is</p>\n\n<pre><code>SELECT HALID, COUNT(HALID) AS CH\nFROM Outages.FaultsInOutages\nGROUP BY HALID\nHAVING COUNT(HALID) &gt; 3\n</code></pre>\n\n<p>This will group items on HALID, then ONLY return results that have more than 3 entries for the specific HALID</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
Hi why doesn't this work in SQL Server 2005? ``` select HALID, count(HALID) as CH from Outages.FaultsInOutages where CH > 3 group by HALID ``` I get invalid column name 'CH' --- i think having was the right way to go but still receive the error: Invalid column name 'CH'. When running: select HALID, count(HALID) as CH from Outages.FaultsInOutages group by HALID having CH > 3
You can't use the alias in the where clause or having clause, as it isn't processed until AFTER the result set is generated, the proper syntax is ``` SELECT HALID, COUNT(HALID) AS CH FROM Outages.FaultsInOutages GROUP BY HALID HAVING COUNT(HALID) > 3 ``` This will group items on HALID, then ONLY return results that have more than 3 entries for the specific HALID
162,421
<p>Being lazy (and liking DRY code), I'm the kind of guy who's going to write a few little wrappers for recurring HTML markup. Those provided by Rails are good already, but sometimes I have something a little more specific that I know I'm going to repeat over and over.</p> <p>In some situations a partial can be the solution, but sometimes I'm just going to call the snippet way too often to justify the overhead of using partials.</p> <p>Right now I create a helpers/html_helper.rb file and stick them in there. The problem is that helpers are not reloaded dynamically per request during development. So each time I tweak my snippet or the code around it, I have to kill the server and restart it.</p> <p>Granted, it's just a 5 seconds process, but I love Rails' convenience of just developing and then refreshing the browser. So I'd love to have that for my markup snippets as well.</p> <p>Note: Just sticking 'unloadable' inside the helper module doesn't work.</p>
[ { "answer_id": 162508, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 0, "selected": false, "text": "<p>It's not a real solution but you could use tests (TestUnit, RSpec or whatever) to make sure your helpers work as expected. That way, you wouldn't rely on automatic reloading of your helpers so much.</p>\n" }, { "answer_id": 162600, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 1, "selected": false, "text": "<p>Good question! This is a technique I should abuse more frequently.</p>\n\n<pre><code> #I go in environment.db (presumably it will work in one of the per-environment files, too.)\n Dependencies.explicitly_unloadable_constants &lt;&lt; 'NameOfHelperToReloadHere'\n</code></pre>\n\n<p>That array starts out empty, incidentally, at least in my install. (Checked via console.)</p>\n\n<p>I tested this locally and it works for me, at least on Rails 2.0.2. Major credit for the solution belongs to <a href=\"http://www.williambharding.com/blog/rails/automatically-reload-modules-on-change-in-rails/\" rel=\"nofollow noreferrer\">this gentleman</a>.</p>\n" }, { "answer_id": 163739, "author": "Steropes", "author_id": 21872, "author_profile": "https://Stackoverflow.com/users/21872", "pm_score": 1, "selected": false, "text": "<p>If you stick them in application_helper.rb they'll be loaded every time and be available for all of your views. This is loaded every time in development mode (or at least I haven't encountered any issues).</p>\n\n<p>I typically will create little helpers that I use throughout the site (sortable table headers for instance) that use the same logic. </p>\n" }, { "answer_id": 164159, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 1, "selected": false, "text": "<p>This should reload ALL helpers on every request (assuming you've stuck to the default naming conventions) </p>\n\n<pre><code>#Put this in config/environments/development.rb\nActiveSupport::Dependencies.explicitly_unloadable_constants.concat(Dir.glob(\"#{RAILS_ROOT}/app/helpers/**/*.rb\").map {|file| File.basename(file, '.rb').camelize})\n</code></pre>\n\n<p>Or if you are using an older version of Rails (2.0.2 or earlier I think)</p>\n\n<pre><code>#Put this in config/environments/development.rb\nDependencies.explicitly_unloadable_constants.concat(Dir.glob(\"#{RAILS_ROOT}/app/helpers/**/*.rb\").map {|file| File.basename(file, '.rb').camelize})\n</code></pre>\n\n<p>Works for me in RoR 2.1.1</p>\n\n<hr>\n\n<p><strong>Update:</strong> modified top snippet to include 'ActiveSupport::', must have copied / pasted incorrectly from my code.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349/" ]
Being lazy (and liking DRY code), I'm the kind of guy who's going to write a few little wrappers for recurring HTML markup. Those provided by Rails are good already, but sometimes I have something a little more specific that I know I'm going to repeat over and over. In some situations a partial can be the solution, but sometimes I'm just going to call the snippet way too often to justify the overhead of using partials. Right now I create a helpers/html\_helper.rb file and stick them in there. The problem is that helpers are not reloaded dynamically per request during development. So each time I tweak my snippet or the code around it, I have to kill the server and restart it. Granted, it's just a 5 seconds process, but I love Rails' convenience of just developing and then refreshing the browser. So I'd love to have that for my markup snippets as well. Note: Just sticking 'unloadable' inside the helper module doesn't work.
Good question! This is a technique I should abuse more frequently. ``` #I go in environment.db (presumably it will work in one of the per-environment files, too.) Dependencies.explicitly_unloadable_constants << 'NameOfHelperToReloadHere' ``` That array starts out empty, incidentally, at least in my install. (Checked via console.) I tested this locally and it works for me, at least on Rails 2.0.2. Major credit for the solution belongs to [this gentleman](http://www.williambharding.com/blog/rails/automatically-reload-modules-on-change-in-rails/).
162,459
<p>I have 3 tables</p> <ol> <li><b>Links</b><br/> Link ID<br/> Link Name<br/> GroupID (FK into Groups)<br/> SubGroupID (FK into Subgroups)<br/> <br/></li> <li><p><b>Groups</b><br/> GroupID<br/> GroupName<br/></p></li> <li><p><b>SubGroup</b><br/> SubGroupID<br/> SubGroupName<br/> GroupID (FK into Groups)<br/></p></li> </ol> <p>Every link needs to have a GroupID but teh SubGroupID is optional. How do i write a SQL query to show: <br/></p> <p><b>Links.LinkName, Groups.GroupName, SubGroup.SubGroupName<br/></b></p> <p>For the records with no subgroup just put a blank entry in that field. If i have 250 link rows, i should get back 250 reecords from this query.</p> <p>Is there a way to do this in one query or do i need to do multiple queries?</p>
[ { "answer_id": 162478, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT \n links.linkname\n , groups.groupname\n , subgroup.groupname\nFROM\n links \n JOIN groups ON links.groupid = groups.groupid\n LEFT OUTER JOIN subgroups ON links.subgroupid = subgroup.subgroupid\n</code></pre>\n\n<p>(re-added to address OP's question)\nincidentally, why not keep groups and subgroups in the same table, and use a self-referential join?</p>\n\n<p>Akantro:</p>\n\n<p>You'd have something like this:\n create table groups(\n groupid integer primary key,\n parentgroupid integer foreign key references groups (groupid),\n groupname varchar(50))</p>\n\n<p>your query would then be</p>\n\n<pre><code>SELECT \n links.linkname\n , groups.groupname\n , SUBGROUPS.groupname\nFROM\n links \n JOIN groups ON links.groupid = groups.groupid\n LEFT OUTER JOIN groups SUBGROUPS ON links.subgroupid = subgroup.groupid\n</code></pre>\n\n<p>there's no functional difference to keeping the tables like this, but the benefit is you only have to go to one place to edit the groups/subgroups</p>\n" }, { "answer_id": 162483, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 4, "selected": true, "text": "<p>This assumes that there is at most only 1 subgroup per group. if there are more, then you have the potential to get additional records.</p>\n\n<pre><code>select links.linkname, groups.groupname, subgroup.subgroupname\nfrom links\n inner join groups on (links.groupid = groups.groupid)\n left outer join subgroup on (links.subgroupid = subgroup.subgroupid)\n</code></pre>\n" }, { "answer_id": 162486, "author": "Prody", "author_id": 21240, "author_profile": "https://Stackoverflow.com/users/21240", "pm_score": 0, "selected": false, "text": "<p>You're not too clear, but I think you want to get all rows including those that don't have a correspondent in the SubGroup table.</p>\n\n<p>For this you can use LEFT JOIN, it will fetch NULLs if there are no matching rows.</p>\n" }, { "answer_id": 162487, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT Links.LinkName, Groups.GroupName, SubGroup.SubGroupName -- Will potentially be NULL\nFROM Links\nINNER JOIN Groups\n ON Group.GroupID = Links.GroupID\nLEFT JOIN SubGroup\n ON SubGroup.SubGroupID = Links.SubGroupID\n</code></pre>\n" }, { "answer_id": 162488, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 1, "selected": false, "text": "<p>You would use an Outer Join:</p>\n\n<pre><code>select Links.LinkName, Groups.GroupName, SubGroup.SubGroupName\nfrom Links \ninner join Groups on Groups.GroupID = Links.GroupID\nleft outer join SubGroup on Links.SubGroupID = SubGroup.SubGroupID\n</code></pre>\n" }, { "answer_id": 162490, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 0, "selected": false, "text": "<p>Just use a LEFT OUTER JOIN on the SubGroup table like:</p>\n\n<pre><code>select\n l.LinkName,\n g.GroupName,\n s.SubGroupName\nfrom\n Links l\n'\n JOIN Group g\n on ( g.GroupId = l.GroupId)\n'\n LEFT OUTER JOIN SubGroup s\n on ( s.SubGroupId = l.SubGroupId )\n</code></pre>\n\n<p>That should do it.</p>\n" }, { "answer_id": 162491, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT LinkName, GroupName, SubGroupNamne\nFROM Links INNER JOIN Groups ON LInks.GroupID = Groups.GroupID\n LEFT JOIN SubGroup ON Links.SubGroupID = SubGroup.SubGroupID\n</code></pre>\n\n<p>This will include rows that do not have a sub group. That column will simply be NULL.</p>\n" }, { "answer_id": 162506, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "<pre><code>select L1.LinkName, G1.GroupName, NVL(S1.SubGroupName,' ')\n from Links L1, Groups G1, SubGroup S1 \nwhere L1.GroupID = G1.GroupID and\n L1.GroupID = S1.GroupID\n</code></pre>\n" }, { "answer_id": 162512, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>Okay, try:</p>\n\n<pre><code>select a.linkname, b.groupname, c.subgroupname\nfrom links a, groups b, subgroup c\nwhere a.groupid = b.groupid\nand a.subgroupid = c.subgroupid\nand a.subgroupid is not null\nunion all\nselect a.linkname, b.groupname, ' '\nfrom links a, groups b\nwhere a.groupid = b.groupid\nand a.subgroupid is null\n</code></pre>\n\n<p>I think that should work (it does in DB2 which is the DBMS I use most) - you'll need to adjust the spaces in the second select to match the subgroup.subgroupname size.</p>\n" }, { "answer_id": 163282, "author": "Swinders", "author_id": 186, "author_profile": "https://Stackoverflow.com/users/186", "pm_score": 0, "selected": false, "text": "<p>Use a LEFT OUTER JOIN on the SubGroup table will give you all rows from the Links table and where a SubGroup exists will return that otherwise you see a NULL value.</p>\n\n<pre><code>SELECT L.LinkName, G.GroupName, S.SubGroupName\n FROM Links As L\n INNER JOIN Groups As G ON L.GroupID=G.GroupID\n LEFT OUTER JOIN SubGroup S ON L.SubGroupID=S.SubGroupID\n</code></pre>\n\n<p>This does not check that your SubGroups.LinkID matches the Links.LinkID which should never happen but if you need to check this then add in another clause to the join:</p>\n\n<pre><code>SELECT L.LinkName, G.GroupName, S.SubGroupName\n FROM Links As L\n INNER JOIN Groups As G ON L.GroupID=G.GroupID\n LEFT OUTER JOIN SubGroup S ON L.SubGroupID=S.SubGroupID AND L.GroupID=S.GroupID\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I have 3 tables 1. **Links** Link ID Link Name GroupID (FK into Groups) SubGroupID (FK into Subgroups) 2. **Groups** GroupID GroupName 3. **SubGroup** SubGroupID SubGroupName GroupID (FK into Groups) Every link needs to have a GroupID but teh SubGroupID is optional. How do i write a SQL query to show: **Links.LinkName, Groups.GroupName, SubGroup.SubGroupName** For the records with no subgroup just put a blank entry in that field. If i have 250 link rows, i should get back 250 reecords from this query. Is there a way to do this in one query or do i need to do multiple queries?
This assumes that there is at most only 1 subgroup per group. if there are more, then you have the potential to get additional records. ``` select links.linkname, groups.groupname, subgroup.subgroupname from links inner join groups on (links.groupid = groups.groupid) left outer join subgroup on (links.subgroupid = subgroup.subgroupid) ```
162,480
<p>Consider:</p> <pre><code>int testfunc1 (const int a) { return a; } int testfunc2 (int const a) { return a; } </code></pre> <p>Are these two functions the same in every aspect or is there a difference?</p> <p>I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.</p>
[ { "answer_id": 162499, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 2, "selected": false, "text": "<p>Yes, they are same for just <code>int</code></p>\n\n<p>and different for <code>int*</code></p>\n" }, { "answer_id": 162504, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": true, "text": "<p><code>const T</code> and <code>T const</code> are identical. With pointer types it becomes more complicated:</p>\n\n<ol>\n<li><code>const char*</code> is a pointer to a constant <code>char</code></li>\n<li><code>char const*</code> is a pointer to a constant <code>char</code></li>\n<li><code>char* const</code> is a constant pointer to a (mutable) <code>char</code></li>\n</ol>\n\n<p>In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) <code>const</code> is to use a suffix-<code>const</code>.</p>\n\n<p>This is why many people prefer to always put <code>const</code> to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).</p>\n" }, { "answer_id": 162505, "author": "user7545", "author_id": 7545, "author_profile": "https://Stackoverflow.com/users/7545", "pm_score": 2, "selected": false, "text": "<p>I think in this case they are the same, but here is an example where order matters:</p>\n\n<pre><code>const int* cantChangeTheData;\nint* const cantChangeTheAddress;\n</code></pre>\n" }, { "answer_id": 162526, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 3, "selected": false, "text": "<p>Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.</p>\n\n<p>\"const int* p\" is a pointer to an int that does not allow the int to be changed through that pointer. \"int* const p\" is a pointer to an int that cannot be changed to point to another int.</p>\n\n<p>See <a href=\"https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const\" rel=\"nofollow noreferrer\">https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const</a>.</p>\n" }, { "answer_id": 162588, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": false, "text": "<p>There is no difference. They both declare \"a\" to be an integer that cannot be changed.</p>\n\n<p>The place where differences start to appear is when you use pointers.</p>\n\n<p>Both of these:</p>\n\n<pre><code>const int *a\nint const *a\n</code></pre>\n\n<p>declare \"a\" to be a pointer to an integer that doesn't change. \"a\" can be assigned to, but \"*a\" cannot.</p>\n\n<pre><code>int * const a\n</code></pre>\n\n<p>declares \"a\" to be a constant pointer to an integer. \"*a\" can be assigned to, but \"a\" cannot.</p>\n\n<pre><code>const int * const a\n</code></pre>\n\n<p>declares \"a\" to be a constant pointer to a constant integer. Neither \"a\" nor \"*a\" can be assigned to.</p>\n\n<pre><code>static int one = 1;\n\nint testfunc3 (const int *a)\n{\n *a = 1; /* Error */\n a = &amp;one;\n return *a;\n}\n\nint testfunc4 (int * const a)\n{\n *a = 1;\n a = &amp;one; /* Error */\n return *a;\n}\n\nint testfunc5 (const int * const a)\n{\n *a = 1; /* Error */\n a = &amp;one; /* Error */\n return *a;\n}\n</code></pre>\n" }, { "answer_id": 162615, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 8, "selected": false, "text": "<p>The trick is to read the declaration backwards (right-to-left):</p>\n\n<pre><code>const int a = 1; // read as \"a is an integer which is constant\"\nint const a = 1; // read as \"a is a constant integer\"\n</code></pre>\n\n<p>Both are the same thing. Therefore:</p>\n\n<pre><code>a = 2; // Can't do because a is constant\n</code></pre>\n\n<p>The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:</p>\n\n<pre><code>const char *s; // read as \"s is a pointer to a char that is constant\"\nchar c;\nchar *const t = &amp;c; // read as \"t is a constant pointer to a char\"\n\n*s = 'A'; // Can't do because the char is constant\ns++; // Can do because the pointer isn't constant\n*t = 'A'; // Can do because the char isn't constant\nt++; // Can't do because the pointer is constant\n</code></pre>\n" }, { "answer_id": 162949, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 2, "selected": false, "text": "<p>This isn't a direct answer but a related tip. To keep things straight, I always use the convection \"put <code>const</code> on the outside\", where by \"outside\" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the <code>*</code>). E.g.,</p>\n\n<pre><code>\n\nint * const foo = ...; // Pointer cannot change, pointed to value can change\nconst int * bar = ...; // Pointer can change, pointed to value cannot change\nint * baz = ...; // Pointer can change, pointed to value can change\nconst int * const qux = ...; // Pointer cannot change, pointed to value cannot change\n</code></pre>\n" }, { "answer_id": 266096, "author": "Emerick Rogul", "author_id": 33837, "author_profile": "https://Stackoverflow.com/users/33837", "pm_score": 3, "selected": false, "text": "<p><code>const int</code> is identical to <code>int const</code>, as is true with all scalar types in C. In general, declaring a scalar function parameter as <code>const</code> is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.</p>\n" }, { "answer_id": 32727873, "author": "Nick Westgate", "author_id": 313445, "author_profile": "https://Stackoverflow.com/users/313445", "pm_score": 3, "selected": false, "text": "<p>They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions <strong>must</strong> be declared this way:</p>\n\n<pre><code>int getInt() const;\n</code></pre>\n\n<p>It changes the <code>this</code> pointer in the function from <code>Foo * const</code> to <code>Foo const * const</code>. <a href=\"https://stackoverflow.com/a/3141107/313445\">See here.</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
Consider: ``` int testfunc1 (const int a) { return a; } int testfunc2 (int const a) { return a; } ``` Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
`const T` and `T const` are identical. With pointer types it becomes more complicated: 1. `const char*` is a pointer to a constant `char` 2. `char const*` is a pointer to a constant `char` 3. `char* const` is a constant pointer to a (mutable) `char` In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) `const` is to use a suffix-`const`. This is why many people prefer to always put `const` to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).
162,497
<p>There is a select dropdown and I want to add &quot;No selection&quot; item to the list which should give me 'null' when submitted. I'm using SimpleFormController derived controller.</p> <pre><code>protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception { Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;(); map.put(&quot;countryList&quot;, Arrays.asList(Country.values())); return map; } </code></pre> <p>And the jspx part is</p> <pre class="lang-html prettyprint-override"><code>&lt;form:select path=&quot;country&quot; items=&quot;${countryList}&quot; title=&quot;country&quot;/&gt; </code></pre> <p>One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'. Is there a better solution?</p> <p>@Edit: I have solved this with a custom validation annotation which checks if the selected value is &quot;No Selection&quot;. Is there a more standard and easier solution?</p>
[ { "answer_id": 171260, "author": "Jacob Mattison", "author_id": 1237, "author_profile": "https://Stackoverflow.com/users/1237", "pm_score": 6, "selected": true, "text": "<p>One option:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;form:select path=\"country\" title=\"country\" &gt;\n &lt;form:option value=\"\"&gt;&amp;nbsp;&lt;/form:option&gt;\n &lt;form:options items=\"${countryList}\" /&gt;\n&lt;/form:select&gt;\n</code></pre>\n" }, { "answer_id": 173448, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>I don't think you should need a property editor for this. If the \"blank\" option is first in the list, and the tag that outputs the list doesn't mark any of them as selected, then the browser should select the first, \"blank\" one automatically.</p>\n\n<p>When you submit the form, try and work it so that the \"blank\" value is bound to your command as a null, which might happen automatically, depending on the type.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted. I'm using SimpleFormController derived controller. ``` protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("countryList", Arrays.asList(Country.values())); return map; } ``` And the jspx part is ```html <form:select path="country" items="${countryList}" title="country"/> ``` One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'. Is there a better solution? @Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?
One option: ```html <form:select path="country" title="country" > <form:option value="">&nbsp;</form:option> <form:options items="${countryList}" /> </form:select> ```
162,534
<p>I just wanna ask what would be better approach to supply these objects in my unit tests.</p> <p>In my unit test I am testing CSLA object. CSLA object is internally using one property and one method of ApplicationUser object. ApplicationUser is inherited from IPrincipal. The properties are: 1) ApplicationContext.User.IsInRole(...) - the method is part of IPrincipal 2) ApplicationContext.User.Identity.Name - the name is property of IIdentity which is part of ApplicationUser aka IPricipal</p> <p>Example of my test (using RhinoMock):</p> <pre><code>public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock&lt;IPrincipal&gt;(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc } } </code></pre> <p>I have slight problem with second value, the identity name. I tried to mock it but have problem to assign mocked IIdentity to ApplicationUser, as it is done internaly. I was told to just create some IIPrincipal (including IIdentity) by myself and not to mock it at all. Which can be done for sure. Not sure if this can be called as Stub using?</p> <p>So can you advice me how to deal with IPrincipal and IIdentity? Any suggestion most welcome.</p>
[ { "answer_id": 162667, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 2, "selected": false, "text": "<p>Here is the code I use to return a test user (using Stubs):</p>\n\n<pre><code> [SetUp]\n public void Setup()\n {\n var identity = MockRepository.GenerateStub&lt;IIdentity&gt;();\n identity.Stub(p =&gt; p.Name).Return(\"TestUser\").Repeat.Any();\n var principal = MockRepository.GenerateStub&lt;IPrincipal&gt;();\n principal.Stub(p =&gt; p.Identity).Return(identity).Repeat.Any();\n\n Thread.CurrentPrincipal = principal;\n }\n</code></pre>\n\n<p>I've got linq in other code so I'm using the var type for the variables; just substitute the correct types (IPrincipal, IIdentity) if needed.</p>\n" }, { "answer_id": 1093800, "author": "Randolpho", "author_id": 12716, "author_profile": "https://Stackoverflow.com/users/12716", "pm_score": 4, "selected": true, "text": "<p>The reason you're getting a null reference error is because <code>IPrincipal.Identity</code> is null; it hasn't been set in your mocked <code>IPrincipal</code> yet. Calling <code>.Name</code> the null <code>Identity</code> results in your exception.</p>\n\n<p>The answer, as Carlton pointed out, is to mock <code>IIdentity</code> <em>also</em>, and set it up to return \"ju\" for its <code>Name</code> property. Then you can tell <code>IPrincipal.Identity</code> to return the mock <code>IIdentity</code>.</p>\n\n<p>Here is an expansion of your code to do this (using Rhino Mocks rather than Stubs):</p>\n\n<pre><code>public void BeforeTest()\n{\n mocks = new MockRepository();\n IPrincipal mockPrincipal = mocks.CreateMock&lt;IPrincipal&gt;();\n IIdentity mockIdentity = mocks.CreateMock&lt;IIdentity&gt;();\n ApplicationContext.User = mockPrincipal;\n using (mocks.Record()) \n {\n Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);\n Expect.Call(mockIdentity.Name).Return(\"ju\"); \n Expect.Call(mockPrincipal.Identity).Return(mockIdentity);\n }\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24507/" ]
I just wanna ask what would be better approach to supply these objects in my unit tests. In my unit test I am testing CSLA object. CSLA object is internally using one property and one method of ApplicationUser object. ApplicationUser is inherited from IPrincipal. The properties are: 1) ApplicationContext.User.IsInRole(...) - the method is part of IPrincipal 2) ApplicationContext.User.Identity.Name - the name is property of IIdentity which is part of ApplicationUser aka IPricipal Example of my test (using RhinoMock): ``` public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc } } ``` I have slight problem with second value, the identity name. I tried to mock it but have problem to assign mocked IIdentity to ApplicationUser, as it is done internaly. I was told to just create some IIPrincipal (including IIdentity) by myself and not to mock it at all. Which can be done for sure. Not sure if this can be called as Stub using? So can you advice me how to deal with IPrincipal and IIdentity? Any suggestion most welcome.
The reason you're getting a null reference error is because `IPrincipal.Identity` is null; it hasn't been set in your mocked `IPrincipal` yet. Calling `.Name` the null `Identity` results in your exception. The answer, as Carlton pointed out, is to mock `IIdentity` *also*, and set it up to return "ju" for its `Name` property. Then you can tell `IPrincipal.Identity` to return the mock `IIdentity`. Here is an expansion of your code to do this (using Rhino Mocks rather than Stubs): ``` public void BeforeTest() { mocks = new MockRepository(); IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>(); IIdentity mockIdentity = mocks.CreateMock<IIdentity>(); ApplicationContext.User = mockPrincipal; using (mocks.Record()) { Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true); Expect.Call(mockIdentity.Name).Return("ju"); Expect.Call(mockPrincipal.Identity).Return(mockIdentity); } } ```
162,537
<p>I just upgraded a VS 2005 project to VS 2008 and was examining the changes. I noticed one of the .Designer.cs files had changed significantly. The majority of the changes were simply replacements of <em>System</em> with <em>global::System</em>. For example,</p> <pre><code>protected override System.Data.DataTable CreateInstance() </code></pre> <p>became</p> <pre><code>protected override global::System.Data.DataTable CreateInstance() </code></pre> <p>What's going on here?</p>
[ { "answer_id": 162554, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": "<p>The :: operator is called a Namespace Alias Qualifier.</p>\n\n<pre><code> global::System.Data.DataTable \n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code> System.Data.DataTable\n</code></pre>\n\n<p>Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example:</p>\n\n<pre><code>class TestApp\n{\n // Define a new class called 'System' to cause problems.\n public class System { }\n\n // Define a constant called 'Console' to cause more problems.\n const int Console = 7;\n const int number = 66;\n\n static void Main()\n {\n // Error Accesses TestApp.Console\n //Console.WriteLine(number);\n }\n}\n</code></pre>\n\n<p>However:</p>\n\n<pre><code>global::System.Console.Writeline(\"This works\");\n</code></pre>\n\n<p>For further reading:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx</a></p>\n" }, { "answer_id": 245443, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 1, "selected": false, "text": "<p>To prevent people from doing <a href=\"http://thesoftwarejedi.blogspot.com/2008/05/4-naughty-c-35-code-changes-for-your.html\" rel=\"nofollow noreferrer\">#1 on this list</a>. :)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
I just upgraded a VS 2005 project to VS 2008 and was examining the changes. I noticed one of the .Designer.cs files had changed significantly. The majority of the changes were simply replacements of *System* with *global::System*. For example, ``` protected override System.Data.DataTable CreateInstance() ``` became ``` protected override global::System.Data.DataTable CreateInstance() ``` What's going on here?
The :: operator is called a Namespace Alias Qualifier. ``` global::System.Data.DataTable ``` is the same as: ``` System.Data.DataTable ``` Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example: ``` class TestApp { // Define a new class called 'System' to cause problems. public class System { } // Define a constant called 'Console' to cause more problems. const int Console = 7; const int number = 66; static void Main() { // Error Accesses TestApp.Console //Console.WriteLine(number); } } ``` However: ``` global::System.Console.Writeline("This works"); ``` For further reading: <http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx>
162,542
<p>How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.</p> <p>For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.</p> <p>Then I went into the routes.rb file and entered <code>map.resources :employees</code>, which gives you access to the URL helper functions.</p> <p>In whatever I want to call the Ajax operation from, I should just have a line like:</p> <pre><code>&lt;%= link_to_remote "Delete", employee_path(@employee), :method =&gt; :delete %&gt; </code></pre> <p>When I click on the link, it is still is sending a POST operation, so it does nothing.</p> <p>What am I missing or doing wrong?</p>
[ { "answer_id": 162590, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": true, "text": "<p>Try </p>\n\n<pre><code>:url =&gt; employee_url(@employee)\n</code></pre>\n\n<p>IIRC, *_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete</p>\n" }, { "answer_id": 162612, "author": "flitzwald", "author_id": 11811, "author_profile": "https://Stackoverflow.com/users/11811", "pm_score": 2, "selected": false, "text": "<p>From my code:</p>\n\n<pre><code>&lt;%= link_to_remote \"Delete\", :url =&gt; post_url(post), :method =&gt; :delete %&gt;\n</code></pre>\n" }, { "answer_id": 169263, "author": "Chris R.", "author_id": 5923, "author_profile": "https://Stackoverflow.com/users/5923", "pm_score": 0, "selected": false, "text": "<p>Just to add a few extra details: Using <code>:url =&gt; employee_url(@employee)</code> helped (from the accepted answer). The other part that was messing me up was the fact that I was expecting an HTTP delete request, but I kept getting POST requests with a parameter \"_method\" (automatically added by rails) which was set to delete.</p>\n\n<p>So it was calling the proper destroy action, which I proved by adding a couple of debug statements to the controller. Yes, my delete code was wrong in the controller, so it wasn't really deleting when I thought it was.</p>\n" }, { "answer_id": 3537455, "author": "user425766", "author_id": 425766, "author_profile": "https://Stackoverflow.com/users/425766", "pm_score": -1, "selected": false, "text": "<p>If your problem is not having AJAX request you have to add proper javascript tags</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5923/" ]
How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work. For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete. Then I went into the routes.rb file and entered `map.resources :employees`, which gives you access to the URL helper functions. In whatever I want to call the Ajax operation from, I should just have a line like: ``` <%= link_to_remote "Delete", employee_path(@employee), :method => :delete %> ``` When I click on the link, it is still is sending a POST operation, so it does nothing. What am I missing or doing wrong?
Try ``` :url => employee_url(@employee) ``` IIRC, \*\_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete
162,564
<p>I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update. Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?</p>
[ { "answer_id": 162584, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p>Shift down and then up again:</p>\n\n<pre><code>UPDATE table\nSET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol))\nWHERE id = @id\n</code></pre>\n\n<p>or, more simply:</p>\n\n<pre><code>UPDATE table\nSET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol)\nWHERE id = @id\n</code></pre>\n" }, { "answer_id": 162661, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 1, "selected": false, "text": "<p>You can do this all in TSQL in Sql Server. Check out the <a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"nofollow noreferrer\">DateDiff</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"nofollow noreferrer\">DateAdd</a> functions.</p>\n\n<p>I expect this would work:</p>\n\n<pre><code>DECLARE @newMonth int\nSET @newMonth = 5 --As an example\n\nUPDATE dbo.TheTable\nSET DateField = DATEADD(month, @newMonth - DATEPART(month, DateField) , DateField)\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update. Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?
Shift down and then up again: ``` UPDATE table SET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol)) WHERE id = @id ``` or, more simply: ``` UPDATE table SET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol) WHERE id = @id ```