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
137,336
<p>PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.</p> <p>Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.</p> <p>Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, <strong><em>I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.</em></strong> </p> <p>How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages? </p> <p>Also, how can you do all this while accounting for inheritance in Php? Consider:</p> <pre><code>&lt;?php class InterfaceClass { #... } class UsesInterfaceClass { function SetObject(&amp;$obj) { // What do I put here to make sure that $obj either // is of type InterfaceObject or inherits from it } } ?&gt; </code></pre> <p>Then a user of this code implements the interface with their own concrete class:</p> <pre><code>&lt;?php class ConcreteClass extends InterfaceClass { } ?&gt; </code></pre> <p>I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?</p>
[ { "answer_id": 137342, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": true, "text": "<p>Actually for classes you can provide type hinting in PHP (5+).</p>\n\n<pre><code> &lt;?php\n class UsesBaseClass\n {\n function SetObject(InterfaceObject $obj) \n {\n }\n }\n ?&gt;\n</code></pre>\n\n<p>This will also work correctly with inheritance as you would expect it to.</p>\n\n<p>As an aside, don't put the word 'object' in your class names...</p>\n" }, { "answer_id": 137351, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 2, "selected": false, "text": "<p>as an addition to Eran Galperin's response you can also use the type hinting to force parameters to be arrays - not just objects of a certain class.</p>\n\n<pre><code>&lt;?php\nclass MyCoolClass {\n public function passMeAnArray(array $array = array()) {\n // do something with the array \n } \n } \n ?&gt;\n</code></pre>\n\n<p>As you can see you can type hint that the <code>::passMeAnArray()</code> method expects an <code>array</code> as well as provide a default value in case the method is called w/o any parameters.</p>\n" }, { "answer_id": 137405, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 1, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/137336/how-do-i-prevent-using-the-incorrect-type-in-php#137342\">Eran Galperin</a>'s response is the preferred method for ensuring the object you are using is of the correct type.</p>\n\n<p>Also worth noting is the <a href=\"http://www.php.net/instanceof\" rel=\"nofollow noreferrer\">instanceOf</a> operator - it is helpful for when you want to check that an object is one of multiple types.</p>\n" }, { "answer_id": 137578, "author": "Ahmad", "author_id": 22449, "author_profile": "https://Stackoverflow.com/users/22449", "pm_score": 0, "selected": false, "text": "<p>You can set the error_reporting ini setting in your php.ini file or use error_reporting function to set it in run time</p>\n" }, { "answer_id": 138100, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 1, "selected": false, "text": "<p>You see, there are multiple answers about <strong>type hinting.</strong> This is the technical solution. But you should also make sure that the whole design is sensible and intuitive. This will make type problems and mistakes more rare.</p>\n\n<p>Remember that even these type failures will be thrown <strong>at runtime</strong>. Make sure you have tests for the code.</p>\n" }, { "answer_id": 143474, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "<p>Even in the case you describe, your script will crash, complaining there is no method / attribute X on the object Y so you'll know where does this come from.</p>\n\n<p>Anyway, I think that always try to prevent grew up programmers to pass the wrong object to a method is not a good time investment : you could spend it in documenting and training instead.</p>\n\n<p>Duck typing and careful colleagues is what you need, not additional checks that will make you app more rigid.</p>\n\n<p>But it may be a Pythonista point of view...</p>\n" }, { "answer_id": 170242, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 2, "selected": false, "text": "<p>For primitive types you could also use the is_* functions : </p>\n\n<pre><code>public function Add($a, $b)\n{\n if (!is_int($a) || !is_int($b))\n throw new InvalidArgumentException();\n return $a + $b;\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature. Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument. Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, ***I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.*** How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages? Also, how can you do all this while accounting for inheritance in Php? Consider: ``` <?php class InterfaceClass { #... } class UsesInterfaceClass { function SetObject(&$obj) { // What do I put here to make sure that $obj either // is of type InterfaceObject or inherits from it } } ?> ``` Then a user of this code implements the interface with their own concrete class: ``` <?php class ConcreteClass extends InterfaceClass { } ?> ``` I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?
Actually for classes you can provide type hinting in PHP (5+). ``` <?php class UsesBaseClass { function SetObject(InterfaceObject $obj) { } } ?> ``` This will also work correctly with inheritance as you would expect it to. As an aside, don't put the word 'object' in your class names...
137,359
<p>I produce a report as an CSV file. When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly.</p> <p>For example, if the CSV file contains</p> <pre><code>...,005,... </code></pre> <p>Then Excel shows it as 5. Is there a way to override this and display 005?</p> <p>I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it.</p> <p>I use Excel 2003.</p>
[ { "answer_id": 137368, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 2, "selected": false, "text": "<p>You can simply format your range as Text.</p>\n\n<p>Also <a href=\"http://peltiertech.com/Excel/NumberFormats.html\" rel=\"nofollow noreferrer\">here</a> is a nice article on the number formats and how you can program them.</p>\n" }, { "answer_id": 137369, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 1, "selected": false, "text": "<p>I believe when you import the file you can select the Column Type. Make it Text instead of Number. I don't have a copy in front of me at the moment to check though.</p>\n" }, { "answer_id": 137373, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 0, "selected": false, "text": "<p>When opening a CSV, you get the text import wizard. At the last step of the wizard, you should be able to import the specific column as text, thereby retaining the '00' prefix. After that you can then format the cell any way that you want.</p>\n\n<p>I tried with with Excel 2007 and it appeared to work.</p>\n" }, { "answer_id": 137473, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>Don't use CSV, use SYLK.<br>\n<a href=\"http://en.wikipedia.org/wiki/SYmbolic_LinK_(SYLK)\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/SYmbolic_LinK_(SYLK)</a></p>\n\n<p>It gives much more control over formatting, and Excel won't try to guess the type of a field by examining the contents. It looks a bit complicated, but you can get away with using a very small subset.</p>\n" }, { "answer_id": 137777, "author": "Sergey Stadnik", "author_id": 10557, "author_profile": "https://Stackoverflow.com/users/10557", "pm_score": 2, "selected": false, "text": "<p>Actually I discovered that, at least starting with Office 2003, you can save an Excel spreadsheet as an XML file.\nThus, I can produce an XML file and when I double-click on it, it'll be opened in Excel.\nIt provides the same level of control as SYLK, but XML syntax is more intuitive.</p>\n" }, { "answer_id": 142073, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 8, "selected": true, "text": "<p>There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.</p>\n\n<p>My preference is the first option.</p>\n\n<p><strong>Option 1 – Change the data in the file</strong></p>\n\n<p>You could change the data in the .csv file as follows ...,<strong>=”005”</strong>,...\nThis will be displayed in Excel as ...,<strong>005</strong>,...</p>\n\n<p>Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting</p>\n\n<p><strong>Option 2</strong> – Format the data</p>\n\n<p>If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format <strong>000</strong></p>\n\n<p><strong>Option 3</strong> – Change the file extension to .dif (Data interchange format)</p>\n\n<p>Change the file extension and use the file import wizard to control the formats.\nFiles with a .dif extension are automatically opened by Excel when double clicked on.</p>\n\n<p><em>Step by step:</em></p>\n\n<ul>\n<li>Change the file extension from <strong>.csv</strong> to <strong>.dif</strong></li>\n<li>Double click on the file to open it in Excel.</li>\n<li>The 'File Import Wizard' will be launched.</li>\n<li>Set the 'File type' to 'Delimited' and click on the 'Next' button.</li>\n<li>Under Delimiters, tick 'Comma' and click on the 'Next' button.</li>\n<li>Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.</li>\n<li>Click on the finish button, the file will be opened by Excel with the formats that you have specified.</li>\n</ul>\n" }, { "answer_id": 1821791, "author": "Narayanan", "author_id": 221565, "author_profile": "https://Stackoverflow.com/users/221565", "pm_score": 0, "selected": false, "text": "<p>Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.</p>\n" }, { "answer_id": 1946566, "author": "John Nicholas", "author_id": 109347, "author_profile": "https://Stackoverflow.com/users/109347", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/1688497/load-csv-into-oledb-and-force-all-inferred-datatypes-to-string\">Load csv into oleDB and force all inferred datatypes to string</a></p>\n\n<p>i asked the same question and then answerd it with code.</p>\n\n<p>basically when the csv file is loaded the oledb driver makes assumptions, you can tell it what assumptions to make.</p>\n\n<p>My code forces all datatypes to string though ... its very easy to change the schema.\nfor my purposes i used an xslt to get ti the way i wanted - but i am parsing a wide variety of files.</p>\n" }, { "answer_id": 3259242, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 0, "selected": false, "text": "<p>Put a single quote before the field. Excel will treat it as text, even if it looks like a number.</p>\n\n<pre><code>...,`005,...\n</code></pre>\n\n<p><strong>EDIT:</strong> This is wrong. The apostrophe trick only works when entering data directly into Excel. When you use it in a CSV file, the apostrophe appears in the field, which you don't want.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/214233\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/214233</a></p>\n" }, { "answer_id": 4597545, "author": "personaelit", "author_id": 42574, "author_profile": "https://Stackoverflow.com/users/42574", "pm_score": 1, "selected": false, "text": "<p>I know this is an old question, but I have a solution that isn't listed here.</p>\n\n<p>When you produce the csv add a space after the comma but before your value e.g. <code>, 005,</code>. </p>\n\n<p>This worked to prevent auto date formatting in excel 2007 anyway .</p>\n" }, { "answer_id": 5568778, "author": "Pickles", "author_id": 695121, "author_profile": "https://Stackoverflow.com/users/695121", "pm_score": 1, "selected": false, "text": "<p>The Text Import Wizard method does NOT work when the CSV file being imported has line breaks within a cell. This method handles this scenario(at least with tab delimited data):</p>\n\n<ol>\n<li>Create new Excel file</li>\n<li>Ctrl+A to select all cells</li>\n<li>In Number Format combobox, select Text</li>\n<li>Open tab delimited file in text editor</li>\n<li>Select all, copy and paste into Excel</li>\n</ol>\n" }, { "answer_id": 10609087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This works for Microsoft Office 2010, Excel Version 14<br/></p>\n\n<p><em>I misread the OP's preference \"to do something to the file itself.\" I'm still keeping this for those who want a solution to format the import directly</em></p>\n\n<ol>\n<li>Open a blank (new) file (File -> New from workbook)<br/></li>\n<li>Open the Import Wizard (Data -> From Text)<br/></li>\n<li>Select your .csv file and Import<br/></li>\n<li>In the dialogue box, choose 'Delimited', and click Next.<br/></li>\n<li>Choose your delimiters (uncheck everything but 'comma'), choose your Text qualifiers (likely {None}), click Next<br/></li>\n<li>In the <strong>Data preview</strong> field select the column you want to be text. It should highlight.<br/></li>\n<li>In the <strong>Column data format</strong> field, select 'Text'.<br/></li>\n<li>Click finished.<br/></li>\n</ol>\n" }, { "answer_id": 19274257, "author": "Kloe2378231", "author_id": 2378231, "author_profile": "https://Stackoverflow.com/users/2378231", "pm_score": 2, "selected": false, "text": "<p>Adding a non-breaking space in the cell could help.\nFor instance: \n<code>\"firstvalue\";\"secondvalue\";\"005 \";\"othervalue\"</code></p>\n\n<p>It forces Excel to treat it as a text and the space is not visible.\nOn Windows you can add a non-breaking space by tiping alt+0160.\nSee here for more info: <a href=\"http://en.wikipedia.org/wiki/Non-breaking_space\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Non-breaking_space</a></p>\n\n<p>Tried on Excel 2010.\nHope this can help people who still search a quite proper solution for this problem.</p>\n" }, { "answer_id": 20070065, "author": "MNassar", "author_id": 319805, "author_profile": "https://Stackoverflow.com/users/319805", "pm_score": 1, "selected": false, "text": "<p>Just add ' before the number in the CSV doc.</p>\n" }, { "answer_id": 21331360, "author": "Richard Pursehouse", "author_id": 994269, "author_profile": "https://Stackoverflow.com/users/994269", "pm_score": 2, "selected": false, "text": "<p>I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \\t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen). </p>\n\n<p>I did like the =\"001\" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data). </p>\n" }, { "answer_id": 23666382, "author": "Ellen", "author_id": 3499045, "author_profile": "https://Stackoverflow.com/users/3499045", "pm_score": 1, "selected": false, "text": "<p>This has been driving me crazy all day (since indeed you can't control the Excel column types before opening the CSV file), and this worked for me, using VB.NET and Excel Interop:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> 'Convert .csv file to .txt file.\n FileName = ConvertToText(FileName)\n\n Dim ColumnTypes(,) As Integer = New Integer(,) {{1, xlTextFormat}, _\n {2, xlTextFormat}, _\n {3, xlGeneralFormat}, _\n {4, xlGeneralFormat}, _\n {5, xlGeneralFormat}, _\n {6, xlGeneralFormat}}\n\n 'We are using OpenText() in order to specify the column types.\n mxlApp.Workbooks.OpenText(FileName, , , Excel.XlTextParsingType.xlDelimited, , , True, , True, , , , ColumnTypes)\n mxlWorkBook = mxlApp.ActiveWorkbook\n mxlWorkSheet = CType(mxlApp.ActiveSheet, Excel.Worksheet)\n\n\nPrivate Function ConvertToText(ByVal FileName As String) As String\n 'Convert the .csv file to a .txt file.\n 'If the file is a text file, we can specify the column types.\n 'Otherwise, the Codes are first converted to numbers, which loses trailing zeros.\n\n Try\n Dim MyReader As New StreamReader(FileName)\n Dim NewFileName As String = FileName.Replace(\".CSV\", \".TXT\")\n Dim MyWriter As New StreamWriter(NewFileName, False)\n Dim strLine As String\n\n Do While Not MyReader.EndOfStream\n strLine = MyReader.ReadLine\n MyWriter.WriteLine(strLine)\n Loop\n\n MyReader.Close()\n MyReader.Dispose()\n MyWriter.Close()\n MyWriter.Dispose()\n\n Return NewFileName\n Catch ex As Exception\n MsgBox(ex.Message)\n Return \"\"\n End Try\n\nEnd Function\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10557/" ]
I produce a report as an CSV file. When I try to open the file in Excel, it makes an assumption about the data type based on the contents of the cell, and reformats it accordingly. For example, if the CSV file contains ``` ...,005,... ``` Then Excel shows it as 5. Is there a way to override this and display 005? I would prefer to do something to the file itself, so that the user could just double-click on the CSV file to open it. I use Excel 2003.
There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help. My preference is the first option. **Option 1 – Change the data in the file** You could change the data in the .csv file as follows ...,**=”005”**,... This will be displayed in Excel as ...,**005**,... Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting **Option 2** – Format the data If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format **000** **Option 3** – Change the file extension to .dif (Data interchange format) Change the file extension and use the file import wizard to control the formats. Files with a .dif extension are automatically opened by Excel when double clicked on. *Step by step:* * Change the file extension from **.csv** to **.dif** * Double click on the file to open it in Excel. * The 'File Import Wizard' will be launched. * Set the 'File type' to 'Delimited' and click on the 'Next' button. * Under Delimiters, tick 'Comma' and click on the 'Next' button. * Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'. * Click on the finish button, the file will be opened by Excel with the formats that you have specified.
137,375
<p>I'm teaching/helping a student to program.</p> <p>I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach.</p> <ol> <li>Read the problem and understand it ( of course ) .</li> <li>Identify possible "functions" and variables.</li> <li>Write how would I do it step by step ( algorithm ) </li> <li>Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving.</li> </ol> <p>With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program.</p> <p>So for a project description like: </p> <blockquote> <p><em>A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )</em></p> </blockquote> <p>I first step is to understand what the problem is.</p> <p>Then identify the item, the rules the variables etc.</p> <p>pseudo code something like:</p> <pre><code>function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int if( hourOfDay &gt; 18 ) then discount = 5% if( quantity &gt; 10 ) then discount = 5% if( clientAge &gt; 60 or &lt; 18 ) then discount = 5% return item_price - discounts... end </code></pre> <p>And then pass it to the programming language..</p> <pre><code>public class Problem1{ public int getPrice( int itemPrice, int quantity,hourOdDay ) { int discount = 0; if( hourOfDay &gt; 10 ) { // uh uh.. U don't know how to calculate percentage... // create a function and move on. discount += percentOf( 5, itemPriece ); . . . you get the idea.. } } public int percentOf( int percent, int i ) { // .... } } </code></pre> <p>Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( ) </p>
[ { "answer_id": 137383, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 3, "selected": true, "text": "<p>I did something similar. </p>\n\n<ul>\n<li>Figure out the rules/logic. </li>\n<li>Figure out the math. </li>\n<li>Then try and code it.</li>\n</ul>\n\n<p>After doing that for a couple of months it just gets internalized. You don't realize your doing it until you come up against a complex problem that requires you to break it down.</p>\n" }, { "answer_id": 137388, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 2, "selected": false, "text": "<p>Wishful thinking is probably the most important tool to solve complex problems. When in doubt, assume that a function exists to solve your problem (create a stub, at first). You'll come back to it later to expand it.</p>\n" }, { "answer_id": 137485, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": false, "text": "<p>I go via the test-driven approach.</p>\n<h3>1. I write down (on paper or plain text editor) a list of tests or specification that would satisfy the needs of the problem.</h3>\n<pre><code>- simple calculations (no discounts and concessions) with:\n - single item\n - two items\n - maximum number of items that doesn't have a discount\n- calculate for discounts based on number of items\n - buying 10 items gives you a 5% discount\n - buying 15 items gives you a 7% discount\n - etc.\n- calculate based on hourly rates\n - calculate morning rates\n - calculate afternoon rates\n - calculate evening rates\n - calculate midnight rates\n- calculate based on buyer's age\n - children\n - adults\n - seniors\n- calculate based on combinations\n - buying 10 items in the afternoon\n</code></pre>\n<h3>2. Look for the items that I think would be the easiest to implement and write a test for it. E.g single items looks easy</h3>\n<p>The sample using Nunit and C#.</p>\n<pre><code>[Test] public void SingleItems()\n{\n Assert.AreEqual(5, GetPrice(5, 1));\n}\n</code></pre>\n<p>Implement that using:</p>\n<pre><code>public decimal GetPrice(decimal amount, int quantity)\n{\n return amount * quantity; // easy!\n}\n</code></pre>\n<p>Then move on to the two items.</p>\n<pre><code>[Test]\npublic void TwoItemsItems()\n{\n Assert.AreEqual(10, GetPrice(5, 2));\n}\n</code></pre>\n<p>The implementation still passes the test so move on to the next test.</p>\n<h3>3. Be always on the lookout for duplication and remove it. You are done when all the tests pass and you can no longer think of any test.</h3>\n<p>This doesn't guarantee that you will create the most efficient algorithm, but as long as you know what to test for and it all passes, it will guarantee that you are getting the right answers.</p>\n" }, { "answer_id": 137511, "author": "stalepretzel", "author_id": 1615, "author_profile": "https://Stackoverflow.com/users/1615", "pm_score": -1, "selected": false, "text": "<p>Keep in mind, if you get 5% off then another 5% off, you don't get 10% off. Rather, you pay 95% of 95%, which is 90.25%, or 9.75% off. So, you shouldn't add the percentage.</p>\n" }, { "answer_id": 137528, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "<p>A good book for beginners looking for a process: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321146530\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Test Driven Development: By Example</a></p>\n" }, { "answer_id": 137568, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "<p>Yes.. well TDD did't existed ( or was not that popular ) when I began. Would be TDD the way to go to pass from problem description to code?... Is not that a little bit advanced? I mean, when a \"future\" developer hardly understand what a programming language is, wouldn't it be counterproductive?</p>\n\n<p>What about hamcrest the make the transition from algorithm to code.</p>\n" }, { "answer_id": 137598, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>the old-school OO way:</p>\n\n<ul>\n<li>write down a description of the problem and its solution</li>\n<li>circle the nouns, these are candidate objects</li>\n<li>draw boxes around the verbs, these are candidate messages</li>\n<li>group the verbs with the nouns that would 'do' the action; list any other nouns that would be required to help</li>\n<li>see if you can restate the solution using the form noun.verb(other nouns)</li>\n<li>code it</li>\n</ul>\n\n<p>[this method preceeds CRC cards, but its been so long (over 20 years) that I don't remember where i learned it]</p>\n" }, { "answer_id": 137632, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>I start at the top and work my way down. Basically, I'll start by writing a high level procedure, sketch out the details inside of it, and then start filling in the details. </p>\n\n<p>Say I had this problem (yoinked from project euler) </p>\n\n<blockquote>\n <p>The sum of the squares of the first\n ten natural numbers is, 1^2 + 2^2 +\n ... + 10^2 = 385</p>\n \n <p>The square of the sum of the first ten\n natural numbers is, (1 + 2 + ... +\n 10)^2 = 55^2 = 3025</p>\n \n <p>Hence the difference between the sum\n of the squares of the first ten\n natural numbers and the square of the\n sum is 3025 385 = 2640.</p>\n \n <p>Find the difference between the sum of\n the squares of the first one hundred\n natural numbers and the square of the\n sum.</p>\n</blockquote>\n\n<p>So I start like this:</p>\n\n<pre><code>(display (- (sum-of-squares (list-to 10))\n (square-of-sums (list-to 10))))\n</code></pre>\n\n<p>Now, in Scheme, there is no sum-of-squares, square-of-sums or list-to functions. So the next step would be to build each of those. In building each of those functions, I may find I need to abstract out more. I try to keep things simple so that each function only really does one thing. When I build some piece of functionality that is testable, I write a unit test for it. When I start noticing a logical grouping for some data, and the functions that act on them, I may push it into an object.</p>\n" }, { "answer_id": 137640, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 2, "selected": false, "text": "<p>when learning programming I don't think TDD is helpful. TDD is good later on when you have some concept of what programming is about, but for starters, having an environment where you write code and see the results in the quickest possible turn around time is the most important thing.</p>\n\n<p>I'd go from problem statement to code instantly. Hack it around. Help the student see different ways of composing software / structuring algorithms. Teach the student to change their minds and rework the code. Try and teach a little bit about code aesthetics.</p>\n\n<p>Once they can hack around code.... then introduce the idea of formal restructuring in terms of refactoring. Then introduce the idea of TDD as a way to make the process a bit more robust. But only once they are feeling comfortable in manipulating code to do what they want. Being able to specify tests is then somewhat easier at that stage. The reason is that TDD is about Design. When learning you don't really care so much about design but about what you can do, what toys do you have to play with, how do they work, how do you combine them together. Once you have a sense of that, then you want to think about design and thats when TDD really kicks in.</p>\n\n<p>From there I'd start introducing micro patterns leading into design patterns</p>\n" }, { "answer_id": 137665, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 2, "selected": false, "text": "<p>My dad had a bunch of flow chart stencils that he used to make me use when he was first teaching me about programming. to this day I draw squares and diamonds to build out a logical process of how to analyze a problem.</p>\n" }, { "answer_id": 322543, "author": "asleep", "author_id": 29445, "author_profile": "https://Stackoverflow.com/users/29445", "pm_score": 2, "selected": false, "text": "<p>I've enjoyed TDD every since it was introduced to me. Helps me plan out my code, and it just puts me at ease having all my tests return with \"success\" every time I modify my code, letting me know I'm going home on time today!</p>\n" }, { "answer_id": 322575, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 2, "selected": false, "text": "<p>I think there are about a dozen different heuristics I know of when it comes to programming and so I tend to go through the list at times with what I'm trying to do. At the start, it is important to know what is the desired end result and then try to work backwards to find it.</p>\n\n<p>I remember an Algorithms class covering some of these ways like:</p>\n\n<ul>\n<li>Reduce it to a known problem or trivial problem</li>\n<li>Divide and conquer (MergeSort being a classic example here)</li>\n<li>Use Data Structures that have the right functions (HeapSort being an example here)</li>\n<li>Recursion (Knowing trivial solutions and being able to reduce to those)</li>\n<li>Dynamic programming</li>\n</ul>\n\n<p>Organizing a solution as well as testing it for odd situations, e.g. if someone thinks L should be a number, are what I'd usually use to test out the idea in pseudo code before writing it up.</p>\n\n<p>Design patterns can be a handy set of tools to use for specific cases like where an Adapter is needed or organizing things into a state or strategy solution.</p>\n" }, { "answer_id": 1480229, "author": "kyoryu", "author_id": 129175, "author_profile": "https://Stackoverflow.com/users/129175", "pm_score": 1, "selected": false, "text": "<p>I think there's a better way to state your problem.</p>\n\n<p>Instead of defining it as 'a system,' define what is expected in terms of user inputs and outputs.</p>\n\n<p>\"On a window, a user should select an item from a list, and a box should show him how much it costs.\"</p>\n\n<p>Then, you can give him some of the factors determining the costs, including sample items and what their costs should end up being.</p>\n\n<p>(this is also very much a TDD-like idea)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
I'm teaching/helping a student to program. I remember the following process always helped me when I started; It looks pretty intuitive and I wonder if someone else have had a similar approach. 1. Read the problem and understand it ( of course ) . 2. Identify possible "functions" and variables. 3. Write how would I do it step by step ( algorithm ) 4. Translate it into code, if there is something you cannot do, create a function that does it for you and keep moving. With the time and practice I seem to have forgotten how hard it was to pass from problem description to a coding solution, but, by applying this method I managed to learn how to program. So for a project description like: > > *A system has to calculate the price of an Item based on the following rules ( a description of the rules... client, discounts, availability etc.. etc.etc. )* > > > I first step is to understand what the problem is. Then identify the item, the rules the variables etc. pseudo code something like: ``` function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int if( hourOfDay > 18 ) then discount = 5% if( quantity > 10 ) then discount = 5% if( clientAge > 60 or < 18 ) then discount = 5% return item_price - discounts... end ``` And then pass it to the programming language.. ``` public class Problem1{ public int getPrice( int itemPrice, int quantity,hourOdDay ) { int discount = 0; if( hourOfDay > 10 ) { // uh uh.. U don't know how to calculate percentage... // create a function and move on. discount += percentOf( 5, itemPriece ); . . . you get the idea.. } } public int percentOf( int percent, int i ) { // .... } } ``` Did you went on a similar approach?.. Did some one teach you a similar approach or did you discovered your self ( as I did :( )
I did something similar. * Figure out the rules/logic. * Figure out the math. * Then try and code it. After doing that for a couple of months it just gets internalized. You don't realize your doing it until you come up against a complex problem that requires you to break it down.
137,387
<p>I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:</p> <pre><code>Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(folder) size = folderObject.Size </code></pre> <p>There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.</p> <p>To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?</p> <p>Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.</p>
[ { "answer_id": 137393, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Sadly, yes...who knows why.</p>\n\n<pre><code>public static long DirSize(DirectoryInfo d) \n{ \n long Size = 0; \n // Add file sizes.\n FileInfo[] fis = d.GetFiles();\n foreach (FileInfo fi in fis) \n { \n Size += fi.Length; \n }\n // Add subdirectory sizes.\n DirectoryInfo[] dis = d.GetDirectories();\n foreach (DirectoryInfo di in dis) \n {\n Size += DirSize(di); \n }\n return(Size); \n}\n</code></pre>\n\n<p>As seen at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.directory.aspx</a></p>\n" }, { "answer_id": 137394, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 3, "selected": true, "text": "<p>I think that you already know the answer; you will need to add up all of the files in the directory (as well as its child directories.) I don't know of any built in function for this, but hey, I don't know everything (not even close).</p>\n" }, { "answer_id": 137424, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 0, "selected": false, "text": "<p>Mads Kristensen <a href=\"http://madskristensen.net/post/Calculate-the-total-size-of-a-directory-in-C.aspx\" rel=\"nofollow noreferrer\">posted</a> about this a while back...</p>\n\n<pre><code>private double size = 0;\n\nprivate double GetDirectorySize(string directory)\n{\n foreach (string dir in Directory.GetDirectories(directory))\n {\n GetDirectorySize(dir);\n }\n\n foreach (FileInfo file in new DirectoryInfo(directory).GetFiles())\n {\n size += file.Length;\n }\n\n return size;\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library: ``` Set fso = CreateObject("Scripting.FileSystemObject") Set folderObject = fso.GetFolder(folder) size = folderObject.Size ``` There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes. To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes? Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.
I think that you already know the answer; you will need to add up all of the files in the directory (as well as its child directories.) I don't know of any built in function for this, but hey, I don't know everything (not even close).
137,392
<p>I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/" rel="nofollow noreferrer">password composer</a> which lets you generate passwords base on the <strong>hostname</strong> and a secret <strong>master password</strong>. But I don't want to use a website or installing software to generate my passwords.</p> <p>So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the <a href="http://en.wikipedia.org/wiki/Solitaire_(cipher)" rel="nofollow noreferrer">solitare cipher</a> without the need for cards.</p> <p>Using a PW store is not an option.</p>
[ { "answer_id": 137421, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Why don't you just use the exact same algorithm as the password composer?</p>\n\n<ul>\n<li>Pick a master password</li>\n<li>Take the application/machine name for which you want a password</li>\n<li>Concatenate the two (or shuffle)</li>\n<li>Apply a code you can do in your head, like <a href=\"http://en.wikipedia.org/wiki/Caesar%27s_cipher\" rel=\"nofollow noreferrer\">Caesar's cipher</a></li>\n<li>Take the first X characters (15 is usually a good length for secure passwords)</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>Master Password: kaboom\nMachine Name: hal9000\nShuffle: khaablo9o0m00\nTransposition table: shift 5 left\nabcdefghijklmnopqrstuvwxyz 1234567890\nvwxyzabcdefghijklmnopqrstu 6789012345 \n\nResult: fcvvwgj4j5h55\n</code></pre>\n\n<p>You could use as complex a substitution as your head can do reliably (with or without a paper). You could also use a different table for each password (say, deduce the table from the first letter of each machine name). As long as your master password is secure, there's nothing to fear about the simplicity of the algorithm.</p>\n" }, { "answer_id": 137432, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>Something I used to do (before I started using <em>pwgen</em> to generate my passwords) was to find a nearby paper document and use the first and last character of each line. So long as you know which document goes with which account, regenerating the password is easy if you lose/forget it and no computer is required to do so. (It is important to use a book or other paper document for this, of course, as anything electronic could change and then you'd be lost.)</p>\n" }, { "answer_id": 137457, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>First pick a person (celebrity, relative, fictional character or whatever). This person's identity is your private key, which you should keep secret.</p>\n\n<p>To generate a password for a site, juxtapose the person with the sitename and think about the two for a while. Whatever mental image you get, sum it up with a memorable phrase and take a moment to fix the image and the phrase in your mind. The phrase is your password for this site.</p>\n\n<p>(edit) The rationale for this method is that any maths-based system would be either insecure, or too complicated to do in your head.</p>\n" }, { "answer_id": 137658, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 0, "selected": false, "text": "<p>Alternate characters of the hostname with characters from your master password until you run out of master password characters.</p>\n\n<p>hostname: stackoverflow.com\nmaster password: homer</p>\n\n<p>new password: shtoamcekro</p>\n\n<p>I can almost do that in my head. No need for paper or pencil.</p>\n\n<p>Don't use this system for anything super important. But for your half dozen email, facebook and other random accounts it should be fine.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ]
I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool [password composer](http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/) which lets you generate passwords base on the **hostname** and a secret **master password**. But I don't want to use a website or installing software to generate my passwords. So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the [solitare cipher](http://en.wikipedia.org/wiki/Solitaire_(cipher)) without the need for cards. Using a PW store is not an option.
Why don't you just use the exact same algorithm as the password composer? * Pick a master password * Take the application/machine name for which you want a password * Concatenate the two (or shuffle) * Apply a code you can do in your head, like [Caesar's cipher](http://en.wikipedia.org/wiki/Caesar%27s_cipher) * Take the first X characters (15 is usually a good length for secure passwords) Example: ``` Master Password: kaboom Machine Name: hal9000 Shuffle: khaablo9o0m00 Transposition table: shift 5 left abcdefghijklmnopqrstuvwxyz 1234567890 vwxyzabcdefghijklmnopqrstu 6789012345 Result: fcvvwgj4j5h55 ``` You could use as complex a substitution as your head can do reliably (with or without a paper). You could also use a different table for each password (say, deduce the table from the first letter of each machine name). As long as your master password is secure, there's nothing to fear about the simplicity of the algorithm.
137,398
<p>I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:</p> <pre><code>SELECT Column1, Column2, Column3+Column4 AS [Added Values] FROM Table </code></pre> <p>where Column3 or Column4 may be null. In this case, I want null to be considered zero (so <code>4 + null = 4, null + null = 0</code>).</p> <p>Any suggestions as to how to accomplish this?</p>
[ { "answer_id": 137410, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 5, "selected": true, "text": "<p>Since ISNULL in Access is a boolean function (one parameter), use it like this:</p>\n\n<pre><code>SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]\nFROM Table\n</code></pre>\n" }, { "answer_id": 137413, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": false, "text": "<p>Use the <strong>ISNULL</strong> replacement command: </p>\n\n<pre><code> SELECT Column1, Column2, ISNULL(Column3, 0) + ISNULL(Column4, 0) AS [Added Values]FROM Table\n</code></pre>\n" }, { "answer_id": 139117, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": -1, "selected": false, "text": "<p>Use COALESCE.</p>\n\n<pre><code>SELECT \n Column1, \n Column2, \n COALESCE(Column3, 0) + COALESCE(Column4, 0) AS [Added Values]\nFROM Table\n</code></pre>\n" }, { "answer_id": 140546, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 2, "selected": false, "text": "<p>Even cleaner would be the nz function</p>\n\n<pre><code>nz (column3, 0)\n</code></pre>\n" }, { "answer_id": 143092, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 1, "selected": false, "text": "<p>The Nz() function from VBA can be used in your MS Access query.</p>\n\n<p>This function substitute a NULL for the value in the given parameter.</p>\n\n<pre><code>SELECT Column1, Column2, Nz(Column3, 0) + Nz(Column4, 0) AS [Added Values]\nFROM Table\n</code></pre>\n" }, { "answer_id": 5461079, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://allenbrowne.com/QueryPerfIssue.html\" rel=\"nofollow noreferrer\">Allen Browne</a>, the fastest way is to use <code>IIF(Column3 is Null; 0; Column3)</code> because both <code>NZ()</code> and <code>ISNULL()</code> are VBA functions and calling VBA functions slows down the JET queries. </p>\n\n<p>I would also add that if you work with linked SQL Server or Oracle tables, the IIF syntax also the query to be executed on the server, which is not the case if you use VBA functions.</p>\n" }, { "answer_id": 26615292, "author": "Steve C.", "author_id": 4191103, "author_profile": "https://Stackoverflow.com/users/4191103", "pm_score": 1, "selected": false, "text": "<p>In your table definition, set the default for Column3 and Column4 to zero, therefore when a record is added with no value in those columns the column value will be zero. You would therefore never have to worry about null values in queries.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14902/" ]
I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance: ``` SELECT Column1, Column2, Column3+Column4 AS [Added Values] FROM Table ``` where Column3 or Column4 may be null. In this case, I want null to be considered zero (so `4 + null = 4, null + null = 0`). Any suggestions as to how to accomplish this?
Since ISNULL in Access is a boolean function (one parameter), use it like this: ``` SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values] FROM Table ```
137,399
<p>Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed.</p> <p>I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it.</p> <p>Just wondering what people's views on this are?</p>
[ { "answer_id": 137409, "author": "chessguy", "author_id": 1908025, "author_profile": "https://Stackoverflow.com/users/1908025", "pm_score": 2, "selected": false, "text": "<p>In some sense, you are making an implicit assertion - that the code doesn't throw an exception. Of course it would be more valuable to actually grab the file and find the appropriate line, but I suppose something's better than nothing.</p>\n" }, { "answer_id": 137412, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>In general, I see this occuring in integration testing, just the fact that something succeeded to completion is good enough. In this case Im cool with that.</p>\n\n<p>I guess if I saw it over and over again in <em>unit tests</em> I would be curious as to how useful the tests really were.</p>\n\n<p>EDIT: In the example given by the OP, there is some testable outcome (logfile result), so assuming that if no error was thrown that it worked is lazy.</p>\n" }, { "answer_id": 137418, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 5, "selected": false, "text": "<p>It's simply a very minimal test, and should be documented as such. It only verifies that it doesn't explode when run. The worst part about tests like this is that they present a false sense of security. Your code coverage will go up, but it's illusory. Very bad odor.</p>\n" }, { "answer_id": 137429, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>It can be a good pragmatic solution, especially if the alternative is no test at all.</p>\n\n<p>The problem is that the test would pass if all the functions called were no-ops. But sometimes it just isn't feasible to verify the side effects are what you expected. In the ideal world there would be enough time to write the checks for every test ... but I don't live there.</p>\n\n<p>The other place I've used this pattern is for embedding some performance tests in with unit tests because that was an easy way to get them run every build. The tests don't assert anything, but measure how long the test took and log that.</p>\n" }, { "answer_id": 137430, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>I have to admit that I have never written a unit test that verified I was logging correctly. But I did think about it and came across this <a href=\"http://www.mail-archive.com/[email protected]/msg08646.html\" rel=\"nofollow noreferrer\">discussion</a> of how it could be done with JUnit and Log4J. Its not too pretty but it looks like it would work.</p>\n" }, { "answer_id": 137438, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": true, "text": "<p>This would be the official way to do it:</p>\n\n<pre><code>// Act\nException ex = Record.Exception(() =&gt; someCode());\n\n// Assert\nAssert.Null(ex);\n</code></pre>\n" }, { "answer_id": 137441, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 3, "selected": false, "text": "<p>Such a test smells. It should check that the file was written to, at least that the modified time was updated perhaps.</p>\n\n<p>I've seen quite a few tests written this way that ended up not testing anything at all i.e. the code didn't work, but it didn't blow up either. </p>\n\n<p>If you have some explicit requirement that the code under test doesn't throw an exception and you want to explicitly call out this fact (tests as requirements docs) then I would do something like this:</p>\n\n<pre><code>try\n{\n unitUnderTest.DoWork()\n}\ncatch\n{\n Assert.Fail(\"code should never throw exceptions but failed with ...\")\n}\n</code></pre>\n\n<p>... but this still smells a bit to me, probably because it's trying to prove a negative.</p>\n" }, { "answer_id": 137462, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>Tests should always assert something, otherwise what are you proving and how can you consistently reproduce evidence that your code works? </p>\n" }, { "answer_id": 137470, "author": "codeLes", "author_id": 3030, "author_profile": "https://Stackoverflow.com/users/3030", "pm_score": 1, "selected": false, "text": "<p>We do this all the time. We mock our dependencies using JMock, so I guess in a sense the JMock framework is doing the assertion for us... but it goes something like this. We have a controller that we want to test:</p>\n\n<pre><code>Class Controller {\n private Validator validator;\n\n public void control(){\n validator.validate;\n }\n\n public setValidator(Validator validator){ this.validator = validator; }\n}\n</code></pre>\n\n<p>Now, when we test Controller we dont' want to test Validator because it has it's own tests. so we have a test with JMock just to make sure we call validate:</p>\n\n<pre><code>public void testControlShouldCallValidate(){\n mockValidator.expects(once()).method(\"validate\");\n controller.control;\n}\n</code></pre>\n\n<p>And that's all, there is no \"assertion\" to see but when you call control and the \"validate\" method is not called then the JMock framework throws you an exception (something like \"expected method not invoked\" or something).</p>\n\n<p>We have those all over the place. It's a little backwards since you basically setup your assertion THEN make the call to the tested method.</p>\n" }, { "answer_id": 137584, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 1, "selected": false, "text": "<p>I've seen something like this before and I think this was done just to prop up code coverage numbers. It's probably not really testing code behaviour. In any case, I agree that it (the intention) should be documented in the test for clarity.</p>\n" }, { "answer_id": 137588, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>These are known as <strong>smoke tests</strong> and are common. They're basic sanity checks. But they shouldn't be the only kinds of tests you have. You'd still need some kind of verification in another test. </p>\n" }, { "answer_id": 137606, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 4, "selected": false, "text": "<p>If there is no assertion, it isn't a test.</p>\n\n<p>Quit being lazy -- it may take a little time to figure out how to get the assertion in there, but well worth it to know that it did what you expected it to do.</p>\n" }, { "answer_id": 156594, "author": "Lee", "author_id": 13943, "author_profile": "https://Stackoverflow.com/users/13943", "pm_score": 1, "selected": false, "text": "<p>I sometimes use my unit testing framework of choice (NUnit) to build methods that act as entry points into specific parts of my code. These methods are useful for profiling performance, memory consumption and resource consumption of a subset of the code.</p>\n\n<p>These methods are definitely not unit tests (even though they're marked with the <em>[Test]</em> attribute) and are always flagged to be ignored and explicitly documented when they're checked into source control.</p>\n\n<p>I also occasionally use these methods as entry points for the Visual Studio debugger. I use Resharper to step directly into the test and then into the code that I want to debug. These methods either don't make it as far as source control, or they acquire their very own asserts.</p>\n\n<p>My \"real\" unit tests are built during normal TDD cycles, and they always assert something, although not always directly - sometimes the assertions are part of the mocking framework, and sometimes I'm able to refactor similar assertions into a single method. The names of those refactored methods always start with the prefix \"Assert\" to make it obvious to me.</p>\n" }, { "answer_id": 1070862, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 1, "selected": false, "text": "<p>The name of the test should document this.</p>\n\n<pre><code>void TestLogDoesNotThrowException(void) {\n log(\"blah blah\");\n}\n</code></pre>\n\n<p>How does the test verify if the log is written without assertion ?</p>\n" }, { "answer_id": 69107709, "author": "Carl G", "author_id": 39396, "author_profile": "https://Stackoverflow.com/users/39396", "pm_score": 0, "selected": false, "text": "<p>I would say that a test with no assertions indicates one of two things:</p>\n<ol>\n<li>a test that isn't testing the code's important behavior, or</li>\n<li>code without any important behaviors, that might be removed.</li>\n</ol>\n<h1>Thing 1</h1>\n<p>Most of the comments in this thread are about thing 1, and I would agree that if code under test has any important behavior, then it should be possible to write tests that make assertions about that behavior, either by</p>\n<ol>\n<li>asserting on a function/method return value,</li>\n<li>asserting on calls to 'test double' dependencies, or</li>\n<li>asserting on changes to visible state.</li>\n</ol>\n<p>If the code under test has important behavior, but there aren't assertions on the correctness of that behavior, then the test is deficient.</p>\n<p>Your question appears to belong in this category. The code under test is supposed to log when a condition is met. So there are at least two tests:</p>\n<ul>\n<li>Given that the condition is met, when we call the method, then does the logging occur?</li>\n<li>Given that the condition is not met, when we call the method, then does the logging not occur?</li>\n</ul>\n<p>The test would need a way to arrange the state of the code so that the condition was or was not met, and it would need a way to confirm that the logging either did or did not occur, probably with some logging 'test double' that just recorded the logging calls (people often use mocking frameworks for this.)</p>\n<h1>Thing 2</h1>\n<p>So how about those other tests, that lack assertions, but it's because the code under test doesn't do anything important? I would say that a judgment call is required. In large code bases with high code velocity (many commits per day) and with many simultaneous contributors, it is necessary to deliver code incrementally in small commits. This is so that:</p>\n<ol>\n<li>your code reviewers are not overwhelmed by large complicated commits</li>\n<li>you avoid merge conflicts</li>\n<li>it is easy to revert your commit if it causes a fault.</li>\n</ol>\n<p>In these situations, I have added 'placeholder' classes, which don't do anything interesting, but which provide the structure for the implementation that will follow. Adding this class now, and even using it from other classes, can help show reviewers how the pieces will fit together even if the important behavior of the new class is not yet implemented.</p>\n<p>So, if we assume that such placeholders are appropriate to add, should we test them? It depends. At the least, you will want to confirm that the class is syntactically valid, and perhaps that none of its incidental behaviors cause uncaught exceptions.</p>\n<p>For examples:</p>\n<ul>\n<li>Python is an interpreted language, and so your continuous build may not have a way to confirm that your placeholder class is syntactically valid unless it executes the code as part of a test.</li>\n<li>Your placeholder may have incidental behavior, such as logging statements. These behaviors are not important enough to assert on because they are not an essential part of the class's behavior, but they are potential sources of exceptions. Most test frameworks treat uncaught exceptions as errors, and so by executing this code in a test, you are confirming that the incidental behavior does not cause uncaught exceptions.</li>\n</ul>\n<p>Personally I believe that this reasoning supports the temporary inclusion of assertion-free tests in a code base. That said, the situation should be temporary, and the placeholder class should soon receive a more complete implementation, or it should be removed.</p>\n<p>As a final note, I don't think it's a good idea to include asserts on incidental behavior just to satisfy a formalism that 'all tests must have assertions'. You or another author may forget to remove these formalistic assertions, and then they will clutter the tests with assertions of non-essential behavior, distracting focus from the important assertions. Many of us are probably familiar with the situation where you come upon a test, and you see something that looks like it doesn't belong, and we say, &quot;I'd really like to remove this...but it makes no sense why it's there. So it might be there for some potentially obscure and important reason that the original author forgot to document. I should probably just leave it so that I 1) respect the intentions of the original author, and 2) don't end up breaking anything and making my life more difficult.&quot; (See <a href=\"https://fs.blog/2020/03/chestertons-fence/\" rel=\"nofollow noreferrer\">Chesterton's fence</a>.)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
Occasionally I come accross a unit test that doesn't Assert anything. The particular example I came across this morning was testing that a log file got written to when a condition was met. The assumption was that if no error was thrown the test passed. I personally don't have a problem with this, however it seems to be a bit of a "code smell" to write a unit test that doesn't have any assertions associated with it. Just wondering what people's views on this are?
This would be the official way to do it: ``` // Act Exception ex = Record.Exception(() => someCode()); // Assert Assert.Null(ex); ```
137,400
<p>Looking at the processmodel element in the Web.Config there are two attributes.</p> <pre><code>maxWorkerThreads="25" maxIoThreads="25" </code></pre> <p>What is the difference between worker threads and I/O threads?</p>
[ { "answer_id": 137431, "author": "chadmyers", "author_id": 10862, "author_profile": "https://Stackoverflow.com/users/10862", "pm_score": 6, "selected": true, "text": "<p>Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data.</p>\n\n<p>I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for \"long\" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput.</p>\n\n<p>Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of \"Thread\". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used.</p>\n\n<p>Worker threads are threads upon which regular \"work\" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput.</p>\n\n<p>[Edit]: I also found this link which is particularly relevant to this question:\n<a href=\"http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx</a></p>\n" }, { "answer_id": 137535, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": false, "text": "<p>Just to add on to chadmyers...\nSeems like I/O Threads was the old way ASP.NET serviced requests, </p>\n\n<blockquote>\n <p>\"Requests in IIS 5.0 are typically\n serviced over I/O threads, or threads\n performing asynchronous I/O because\n requests are dispatched to the worker\n process using asynchronous writes to a\n named pipe.\"</p>\n</blockquote>\n\n<p>with IIS6.0 this has changed.</p>\n\n<blockquote>\n <p>\"Thus all requests are now serviced by\n worker threads drawn from the CLR\n thread pool and never on I/O threads.\"</p>\n</blockquote>\n\n<p>Source: <a href=\"http://msdn.microsoft.com/hi-in/magazine/cc164128(en-us).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/hi-in/magazine/cc164128(en-us).aspx</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19490/" ]
Looking at the processmodel element in the Web.Config there are two attributes. ``` maxWorkerThreads="25" maxIoThreads="25" ``` What is the difference between worker threads and I/O threads?
Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data. I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds). They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel. A single I/O thread may be managing multiple completion ports to maintain throughput. Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread". ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used. Worker threads are threads upon which regular "work" or just plain code/processing happens. Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput. [Edit]: I also found this link which is particularly relevant to this question: <http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx>
137,448
<p>Take the following snippet:</p> <pre><code>List&lt;int&gt; distances = new List&lt;int&gt;(); </code></pre> <p>Was the redundancy intended by the language designers? If so, why?</p>
[ { "answer_id": 137455, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 4, "selected": false, "text": "<p>You could always say: <br></p>\n\n<pre><code> var distances = new List&lt;int&gt;();\n</code></pre>\n" }, { "answer_id": 137456, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": -1, "selected": false, "text": "<p>Because we're addicted to compilers and compiler errors.</p>\n" }, { "answer_id": 137458, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>C# is definitely getting less verbose after the addition of functional support.</p>\n" }, { "answer_id": 137459, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "<p>A historical artifact of static typing / C syntax; compare the Ruby example:</p>\n\n<pre><code>distances = []\n</code></pre>\n" }, { "answer_id": 137475, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>What's redudant about this?</p>\n\n<pre><code>List&lt;int&gt; listOfInts = new List&lt;int&gt;():\n</code></pre>\n\n<p>Translated to English: (EDIT, cleaned up a little for clarification)</p>\n\n<ul>\n<li>Create a pointer of type List&lt;int&gt; and name it listofInts. </li>\n<li>listOfInts is now created but its just a reference pointer pointing to nowhere (null)</li>\n<li>Now, create an object of type List&lt;int&gt; on the heap, and return the pointer to listOfInts.</li>\n<li>Now listOfInts points to a List&lt;int&gt; on the heap.</li>\n</ul>\n\n<p>Not really verbose when you think about what it does.</p>\n\n<p>Of course there is an alternative:</p>\n\n<pre><code>var listOfInts = new List&lt;int&gt;();\n</code></pre>\n\n<p>Here we are using C#'s type inference, because you are assigning to it immediately, C# can figure out what type you want to create by the object just created in the heap.</p>\n\n<p>To fully understand how the CLR handles types, I recommend reading <a href=\"http://www.microsoft.com/MSPress/books/6522.aspx\" rel=\"noreferrer\">CLR Via C#</a>.</p>\n" }, { "answer_id": 137476, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 2, "selected": false, "text": "<p>The compiler improvements for C# 3.0 (which corresponds with .Net 3.5) eliminate some of this sort of thing. So your code can now be written as:</p>\n\n<pre><code>var distances = new List&lt;int&gt;();\n</code></pre>\n\n<p>The updated compiler is much better at figuring out types based on additional information in the statement. That means that there are fewer instances where you need to specify a type either for an assignment, or as part of a Generic.</p>\n\n<p>That being said, there are still some areas which could be improved. Some of that is API and some is simply due to the restrictions of strong typing.</p>\n" }, { "answer_id": 137492, "author": "Tom Kidd", "author_id": 2577, "author_profile": "https://Stackoverflow.com/users/2577", "pm_score": 0, "selected": false, "text": "<p>Your particular example is indeed a bit verbose but in most ways C# is rather lean.</p>\n\n<p>I'd much prefer this (C#)</p>\n\n<pre><code>int i;\n</code></pre>\n\n<p>to this (VB.NET)</p>\n\n<pre><code>Dim i as Integer\n</code></pre>\n\n<p>Now, the particular example you chose is something about .NET in general which is a bit on the long side, but I don't think that's C#'s fault. Maybe the question should be rephrased \"Why is .NET code so verbose?\"</p>\n" }, { "answer_id": 137514, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 2, "selected": false, "text": "<p>Because declaring a type doesn't necessarily have anything to do with initializing it.</p>\n\n<p>I can declare </p>\n\n<pre><code>List&lt;int&gt; foo; \n</code></pre>\n\n<p>and leave it to be initialized later. Where's the redundancy then? Maybe it receives the value from another function like BuildList().</p>\n\n<p>As others have mentioned the new var keyword lets you get around that, but you <em>have</em> to initialize the variable at declaration so that the compiler can tell what type it is. </p>\n" }, { "answer_id": 137537, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 7, "selected": true, "text": "<p>The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:</p>\n\n<ol>\n<li>A variable named distances of type <code>List&lt;int&gt;</code>. </li>\n<li>An object on the heap of type <code>List&lt;int&gt;</code>.</li>\n</ol>\n\n<p>Consider the following:</p>\n\n<pre><code>Person[] coworkers = new Employee[20];\n</code></pre>\n\n<p>Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).</p>\n" }, { "answer_id": 137543, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>instead of thinking of it as redundant, think of that construct as a feature to allow you to save a line.</p>\n\n<p>instead of having</p>\n\n<p>List distances;\ndistances = new List();</p>\n\n<p>c# lets you put them on one line.</p>\n\n<p>One line says \"I will be using a variable called <em>distances</em>, and it will be of type List.\" Another line says \"Allocate a new List and call the parameterless constructor\".</p>\n\n<p>Is that too redundant? Perhaps. doing it this way gives you some things, though</p>\n\n<p><strong>1</strong>. Separates out the variable declaration from object allocation. Allowing:</p>\n\n<pre><code>IEnumerable&lt;int&gt; distances = new List&lt;int&gt;();\n// or more likely...\nIEnumerable&lt;int&gt; distances = GetList();\n</code></pre>\n\n<p><strong>2.</strong> It allows for more strong static type checking by the compiler - giving compiler errors when your declarations don't match the assignments, rather than runtime errors.</p>\n\n<p>Are both of these required for writing software? No. There are plenty of languages that don't do this, and/or differ on many other points. </p>\n\n<p><em>\"Doctor! it hurts when I do this!\" - \"Don't do that anymore\"</em></p>\n\n<p>If you find that you don't need or want the things that c# gives you, try other languages. Even if you don't use them, knowing other ones can give you a huge boost in how you approach problems. If you do use one, great!</p>\n\n<p>Either way, you may find enough perspective to allow yourself to say \"I don't need the strict static type checking enforced by the c# compiler. I'll use python\", rather than flaming c# as too redundant.</p>\n" }, { "answer_id": 137545, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>The redunancy wasn't intended, per se, but was a side-effect of the fact that all variables and fields needed to have a type declaration. When you take into account that all object instantiations also mention the type's name in a <em>new</em> expression, you get redundant looking statements.</p>\n\n<p>Now with type-inferencing using the <strong>var</strong> keyword, that redundancy can be eliminated. The compiler is smart enough to figure it out. The next C++ also has an <strong>auto</strong> keyword that does the same thing.</p>\n\n<p>The main reason they introduced <strong>var</strong>, though, was for anonymous types, which have no name:</p>\n\n<pre><code>var x = new {Foo = Bar, Number = 1};\n</code></pre>\n" }, { "answer_id": 139067, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>As others have said: <code>var</code> removes the redundancy, but it has <em>potential</em> negative maintenance consequences. I'd say it also has potential <em>positive</em> maintenance consequences.</p>\n\n<p>Fortunately Eric Lippert writes about it a lot more eloquently than I do:\n<a href=\"http://csharpindepth.com/ViewNote.aspx?NoteID=63\" rel=\"noreferrer\">http://csharpindepth.com/ViewNote.aspx?NoteID=63</a>\n<a href=\"http://csharpindepth.com/ViewNote.aspx?NoteID=61\" rel=\"noreferrer\">http://csharpindepth.com/ViewNote.aspx?NoteID=61</a></p>\n" }, { "answer_id": 147200, "author": "trampster", "author_id": 78561, "author_profile": "https://Stackoverflow.com/users/78561", "pm_score": 1, "selected": false, "text": "<p>Use var if it is obvious what the type is to the reader.</p>\n\n<pre><code>//Use var here\nvar names = new List&lt;string&gt;();\n\n//but not here\nList&lt;string&gt; names = GetNames();\n</code></pre>\n\n<p>From microsofts <a href=\"http://msdn.microsoft.com/en-us/library/bb384061.aspx\" rel=\"nofollow noreferrer\">C# programing guide</a></p>\n\n<blockquote>\n <p>The var keyword can also be useful\n when the specific type of the variable\n is tedious to type on the keyboard, or\n is obvious, or does not add to the\n readability of the code</p>\n</blockquote>\n" }, { "answer_id": 421926, "author": "Joan Venge", "author_id": 51816, "author_profile": "https://Stackoverflow.com/users/51816", "pm_score": 2, "selected": false, "text": "<p>Could also do:</p>\n\n<pre><code>var distances = new List&lt;int&gt;();\n</code></pre>\n" }, { "answer_id": 423619, "author": "Oliver Friedrich", "author_id": 44532, "author_profile": "https://Stackoverflow.com/users/44532", "pm_score": 0, "selected": false, "text": "<p>I see one other problem with the using of var for laziness like that</p>\n\n<pre><code>var names = new List&lt;string&gt;();\n</code></pre>\n\n<p>If you use var, the variable named \"names\" is typed as <code>List&lt;string&gt;,</code> but you would eventually only use one of the interfaces inherited by <code>List&lt;T&gt;.</code></p>\n\n<pre><code>IList&lt;string&gt; = new List&lt;string&gt;();\nICollection&lt;string&gt; = new List&lt;string&gt;();\nIEnumerable&lt;string&gt; = new List&lt;string&gt;();\n</code></pre>\n\n<p>You can automatically use everything of that, but can you consider what interface you wanted to use at the time you wrote the code?</p>\n\n<p>The var keyword does not improve readability in this example.</p>\n" }, { "answer_id": 424397, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 2, "selected": false, "text": "<p>It's only \"redundant\" if you are comparing it to dynamically typed languages. It's useful for polymorphism and finding bugs at compile time. Also, it makes code auto-complete/intellisense easier for your IDE (if you use one).</p>\n" }, { "answer_id": 2767703, "author": "Greg Bacon", "author_id": 123109, "author_profile": "https://Stackoverflow.com/users/123109", "pm_score": 0, "selected": false, "text": "<p>In many of the answers to this question, the authors are thinking like compilers or apologists. An important rule of good programming is <strong>Don't repeat yourself!</strong></p>\n\n<p>Avoiding this unnecessary repetition is an <a href=\"http://golang.org/doc/go_lang_faq.html#principles\" rel=\"nofollow noreferrer\">explicit design goal</a> of Go, for example:</p>\n\n<blockquote>\n <p>Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by simple type derivation using the <code>:=</code> declare-and-initialize construct.</p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
Take the following snippet: ``` List<int> distances = new List<int>(); ``` Was the redundancy intended by the language designers? If so, why?
The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following: 1. A variable named distances of type `List<int>`. 2. An object on the heap of type `List<int>`. Consider the following: ``` Person[] coworkers = new Employee[20]; ``` Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).
137,449
<p>I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.</p> <pre><code>&lt;div class="app_setting"&gt; &lt;label"&gt;Name&lt;/label&gt; &lt;input type="text" name="name"/&gt; &lt;/div&gt; .app_setting:hover { cursor:move; } </code></pre> <p>Any ideas how to get the hover to apply also to the child elements?</p>
[ { "answer_id": 137466, "author": "garrow", "author_id": 21095, "author_profile": "https://Stackoverflow.com/users/21095", "pm_score": 6, "selected": true, "text": "<pre><code>.app_setting *:hover { cursor:move }\n</code></pre>\n" }, { "answer_id": 137496, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 5, "selected": false, "text": "<p>At least 2 ways of doing it: </p>\n\n<ul>\n<li>hover states for each child, either explicitly or with <code>*</code> selector, as suggested by garrow <code>.class *:hover</code></li>\n<li>cascade hover state to children <code>.class:hover *</code></li>\n</ul>\n\n<p>There are probably others</p>\n" }, { "answer_id": 137564, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 1, "selected": false, "text": "<p>You might have to resort to JS to make it happen for IE6.</p>\n" }, { "answer_id": 137603, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 2, "selected": false, "text": "<p>This isn't a css answer, but it might still be useful to you.</p>\n\n<p>Someone else already suggested that you might have to resort to javascript for browser compatibility. If you do resort to javascript, you can use the jquery library to make it easy.</p>\n\n<p><code>$(\".appsetting\").hover(hoverInFunc,hoverOutFunc);</code></p>\n\n<p>This sets an event handler for hovering into and out of the selected element(s) as matched by the css style selector in the <code>$()</code> call.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14971/" ]
I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled. ``` <div class="app_setting"> <label">Name</label> <input type="text" name="name"/> </div> .app_setting:hover { cursor:move; } ``` Any ideas how to get the hover to apply also to the child elements?
``` .app_setting *:hover { cursor:move } ```
137,452
<p>I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries?</p>
[ { "answer_id": 137460, "author": "John Hoven", "author_id": 1907, "author_profile": "https://Stackoverflow.com/users/1907", "pm_score": 0, "selected": false, "text": "<p>You'll have to change the database collation. You'll also need to alter the table and column level collation. I beleive you can find a script out there if you google it.</p>\n" }, { "answer_id": 137480, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 4, "selected": false, "text": "<p>You don't actually need to change the collation on the entire database, if you declare it on the table or columns that need to be case-sensitive. In fact, you can actually append it to individual operations as needed.</p>\n\n<pre>\nSELECT name WHERE 'greg' = name COLLATE Latin1_GENERAL_CS_AS\n</pre>\n\n<p>I know, you said that you want this to apply throughout the database. But I mention this because in certain hosted environments, you can't control this property, which is set when the database is created.</p>\n" }, { "answer_id": 137505, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 4, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>ALTER DATABASE database_name COLLATE collation_name\n</code></pre>\n\n<p>See BOL for a <a href=\"http://msdn.microsoft.com/en-us/library/ms144250(SQL.90).aspx\" rel=\"noreferrer\">list of collation options</a> and pick the case-sensitive one that best fits your needs (i.e. the one your client is using).<br>\nObviously, it's probably a good idea to make a full backup of your database before you try this. I've never personally tried to use a database with a different collation than the server's default collation, so I don't know of any \"gotchas\". But if you have good backups and test it in your environment before deploying it to your client, I can't imagine that there's much risk involved.</p>\n" }, { "answer_id": 289842, "author": "nickd", "author_id": 2373, "author_profile": "https://Stackoverflow.com/users/2373", "pm_score": 1, "selected": false, "text": "<p>If you have a DB that has a different collation to the instance default, you can run into problems when you try and join your tables with temporary ones. Temporary tables have to collation of the instance (because they're system objects) so you need to use the <strong>COLLATE database_default</strong> clause in your joins.</p>\n\n<pre><code>select temp.A, table.B\nfrom #TEMPORARY_TABLE temp inner join table\non temp.X COLLATE database_default = table.Y\n</code></pre>\n\n<p>This forces the collation of temp.X (in this example) to the collation of the current DB.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I hate case sensitivity in databases, but I'm developing for a client who uses it. How can I turn on this option on my SQL Server, so I can be sure I've gotten the case right in all my queries?
How about: ``` ALTER DATABASE database_name COLLATE collation_name ``` See BOL for a [list of collation options](http://msdn.microsoft.com/en-us/library/ms144250(SQL.90).aspx) and pick the case-sensitive one that best fits your needs (i.e. the one your client is using). Obviously, it's probably a good idea to make a full backup of your database before you try this. I've never personally tried to use a database with a different collation than the server's default collation, so I don't know of any "gotchas". But if you have good backups and test it in your environment before deploying it to your client, I can't imagine that there's much risk involved.
137,487
<p>I am told that good developers can spot/utilize the difference between <code>Null</code> and <code>False</code> and <code>0</code> and all the other good "nothing" entities.<br> What <em>is</em> the difference, specifically in PHP? Does it have something to do with <code>===</code>?</p>
[ { "answer_id": 137500, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely, <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">wrong code should look wrong</a>).</p>\n" }, { "answer_id": 137503, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 0, "selected": false, "text": "<p>Null is nothing, False is a bit, and 0 is (probably) 32 bits.</p>\n\n<p>Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially.</p>\n" }, { "answer_id": 137539, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "<p><strong>False, Null, Nothing, 0, Undefined</strong>, etc., etc.</p>\n\n<p>Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value.</p>\n\n<p>In <strong>C</strong> and <strong>C++</strong>, <code>NULL</code>, <code>False</code> and <code>0</code> are overloaded to the same value.\nIn <strong>C#</strong> they're 3 distinct concepts.</p>\n\n<p><code>null</code> or <code>NULL</code> usually indicates a lack of value, but usually doesn't specify why.\n<code>0</code> indicates the natural number zero and has type-equivalence to <strong>1, 2, 3,</strong> etc. and in languages that support separate concepts of <code>NULL</code> should be treated only a number.</p>\n\n<p><strong>False</strong> indicates non-truth. And it used in <strong>binary values</strong>. It doesn't mean unset, nor does it mean <code>0</code>. It simply indicates one of two binary values.</p>\n\n<p>Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.</p>\n\n<p>Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.</p>\n" }, { "answer_id": 137547, "author": "Peter", "author_id": 22517, "author_profile": "https://Stackoverflow.com/users/22517", "pm_score": 1, "selected": false, "text": "<p>Null is used in databases to represent \"no record\" or \"no information\". So you might have a bit field that describes \"does this user want to be sent e-mails by us\", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike. </p>\n\n<p>The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false.</p>\n\n<p>So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing).</p>\n" }, { "answer_id": 137552, "author": "jasonmray", "author_id": 17230, "author_profile": "https://Stackoverflow.com/users/17230", "pm_score": 0, "selected": false, "text": "<p>Well, I can't remember enough from my PHP days to answer the \"===\" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.</p>\n\n<p>So.. the quick answer is: context.</p>\n" }, { "answer_id": 137553, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 1, "selected": false, "text": "<p>In PHP it depends on if you are validating types:</p>\n\n<pre><code>( \n ( false !== 0 ) &amp;&amp; ( false !== -1 ) &amp;&amp; ( false == 0 ) &amp;&amp; ( false == -1 ) &amp;&amp;\n ( false !== null ) &amp;&amp; ( false == null ) \n)\n</code></pre>\n\n<p>Technically null is <code>0x00</code> but in PHP <code>( null == 0x00 ) &amp;&amp; ( null !== 0x00 )</code>.</p>\n\n<p><code>0</code> is an integer value.</p>\n" }, { "answer_id": 137575, "author": "Chad", "author_id": 17382, "author_profile": "https://Stackoverflow.com/users/17382", "pm_score": 1, "selected": false, "text": "<p>I think bad developers find all different uses of null/0/false in there code.</p>\n\n<p>For example, one of the most common mistakes developers make is to return error code in the form of data with a function.</p>\n\n<pre><code>// On error GetChar returns -1\nint GetChar()\n</code></pre>\n\n<p>This is an example of a sugar interface. This is exsplained in the book \"Debuging the software development proccess\" and also in another book \"writing correct code\". </p>\n\n<p>The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.</p>\n\n<p>Instead, the best way is not to mix error code with your data. So the following function.</p>\n\n<pre><code>char GetChar()\n</code></pre>\n\n<p>now becomes</p>\n\n<pre><code>// On success return 1\n// on failure return 0\nbool GetChar(int &amp;char)\n</code></pre>\n\n<p>This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.</p>\n\n<p>So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.</p>\n" }, { "answer_id": 137577, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>In pretty much all modern languages, null <em>logically</em> refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.</p>\n\n<p>Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.</p>\n\n<p>Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.</p>\n" }, { "answer_id": 137701, "author": "Javier Constanzo", "author_id": 21996, "author_profile": "https://Stackoverflow.com/users/21996", "pm_score": 2, "selected": false, "text": "<p>From the <a href=\"http://ar2.php.net/manual/en/language.types.boolean.php\" rel=\"nofollow noreferrer\">PHP online documentation</a>:</p>\n\n<blockquote>\n <p>To explicitly convert a value to boolean, use the (bool) or (boolean) casts.<br>\n However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.<br>\n When converting to boolean, the following values are considered FALSE: </p>\n</blockquote>\n\n<ul>\n<li>the boolean <code>FALSE</code> itself </li>\n<li>the integer ``0 (zero) </li>\n<li>the float <code>0.0</code> (zero) </li>\n<li>the empty string, and the string <code>\"0\"</code> </li>\n<li>an array with zero elements </li>\n<li>an object with zero member variables (PHP 4 only) </li>\n<li>the special type <code>NULL</code> (including unset variables) </li>\n<li>SimpleXML objects created from empty tags<br>\nEvery other value is considered <code>TRUE</code> (including any resource). </li>\n</ul>\n\n<p>So, in most cases, it's the same. </p>\n\n<p>On the other hand, the <code>===</code> and the <code>==</code>are not the same thing. Regularly, you just need the \"equals\" operator. To clarify: </p>\n\n<pre><code>$a == $b //Equal. TRUE if $a is equal to $b.\n$a === $b //Identical. TRUE if $a is equal to $b, and they are of the same type. \n</code></pre>\n\n<p>For more information, check the \"<a href=\"http://ar2.php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">Comparison Operators</a>\" page in the PHP online docs. </p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 137715, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<p>One interesting fact about <code>NULL</code> in PHP: If you set a var equal to <code>NULL</code>, it is the same as if you had called <code>unset()</code> on it.</p>\n\n<p><code>NULL</code> essentially means a variable has no value assigned to it; <code>false</code> is a valid Boolean value, <code>0</code> is a valid integer value, and PHP has some fairly ugly conversions between <code>0</code>, <code>\"0\"</code>, <code>\"\"</code>, and <code>false</code>.</p>\n" }, { "answer_id": 137776, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 0, "selected": false, "text": "<p>False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.</p>\n\n<p>In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:</p>\n\n<pre><code>x + 0 = x\n</code></pre>\n\n<p>Similarly, False is a value such that a disjunction of it and any other value is that same value:</p>\n\n<pre><code>x || False = x\n</code></pre>\n\n<p>Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an \"initial value\" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called \"bottom\" rather than \"null\", which is a placeholder for the value of a computation that does not terminate.</p>\n\n<p><a href=\"http://apocalisp.wordpress.com/2008/05/03/null-vs-pure-reason/\" rel=\"nofollow noreferrer\">I've written more extensively about the implications of NULL elsewhere.</a></p>\n" }, { "answer_id": 138020, "author": "inkredibl", "author_id": 22129, "author_profile": "https://Stackoverflow.com/users/22129", "pm_score": 3, "selected": false, "text": "<p>In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: <code>0 == false</code> is <code>true</code>, but <code>0 === false</code> is <code>false</code>. The same goes for <code>!=</code> versus <code>!==</code>. Also in case you compare <code>null</code> to the other two using the mentioned operators, expect similar results.</p>\n\n<p>Now in PHP this quality of values is usually used when returning a value which sometimes can be <code>0</code> (zero), but sometimes it might be that the function failed. In such cases in PHP you return <code>false</code> and you have to check for these cases using the identity operator <code>===</code>. For example if you are searching for a position of one string inside the other and you're using <code>strpos()</code>, this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then <code>strpos()</code> will return <code>false</code> and you have to take this into account when dealing with the result.</p>\n\n<p>If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.</p>\n" }, { "answer_id": 138954, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 9, "selected": true, "text": "<h2>It's language specific, but in PHP :</h2>\n\n<p><strong><code>Null</code></strong> means \"<strong>nothing</strong>\". The var has not been initialized.</p>\n\n<p><strong><code>False</code></strong> means \"<strong>not true in a boolean context</strong>\". Used to explicitly show you are dealing with logical issues.</p>\n\n<p><strong><code>0</code></strong> is an <strong><code>int</code></strong>. Nothing to do with the rest above, used for mathematics.</p>\n\n<p>Now, what is tricky, it's that in dynamic languages like PHP, <em>all of them have a value in a boolean context</em>, which (in PHP) is <code>False</code>.</p>\n\n<p>If you test it with <code>==</code>, it's testing the boolean value, so you will get equality. If you test it with <code>===</code>, it will test the type, and you will get inequality.</p>\n\n<h2>So why are they useful ?</h2>\n\n<p>Well, look at the <code>strrpos()</code> function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !</p>\n\n<pre><code>&lt;?php\n// pitfall :\nif (strrpos(\"Hello World\", \"Hello\")) { \n // never exectuted\n}\n\n// smart move :\nif (strrpos(\"Hello World\", \"Hello\") !== False) {\n // that works !\n}\n?&gt;\n</code></pre>\n\n<p>And of course, if you deal with states:</p>\n\n<p>You want to make a difference between <code>DebugMode = False</code> (set to off), <code>DebugMode = True</code> (set to on) and <code>DebugMode = Null</code> (not set at all, will lead to hard debugging ;-)).</p>\n" }, { "answer_id": 5700831, "author": "gcb", "author_id": 183132, "author_profile": "https://Stackoverflow.com/users/183132", "pm_score": 6, "selected": false, "text": "<p><code>null</code> is <code>null</code>. <code>false</code> is <code>false</code>. Sad but true.</p>\n<p>there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use <code>false</code>/<code>null</code> in not-so-easy to reason ways.</p>\n<p>You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?)</p>\n<p>Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with <code>filter_input()</code> you can check for <code>===false</code> or <code>===null</code> if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for <code>===null</code> if they only remembered to write the test case for <code>===false</code>. And most php unit test/coverage tools will not call your attention for the missing, untested code path!</p>\n<p>Lastly, here's some fun with type juggling. not even including arrays or objects.</p>\n<pre><code>var_dump( 0&lt;0 ); #bool(false)\nvar_dump( 1&lt;0 ); #bool(false)\nvar_dump( -1&lt;0 ); #bool(true)\nvar_dump( false&lt;0 ); #bool(false)\nvar_dump( null&lt;0 ); #bool(false)\nvar_dump( ''&lt;0 ); #bool(false)\nvar_dump( 'a'&lt;0 ); #bool(false)\necho &quot;\\n&quot;;\nvar_dump( !0 ); #bool(true)\nvar_dump( !1 ); #bool(false)\nvar_dump( !-1 ); #bool(false)\nvar_dump( !false ); #bool(true)\nvar_dump( !null ); #bool(true)\nvar_dump( !'' ); #bool(true)\nvar_dump( !'a' ); #bool(false)\necho &quot;\\n&quot;;\nvar_dump( false == 0 ); #bool(true)\nvar_dump( false == 1 ); #bool(false)\nvar_dump( false == -1 ); #bool(false)\nvar_dump( false == false ); #bool(true)\nvar_dump( false == null ); #bool(true)\nvar_dump( false == '' ); #bool(true)\nvar_dump( false == 'a' ); #bool(false)\necho &quot;\\n&quot;;\nvar_dump( null == 0 ); #bool(true)\nvar_dump( null == 1 ); #bool(false)\nvar_dump( null == -1 ); #bool(false)\nvar_dump( null == false ); #bool(true)\nvar_dump( null == null ); #bool(true)\nvar_dump( null == '' ); #bool(true)\nvar_dump( null == 'a' ); #bool(false)\necho &quot;\\n&quot;;\n$a=0; var_dump( empty($a) ); #bool(true)\n$a=1; var_dump( empty($a) ); #bool(false)\n$a=-1; var_dump( empty($a) ); #bool(false)\n$a=false; var_dump( empty($a) ); #bool(true)\n$a=null; var_dump( empty($a) ); #bool(true)\n$a=''; var_dump( empty($a) ); #bool(true)\n$a='a'; var_dump( empty($a)); # bool(false)\necho &quot;\\n&quot;; #new block suggested by @thehpi\nvar_dump( null &lt; -1 ); #bool(true)\nvar_dump( null &lt; 0 ); #bool(false)\nvar_dump( null &lt; 1 ); #bool(true)\nvar_dump( -1 &gt; true ); #bool(false)\nvar_dump( 0 &gt; true ); #bool(false)\nvar_dump( 1 &gt; true ); #bool(true)\nvar_dump( -1 &gt; false ); #bool(true)\nvar_dump( 0 &gt; false ); #bool(false)\nvar_dump( 1 &gt; true ); #bool(true)\n</code></pre>\n" }, { "answer_id": 27606553, "author": "madesignUK", "author_id": 3037182, "author_profile": "https://Stackoverflow.com/users/3037182", "pm_score": 2, "selected": false, "text": "<p>I have just wasted 1/2 a day trying to get either a <code>0</code>, <code>null</code>, <code>false</code> to return from <code>strops</code>!</p>\n\n<p>Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:</p>\n\n<p>Concept\ntake a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.</p>\n\n<p>Anyway here was the basis of the cosing:</p>\n\n<pre><code>if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) \n{ \n do this \n} else {\n or that\n}\n\n{\necho strpos(mydomain.co.uk, mydomain); \n\nif ( strpos(mydomain, xmas) == null ) \n {\n echo \"\\n1 is null\"; \n }\n\nif ( (strpos(mydomain.co.uk, mydomain)) == 0 ) \n {\n echo \"\\n2 is 0\"; \n } else {\n echo \"\\n2 Something is WRONG\"; \n }\n\nif ( (mydomain.co.uk, mydomain)) != 0 ) \n {\n echo \"\\n3 is 0\"; \n } else {\n echo \"\\n3 it is not 0\"; \n }\n\nif ( (mydomain.co.uk, mydomain)) == null ) \n {\n echo \"\\n4 is null\"; \n } else {\n echo \"\\n4 Something is WRONG\"; \n }\n}\n</code></pre>\n\n<p>FINALLY after reading this Topic, \nI found that this worked!!!</p>\n\n<pre><code>{\nif ((mydomain.co.uk, mydomain)) !== false ) \n {\n echo \"\\n5 is True\"; \n } else {\n echo \"\\n5 is False\"; \n }\n}\n</code></pre>\n\n<p>Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as <code>false</code>, as its also can be a <code>NULL</code> day!</p>\n\n<p>After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as <code>False</code>, <code>NULL</code> and <code>0</code> are not all the same as <code>True or False or NULL</code>?</p>\n" }, { "answer_id": 33293119, "author": "kriscondev", "author_id": 5159914, "author_profile": "https://Stackoverflow.com/users/5159914", "pm_score": 5, "selected": false, "text": "<p>Below is an example:</p>\n\n<pre><code> Comparisons of $x with PHP functions\n\nExpression gettype() empty() is_null() isset() boolean : if($x)\n$x = \"\"; string TRUE FALSE TRUE FALSE\n$x = null; NULL TRUE TRUE FALSE FALSE\nvar $x; NULL TRUE TRUE FALSE FALSE\n$x is undefined NULL TRUE TRUE FALSE FALSE\n$x = array(); array TRUE FALSE TRUE FALSE\n$x = false; boolean TRUE FALSE TRUE FALSE\n$x = true; boolean FALSE FALSE TRUE TRUE\n$x = 1; integer FALSE FALSE TRUE TRUE\n$x = 42; integer FALSE FALSE TRUE TRUE\n$x = 0; integer TRUE FALSE TRUE FALSE\n$x = -1; integer FALSE FALSE TRUE TRUE\n$x = \"1\"; string FALSE FALSE TRUE TRUE\n$x = \"0\"; string TRUE FALSE TRUE FALSE\n$x = \"-1\"; string FALSE FALSE TRUE TRUE\n$x = \"php\"; string FALSE FALSE TRUE TRUE\n$x = \"true\"; string FALSE FALSE TRUE TRUE\n$x = \"false\"; string FALSE FALSE TRUE TRUE\n</code></pre>\n\n<p>Please see this for more reference of <a href=\"http://php.net/manual/en/types.comparisons.php\" rel=\"noreferrer\">type comparisons</a> in PHP. It should give you a clear understanding.</p>\n" }, { "answer_id": 53140612, "author": "adrian", "author_id": 10603435, "author_profile": "https://Stackoverflow.com/users/10603435", "pm_score": -1, "selected": false, "text": "<p>The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.</p>\n\n<pre><code>'*' == true -&gt; true (string match)\n'*' === true -&gt; false (numberic match)\n\n(int)'*' == true -&gt; false\n(string)'*' == true -&gt; true\n</code></pre>\n\n<p>PHP7 strictness is a step forward, but maybe not enough. <a href=\"https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/\" rel=\"nofollow noreferrer\">https://web-techno.net/typing-with-php-7-what-you-shouldnt-do/</a></p>\n" }, { "answer_id": 54472049, "author": "vladzur", "author_id": 797716, "author_profile": "https://Stackoverflow.com/users/797716", "pm_score": 0, "selected": false, "text": "<p>Somebody can explain to me why 'NULL' is not just a string in a comparison instance?</p>\n\n<pre><code>$x = 0;\nvar_dump($x == 'NULL'); # TRUE !!!WTF!!!\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
I am told that good developers can spot/utilize the difference between `Null` and `False` and `0` and all the other good "nothing" entities. What *is* the difference, specifically in PHP? Does it have something to do with `===`?
It's language specific, but in PHP : ------------------------------------ **`Null`** means "**nothing**". The var has not been initialized. **`False`** means "**not true in a boolean context**". Used to explicitly show you are dealing with logical issues. **`0`** is an **`int`**. Nothing to do with the rest above, used for mathematics. Now, what is tricky, it's that in dynamic languages like PHP, *all of them have a value in a boolean context*, which (in PHP) is `False`. If you test it with `==`, it's testing the boolean value, so you will get equality. If you test it with `===`, it will test the type, and you will get inequality. So why are they useful ? ------------------------ Well, look at the `strrpos()` function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string ! ``` <?php // pitfall : if (strrpos("Hello World", "Hello")) { // never exectuted } // smart move : if (strrpos("Hello World", "Hello") !== False) { // that works ! } ?> ``` And of course, if you deal with states: You want to make a difference between `DebugMode = False` (set to off), `DebugMode = True` (set to on) and `DebugMode = Null` (not set at all, will lead to hard debugging ;-)).
137,497
<p>In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables?</p>
[ { "answer_id": 137750, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>Get the query text of your view.</p>\n\n<pre><code>SELECT text FROM dba_views\nWHERE owner = 'the-owner' AND view_name = 'the-view-name';\n</code></pre></li>\n<li><p>Parse. Search for view names within the query text.</p></li>\n<li><p>Get the query text for each view name found. (see item 1.)</p></li>\n<li><p>Replace each view name in the query with the related query text.</p></li>\n<li><p>Do this recursively until there are no more views found.</p></li>\n</ol>\n\n<p>Easy?</p>\n\n<p><strong>EDIT:</strong> The above instructions do not do everything required. Thinking about this a little more it gets hairy, grows legs, and maybe another arm. Finding column names, and column names that might be elaborate functions and subqueries. Bringing it all back together with the joins and clauses. The resulting query might look very ugly.</p>\n\n<p>Somewhere within Oracle there may be something that is actually unwrapping a view. I don't know. I am glad I didn't use views that much in Oracle.</p>\n" }, { "answer_id": 138751, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>The concept of <a href=\"http://www.psoug.org/reference/inline_view.html\" rel=\"nofollow noreferrer\">in-line views</a> can be used to do this. Suppose you have these 2 views:</p>\n\n<pre><code>create or replace view london_dept as\nselect * from dept\nwhere loc = 'LONDON';\n</code></pre>\n\n<p>and </p>\n\n<pre><code>create or replace view london_mgr as\nselect * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from london_dept);\n</code></pre>\n\n<p>In the second view's SQL, the reference to view london_dept can be replaced by an in-line view using the SQL from the london_dept view definition as follows:</p>\n\n<pre><code>select * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from (select * from dept\nwhere loc = 'LONDON'));\n</code></pre>\n\n<p>Of course, you can now see that is overly verbose and could be simplified to:</p>\n\n<pre><code>select * from emp \nwhere job='MANAGER'\nand deptno in (select deptno from dept where loc = 'LONDON');\n</code></pre>\n\n<p>Finally, some advice from Tom Kyte on the advantages and disadvantages of creating <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9087996409290\" rel=\"nofollow noreferrer\">views of views</a></p>\n" }, { "answer_id": 41828960, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Up until Oracle 12.1 the correct answer is no, there is no easy way. Now, in 12.1 there is DBMS_UTILITY.EXPAND_SQL_TEXT : Expand SQL References to Views in Oracle Database 12c Release 1 (12.1) does exactly this. See the <a href=\"http://docs.oracle.com/database/121/ARPLS/d_util.htm#ARPLS73973\" rel=\"nofollow noreferrer\">documentation of dbms_utility</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables?
1. Get the query text of your view. ``` SELECT text FROM dba_views WHERE owner = 'the-owner' AND view_name = 'the-view-name'; ``` 2. Parse. Search for view names within the query text. 3. Get the query text for each view name found. (see item 1.) 4. Replace each view name in the query with the related query text. 5. Do this recursively until there are no more views found. Easy? **EDIT:** The above instructions do not do everything required. Thinking about this a little more it gets hairy, grows legs, and maybe another arm. Finding column names, and column names that might be elaborate functions and subqueries. Bringing it all back together with the joins and clauses. The resulting query might look very ugly. Somewhere within Oracle there may be something that is actually unwrapping a view. I don't know. I am glad I didn't use views that much in Oracle.
137,521
<p>My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:</p> <pre><code>invoice.address_id = 1 invoice.address = some_address </code></pre> <p>Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling</p> <pre><code>attr_protected :address_id </code></pre> <p>is most likely not the solution since based on the documentation it only prevents mass assignments.</p> <p>Thanks!</p>
[ { "answer_id": 137538, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 2, "selected": false, "text": "<p>Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable' method)</p>\n\n<pre><code>def address_id=(id)\n if new_record?\n write_attribute(:address_id, id)\n else\n raise 'address is immutable!'\n end\nend \n</code></pre>\n" }, { "answer_id": 137551, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 5, "selected": true, "text": "<p>You want <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001317\" rel=\"noreferrer\"><code>attr_readonly</code></a>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082/" ]
My Invoice model has an address\_id attribute, and I don't want this address\_id to change FOREVER. So I don't want this to happen outside the class: ``` invoice.address_id = 1 invoice.address = some_address ``` Rails automatically adds this address\_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling ``` attr_protected :address_id ``` is most likely not the solution since based on the documentation it only prevents mass assignments. Thanks!
You want [`attr_readonly`](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001317).
137,530
<p>Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as <code>null</code>, even though it's definitely being sent <code>1</code>.</p> <p>The Delphi code uses a TADOQuery to execute the stored procedure (anonymized):</p> <pre><code> ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy"; ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction()); // other parameters all set similarly ADOQuery1.ExecSQL; </code></pre> <p><code>Integer(SomeFunction())</code> currently always returns 1 - I checked with the debugger.</p> <p>However, in my stored proc ( altered for debug purposes ):</p> <pre><code>create procedure MyStoredProcedure ( @Foo int, @Bar int, @Baz int, @Qux int, @Smang int, @Jimmy varchar(20) ) as begin -- temp debug if ( @Foo is null ) begin insert into TempLog values ( "oh crap" ) end -- do the rest of the stuff here.. end </code></pre> <p><code>TempLog</code> does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?).</p> <p>Here's an example trace from profiler:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p3 int set @p3=NULL exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int', @p3 output,1,1,1,0,200 select @p3 </code></pre> <p>This looks a little strange to me. Notice that it's using @p3 <em>and</em> @P3 - could this be causing my issue? </p> <p>The other strange thing is that it seems to depend on which TADOConnection I use. </p> <p>The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection.</p> <p>If instead of using this connection, I first do this:</p> <pre><code>ConnectionNew := TADOQuery.Create(ConnectionOld.Owner); ConnectionNew.ConnectionString := ConnectionOld.ConnectionString; TADOQuery1.Connection := ConnectionNew; </code></pre> <p>Then the issue does not occur! The trace from this situation is this:</p> <pre><code>exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p1 int set @p1=64 exec sp_prepare @p1 output, N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', 1 select @p1 SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF exec sp_unprepare 64 SET NO_BROWSETABLE OFF exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', 1,1,1,3,0,'400.00' </code></pre> <p>Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this?</p> <p>Does anyone have any ideas?</p> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214">Update below</a> (didn't want to make this question any longer :P)</p>
[ { "answer_id": 137694, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>caveat: i don't know delphi, but this issue rings a faint bell and so i'm interested in it</p>\n\n<p>do you get the same result if you use a TADOStoredProc instead of a TADOQuery? <a href=\"http://www.podgoretsky.com/ftp/Docs/Delphi/D5/dg/ado_comp.html\" rel=\"nofollow noreferrer\">see delphi 5 developers guide</a></p>\n\n<p>also, it looks like the first trace does no prepare call and thinks @P1 is an output paramer in the execute, while the second trace does a prepare call with @P1 as an output but does not show @P1 as an output in the execute step - is this significant? it does seem odd, and so may be a clue</p>\n\n<p>you might also try replacing the function call with a constant 1</p>\n\n<p>good luck, and please let us know what you find out!</p>\n" }, { "answer_id": 137899, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 1, "selected": false, "text": "<p>In my programs, I have <strong>lots</strong> of code very similar to your first snippet, and I haven't encountered this problem.</p>\n\n<p>Is that <strong>actually</strong> your code, or is that how you've represented the problem for us to understand? Is the text for the SQL stored in your DFM or populated dynamically? </p>\n\n<p>I was wondering if perhaps somehow the Params property of the query had already got a list of parameters defined/cached, in the IDE, and that might explain why P1 was being seen as output (which is almost certainly causing your NULL problem).</p>\n\n<p>Just before you set the ParamByName.Value, try</p>\n\n<pre>\nParamByName(\"Foo\").ParamType=ptInput;\n</pre>\n\n<p>I'm not sure why you changing the connection string would also fix this, unless it's resetting the internal sense of the parameters for that query.</p>\n\n<p>Under TSQLQuery, the Params property of a query gets reset/recreated whenever the SQL.Text value is changed (I'm not sure if that's true for a TADOQuery mind you), so that first snippet of yours ought to have caused any existing Params information to have been dropped.</p>\n\n<p>If the 'ParamByname.ParamType' suggestion above does fix it for you, then surely there's something happening to the query elsewhere (at create-time? on the form?) that is causing it to think Foo is an output parameter...</p>\n\n<p>does that help at all? :-)</p>\n" }, { "answer_id": 152251, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 0, "selected": false, "text": "<p>I suspect you have some parameters mismatch left over from the previous use of your ADOQuery.</p>\n\n<p>Have you tried to reset your parameters after changing the SQL.Text: </p>\n\n<pre><code> ADOQuery1.Parameters.Refresh;\n</code></pre>\n\n<p>Also you could try to clear the parameters and explicitly recreate them: </p>\n\n<pre><code> ADOQuery1.Parameters.Clear;\n ADOQuery1.Parameters.CreateParameter('Foo', ftInteger, pdInput, 0, 1);\n [...]\n</code></pre>\n\n<p>I think changing the connection actually forces an InternalRefresh of the parameters.</p>\n" }, { "answer_id": 152265, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "<pre><code> ADOQuery1.Parameters.ParamByName(\"Foo\").Value = Integer(someFunction()); \n</code></pre>\n\n<p>Don't they use <code>:=</code> for assignment in Object Pascal?</p>\n" }, { "answer_id": 153324, "author": "Fabricio Araujo", "author_id": 10300, "author_profile": "https://Stackoverflow.com/users/10300", "pm_score": 0, "selected": false, "text": "<p>@Constantin</p>\n\n<p>It must be a typo from the Author of the question.</p>\n\n<p>@Blorgbeard</p>\n\n<p>Hmmm... When you change SQL of a TADOQuery, is good use to \nclear the parameters and recreate then using CreateParameter.\nI would not rely on ParamCheck in runtime - since it leaves \nthe parameters' properties mostly undefined.\nI've had such type of problem when relying on ParamCheck to\nautofill the parameters - is rare but occurs.\nAh, if you go the CreateParameter route, create as first \nparameter the @RETURN_VALUE one, since it'll catch the returned\nvalue of the MSSQL SP.</p>\n" }, { "answer_id": 153364, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<p>The only time I've had a problem like this was when the DB Provider couldn't distinguish between Output (always sets it to null) and InputOutput (uses what you provide) parameters.</p>\n" }, { "answer_id": 177214, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": true, "text": "<p>Ok, progress is made.. sort of.</p>\n\n<p>@Robsoft was correct, setting the parameter direction to <code>pdInput</code> fixed the issue.</p>\n\n<p>I traced into the VCL code, and it came down to <code>TParameters.InternalRefresh.RefreshFromOleDB</code>. This function is being called when I set the SQL.Text. Here's the (abridged) code:</p>\n\n<pre><code>function TParameters.InternalRefresh: Boolean;\n procedure RefreshFromOleDB;\n // ..\n if OLEDBParameters.GetParameterInfo(ParamCount, PDBPARAMINFO(ParamInfo), @NamesBuffer) = S_OK then\n for I := 0 to ParamCount - 1 do\n with ParamInfo[I] do\n begin\n // ..\n Direction := dwFlags and $F; // here's where the wrong value comes from\n // ..\n end;\n // ..\n end;\n // ..\nend;\n</code></pre>\n\n<p>So, <a href=\"http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>OLEDBParameters.GetParameterInfo</code></a> is returning the wrong flags for some reason. </p>\n\n<p>I've verified that with the original connection, <code>(dwFlags and $F)</code> is <code>2</code> (<code>DBPARAMFLAGS_ISOUTPUT</code>), and with the new connection, it's <code>1</code> (<code>DBPARAMFLAGS_ISINPUT</code>).</p>\n\n<p>I'm not really sure I want to dig any deeper than that, for now at least.</p>\n\n<p>Until I have more time and inclination, I'll just make sure all parameters are set to <code>pdInput</code> before I open the query. <br/>Unless anyone has any more bright ideas now..?</p>\n\n<p>Anyway, thanks everyone for your suggestions so far.</p>\n" }, { "answer_id": 53598601, "author": "Volpato", "author_id": 5621923, "author_profile": "https://Stackoverflow.com/users/5621923", "pm_score": 0, "selected": false, "text": "<p>I was having a very similar issue using TADOQuery to retrieve some LDAP info, there is a bug in the TParameter.InternalRefresh function that causes an access violation even if your query has no parameters.</p>\n\n<p>To solve this, simply set TADOQuery.ParamCheck to false.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
Ok, this is a curly one. I'm working on some Delphi code that I didn't write, and I'm encountering a very strange problem. One of my stored procedures' parameters is coming through as `null`, even though it's definitely being sent `1`. The Delphi code uses a TADOQuery to execute the stored procedure (anonymized): ``` ADOQuery1.SQL.Text := "exec MyStoredProcedure :Foo,:Bar,:Baz,:Qux,:Smang,:Jimmy"; ADOQuery1.Parameters.ParamByName("Foo").Value := Integer(someFunction()); // other parameters all set similarly ADOQuery1.ExecSQL; ``` `Integer(SomeFunction())` currently always returns 1 - I checked with the debugger. However, in my stored proc ( altered for debug purposes ): ``` create procedure MyStoredProcedure ( @Foo int, @Bar int, @Baz int, @Qux int, @Smang int, @Jimmy varchar(20) ) as begin -- temp debug if ( @Foo is null ) begin insert into TempLog values ( "oh crap" ) end -- do the rest of the stuff here.. end ``` `TempLog` does indeed end up with "oh crap" in it (side question: there must be a better way of debugging stored procs: what is it?). Here's an example trace from profiler: ``` exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p3 int set @p3=NULL exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int OUTPUT,@P2 int,@P3 int,@P4 int,@P5 int,@P6 int', @p3 output,1,1,1,0,200 select @p3 ``` This looks a little strange to me. Notice that it's using @p3 *and* @P3 - could this be causing my issue? The other strange thing is that it seems to depend on which TADOConnection I use. The project is a dll which is passed a TADOConnection from another application. It calls all the stored procedures using this connection. If instead of using this connection, I first do this: ``` ConnectionNew := TADOQuery.Create(ConnectionOld.Owner); ConnectionNew.ConnectionString := ConnectionOld.ConnectionString; TADOQuery1.Connection := ConnectionNew; ``` Then the issue does not occur! The trace from this situation is this: ``` exec [MYDB]..sp_procedure_params_rowset N'MyStoredProcedure',1,NULL,NULL declare @p1 int set @p1=64 exec sp_prepare @p1 output, N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', 1 select @p1 SET FMTONLY ON exec sp_execute 64,0,0,0,0,0,' ' SET FMTONLY OFF exec sp_unprepare 64 SET NO_BROWSETABLE OFF exec sp_executesql N'exec MyStoredProcedure @P1,@P2,@P3,@P4,@P5,@P6', N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int,@P6 varchar(20)', 1,1,1,3,0,'400.00' ``` Which is a bit much for lil ol' me to follow, unfortunately. What sort of TADOConnection options could be influencing this? Does anyone have any ideas? **Edit:** [Update below](https://stackoverflow.com/questions/137530/why-is-my-stored-procedure-receiving-a-null-parameter#177214) (didn't want to make this question any longer :P)
Ok, progress is made.. sort of. @Robsoft was correct, setting the parameter direction to `pdInput` fixed the issue. I traced into the VCL code, and it came down to `TParameters.InternalRefresh.RefreshFromOleDB`. This function is being called when I set the SQL.Text. Here's the (abridged) code: ``` function TParameters.InternalRefresh: Boolean; procedure RefreshFromOleDB; // .. if OLEDBParameters.GetParameterInfo(ParamCount, PDBPARAMINFO(ParamInfo), @NamesBuffer) = S_OK then for I := 0 to ParamCount - 1 do with ParamInfo[I] do begin // .. Direction := dwFlags and $F; // here's where the wrong value comes from // .. end; // .. end; // .. end; ``` So, [`OLEDBParameters.GetParameterInfo`](http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx) is returning the wrong flags for some reason. I've verified that with the original connection, `(dwFlags and $F)` is `2` (`DBPARAMFLAGS_ISOUTPUT`), and with the new connection, it's `1` (`DBPARAMFLAGS_ISINPUT`). I'm not really sure I want to dig any deeper than that, for now at least. Until I have more time and inclination, I'll just make sure all parameters are set to `pdInput` before I open the query. Unless anyone has any more bright ideas now..? Anyway, thanks everyone for your suggestions so far.
137,580
<p>I know how to do a HEAD request with httplib, but I have to use mechanize for this site. </p> <p>Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.</p> <p>Any suggestions how I could accomplish this?</p>
[ { "answer_id": 137624, "author": "Michał Kwiatkowski", "author_id": 21998, "author_profile": "https://Stackoverflow.com/users/21998", "pm_score": 4, "selected": true, "text": "<p>Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:</p>\n\n<pre><code>import mechanize\n\nclass HeadRequest(mechanize.Request):\n def get_method(self):\n return \"HEAD\"\n\nrequest = HeadRequest(\"http://www.example.com/\")\nresponse = mechanize.urlopen(request)\n\nprint response.info()\n</code></pre>\n" }, { "answer_id": 12680334, "author": "Nuncjo", "author_id": 977337, "author_profile": "https://Stackoverflow.com/users/977337", "pm_score": 0, "selected": false, "text": "<p>In mechanize there is no need to do HeadRequest class etc.</p>\n\n<p>Simply</p>\n\n<pre><code>\nimport mechanize\n\nbr = mechanize.Browser()\n\nr = br.open(\"http://www.example.com/\")\n\nprint r.info()\n\n</code></pre>\n\n<p>That's all.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
I know how to do a HEAD request with httplib, but I have to use mechanize for this site. Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file. Any suggestions how I could accomplish this?
Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example: ``` import mechanize class HeadRequest(mechanize.Request): def get_method(self): return "HEAD" request = HeadRequest("http://www.example.com/") response = mechanize.urlopen(request) print response.info() ```
137,621
<p>I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable.</p> <p>Is this true and if so can someone explain why?</p>
[ { "answer_id": 137636, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>Virtual methods are discouraged in both constructors and destructors. </p>\n\n<p>The reason is more practical than anything: virtual methods can be overridden in any manner chosen by the overrider, and things like object initialization during construction, for example, <em>have to be ensured</em> lest you end up with an object that has random nulls and an invalid state.</p>\n" }, { "answer_id": 137690, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 0, "selected": false, "text": "<p>To expand on Jon's answer, instead of calling virtual methods you should be overriding the dispose or the destructor on sub classes if you need to handle resources at that level.</p>\n\n<p>Although, I don't believe there is a \"rule\" in regards to behavior here. But the general thought is that you want to isolate resource cleanup to only that instance at that level of the implementation.</p>\n" }, { "answer_id": 137892, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 1, "selected": false, "text": "<p>I do not believe there is any recommendation against calling virtual methods. The prohibition you are remembering might be the rule against referencing managed objects in the finalizer.</p>\n\n<p>There is a standard pattern that is defined the .Net documentation for how Dispose() should be implemented. The pattern is very well designed, and it should be followed closely.</p>\n\n<p>The gist is this: Dispose() is a non-virtual method that calls a virtual method Dispose(bool). The boolean parameter indicates whether the method is being called from Dispose() (true) or the object's destructor (false). At each level of inheritance, the Dispose(bool) method should be implemented to handle any cleanup.</p>\n\n<p>When Dispose(bool) is passed the value false, this indicates that the finalizer has called the dispose method. In this circumstance, only cleanup of unmanaged objects should be attempted (except in certain rare circumstances). The reason for this is the fact that the garbage collector has just called the finalize method, therefore the current object must have been marked ready-for-finalization. Therefore, any object that it references may also have been marked read-for-finalization, and since the sequence in non-deterministic, the finalization may have already occurred.</p>\n\n<p>I highly recommend looking up the Dispose() pattern in the .Net documentation and following it precisely, because it will likely protect you from bizarre and difficult bugs!</p>\n" }, { "answer_id": 137947, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 4, "selected": true, "text": "<p>Calling virtual methods from a finalizer/<code>Dispose</code> is unsafe, for the same reasons <a href=\"https://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor\">it is unsafe to do in a constructor</a>. It is impossible to be sure that the derived class has not already cleaned-up some state that the virtual method requires to execute properly.</p>\n\n<p>Some people are confused by the standard Disposable pattern, and its use of a virtual method, <code>virtual Dispose(bool disposing)</code>, and think this makes it Ok to use <em>any</em> virtual method durring a dispose. Consider the following code:</p>\n\n<pre><code>class C : IDisposable {\n private IDisposable.Dispose() {\n this.Dispose(true);\n }\n protected virtual Dispose(bool disposing) {\n this.DoSomething();\n }\n\n protected virtual void DoSomething() { }\n}\nclass D : C {\n IDisposable X;\n\n protected override Dispose(bool disposing) {\n X.Dispose();\n base.Dispose(disposing);\n }\n\n protected override void DoSomething() {\n X.Whatever();\n }\n}\n</code></pre>\n\n<p>Here's what happens when you Dispose and object of type <code>D</code>, called <code>d</code>:</p>\n\n<ol>\n<li>Some code calls <code>((IDisposable)d).Dispose()</code></li>\n<li><code>C.IDisposable.Dispose()</code> calls the virtual method <code>D.Dispose(bool)</code></li>\n<li><code>D.Dispose(bool)</code> disposes of <code>D.X</code></li>\n<li><code>D.Dispose(bool)</code> calls <code>C.Dispose(bool)</code> <strong>statically</strong> (the target of the call is known <em>at compile-time</em>)</li>\n<li><code>C.Dispose(bool)</code> calls the virtual methods <code>D.DoSomething()</code></li>\n<li><code>D.DoSomething</code> calls the method <code>D.X.Whatever()</code> on the already disposed <code>D.X</code></li>\n<li>?</li>\n</ol>\n\n<p>Now, most people who run this code do one thing to fix it -- they move the <code>base.Dispose(dispose)</code> call to before they clean-up their own object. And, yes, that does work. But do you really trust Programmer X, the Ultra-Junior Developer from the company you developed <code>C</code> for, assigned to write <code>D</code>, to write it in a way that the error is either detected, or has the <code>base.Dispose(disposing)</code> call in the right spot?</p>\n\n<p>I'm not saying you should never, <strong>ever</strong> write code that calls a virtual method from Dispose, just that you'll need to <strong>document</strong> that virtual method's <em>requirement</em> that it never use any state that's defined in any class derived below <code>C</code>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
I can't find a reference to it but I remember reading that it wasn't a good idea to call virtual (polymorphic) methods within a destructor or the Dispose() method of IDisposable. Is this true and if so can someone explain why?
Calling virtual methods from a finalizer/`Dispose` is unsafe, for the same reasons [it is unsafe to do in a constructor](https://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor). It is impossible to be sure that the derived class has not already cleaned-up some state that the virtual method requires to execute properly. Some people are confused by the standard Disposable pattern, and its use of a virtual method, `virtual Dispose(bool disposing)`, and think this makes it Ok to use *any* virtual method durring a dispose. Consider the following code: ``` class C : IDisposable { private IDisposable.Dispose() { this.Dispose(true); } protected virtual Dispose(bool disposing) { this.DoSomething(); } protected virtual void DoSomething() { } } class D : C { IDisposable X; protected override Dispose(bool disposing) { X.Dispose(); base.Dispose(disposing); } protected override void DoSomething() { X.Whatever(); } } ``` Here's what happens when you Dispose and object of type `D`, called `d`: 1. Some code calls `((IDisposable)d).Dispose()` 2. `C.IDisposable.Dispose()` calls the virtual method `D.Dispose(bool)` 3. `D.Dispose(bool)` disposes of `D.X` 4. `D.Dispose(bool)` calls `C.Dispose(bool)` **statically** (the target of the call is known *at compile-time*) 5. `C.Dispose(bool)` calls the virtual methods `D.DoSomething()` 6. `D.DoSomething` calls the method `D.X.Whatever()` on the already disposed `D.X` 7. ? Now, most people who run this code do one thing to fix it -- they move the `base.Dispose(dispose)` call to before they clean-up their own object. And, yes, that does work. But do you really trust Programmer X, the Ultra-Junior Developer from the company you developed `C` for, assigned to write `D`, to write it in a way that the error is either detected, or has the `base.Dispose(disposing)` call in the right spot? I'm not saying you should never, **ever** write code that calls a virtual method from Dispose, just that you'll need to **document** that virtual method's *requirement* that it never use any state that's defined in any class derived below `C`.
137,629
<p>How do you render primitives as wireframes in OpenGL?</p>
[ { "answer_id": 137644, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"https://web.archive.org/web/20090119194513/http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5\" rel=\"noreferrer\">http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5</a></p>\n\n<pre><code>// Turn on wireframe mode\nglPolygonMode(GL_FRONT, GL_LINE);\nglPolygonMode(GL_BACK, GL_LINE);\n\n// Draw the box\nDrawBox();\n\n// Turn off wireframe mode\nglPolygonMode(GL_FRONT, GL_FILL);\nglPolygonMode(GL_BACK, GL_FILL);\n</code></pre>\n" }, { "answer_id": 137649, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<pre><code>glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );\n</code></pre>\n\n<p>to switch on,</p>\n\n<pre><code>glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );\n</code></pre>\n\n<p>to go back to normal.</p>\n\n<p>Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird.</p>\n" }, { "answer_id": 22497914, "author": "Hochester", "author_id": 3436093, "author_profile": "https://Stackoverflow.com/users/3436093", "pm_score": 2, "selected": false, "text": "<p>The easiest way is to draw the primitives as <code>GL_LINE_STRIP</code>.</p>\n\n<pre><code>glBegin(GL_LINE_STRIP);\n/* Draw vertices here */\nglEnd();\n</code></pre>\n" }, { "answer_id": 33004265, "author": "the swine", "author_id": 1140976, "author_profile": "https://Stackoverflow.com/users/1140976", "pm_score": 5, "selected": false, "text": "<p>Assuming a forward-compatible context in OpenGL 3 and up, you can either use <code>glPolygonMode</code> as mentioned before, but note that lines with thickness more than 1px are now deprecated. So while you can draw triangles as wire-frame, they need to be very thin. In OpenGL ES, you can use <code>GL_LINES</code> with the same limitation.</p>\n\n<p>In OpenGL it is possible to use geometry shaders to take incoming triangles, disassemble them and send them for rasterization as quads (pairs of triangles really) emulating thick lines. Pretty simple, really, except that geometry shaders are notorious for poor performance scaling.</p>\n\n<p>What you can do instead, and what will also work in OpenGL ES is to employ <em>fragment</em> shader. Think of applying a texture of wire-frame triangle to the triangle. Except that no texture is needed, it can be generated procedurally. But enough talk, let's code. Fragment shader:</p>\n\n\n\n<pre class=\"lang-c prettyprint-override\"><code>in vec3 v_barycentric; // barycentric coordinate inside the triangle\nuniform float f_thickness; // thickness of the rendered lines\n\nvoid main()\n{\n float f_closest_edge = min(v_barycentric.x,\n min(v_barycentric.y, v_barycentric.z)); // see to which edge this pixel is the closest\n float f_width = fwidth(f_closest_edge); // calculate derivative (divide f_thickness by this to have the line width constant in screen-space)\n float f_alpha = smoothstep(f_thickness, f_thickness + f_width, f_closest_edge); // calculate alpha\n gl_FragColor = vec4(vec3(.0), f_alpha);\n}\n</code></pre>\n\n<p>And vertex shader:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>in vec4 v_pos; // position of the vertices\nin vec3 v_bc; // barycentric coordinate inside the triangle\n\nout vec3 v_barycentric; // barycentric coordinate inside the triangle\n\nuniform mat4 t_mvp; // modeview-projection matrix\n\nvoid main()\n{\n gl_Position = t_mvp * v_pos;\n v_barycentric = v_bc; // just pass it on\n}\n</code></pre>\n\n<p>Here, the barycentric coordinates are simply <code>(1, 0, 0)</code>, <code>(0, 1, 0)</code> and <code>(0, 0, 1)</code> for the three triangle vertices (the order does not really matter, which makes packing into triangle strips potentially easier).</p>\n\n<p>The obvious disadvantage of this approach is that it will eat some texture coordinates and you need to modify your vertex array. Could be solved with a very simple geometry shader but I'd still suspect it will be slower than just feeding the GPU with more data.</p>\n" }, { "answer_id": 43410404, "author": "H.Mohcen", "author_id": 7258877, "author_profile": "https://Stackoverflow.com/users/7258877", "pm_score": 1, "selected": false, "text": "<p>You can use glut libraries like this: </p>\n\n<ol>\n<li><p>for a sphere:</p>\n\n<pre><code>glutWireSphere(radius,20,20);\n</code></pre></li>\n<li><p>for a Cylinder: </p>\n\n<pre><code>GLUquadric *quadratic = gluNewQuadric();\ngluQuadricDrawStyle(quadratic,GLU_LINE);\ngluCylinder(quadratic,1,1,1,12,1);\n</code></pre></li>\n<li><p>for a Cube:</p>\n\n<pre><code>glutWireCube(1.5);\n</code></pre></li>\n</ol>\n" }, { "answer_id": 47037419, "author": "LMD", "author_id": 7185318, "author_profile": "https://Stackoverflow.com/users/7185318", "pm_score": 3, "selected": false, "text": "<p>In Modern OpenGL(OpenGL 3.2 and higher), you could use a Geometry Shader for this : </p>\n\n<pre><code>#version 330\n\nlayout (triangles) in;\nlayout (line_strip /*for lines, use \"points\" for points*/, max_vertices=3) out;\n\nin vec2 texcoords_pass[]; //Texcoords from Vertex Shader\nin vec3 normals_pass[]; //Normals from Vertex Shader\n\nout vec3 normals; //Normals for Fragment Shader\nout vec2 texcoords; //Texcoords for Fragment Shader\n\nvoid main(void)\n{\n int i;\n for (i = 0; i &lt; gl_in.length(); i++)\n {\n texcoords=texcoords_pass[i]; //Pass through\n normals=normals_pass[i]; //Pass through\n gl_Position = gl_in[i].gl_Position; //Pass through\n EmitVertex();\n }\n EndPrimitive();\n}\n</code></pre>\n\n<p>Notices : </p>\n\n<ul>\n<li>for points, change <code>layout (line_strip, max_vertices=3) out;</code> to <code>layout (points, max_vertices=3) out;</code></li>\n<li><a href=\"https://open.gl/geometry\" rel=\"noreferrer\">Read more about Geometry Shaders</a></li>\n</ul>\n" }, { "answer_id": 47054000, "author": "Victor", "author_id": 789999, "author_profile": "https://Stackoverflow.com/users/789999", "pm_score": 0, "selected": false, "text": "<p>If it's <strong>OpenGL ES 2.0</strong> you're dealing with, you can choose one of draw mode constants from</p>\n\n<p><code>GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES,</code> to draw lines,</p>\n\n<p><code>GL_POINTS</code> (if you need to draw only vertices), or</p>\n\n<p><code>GL_TRIANGLE_STRIP</code>, <code>GL_TRIANGLE_FAN</code>, and <code>GL_TRIANGLES</code> to draw filled triangles</p>\n\n<p>as first argument to your </p>\n\n<pre><code>glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)\n</code></pre>\n\n<p>or</p>\n\n<p><code>glDrawArrays(GLenum mode, GLint first, GLsizei count)</code> calls. </p>\n" }, { "answer_id": 47064476, "author": "Zaphyk", "author_id": 3430546, "author_profile": "https://Stackoverflow.com/users/3430546", "pm_score": 3, "selected": false, "text": "<p>If you are using the fixed pipeline (OpenGL &lt; 3.3) or the compatibility profile you can use</p>\n\n<pre><code>//Turn on wireframe mode\nglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\n//Draw the scene with polygons as lines (wireframe)\nrenderScene();\n\n//Turn off wireframe mode\nglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n</code></pre>\n\n<p>In this case you can change the line width by calling <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLineWidth.xhtml\" rel=\"noreferrer\">glLineWidth</a></p>\n\n<p>Otherwise you need to change the polygon mode inside your draw method (glDrawElements, glDrawArrays, etc) and you may end up with some rough results because your vertex data is for triangles and you are outputting lines. For best results consider using a <a href=\"https://www.khronos.org/opengl/wiki/Geometry_Shader\" rel=\"noreferrer\">Geometry shader</a> or creating new data for the wireframe.</p>\n" }, { "answer_id": 58364408, "author": "Gravitysensation", "author_id": 4650120, "author_profile": "https://Stackoverflow.com/users/4650120", "pm_score": 0, "selected": false, "text": "<p>A good and simple way of drawing anti-aliased lines on a non anti-aliased render target is to draw rectangles of 4 pixel width with an 1x4 texture, with alpha channel values of {0.,1.,1.,0.}, and use linear filtering with mip-mapping off. This will make the lines 2 pixels thick, but you can change the texture for different thicknesses.\nThis is faster and easier than barymetric calculations.</p>\n" }, { "answer_id": 59473781, "author": "Omar Ghannou", "author_id": 11969743, "author_profile": "https://Stackoverflow.com/users/11969743", "pm_score": 1, "selected": false, "text": "<p>Use this function:</p>\n<pre><code>void glPolygonMode(GLenum face, GLenum mode);\n</code></pre>\n<p><code>face</code>: Specifies the polygon faces that mode applies to. Can be <code>GL_FRONT</code> for the front side of the polygon, <code>GL_BACK</code> for the back and <code>GL_FRONT_AND_BACK</code> for both.</p>\n<p><code>mode</code>: Three modes are defined.</p>\n<ul>\n<li><p><code>GL_POINT</code>: Polygon vertices that are marked as the start of a boundary edge are drawn as points.</p>\n</li>\n<li><p><code>GL_LINE</code>: Boundary edges of the polygon are drawn as line segments. (your target)</p>\n</li>\n<li><p><code>GL_FILL</code>: The interior of the polygon is filled.</p>\n</li>\n</ul>\n<p>P.S: <code>glPolygonMode</code> controls the interpretation of polygons for rasterization in the graphics pipeline.</p>\n<p>For more information look at the <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glPolygonMode.xhtml\" rel=\"nofollow noreferrer\">OpenGL reference pages</a> in khronos group.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you render primitives as wireframes in OpenGL?
``` glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); ``` to switch on, ``` glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); ``` to go back to normal. Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird.
137,630
<p>I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.</p>
[ { "answer_id": 137643, "author": "macarthy", "author_id": 17232, "author_profile": "https://Stackoverflow.com/users/17232", "pm_score": 0, "selected": false, "text": "<p>sure why not </p>\n\n<p>:named_scope :conditions => [ your sql ]</p>\n" }, { "answer_id": 180440, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>While you can put any SQL you like in the conditions of a named scope, if you then call <code>find_by_sql</code> then the 'scopes' get thrown away.</p>\n\n<p>Given:</p>\n\n<pre><code>class Item\n # Anything you can put in an sql WHERE you can put here\n named_scope :mine, :conditions=&gt;'user_id = 12345 and IS_A_NINJA() = 1'\nend\n</code></pre>\n\n<p>This works (it just sticks the SQL string in there - if you have more than one they get joined with AND)</p>\n\n<pre><code>Item.mine.find :all\n=&gt; SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1)\n</code></pre>\n\n<p>However, this doesn't</p>\n\n<pre><code>Items.mine.find_by_sql 'select * from items limit 1'\n=&gt; select * from items limit 1\n</code></pre>\n\n<p>So the answer is \"No\". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together.<br>\nWhen you create normal queries, the <code>select</code>, <code>joins</code>, <code>conditions</code>, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how <code>with_scope</code> and <code>named_scope</code> work).</p>\n\n<p>With <code>find_by_sql</code> however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work.</p>\n" }, { "answer_id": 927136, "author": "jdwyah", "author_id": 53387, "author_profile": "https://Stackoverflow.com/users/53387", "pm_score": 1, "selected": false, "text": "<p>This doesn't address exactly what you asked about, but you might investigate 'contruct_finder_sql'. It lets you can get the SQL of a named scope.</p>\n\n<pre><code>named_scope :mine, :conditions=&gt;'user_id = 12345 and IS_A_NINJA() = 1'\nnamed_scope :additional {\n :condtions =&gt; mine.send(:construct_finder_sql,{}) + \" additional = 'foo'\"\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
I was wondering if there was a way to use "find\_by\_sql" within a named\_scope. I'd like to treat custom sql as named\_scope so I can chain it to my existing named\_scopes. It would also be good for optimizing a sql snippet I use frequently.
While you can put any SQL you like in the conditions of a named scope, if you then call `find_by_sql` then the 'scopes' get thrown away. Given: ``` class Item # Anything you can put in an sql WHERE you can put here named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' end ``` This works (it just sticks the SQL string in there - if you have more than one they get joined with AND) ``` Item.mine.find :all => SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1) ``` However, this doesn't ``` Items.mine.find_by_sql 'select * from items limit 1' => select * from items limit 1 ``` So the answer is "No". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together. When you create normal queries, the `select`, `joins`, `conditions`, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how `with_scope` and `named_scope` work). With `find_by_sql` however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work.
137,660
<p>In a J2EE application (like one running in WebSphere), when I use <code>System.out.println()</code>, my text goes to standard out, which is mapped to a file by the WebSphere admin console.</p> <p>In an ASP.NET application (like one running in IIS), where does the output of <code>Console.WriteLine()</code> go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here?</p> <p>I'm <strong>not asking</strong> if I should log there (I use log4net), but where does the output go? My best info came from this <a href="http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html" rel="noreferrer">discussion</a> where they say <code>Console.SetOut()</code> can change the <code>TextWriter</code>, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.</p>
[ { "answer_id": 137704, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": -1, "selected": false, "text": "<p>In an ASP.NET application, I think it goes to the Output or Console window which is visible during debugging.</p>\n" }, { "answer_id": 137736, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 3, "selected": false, "text": "<p>Unless you are in a strict console application, I wouldn't use it, because you can't really see it. I would use Trace.WriteLine() for debugging-type information that can be turned on and off in production.</p>\n" }, { "answer_id": 139903, "author": "Craig Tyler", "author_id": 5408, "author_profile": "https://Stackoverflow.com/users/5408", "pm_score": 3, "selected": false, "text": "<p>There simply is no console listening by default. Running in debug mode there is a console attached, but in a production environment it is as you suspected, the message just doesn't go anywhere because nothing is listening.</p>\n" }, { "answer_id": 879928, "author": "Greg Bernhardt", "author_id": 24387, "author_profile": "https://Stackoverflow.com/users/24387", "pm_score": 10, "selected": false, "text": "<p>If you use <code>System.Diagnostics.Debug.WriteLine(...)</code> instead of <code>Console.WriteLine()</code>, then you can see the results in the <strong>Output</strong> window of Visual Studio.</p>\n" }, { "answer_id": 1432088, "author": "Ruben", "author_id": 143854, "author_profile": "https://Stackoverflow.com/users/143854", "pm_score": 9, "selected": true, "text": "<p>If you look at the <code>Console</code> class in <a href=\"http://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"noreferrer\">.NET Reflector</a>, you'll find that if a process doesn't have an associated console, <code>Console.Out</code> and <code>Console.Error</code> are backed by <code>Stream.Null</code> (wrapped inside a <code>TextWriter</code>), which is a dummy implementation of <code>Stream</code> that basically ignores all input, and gives no output.</p>\n<p>So it is conceptually equivalent to <code>/dev/null</code>, but the implementation is more streamlined: there's no actual I/O taking place with the null device.</p>\n<p>Also, apart from calling <code>SetOut</code>, there is no way to configure the default.</p>\n<p><strong>Update 2020-11-02</strong>: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually <em>is</em> a console attached. You can configure the <a href=\"https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module\" rel=\"noreferrer\">ASP.NET Core IIS Module</a> to redirect all stdout and stderr output to a log file via the <code>stdoutLogEnabled</code> and <code>stdoutLogFile</code> settings:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;system.webServer&gt;\n &lt;aspNetCore processPath=&quot;dotnet&quot;\n arguments=&quot;.\\MyApp.dll&quot;\n hostingModel=&quot;inprocess&quot;\n stdoutLogEnabled=&quot;true&quot;\n stdoutLogFile=&quot;.\\logs\\stdout&quot; /&gt;\n&lt;system.webServer&gt;\n</code></pre>\n" }, { "answer_id": 3896183, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 5, "selected": false, "text": "<p>I've found this question by trying to change the Log output of the DataContext to the output window. So to anyone else trying to do the same, what I've done was create this:</p>\n\n<pre><code>class DebugTextWriter : System.IO.TextWriter {\n public override void Write(char[] buffer, int index, int count) {\n System.Diagnostics.Debug.Write(new String(buffer, index, count));\n }\n\n public override void Write(string value) {\n System.Diagnostics.Debug.Write(value);\n }\n\n public override Encoding Encoding {\n get { return System.Text.Encoding.Default; }\n }\n}\n</code></pre>\n\n<p>Annd after that: dc.Log = new DebugTextWriter() and I can see all the queries in the output window (dc is the DataContext).</p>\n\n<p>Have a look at this for more info: <a href=\"http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers\" rel=\"noreferrer\">http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers</a></p>\n" }, { "answer_id": 9541047, "author": "Brian Griffin", "author_id": 1246074, "author_profile": "https://Stackoverflow.com/users/1246074", "pm_score": 2, "selected": false, "text": "<p>The <code>TraceContext</code> object in ASP.NET writes to the <code>DefaultTraceListener</code> which outputs to the host process’ <a href=\"https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29\" rel=\"nofollow noreferrer\">standard output</a>. Rather than using <code>Console.Write()</code>, if you use <code>Trace.Write</code>, output will go to the standard output of the process.</p>\n\n<p>You could use the <code>System.Diagnostics.Process</code> object to get the ASP.NET process for your site and monitor standard output using the <code>OutputDataRecieved</code> event.</p>\n" }, { "answer_id": 18887673, "author": "Nik", "author_id": 2228791, "author_profile": "https://Stackoverflow.com/users/2228791", "pm_score": 4, "selected": false, "text": "<p><code>System.Diagnostics.Debug.WriteLine(...);</code> gets it into the <em>Immediate Window</em> in Visual&nbsp;Studio&nbsp;2008.</p>\n\n<p>Go to menu <em>Debug</em> -> <em>Windows</em> -> <em>Immediate</em>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/yq68G.png\" alt=\"Enter image description here\"></p>\n" }, { "answer_id": 19523569, "author": "Chris", "author_id": 945840, "author_profile": "https://Stackoverflow.com/users/945840", "pm_score": 4, "selected": false, "text": "<p>If you are using IIS Express and launch it via a command prompt, it will leave the <a href=\"http://en.wikipedia.org/wiki/DOS\" rel=\"noreferrer\">DOS</a> window open, and you will see <code>Console.Write</code> statements there.</p>\n\n<p>So for example get a command window open and type:</p>\n\n<pre><code>\"C:\\Program Files (x86)\\IIS Express\\iisexpress\" /path:C:\\Projects\\Website1 /port:1655\n</code></pre>\n\n<p>This assumes you have a website directory at C:\\Projects\\Website1. It will start IIS Express and serve the pages in your website directory. It will leave the command windows open, and you will see output information there. Let's say you had a file there, default.aspx, with this code in it:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" %&gt;\n&lt;html&gt;\n&lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n Hello!\n\n &lt;% for(int i = 0; i &lt; 6; i++) %&gt;\n &lt;% { Console.WriteLine(i.ToString()); }%&gt;\n\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Arrange your browser and command windows so you can see them both on the screen. Now type into your browser: <code>http://localhost:1655/</code>. You will see Hello! on the webpage, but in the command window you will see something like</p>\n\n<pre><code>Request started: \"GET\" http://localhost:1655/\n0\n1\n2\n3\n4\n5\nRequest ended: http://localhost:1655/default.aspx with HTTP status 200.0\n</code></pre>\n\n<p>I made it simple by having the code in a code block in the markup, but any console statements in your <a href=\"http://en.wiktionary.org/wiki/code-behind\" rel=\"noreferrer\">code-behind</a> or anywhere else in your code will show here as well.</p>\n" }, { "answer_id": 45516904, "author": "Chris Go", "author_id": 6614505, "author_profile": "https://Stackoverflow.com/users/6614505", "pm_score": 0, "selected": false, "text": "<p>This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.</p>\n\n<p>For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.</p>\n\n<p>Good news CORE 2.0 this will all be changing: <a href=\"https://github.com/aspnet/Announcements/issues/255\" rel=\"nofollow noreferrer\">https://github.com/aspnet/Announcements/issues/255</a></p>\n" }, { "answer_id": 53953125, "author": "mickey", "author_id": 529059, "author_profile": "https://Stackoverflow.com/users/529059", "pm_score": 1, "selected": false, "text": "<p>if you happened to use NLog in your ASP.net project, you can add a <a href=\"https://github.com/NLog/NLog/wiki/Debugger-target\" rel=\"nofollow noreferrer\">Debugger target</a>:</p>\n\n<pre><code>&lt;targets&gt;\n &lt;target name=\"debugger\" xsi:type=\"Debugger\"\n layout=\"${date:format=HH\\:mm\\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} \"/&gt;\n</code></pre>\n\n<p>and writes logs to this target for the levels you want:</p>\n\n<pre><code>&lt;rules&gt;\n &lt;logger name=\"*\" minlevel=\"Trace\" writeTo=\"debugger\" /&gt;\n</code></pre>\n\n<p>now you have console output just like Jetty in \"Output\" window of VS, and make sure you are running in Debug Mode(F5).</p>\n" }, { "answer_id": 60542156, "author": "Thushara Buddhika", "author_id": 12162813, "author_profile": "https://Stackoverflow.com/users/12162813", "pm_score": 0, "selected": false, "text": "<p>Mac, In Debug mode there is a tab for the Output.\n<a href=\"https://i.stack.imgur.com/ZFU1Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZFU1Q.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 70121857, "author": "PyroMani", "author_id": 14844450, "author_profile": "https://Stackoverflow.com/users/14844450", "pm_score": 0, "selected": false, "text": "<p>Using console.Writeline did not work for me.</p>\n<p>What did help was putting a breakpoint and then running the test on debug.\nWhen it reaches the breakpoint you can observe what is returned.</p>\n" }, { "answer_id": 70324600, "author": "Shoaib Khalil", "author_id": 11966556, "author_profile": "https://Stackoverflow.com/users/11966556", "pm_score": 1, "selected": false, "text": "<p>Try to attach kinda 'backend debugger' to log your msg or data to the console or output window the way we can do in node console.</p>\n<p><code>System.Diagnostics.Debug.WriteLine(&quot;Message&quot; + variable)</code> instead of <code>Console.WriteLine()</code></p>\n<p>this way you can see the results in Output window aka Console of Visual Studio.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22514/" ]
In a J2EE application (like one running in WebSphere), when I use `System.out.println()`, my text goes to standard out, which is mapped to a file by the WebSphere admin console. In an ASP.NET application (like one running in IIS), where does the output of `Console.WriteLine()` go? The IIS process must have a stdin, stdout and stderr; but is stdout mapped to the Windows version of /dev/null or am I missing a key concept here? I'm **not asking** if I should log there (I use log4net), but where does the output go? My best info came from this [discussion](http://www.velocityreviews.com/forums/t91075-where-does-consolewriteline-goto.html) where they say `Console.SetOut()` can change the `TextWriter`, but it still didn't answer the question on what the initial value of the Console is, or how to set it in config/outside of runtime code.
If you look at the `Console` class in [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflector), you'll find that if a process doesn't have an associated console, `Console.Out` and `Console.Error` are backed by `Stream.Null` (wrapped inside a `TextWriter`), which is a dummy implementation of `Stream` that basically ignores all input, and gives no output. So it is conceptually equivalent to `/dev/null`, but the implementation is more streamlined: there's no actual I/O taking place with the null device. Also, apart from calling `SetOut`, there is no way to configure the default. **Update 2020-11-02**: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually *is* a console attached. You can configure the [ASP.NET Core IIS Module](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module) to redirect all stdout and stderr output to a log file via the `stdoutLogEnabled` and `stdoutLogFile` settings: ```xml <system.webServer> <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" hostingModel="inprocess" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" /> <system.webServer> ```
137,661
<p>In C#, I can do this:</p> <pre><code>class Program { static void Main(string[] args) { List&lt;Animal&gt; animals = new List&lt;Animal&gt;(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } } </code></pre> <p>Obviously, the output is (Slightly paraphrased):</p> <ul> <li>Woof</li> <li>Dog is Sleeping</li> <li>Meow</li> <li>Cat is Sleeping</li> </ul> <p>Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?</p>
[ { "answer_id": 137675, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "<p>edit: added more code for your updated question</p>\n\n<p>disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct.</p>\n\n<hr>\n\n<p>The exact same way, with classes and overridden methods:</p>\n\n<pre><code>class Animal\n def MakeNoise\n return \"\"\n end\n def Sleep\n print self.class.name + \" is sleeping.\\n\"\n end\nend\n\nclass Dog &lt; Animal\n def MakeNoise\n return \"Woof!\"\n end\nend\n\nclass Cat &lt; Animal\n def MakeNoise\n return \"Meow!\"\n end\nend\n\nanimals = [Dog.new, Cat.new]\nanimals.each {|a|\n print a.MakeNoise + \"\\n\"\n a.Sleep\n}\n</code></pre>\n" }, { "answer_id": 137716, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": "<p>Building on the previous answer, is this how you might do it?</p>\n\n<hr>\n\n<p>Second cut after clarification:</p>\n\n<pre><code>class Animal\n def MakeNoise\n raise NotImplementedError # I don't remember the exact error class\n end\n def Sleep\n puts self.class.to_s + \" is sleeping.\"\n end\nend\n\nclass Dog &lt; Animal\n def MakeNoise\n return \"Woof!\"\n end\nend\n\nclass Cat &lt; Animal\n def MakeNoise\n return \"Meow!\"\n end\nend\n\nanimals = [Dog.new, Cat.new]\nanimals.each {|a|\n puts a.MakeNoise\n a.Sleep\n}\n</code></pre>\n\n<p>(I'll leave this as is, but \"self.class.name\" wins over \".to_s\")</p>\n" }, { "answer_id": 137916, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 3, "selected": false, "text": "<p>Using idiomatic Ruby</p>\n\n<pre><code>class Animal\n def sleep\n puts \"#{self.class} is sleeping\"\n end\nend\n\nclass Dog &lt; Animal\n def make_noise\n \"Woof!\"\n end\nend\n\nclass Cat &lt; Animal\n def make_noise\n \"Meow!\"\n end\nend\n\n[Dog, Cat].each do |clazz|\n animal = clazz.new\n puts animal.make_noise\n animal.sleep\nend\n</code></pre>\n" }, { "answer_id": 138131, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 0, "selected": false, "text": "<p>This is how I would write it:</p>\n\n<pre><code>class Animal\n def make_noise; '' end\n def sleep; puts \"#{self.class.name} is sleeping.\" end\nend\n\nclass Dog &lt; Animal; def make_noise; 'Woof!' end end\nclass Cat &lt; Animal; def make_noise; 'Meow!' end end\n\n[Dog.new, Cat.new].each do |animal|\n puts animal.make_noise\n animal.sleep\nend\n</code></pre>\n\n<p>It's not <em>really</em> different from the other solutions, but this is the style that I would prefer.</p>\n\n<p>That's 12 lines vs. the 41 lines (actually, you can shave off 3 lines by using a collection initializer) from the original C# example. Not bad!</p>\n" }, { "answer_id": 141457, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 5, "selected": false, "text": "<p>All the answers so far look pretty good to me. I thought I'd just mention that the whole inheritance thing is not entirely necessary. Excluding the \"sleep\" behaviour for a moment, we can achieve the whole desired outcome using duck-typing and omitting the need to create an Animal base class at all. Googling for \"duck-typing\" should yield any number of explanations, so for here let's just say \"if it walks like a duck and quacks like a duck...\"</p>\n\n<p>The \"sleep\" behaviour could be provided by using a mixin module, like Array, Hash and other Ruby built-in classes inclue Enumerable. I'm not suggesting it's necessarily better, just a different and perhaps more idiomatically Ruby way of doing it.</p>\n\n<pre><code>module Animal\n def sleep\n puts self.class.name + \" sleeps\"\n end\nend\n\nclass Dog\n include Animal\n def make_noise\n puts \"Woof\"\n end\nend\n\nclass Cat\n include Animal\n def make_noise\n puts \"Meow\"\n end\nend\n</code></pre>\n\n<p>You know the rest...</p>\n" }, { "answer_id": 144185, "author": "zimbatm", "author_id": 17533, "author_profile": "https://Stackoverflow.com/users/17533", "pm_score": 1, "selected": false, "text": "<p>The principle of duck typing is just that the object has to respond to the called methods. So something like that may do the trick too :</p>\n\n<pre><code>module Sleeping\n def sleep; puts \"#{self} sleeps\"\nend\n\ndog = \"Dog\"\ndog.extend Sleeping\nclass &lt;&lt; dog\n def make_noise; puts \"Woof!\" end\nend\n\nclass Cat\n include Sleeping\n def to_s; \"Cat\" end\n def make_noise; puts \"Meow!\" end\nend\n\n[dog, Cat.new].each do |a|\n a.sleep\n a.make_noise\nend\n</code></pre>\n" }, { "answer_id": 3121417, "author": "bitTnkr", "author_id": 376528, "author_profile": "https://Stackoverflow.com/users/376528", "pm_score": 1, "selected": false, "text": "<p>A little variant of manveru's solution which dynamic create different kind of object based in an array of Class types. Not really different, just a little more clear.</p>\n\n<pre><code>Species = [Dog, Cat]\n\nSpecies.each do |specie|\n animal = specie.new # this will create a different specie on each call of new\n print animal.MakeNoise + \"\\n\"\n animal.Sleep\nend\n</code></pre>\n" }, { "answer_id": 37137558, "author": "itsnikolay", "author_id": 1117851, "author_profile": "https://Stackoverflow.com/users/1117851", "pm_score": 0, "selected": false, "text": "<p>There's a method <code>becomes</code> which implements a polymorphism (by coping all instance variables from given class to new one)</p>\n\n<pre><code>class Animal\n attr_reader :name\n\n def initialize(name = nil)\n @name = name\n end\n\n def make_noise\n ''\n end\n\n def becomes(klass)\n became = klass.new\n became.instance_variables.each do |instance_variable|\n value = self.instance_variable_get(instance_variable)\n became.instance_variable_set(instance_variable, value)\n end\n\n became\n end\nend\n\nclass Dog &lt; Animal\n def make_noise\n 'Woof'\n end\nend\n\nclass Cat &lt; Animal\n def make_noise\n 'Meow'\n end\nend\n\nanimals = [Dog.new('Spot'), Cat.new('Tom')]\n\nanimals.each do |animal|\n new_animal = animal.becomes(Cat)\n puts \"#{animal.class} with name #{animal.name} becomes #{new_animal.class}\"\n puts \"and makes a noise: #{new_animal.make_noise}\"\n puts '----'\nend\n</code></pre>\n\n<p>and result is:</p>\n\n<pre><code>Dog with name Spot becomes Cat\nand makes a noise: Meow\n----\nCat with name Tom becomes Cat\nand makes a noise: Meow\n----\n</code></pre>\n\n<ul>\n<li><p>A polymorphism could be useful to avoid <code>if</code> statement (<a href=\"http://antiifcampaign.com/\" rel=\"nofollow\">antiifcampaign.com</a>)</p></li>\n<li><p>If you use <code>RubyOnRails</code> <code>becomes</code> method is already implemented: <a href=\"http://edgeapi.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes\" rel=\"nofollow\"><code>becomes</code></a></p></li>\n<li><p>Quicktip: if you mix polymorphism with <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html\" rel=\"nofollow\">STI</a> it brings you the most efficient combo to refactor your code</p></li>\n</ul>\n\n<p>I wish it helped you</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
In C#, I can do this: ``` class Program { static void Main(string[] args) { List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } } ``` Obviously, the output is (Slightly paraphrased): * Woof * Dog is Sleeping * Meow * Cat is Sleeping Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?
edit: added more code for your updated question disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct. --- The exact same way, with classes and overridden methods: ``` class Animal def MakeNoise return "" end def Sleep print self.class.name + " is sleeping.\n" end end class Dog < Animal def MakeNoise return "Woof!" end end class Cat < Animal def MakeNoise return "Meow!" end end animals = [Dog.new, Cat.new] animals.each {|a| print a.MakeNoise + "\n" a.Sleep } ```
137,679
<p>I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working:</p> <pre><code>RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1 </code></pre>
[ { "answer_id": 137692, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>You need to use a Cond to test for both port (http or httpd) and query string:</p>\n\n<pre><code>RewriteCond %{SERVER_PORT} 80\nRewriteCond %{QUERY_STRING} (.+)\nRewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1\n</code></pre>\n\n<p>if on .htaccess you must use instead</p>\n\n<pre><code>RewriteCond %{SERVER_PORT} 80\nRewriteCond %{QUERY_STRING} (.+)\nRewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1\n</code></pre>\n" }, { "answer_id": 438964, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 0, "selected": false, "text": "<p>A better solution would be:</p>\n\n<pre>\n RewriteCond %{SERVER_PORT} !^443$\n RewriteRule ^openid/index\\.php$ https://%{SERVER_NAME}/openid/index.php\n</pre>\n\n<p>Explaination: <code>RewriteCond %{SERVER_PORT} 80</code> does also match ports that just include <code>80</code>. The same applies to the pattern <code>openid/index.php</code> (where “<code>.</code>” also can be any character). And appending the query is not necessary since mod_rewrite automatically appends the originally requested query to the substitute unless the query of the substitute is given.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I setup phpMyID on one of my machines, and I'm trying to get apache to redirect to HTTPS only when a password is being submitted. I am doing this as my original setup of redirecting all openid traffic didn't work stackoverflow doesn't like my self signed certificate. This is the new rule I've written, but its not working: ``` RewriteRule http://%{SERVER_NAME}/openid/index.php(\?.+)$ https://%{SERVER_NAME}/openid/index.php$1 ```
You need to use a Cond to test for both port (http or httpd) and query string: ``` RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule /openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 ``` if on .htaccess you must use instead ``` RewriteCond %{SERVER_PORT} 80 RewriteCond %{QUERY_STRING} (.+) RewriteRule openid/index.php https://%{SERVER_NAME}/openid/index.php?%1 ```
137,730
<p>How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.</p>
[ { "answer_id": 137751, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>You should use the <code>$_FILES</code> superglobal and <code>move_uploaded_file()</code> function to see which files were uploaded successfully and move them to their final location in case they were.</p>\n\n<p>The <code>$_POST</code> superglobal will contain the submitted username and password.</p>\n" }, { "answer_id": 137907, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 4, "selected": true, "text": "<p>first off check out these pages on PHP.net</p>\n\n<ol>\n<li><a href=\"http://us3.php.net/features.file-upload\" rel=\"noreferrer\">file upload info</a></li>\n<li><a href=\"http://us3.php.net/manual/en/function.move-uploaded-file.php\" rel=\"noreferrer\"><code>move_uploaded_file</code></a></li>\n</ol>\n\n<p>But to get you started here's a couple stub files.</p>\n\n<p><strong>uploadForm.html</strong></p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n &lt;form action=\"processStuff.php\" enctype=\"multipart/form-data\" method=\"POST\"&gt;\n username: &lt;input type=\"text\" name=\"username\" /&gt;\n password: &lt;input type=\"password\" name=\"password\" /&gt;\n\n &lt;p&gt;\n &lt;input type=\"file\" name=\"uploadFile[]\" /&gt;&lt;br /&gt;\n &lt;input type=\"file\" name=\"uploadFile[]\" /&gt;&lt;br /&gt;\n &lt;input type=\"file\" name=\"uploadFile[]\" /&gt;&lt;br /&gt;\n &lt;!-- Add as many of these as you want --&gt;\n &lt;/p&gt;\n\n &lt;p&gt;\n &lt;input type=\"submit\" /&gt;\n &lt;/p&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p><strong>processStuff.php</strong></p>\n\n<pre><code>&lt;pre&gt;\n&lt;?php\n\n echo '&lt;h2&gt;Username &amp; password&lt;/h2&gt;'\n echo \"Username: {$_POST['username']}\\nPassword: {$_POST['password']}\";\n echo '&lt;hr /&gt;';\n\n echo '&lt;h2&gt;Uploaded files&lt;/h2&gt;' \n foreach($_FILES['uploadFile']['tmp_name'] as $i =&gt; $tempUploadPath) {\n if (empty($tempUploadPath)) {\n // this &lt;input type=\"file\" /&gt; was \"blank\"... no file selected\n } else {\n // a file was uploaded\n echo '&lt;strong&gt;A file named \"', $_FILES['uploadFile']['name'][$i], \"\\\" was uploaded&lt;/strong&gt;\\n\";\n echo \"\\ttemporarily stored at: \", $tempUploadPath, \"\\n\"; \n echo \"\\tmime type: \", $_FILES['uploadFile']['type'][$i], \"\\n\";\n echo \"\\tsize: \", $_FILES['uploadFile']['size'][$i], \" bytes\\n\"; \n echo \"\\terror code\", \n ((empty($_FILES['uploadFile']['size'][$i]) \n ? '&lt;em&gt;no errror&lt;/em&gt;' \n : $_FILES['uploadFile']['size'][$i])), \n \"\\n\\n\";\n\n // do something useful with the uploaded file \n // access it via $tempUploadPath and use move_uploaded_file() to move \n // it out of the temp path before you manipulate it in any way!!!!!\n // see http://us3.php.net/features.file-upload\n // and http://us3.php.net/manual/en/function.move-uploaded-file.php\n } \n }\n\n?&gt;\n&lt;/pre&gt;\n</code></pre>\n\n<p>The HTML file shows how to set the <code>enctype</code> of the <code>&lt;form&gt;</code> &amp; the second form show you how to access the submitted username &amp; password &amp; finally how to loop thru every uploaded file.</p>\n\n<p>As noted you MUST move the file(s) ASAP. They're uploaded to a temp location and the system will delete them unless you deal with them. So move 'em somewhere first then do whatever you need w/ them.</p>\n\n<p>Hoep this helps</p>\n\n<p>Arin</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
How to post a username, password and multiple binary files from a single html form and process it using php? I'm not allowed to use ajax.
first off check out these pages on PHP.net 1. [file upload info](http://us3.php.net/features.file-upload) 2. [`move_uploaded_file`](http://us3.php.net/manual/en/function.move-uploaded-file.php) But to get you started here's a couple stub files. **uploadForm.html** ``` <html> <body> <form action="processStuff.php" enctype="multipart/form-data" method="POST"> username: <input type="text" name="username" /> password: <input type="password" name="password" /> <p> <input type="file" name="uploadFile[]" /><br /> <input type="file" name="uploadFile[]" /><br /> <input type="file" name="uploadFile[]" /><br /> <!-- Add as many of these as you want --> </p> <p> <input type="submit" /> </p> </form> </body> </html> ``` **processStuff.php** ``` <pre> <?php echo '<h2>Username & password</h2>' echo "Username: {$_POST['username']}\nPassword: {$_POST['password']}"; echo '<hr />'; echo '<h2>Uploaded files</h2>' foreach($_FILES['uploadFile']['tmp_name'] as $i => $tempUploadPath) { if (empty($tempUploadPath)) { // this <input type="file" /> was "blank"... no file selected } else { // a file was uploaded echo '<strong>A file named "', $_FILES['uploadFile']['name'][$i], "\" was uploaded</strong>\n"; echo "\ttemporarily stored at: ", $tempUploadPath, "\n"; echo "\tmime type: ", $_FILES['uploadFile']['type'][$i], "\n"; echo "\tsize: ", $_FILES['uploadFile']['size'][$i], " bytes\n"; echo "\terror code", ((empty($_FILES['uploadFile']['size'][$i]) ? '<em>no errror</em>' : $_FILES['uploadFile']['size'][$i])), "\n\n"; // do something useful with the uploaded file // access it via $tempUploadPath and use move_uploaded_file() to move // it out of the temp path before you manipulate it in any way!!!!! // see http://us3.php.net/features.file-upload // and http://us3.php.net/manual/en/function.move-uploaded-file.php } } ?> </pre> ``` The HTML file shows how to set the `enctype` of the `<form>` & the second form show you how to access the submitted username & password & finally how to loop thru every uploaded file. As noted you MUST move the file(s) ASAP. They're uploaded to a temp location and the system will delete them unless you deal with them. So move 'em somewhere first then do whatever you need w/ them. Hoep this helps Arin
137,753
<p>I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas?</p>
[ { "answer_id": 137762, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>Hash based collections (Dictionary, Hashtable, HashSet) are out because you won't have an index, since you want an index, I'd use a nested generic:</p>\n\n<pre><code>List&lt;KeyValuePair&lt;K,V&gt;&gt;\n</code></pre>\n\n<p>Of course, you lose the O(1) Key lookup that you get with hashes.</p>\n" }, { "answer_id": 137772, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>There's System.Collections.ObjectModel.<strong>KeyedCollection&lt; string,TItem></strong>, which derives from Collection&lt; TItem>. <strong>Retrieval is O(1)</strong>.</p>\n\n<pre><code>class IndexableDictionary&lt;TItem&gt; : KeyedCollection&lt;string, TItem&gt;\n { Dictionary&lt;TItem, string&gt; keys = new Dictionary&lt;TItem, string&gt;();\n\n protected override string GetKeyForItem(TItem item) { return keys[item];}\n\n public void Add(string key, TItem item) \n { keys[item] = key;\n this.Add(item);\n }\n }\n</code></pre>\n" }, { "answer_id": 137864, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": -1, "selected": false, "text": "<p>You are looking for something like the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.sortedlist(VS.71).aspx\" rel=\"nofollow noreferrer\">SortedList class</a> (here's the <a href=\"http://msdn.microsoft.com/en-us/library/ms132319.aspx\" rel=\"nofollow noreferrer\">generic version</a> as well).</p>\n" }, { "answer_id": 137883, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "<p>You want the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx\" rel=\"nofollow noreferrer\">OrderedDictionary</a> class. You will need to include the System.Collections.Specialized namespace:</p>\n\n<pre><code> OrderedDictionary od = new OrderedDictionary(); \n od.Add(\"abc\", 1); \n od.Add(\"def\", 2); \n od.Add(\"ghi\", 3); \n od.Add(\"jkl\", 4); \n\n // Can access via index or key value: \n Console.WriteLine(od[1]); \n Console.WriteLine(od[\"def\"]);\n</code></pre>\n" }, { "answer_id": 138259, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>One word of warning. The <code>OrderedDictionary</code> has really <strong>bad performance characteristics</strong> for most operations except insertion and lookup: Both removal and modification of a value may require a linear search of the whole list, resulting in runtime <em>O</em>(<em>n</em>). (For modification, this depends on whether access occurred by index or by key.)</p>\n\n<p>For most operations with reasonable amounts of data, this is completely inacceptable. Furthermore, the data structure stores elements both in a linear vector and in a hash table, resulting in some memory overhead.</p>\n\n<p>If retrieval by index doesn't happen too often, a <strong><code>SortedList</code></strong> or <strong><code>SortedDictionary</code></strong> will have much better performance characteristics (access by index can be achieved through the <code>ElementAt</code> extension method).</p>\n\n<p>If, on the other hand, access by index is the norm, then stop using dictionary data structures alltogether and simply store your values in a <strong><code>List&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;</code></strong>. Although this means a linear search for access by key, all other operations are very cheap and overall performance is hard to beat in practice.</p>\n\n<p>/EDIT: Of course, the latter is also a dictionary data structure in the theoretical sense. You could even encapsulate it in a class implementing the appropriate interface.</p>\n" }, { "answer_id": 138264, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>A Dictionary could work with linq. Although i dont know about possible performance issues. Dictionary.ElementAt(index);</p>\n" }, { "answer_id": 139478, "author": "Magnus Akselvoll", "author_id": 4683, "author_profile": "https://Stackoverflow.com/users/4683", "pm_score": 0, "selected": false, "text": "<p>I recommend using SortedDictionary&lt;string, TValue&gt; or SortedList&lt;string, TValue&gt;. Both have O(log n) search performance.</p>\n\n<p>The differences are, as quoted from\nthe <a href=\"http://msdn.microsoft.com/en-us/library/f7fta44c.aspx\" rel=\"nofollow noreferrer\">MSDN library</a>:</p>\n\n<blockquote>\n <p>SortedList&lt;(Of\n &lt;(TKey, TValue>)>) uses less memory\n than SortedDictionary&lt;(Of &lt;(TKey,\n TValue>)>).</p>\n \n <p>SortedDictionary&lt;(Of &lt;(TKey,\n TValue>)>) has faster insertion and\n removal operations for unsorted data:\n O(log n) as opposed to O(n) for\n SortedList&lt;(Of &lt;(TKey, TValue>)>).</p>\n \n <p>If the list is populated all at once\n from sorted data, SortedList&lt;(Of\n &lt;(TKey, TValue>)>) is faster than\n SortedDictionary&lt;(Of &lt;(TKey,\n TValue>)>).</p>\n</blockquote>\n\n<p>In my experience SortedDictionary is more adequate for most typical business scenarios, since the data is usually initially unsorted when using structures like this, and the memory overhead of SortedDictionary is seldom critical. But if performance is key for you, I suggest you implement both and do measurements.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas?
You want the [OrderedDictionary](http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx) class. You will need to include the System.Collections.Specialized namespace: ``` OrderedDictionary od = new OrderedDictionary(); od.Add("abc", 1); od.Add("def", 2); od.Add("ghi", 3); od.Add("jkl", 4); // Can access via index or key value: Console.WriteLine(od[1]); Console.WriteLine(od["def"]); ```
137,773
<p>In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs:</p> <pre><code>./authpam: /lib/libpam.so.0: no version information available (required by authpam) </code></pre> <p>The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning.</p> <p>I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :(</p> <p>Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem?</p> <p>Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc?</p>
[ { "answer_id": 137810, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>Have you seen <a href=\"http://answers.google.com/answers/threadview/id/786136.html\" rel=\"nofollow noreferrer\">this</a> already? The cause seems to be a very old libpam on one of the sides, probably on that customer.</p>\n\n<p>Or the links for the version might be missing : <a href=\"http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html\" rel=\"nofollow noreferrer\">http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html</a></p>\n" }, { "answer_id": 156387, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 6, "selected": false, "text": "<p>The \"no version information available\" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.</p>\n\n<p>You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.</p>\n\n<p>Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)</p>\n\n<p>Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)</p>\n\n<p>You last option will be compiling with a library with a different minor version number, using a custom linking script:\n<a href=\"http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html\" rel=\"noreferrer\">http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html</a></p>\n\n<p>To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.</p>\n" }, { "answer_id": 156442, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "<p>How are you compiling your app? What compiler flags?</p>\n\n<p>In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.</p>\n" }, { "answer_id": 3387789, "author": "Dieter_be", "author_id": 408644, "author_profile": "https://Stackoverflow.com/users/408644", "pm_score": 2, "selected": false, "text": "<p>Fwiw, I had this problem when running check_nrpe on a system that had the zenoss monitoring system installed. To add to the confusion, it worked fine as root user but not as zenoss user.</p>\n\n<p>I found out that the zenoss user had an LD_LIBRARY_PATH that caused it to use zenoss libraries, which issue these warnings. Ie:</p>\n\n<pre><code>root@monitoring:$ echo $LD_LIBRARY_PATH\n\nsu - zenoss\nzenoss@monitoring:/root$ echo $LD_LIBRARY_PATH\n/usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib::\nzenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq\n/usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8)\n(...)\nzenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq\n(...)\n</code></pre>\n\n<p>So anyway, what I'm trying to say: check your variables like LD_LIBRARY_PATH, LD_PRELOAD etc as well.</p>\n" }, { "answer_id": 38851073, "author": "Roman Khimov", "author_id": 165063, "author_profile": "https://Stackoverflow.com/users/165063", "pm_score": 5, "selected": false, "text": "<p>What this message from the glibc dynamic linker actually means is that the library mentioned (<code>/lib/libpam.so.0</code> in your case) doesn't have the <code>VERDEF</code> ELF section while the binary (<code>authpam</code> in your case) has some version definitions in <code>VERNEED</code> section for this library (presumably, <code>libpam.so.0</code>). You can easily see it with <code>readelf</code>, just look at <code>.gnu.version_d</code> and <code>.gnu.version_r</code> sections (or lack thereof).</p>\n\n<p>So it's not a symbol version mismatch, because if the binary wanted to get some specific version via <code>VERNEED</code> and the library didn't provide it in its actual <code>VERDEF</code>, that would be a hard linker error and the binary wouldn't run at all (like <a href=\"https://stackoverflow.com/questions/37802196/libcrypto-so-1-0-0-version-openssl-1-0-1-not-found-during-shell-exec\">this</a> compared to <a href=\"https://stackoverflow.com/questions/33564563/how-to-solve-ssh-usr-lib64-libcrypto-so-10-no-version-information-available\">this</a> or <a href=\"https://stackoverflow.com/questions/18390833/no-version-information-available\">that</a>). It's that the binary wants some versions, but the library doesn't provide any information about its versions.</p>\n\n<p>What does it mean in practice? Usually, exactly what is seen in this example &mdash; nothing, things just work ignoring versioning. Could things break? Of course, yes, so the other answers are correct in the fact that one should use the same libraries at runtime as the ones the binary was linked to at build time.</p>\n\n<p>More information could be found in Ulrich Dreppers <a href=\"https://www.akkadia.org/drepper/symbol-versioning\" rel=\"noreferrer\">\"ELF Symbol Versioning\"</a>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs: ``` ./authpam: /lib/libpam.so.0: no version information available (required by authpam) ``` The application runs fine and executes code from the dynamic library. So this is not a fatal error, it's really just a warning. I figure that this is error comes from the dynamic linker when the system installed library is missing something our executable expects. I don't know much about the internals of the dynamic linking process ... and googling the topic doesn't help much. :( Anyone know what causes this error? ... how I can diagnose the cause? ... and how we could change our executables to avoid this problem? Update: The customer upgraded to the latest version of debian "testing" and the same error occurred. So it's not an out of date libpam library. I guess I'd like to understand what the linker is complaining about? How can I investigate the underlying cause, etc?
The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning. You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers. Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.) Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.) You last option will be compiling with a library with a different minor version number, using a custom linking script: <http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html> To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.
137,775
<p>I've wanted this for fluent interfaces. See, for example <a href="http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/" rel="nofollow noreferrer">this</a> Channel9 discussion. Would probably <a href="http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx" rel="nofollow noreferrer">require</a> also adding indexed properties.</p> <p>What are your thoughts? Would the advantages outweigh the "language clutter"?</p>
[ { "answer_id": 137787, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": false, "text": "<p>Since properties are just syntactic sugar for methods, I don't see why C# should have extension methods without extension properties.</p>\n" }, { "answer_id": 137788, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>I don't know why not. Properties are just getter/setter methods with differant syntax.</p>\n" }, { "answer_id": 137789, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 1, "selected": false, "text": "<p>I guess it would be great, as long as there's no or minimal performance penalty in using them.</p>\n" }, { "answer_id": 137796, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>Would definately add to the repertoire of tools at our disposal. </p>\n\n<p>Now as for my opinion, yes they should, but like anything, developers need to use it properly and when needed. Like most new features, a lot of dev's use them without fully understanding them and when/how/where/how best to use them. I know I get sucked into this sometimes too.</p>\n\n<p>But ya, sure, bring it on. I could see myself using it in certain scenarios</p>\n" }, { "answer_id": 137819, "author": "J Healy", "author_id": 5946, "author_profile": "https://Stackoverflow.com/users/5946", "pm_score": 0, "selected": false, "text": "<p>I'm guessing indexed properties will be a mere stocking stuffer among a large bag of of significant enhancements we'll be seeing in 4.0.</p>\n" }, { "answer_id": 137882, "author": "foson", "author_id": 22539, "author_profile": "https://Stackoverflow.com/users/22539", "pm_score": 2, "selected": false, "text": "<p>I don't think extension properties would be nearly as useful. I find myself mostly using properties to encapsulate fields (classic get; set;) or to provide read only goodness (just a get on a private, readonly, contructor-set field). Since extensions can't access private members, I don't really see the point, especially for \"set;\". To do anything, \"set;\" would just have to call other methods anyway. Then you run into the issue of properties throwing exceptions. <br>\nSince extensions are limited to using public properties and methods, I find it cleaner and easier to read code that uses a utility class. When it comes down to it, we are using extension methods to make LINQ look pretty. To keep developers from doing the wrong thing, I can deal with an extra () here and there in my LINQ and stick to just extension methods. </p>\n" }, { "answer_id": 137891, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": -1, "selected": false, "text": "<p>No, a property is just a way to hide what has really been generated for the code. If you look at the reflected code or the IL you can determine what you're really getting and it is the following:</p>\n\n<pre><code>public string MyProperty { get; set; }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public string get_MyProperty(){ return &lt;some generated variable&gt;; }\npublic string set_MyProperty(string value) { &lt;some generated variable&gt; = value; }\n</code></pre>\n\n<p>It's just 2 methods.</p>\n" }, { "answer_id": 137948, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 1, "selected": false, "text": "<p>Seems like it could be easily misused. As others have mentioned, C# properties are just syntactic sugar for methods. However, implementing those as properties has certain connotations: accessing won't have side effects and modifying a property should be very inexpensive. The latter point is crucial as it seems like extension properties will almost always be more expensive than conventional properties.</p>\n" }, { "answer_id": 619112, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 3, "selected": false, "text": "<p>It's about databinding, let's say I have an object for binding to my UI and I want to hide show it based on other properties of the object. I could add an extension property for IsVisible or Visibility and bind that property to the UI.</p>\n\n<p>You can't bind extension methods, but being able to add properties for databinding to existing types you can't extend could be very useful.</p>\n" }, { "answer_id": 1884696, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 4, "selected": true, "text": "<p>In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to</p>\n\n<pre><code>public bool IsInTransaction\n{\n get { return _session.Is().Not.Null &amp;&amp; _session.Is().InTransaction; }\n}\n</code></pre>\n\n<p>Which looks very stupid that Is must be a method as there is no way for me to insert the Is as a property unless I directly modify the source on the session object.</p>\n" }, { "answer_id": 2008371, "author": "alpav", "author_id": 195446, "author_profile": "https://Stackoverflow.com/users/195446", "pm_score": 0, "selected": false, "text": "<p>Developers should use properties to organize hierarchy of names and avoid name concatenation with camel casing or underscores.\nFor example, instead of HttpUtility.UrlDecode they should extend string class to use something like \"some str\".decode.url\nCurrently the only way to do it in C# is this: \"some str\".decode().url</p>\n" }, { "answer_id": 2043128, "author": "JHiller", "author_id": 33127, "author_profile": "https://Stackoverflow.com/users/33127", "pm_score": 1, "selected": false, "text": "<p>Would be a nice thing to have, but I see many people saying they want it for data binding which isn't possible since it's using reflection.</p>\n" }, { "answer_id": 3230054, "author": "Turing Complete", "author_id": 372920, "author_profile": "https://Stackoverflow.com/users/372920", "pm_score": 0, "selected": false, "text": "<p>Yes, please.</p>\n\n<p>And also add indexed properties and STATIC extension stuff, because I SERIOUSLY want that for System.Console (this is not meant as a joke!).</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22528/" ]
I've wanted this for fluent interfaces. See, for example [this](http://channel9.msdn.com/forums/Coffeehouse/257556-C-Extension-Properties/) Channel9 discussion. Would probably [require](http://ayende.com/Blog/archive/2007/12/02/Why-C-doesnt-have-extension-properties.aspx) also adding indexed properties. What are your thoughts? Would the advantages outweigh the "language clutter"?
In my book the #1 most substantial reason for extension properties is implementing fluent interface patterns around unowned code. I built a wrapper around the NHibernate session to make it more intitutive to work with so I can do logic similar to ``` public bool IsInTransaction { get { return _session.Is().Not.Null && _session.Is().InTransaction; } } ``` Which looks very stupid that Is must be a method as there is no way for me to insert the Is as a property unless I directly modify the source on the session object.
137,783
<p>Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.</p>
[ { "answer_id": 137807, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": false, "text": "<p>Are homework problems allowed here?</p>\n\n<p>This function does crude \"base 5\" math to generate a number between 0 and 6.</p>\n\n<pre><code>function rnd7() {\n do {\n r1 = rnd5() - 1;\n do {\n r2=rnd5() - 1;\n } while (r2 &gt; 1);\n result = r2 * 5 + r1;\n } while (result &gt; 6);\n return result + 1;\n}\n</code></pre>\n" }, { "answer_id": 137809, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 9, "selected": false, "text": "<p>There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.:</p>\n\n<pre><code>\nint i;\ndo\n{\n i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25\n} while(i > 21);\n// i is now uniformly random between 1 and 21\nreturn i % 7 + 1; // result is now uniformly random between 1 and 7\n</code></pre>\n\n<p>This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever.</p>\n" }, { "answer_id": 137823, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 4, "selected": false, "text": "<pre><code>int ans = 0;\nwhile (ans == 0) \n{\n for (int i=0; i&lt;3; i++) \n {\n while ((r = rand5()) == 3){};\n ans += (r &lt; 3) &gt;&gt; i\n }\n}\n</code></pre>\n" }, { "answer_id": 137833, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 4, "selected": false, "text": "<pre><code>rand7() = (rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5())%7+1\n</code></pre>\n\n<p>Edit: That doesn't quite work. It's off by about 2 parts in 1000 (assuming a perfect rand5). The buckets get:</p>\n\n<pre><code>value Count Error%\n1 11158 -0.0035\n2 11144 -0.0214\n3 11144 -0.0214\n4 11158 -0.0035\n5 11172 +0.0144\n6 11177 +0.0208\n7 11172 +0.0144\n</code></pre>\n\n<p>By switching to a sum of</p>\n\n<pre><code>n Error%\n10 +/- 1e-3,\n12 +/- 1e-4,\n14 +/- 1e-5,\n16 +/- 1e-6,\n...\n28 +/- 3e-11\n</code></pre>\n\n<p>seems to gain an order of magnitude for every 2 added</p>\n\n<p>BTW: the table of errors above was not generated via sampling but by the following recurrence relation:</p>\n\n<blockquote>\n <p><code>p[x,n]</code> is the number ways <code>output=x</code> can happen given <code>n</code> calls to <code>rand5</code>.</p>\n</blockquote>\n\n<pre><code> p[1,1] ... p[5,1] = 1\n p[6,1] ... p[7,1] = 0\n\n p[1,n] = p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1]\n p[2,n] = p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1] + p[4,n-1]\n p[3,n] = p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1] + p[5,n-1]\n p[4,n] = p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1] + p[6,n-1]\n p[5,n] = p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1] + p[7,n-1]\n p[6,n] = p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1] + p[1,n-1]\n p[7,n] = p[6,n-1] + p[5,n-1] + p[4,n-1] + p[3,n-1] + p[2,n-1]\n</code></pre>\n" }, { "answer_id": 137862, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>int randbit( void )\n{\n while( 1 )\n {\n int r = rand5();\n if( r &lt;= 4 ) return(r &amp; 1);\n }\n}\n\nint randint( int nbits )\n{\n int result = 0;\n while( nbits-- )\n {\n result = (result&lt;&lt;1) | randbit();\n }\n return( result );\n}\n\nint rand7( void )\n{\n while( 1 )\n {\n int r = randint( 3 ) + 1;\n if( r &lt;= 7 ) return( r );\n }\n}\n</code></pre>\n" }, { "answer_id": 324595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>solution in php</p>\n\n<pre><code>&lt;?php\nfunction random_5(){\n return rand(1,5);\n}\n\n\nfunction random_7(){\n $total = 0;\n\n for($i=0;$i&lt;7;$i++){\n $total += random_5();\n }\n\n return ($total%7)+1; \n}\n\necho random_7();\n?&gt;\n</code></pre>\n" }, { "answer_id": 445623, "author": "jason", "author_id": 45914, "author_profile": "https://Stackoverflow.com/users/45914", "pm_score": 4, "selected": false, "text": "<p>The following produces a uniform distribution on {1, 2, 3, 4, 5, 6, 7} using a random number generator producing a uniform distribution on {1, 2, 3, 4, 5}. The code is messy, but the logic is clear.</p>\n\n<pre><code>public static int random_7(Random rg) {\n int returnValue = 0;\n while (returnValue == 0) {\n for (int i = 1; i &lt;= 3; i++) {\n returnValue = (returnValue &lt;&lt; 1) + SimulateFairCoin(rg);\n }\n }\n return returnValue;\n}\n\nprivate static int SimulateFairCoin(Random rg) {\n while (true) {\n int flipOne = random_5_mod_2(rg);\n int flipTwo = random_5_mod_2(rg);\n\n if (flipOne == 0 &amp;&amp; flipTwo == 1) {\n return 0;\n }\n else if (flipOne == 1 &amp;&amp; flipTwo == 0) {\n return 1;\n }\n }\n}\n\nprivate static int random_5_mod_2(Random rg) {\n return random_5(rg) % 2;\n}\n\nprivate static int random_5(Random rg) {\n return rg.Next(5) + 1;\n} \n</code></pre>\n" }, { "answer_id": 806137, "author": "Joshua Fox", "author_id": 39242, "author_profile": "https://Stackoverflow.com/users/39242", "pm_score": 3, "selected": false, "text": "<p>Assuming that <strong>rand(n)</strong> here means \"random integer in a uniform distribution from <strong>0</strong> to <strong>n-1</strong>\", here's a code sample using Python's randint, which has that effect. It uses only <strong>randint(5)</strong>, and constants, to produce the effect of <strong>randint(7)</strong>. A little silly, actually</p>\n\n<pre><code>from random import randint\nsum = 7\nwhile sum &gt;= 7:\n first = randint(0,5) \n toadd = 9999\n while toadd&gt;1:\n toadd = randint(0,5)\n if toadd:\n sum = first+5\n else:\n sum = first\n\nassert 7&gt;sum&gt;=0 \nprint sum\n</code></pre>\n" }, { "answer_id": 807033, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 5, "selected": false, "text": "<p>(I have stolen <a href=\"https://stackoverflow.com/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun/137809#137809\">Adam Rosenfeld's answer</a> and made it run about 7% faster.)</p>\n\n<p>Assume that rand5() returns one of {0,1,2,3,4} with equal distribution and the goal is return {0,1,2,3,4,5,6} with equal distribution.</p>\n\n<pre><code>int rand7() {\n i = 5 * rand5() + rand5();\n max = 25;\n //i is uniform among {0 ... max-1}\n while(i &lt; max%7) {\n //i is uniform among {0 ... (max%7 - 1)}\n i *= 5;\n i += rand5(); //i is uniform {0 ... (((max%7)*5) - 1)}\n max %= 7;\n max *= 5; //once again, i is uniform among {0 ... max-1}\n }\n return(i%7);\n}\n</code></pre>\n\n<p>We're keeping track of the largest value that the loop can make in the variable <code>max</code>. If the reult so far is between max%7 and max-1 then the result will be uniformly distrubuted in that range. If not, we use the remainder, which is random between 0 and max%7-1, and another call to rand() to make a new number and a new max. Then we start again.</p>\n\n<p>Edit: Expect number of times to call rand5() is x in this equation:</p>\n\n<pre><code>x = 2 * 21/25\n + 3 * 4/25 * 14/20\n + 4 * 4/25 * 6/20 * 28/30\n + 5 * 4/25 * 6/20 * 2/30 * 7/10\n + 6 * 4/25 * 6/20 * 2/30 * 3/10 * 14/15\n + (6+x) * 4/25 * 6/20 * 2/30 * 3/10 * 1/15\nx = about 2.21 calls to rand5()\n</code></pre>\n" }, { "answer_id": 807434, "author": "Patrick Hogan", "author_id": 4065, "author_profile": "https://Stackoverflow.com/users/4065", "pm_score": -1, "selected": false, "text": "<p>A constant time solution that produces approximately uniform distribution. <s>The trick is 625 happens to be cleanly divisible by 7 and you can get uniform distributions as you build up to that range.</s> </p>\n\n<p><b>Edit:</b> My bad, I miscalculated, but instead of pulling it I'll leave it in case someone finds it useful/entertaining. It <i>does</i> actually work after all... :)</p>\n\n<pre><code>int rand5()\n{\n return (rand() % 5) + 1;\n}\n\nint rand25()\n{ \n return (5 * (rand5() - 1) + rand5());\n}\n\nint rand625()\n{\n return (25 * (rand25() - 1) + rand25());\n}\n\nint rand7()\n{\n return ((625 * (rand625() - 1) + rand625()) - 1) % 7 + 1;\n}\n</code></pre>\n" }, { "answer_id": 808183, "author": "mangokun", "author_id": 59389, "author_profile": "https://Stackoverflow.com/users/59389", "pm_score": -1, "selected": false, "text": "<pre><code>int rand7()\n{\n int zero_one_or_two = ( rand5() + rand5() - 1 ) % 3 ;\n return rand5() + zero_one_or_two ;\n}\n</code></pre>\n" }, { "answer_id": 808199, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": -1, "selected": false, "text": "<p>I feel stupid in front of all this complicated answsers.</p>\n\n<p>Why can't it be :</p>\n\n<pre><code>int random1_to_7()\n{\n return (random1_to_5() * 7) / 5; \n}\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 808267, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": -1, "selected": false, "text": "<pre><code>#!/usr/bin/env ruby\nclass Integer\n def rand7\n rand(6)+1\n end\nend\n\ndef rand5\n rand(4)+1\nend\n\nx = rand5() # x =&gt; int between 1 and 5\n\ny = x.rand7() # y =&gt; int between 1 and 7\n</code></pre>\n\n<p>..although that may possibly be considered cheating..</p>\n" }, { "answer_id": 816738, "author": "Peter Stegnar", "author_id": 99422, "author_profile": "https://Stackoverflow.com/users/99422", "pm_score": -1, "selected": false, "text": "<p>I have played around and I write <a href=\"http://gist.github.com/105929\" rel=\"nofollow noreferrer\">\"testing environment\"</a> for this Rand(7) algorithm. For example if you want to try what distribution gives your algorithm or how much iterations takes to generate all distinct random values (for Rand(7) 1-7), you <a href=\"http://gist.github.com/105929\" rel=\"nofollow noreferrer\">can use it</a>.</p>\n\n<p>My core algorithm is this:</p>\n\n<pre><code>return (Rand5() + Rand5()) % 7 + 1;\n</code></pre>\n\n<p>Well is no less uniformly distributed then Adam Rosenfield's one. (<a href=\"http://gist.github.com/105929\" rel=\"nofollow noreferrer\">which I included in my snippet code</a>)</p>\n\n<pre><code>private static int Rand7WithRand5()\n{\n //PUT YOU FAVOURITE ALGORITHM HERE//\n\n //1. Stackoverflow winner\n int i;\n do\n {\n i = 5 * (Rand5() - 1) + Rand5(); // i is now uniformly random between 1 and 25\n } while (i &gt; 21);\n // i is now uniformly random between 1 and 21\n return i % 7 + 1;\n\n //My 2 cents\n //return (Rand5() + Rand5()) % 7 + 1;\n}\n</code></pre>\n\n<p>This \"testing environment\" can take any Rand(n) algorithm and test and evaluate it (distribution and speed). Just put your code into the \"Rand7WithRand5\" method and run the snippet.</p>\n\n<p>Few observations:</p>\n\n<ul>\n<li>Adam Rosenfield's algorithm is no better distributed then, for example, mine. Anyway, both algorithms distribution is horrible.</li>\n<li>Native Rand7 (<code>random.Next(1, 8)</code>) is completed as it generated all members in given interval in around 200+ iterations, Rand7WithRand5 algorithms take order of 10k (around 30-70k)</li>\n<li>Real challenge is not to write a method to generate Rand(7) from Rand(5), but it generate values more or less uniformly distributed.</li>\n</ul>\n" }, { "answer_id": 818817, "author": "James McMahon", "author_id": 20774, "author_profile": "https://Stackoverflow.com/users/20774", "pm_score": 3, "selected": false, "text": "<p>Here is a working Python implementation of <a href=\"https://stackoverflow.com/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun/137809#137809\">Adam's answer</a>.</p>\n\n<pre><code>import random\n\ndef rand5():\n return random.randint(1, 5)\n\ndef rand7():\n while True:\n r = 5 * (rand5() - 1) + rand5()\n #r is now uniformly random between 1 and 25\n if (r &lt;= 21):\n break\n #result is now uniformly random between 1 and 7\n return r % 7 + 1\n</code></pre>\n\n<p>I like to throw algorithms I'm looking at into Python so I can play around with them, thought I'd post it here in the hopes that it is useful to someone out there, not that it took long to throw together.</p>\n" }, { "answer_id": 832809, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>By using a <em>rolling total</em>, you can both</p>\n\n<ul>\n<li>maintain an equal distribution; and</li>\n<li>not have to sacrifice any element in the random sequence.</li>\n</ul>\n\n<p>Both these problems are an issue with the simplistic <code>rand(5)+rand(5)...</code>-type solutions. The following Python code shows how to implement it (most of this is proving the distribution).</p>\n\n<pre><code>import random\nx = []\nfor i in range (0,7):\n x.append (0)\nt = 0\ntt = 0\nfor i in range (0,700000):\n ########################################\n ##### qq.py #####\n r = int (random.random () * 5)\n t = (t + r) % 7\n ########################################\n ##### qq_notsogood.py #####\n #r = 20\n #while r &gt; 6:\n #r = int (random.random () * 5)\n #r = r + int (random.random () * 5)\n #t = r\n ########################################\n x[t] = x[t] + 1\n tt = tt + 1\nhigh = x[0]\nlow = x[0]\nfor i in range (0,7):\n print \"%d: %7d %.5f\" % (i, x[i], 100.0 * x[i] / tt)\n if x[i] &lt; low:\n low = x[i]\n if x[i] &gt; high:\n high = x[i]\ndiff = high - low\nprint \"Variation = %d (%.5f%%)\" % (diff, 100.0 * diff / tt)\n</code></pre>\n\n<p>And this output shows the results:</p>\n\n<pre><code>pax$ python qq.py\n0: 99908 14.27257\n1: 100029 14.28986\n2: 100327 14.33243\n3: 100395 14.34214\n4: 99104 14.15771\n5: 99829 14.26129\n6: 100408 14.34400\nVariation = 1304 (0.18629%)\n\npax$ python qq.py\n0: 99547 14.22100\n1: 100229 14.31843\n2: 100078 14.29686\n3: 99451 14.20729\n4: 100284 14.32629\n5: 100038 14.29114\n6: 100373 14.33900\nVariation = 922 (0.13171%)\n\npax$ python qq.py\n0: 100481 14.35443\n1: 99188 14.16971\n2: 100284 14.32629\n3: 100222 14.31743\n4: 99960 14.28000\n5: 99426 14.20371\n6: 100439 14.34843\nVariation = 1293 (0.18471%)\n</code></pre>\n\n<p>A simplistic <code>rand(5)+rand(5)</code>, ignoring those cases where this returns more than 6 has a typical variation of 18%, <em>100 times</em> that of the method shown above:</p>\n\n<pre><code>pax$ python qq_notsogood.py\n0: 31756 4.53657\n1: 63304 9.04343\n2: 95507 13.64386\n3: 127825 18.26071\n4: 158851 22.69300\n5: 127567 18.22386\n6: 95190 13.59857\nVariation = 127095 (18.15643%)\n\npax$ python qq_notsogood.py\n0: 31792 4.54171\n1: 63637 9.09100\n2: 95641 13.66300\n3: 127627 18.23243\n4: 158751 22.67871\n5: 126782 18.11171\n6: 95770 13.68143\nVariation = 126959 (18.13700%)\n\npax$ python qq_notsogood.py\n0: 31955 4.56500\n1: 63485 9.06929\n2: 94849 13.54986\n3: 127737 18.24814\n4: 159687 22.81243\n5: 127391 18.19871\n6: 94896 13.55657\nVariation = 127732 (18.24743%)\n</code></pre>\n\n<p>And, on the advice of Nixuz, I've cleaned the script up so you can just extract and use the <code>rand7...</code> stuff:</p>\n\n<pre><code>import random\n\n# rand5() returns 0 through 4 inclusive.\n\ndef rand5():\n return int (random.random () * 5)\n\n# rand7() generator returns 0 through 6 inclusive (using rand5()).\n\ndef rand7():\n rand7ret = 0\n while True:\n rand7ret = (rand7ret + rand5()) % 7\n yield rand7ret\n\n# Number of test runs.\n\ncount = 700000\n\n# Work out distribution.\n\ndistrib = [0,0,0,0,0,0,0]\nrgen =rand7()\nfor i in range (0,count):\n r = rgen.next()\n distrib[r] = distrib[r] + 1\n\n# Print distributions and calculate variation.\n\nhigh = distrib[0]\nlow = distrib[0]\nfor i in range (0,7):\n print \"%d: %7d %.5f\" % (i, distrib[i], 100.0 * distrib[i] / count)\n if distrib[i] &lt; low:\n low = distrib[i]\n if distrib[i] &gt; high:\n high = distrib[i]\ndiff = high - low\nprint \"Variation = %d (%.5f%%)\" % (diff, 100.0 * diff / count)\n</code></pre>\n" }, { "answer_id": 842183, "author": "Rob McAfee", "author_id": 103834, "author_profile": "https://Stackoverflow.com/users/103834", "pm_score": 9, "selected": false, "text": "<p>This is equivalent to Adam Rosenfield's solution, but may be a bit more clear for some readers. It assumes rand5() is a function that returns a statistically random integer in the range 1 through 5 inclusive.</p>\n\n<pre><code>int rand7()\n{\n int vals[5][5] = {\n { 1, 2, 3, 4, 5 },\n { 6, 7, 1, 2, 3 },\n { 4, 5, 6, 7, 1 },\n { 2, 3, 4, 5, 6 },\n { 7, 0, 0, 0, 0 }\n };\n\n int result = 0;\n while (result == 0)\n {\n int i = rand5();\n int j = rand5();\n result = vals[i-1][j-1];\n }\n return result;\n}\n</code></pre>\n\n<p>How does it work? Think of it like this: imagine printing out this double-dimension array on paper, tacking it up to a dart board and randomly throwing darts at it. If you hit a non-zero value, it's a statistically random value between 1 and 7, since there are an equal number of non-zero values to choose from. If you hit a zero, just keep throwing the dart until you hit a non-zero. That's what this code is doing: the i and j indexes randomly select a location on the dart board, and if we don't get a good result, we keep throwing darts.</p>\n\n<p>Like Adam said, this can run forever in the worst case, but statistically the worst case never happens. :)</p>\n" }, { "answer_id": 842343, "author": "Ivan", "author_id": 103673, "author_profile": "https://Stackoverflow.com/users/103673", "pm_score": 4, "selected": false, "text": "<p>If we consider the additional constraint of trying to give the most efficient answer i.e one that given an input stream, <code>I</code>, of uniformly distributed integers of length <code>m</code> from 1-5 outputs a stream <code>O</code>, of uniformly distributed integers from 1-7 of the longest length relative to <code>m</code>, say <code>L(m)</code>. </p>\n\n<p>The simplest way to analyse this is to treat the streams I and <code>O</code> as 5-ary and 7-ary numbers respectively. This is achieved by the main answer's idea of taking the stream <code>a1, a2, a3,... -&gt; a1+5*a2+5^2*a3+..</code> and similarly for stream <code>O</code>.</p>\n\n<p>Then if we take a section of the input stream of length <code>m choose n s.t. 5^m-7^n=c</code> where <code>c&gt;0</code> and is as small as possible. Then there is a uniform map from the input stream of length m to integers from <code>1</code> to <code>5^m</code> and another uniform map from integers from 1 to <code>7^n</code> to the output stream of length n where we may have to lose a few cases from the input stream when the mapped integer exceeds <code>7^n</code>.</p>\n\n<p>So this gives a value for <code>L(m)</code> of around <code>m (log5/log7)</code> which is approximately <code>.82m</code>.</p>\n\n<p>The difficulty with the above analysis is the equation <code>5^m-7^n=c</code> which is not easy to solve exactly and the case where the uniform value from <code>1</code> to <code>5^m</code> exceeds <code>7^n</code> and we lose efficiency. </p>\n\n<p>The question is how close to the best possible value of m (log5/log7) can be attain. For example when this number approaches close to an integer can we find a way to achieve this exact integral number of output values? </p>\n\n<p>If <code>5^m-7^n=c</code> then from the input stream we effectively generate a uniform random number from <code>0</code> to <code>(5^m)-1</code> and don't use any values higher than <code>7^n</code>. However these values can be rescued and used again. They effectively generate a uniform sequence of numbers from 1 to <code>5^m-7^n</code>. So we can then try to use these and convert them into 7-ary numbers so that we can create more output values. </p>\n\n<p>If we let <code>T7(X)</code> to be the average length of the output sequence of <code>random(1-7)</code> integers derived from a uniform input of size <code>X</code>, and assuming that <code>5^m=7^n0+7^n1+7^n2+...+7^nr+s, s&lt;7</code>.</p>\n\n<p>Then <code>T7(5^m)=n0x7^n0/5^m + ((5^m-7^n0)/5^m) T7(5^m-7^n0)</code> since we have a length no sequence with probability 7^n0/5^m with a residual of length <code>5^m-7^n0</code> with probability <code>(5^m-7^n0)/5^m)</code>.</p>\n\n<p>If we just keep substituting we obtain:</p>\n\n<pre><code>T7(5^m) = n0x7^n0/5^m + n1x7^n1/5^m + ... + nrx7^nr/5^m = (n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/5^m\n</code></pre>\n\n<p>Hence</p>\n\n<pre><code>L(m)=T7(5^m)=(n0x7^n0 + n1x7^n1 + ... + nrx7^nr)/(7^n0+7^n1+7^n2+...+7^nr+s)\n</code></pre>\n\n<p>Another way of putting this is:</p>\n\n<pre><code>If 5^m has 7-ary representation `a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r\nThen L(m) = (a1*7 + 2a2*7^2 + 3a3*7^3+...+rar*7^r)/(a0+a1*7 + a2*7^2 + a3*7^3+...+ar*7^r)\n</code></pre>\n\n<p>The best possible case is my original one above where <code>5^m=7^n+s</code>, where <code>s&lt;7</code>.</p>\n\n<p>Then <code>T7(5^m) = nx(7^n)/(7^n+s) = n+o(1) = m (Log5/Log7)+o(1)</code> as before.</p>\n\n<p>The worst case is when we can only find k and s.t 5^m = kx7+s.</p>\n\n<pre><code>Then T7(5^m) = 1x(k.7)/(k.7+s) = 1+o(1)\n</code></pre>\n\n<p>Other cases are somewhere inbetween. It would be interesting to see how well we can do for very large m, i.e. how good can we get the error term:</p>\n\n<pre><code>T7(5^m) = m (Log5/Log7)+e(m)\n</code></pre>\n\n<p>It seems impossible to achieve <code>e(m) = o(1)</code> in general but hopefully we can prove <code>e(m)=o(m)</code>.</p>\n\n<p>The whole thing then rests on the distribution of the 7-ary digits of <code>5^m</code> for various values of <code>m</code>.</p>\n\n<p>I'm sure there is a lot of theory out there that covers this I may have a look and report back at some point. </p>\n" }, { "answer_id": 859341, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 2, "selected": false, "text": "<p>This answer is more an experiment in obtaining the most entropy possible from the Rand5 function. t is therefore somewhat unclear and almost certainly a lot slower than other implementations.</p>\n\n<p>Assuming the uniform distribution from 0-4 and resulting uniform distribution from 0-6:</p>\n\n<pre><code>public class SevenFromFive\n{\n public SevenFromFive()\n {\n // this outputs a uniform ditribution but for some reason including it \n // screws up the output distribution\n // open question Why?\n this.fifth = new ProbabilityCondensor(5, b =&gt; {});\n this.eigth = new ProbabilityCondensor(8, AddEntropy);\n } \n\n private static Random r = new Random();\n private static uint Rand5()\n {\n return (uint)r.Next(0,5);\n }\n\n private class ProbabilityCondensor\n {\n private readonly int samples;\n private int counter;\n private int store;\n private readonly Action&lt;bool&gt; output;\n\n public ProbabilityCondensor(int chanceOfTrueReciprocal,\n Action&lt;bool&gt; output)\n {\n this.output = output;\n this.samples = chanceOfTrueReciprocal - 1; \n }\n\n public void Add(bool bit)\n {\n this.counter++;\n if (bit)\n this.store++; \n if (counter == samples)\n {\n bool? e;\n if (store == 0)\n e = false;\n else if (store == 1)\n e = true;\n else\n e = null;// discard for now \n counter = 0;\n store = 0;\n if (e.HasValue)\n output(e.Value);\n }\n }\n }\n\n ulong buffer = 0;\n const ulong Mask = 7UL;\n int bitsAvail = 0;\n private readonly ProbabilityCondensor fifth;\n private readonly ProbabilityCondensor eigth;\n\n private void AddEntropy(bool bit)\n {\n buffer &lt;&lt;= 1;\n if (bit)\n buffer |= 1; \n bitsAvail++;\n }\n\n private void AddTwoBitsEntropy(uint u)\n {\n buffer &lt;&lt;= 2;\n buffer |= (u &amp; 3UL); \n bitsAvail += 2;\n }\n\n public uint Rand7()\n {\n uint selection; \n do\n {\n while (bitsAvail &lt; 3)\n {\n var x = Rand5();\n if (x &lt; 4)\n {\n // put the two low order bits straight in\n AddTwoBitsEntropy(x);\n fifth.Add(false);\n }\n else\n { \n fifth.Add(true);\n }\n }\n // read 3 bits\n selection = (uint)((buffer &amp; Mask));\n bitsAvail -= 3; \n buffer &gt;&gt;= 3;\n if (selection == 7)\n eigth.Add(true);\n else\n eigth.Add(false);\n }\n while (selection == 7); \n return selection;\n }\n}\n</code></pre>\n\n<p>The number of bits added to the buffer per call to Rand5 is currently 4/5 * 2 so 1.6.\nIf the 1/5 probability value is included that increases by 0.05 so 1.65 but see the comment in the code where I have had to disable this.</p>\n\n<p>Bits consumed by call to Rand7 = 3 + 1/8 * (3 + 1/8 * (3 + 1/8 * (...<br>\nThis is 3 + 3/8 + 3/64 + 3/512 ... so approx 3.42</p>\n\n<p>By extracting information from the sevens I reclaim 1/8*1/7 bits per call so about 0.018</p>\n\n<p>This gives a net consumption 3.4 bits per call which means the ratio is 2.125 calls to Rand5 for every Rand7. The optimum should be 2.1.</p>\n\n<p>I would imagine this approach is <em>significantly</em> slower than many of the other ones here unless the cost of the call to Rand5 is extremely expensive (say calling out to some external source of entropy).</p>\n" }, { "answer_id": 891304, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 7, "selected": false, "text": "<p>I'd like to add another answer, in addition to <a href=\"https://stackoverflow.com/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun/137809#137809\">my first answer</a>. This answer attempts to minimize the number of calls to <code>rand5()</code> per call to <code>rand7()</code>, to maximize the usage of randomness. That is, if you consider randomness to be a precious resource, we want to use as much of it as possible, without throwing away any random bits. This answer also has some similarities with the logic presented in <a href=\"https://stackoverflow.com/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun/842343#842343\">Ivan's answer</a>.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Entropy_(information_theory)\" rel=\"noreferrer\">entropy of a random variable</a> is a well-defined quantity. For a random variable which takes on N states with equal probabilities (a uniform distribution), the entropy is log<sub>2</sub> N. Thus, <code>rand5()</code> has approximately 2.32193 bits of entropy, and <code>rand7()</code> has about 2.80735 bits of entropy. If we hope to maximize our use of randomness, we need to use all 2.32193 bits of entropy from each call to <code>rand5()</code>, and apply them to generating 2.80735 bits of entropy needed for each call to <code>rand7()</code>. The fundamental limit, then, is that we can do no better than log(7)/log(5) = 1.20906 calls to <code>rand5()</code> per call to <code>rand7()</code>.</p>\n\n<p><em>Side notes: all logarithms in this answer will be base 2 unless specified otherwise. <code>rand5()</code> will be assumed to return numbers in the range [0, 4], and <code>rand7()</code> will be assumed to return numbers in the range [0, 6]. Adjusting the ranges to [1, 5] and [1, 7] respectively is trivial.</em></p>\n\n<p>So how do we do it? We generate an <em>infinitely precise</em> random real number between 0 and 1 (pretend for the moment that we could actually compute and store such an infinitely precise number -- we'll fix this later). We can generate such a number by generating its digits in base 5: we pick the random number 0.<code>a</code><sub>1</sub><code>a</code><sub>2</sub><code>a</code><sub>3</sub>..., where each digit a<sub><code>i</code></sub> is chosen by a call to <code>rand5()</code>. For example, if our RNG chose a<sub><code>i</code></sub> = 1 for all <code>i</code>, then ignoring the fact that that isn't very random, that would correspond to the real number 1/5 + 1/5<sup>2</sup> + 1/5<sup>3</sup> + ... = 1/4 (sum of a geometric series).</p>\n\n<p>Ok, so we've picked a random real number between 0 and 1. I now claim that such a random number is uniformly distributed. Intuitively, this is easy to understand, since each digit was picked uniformly, and the number is infinitely precise. However, a formal proof of this is somewhat more involved, since now we're dealing with a continuous distribution instead of a discrete distribution, so we need to prove that the probability that our number lies in an interval [<code>a</code>, <code>b</code>] equals the length of that interval, <code>b - a</code>. The proof is left as an exercise for the reader =).</p>\n\n<p>Now that we have a random real number selected uniformly from the range [0, 1], we need to convert it to a series of uniformly random numbers in the range [0, 6] to generate the output of <code>rand7()</code>. How do we do this? Just the reverse of what we just did -- we convert it to an infinitely precise decimal in base 7, and then each base 7 digit will correspond to one output of <code>rand7()</code>.</p>\n\n<p>Taking the example from earlier, if our <code>rand5()</code> produces an infinite stream of 1's, then our random real number will be 1/4. Converting 1/4 to base 7, we get the infinite decimal 0.15151515..., so we will produce as output 1, 5, 1, 5, 1, 5, etc.</p>\n\n<p>Ok, so we have the main idea, but we have two problems left: we can't actually compute or store an infinitely precise real number, so how do we deal with only a finite portion of it? Secondly, how do we actually convert it to base 7?</p>\n\n<p>One way we can convert a number between 0 and 1 to base 7 is as follows:</p>\n\n<ol>\n<li>Multiply by 7</li>\n<li>The integral part of the result is the next base 7 digit</li>\n<li>Subtract off the integral part, leaving only the fractional part</li>\n<li>Goto step 1</li>\n</ol>\n\n<p>To deal with the problem of infinite precision, we compute a partial result, and we also store an upper bound on what the result could be. That is, suppose we've called <code>rand5()</code> twice and it returned 1 both times. The number we've generated so far is 0.11 (base 5). Whatever the rest of the infinite series of calls to <code>rand5()</code> produce, the random real number we're generating will never be larger than 0.12: it is always true that 0.11 ≤ 0.11xyz... &lt; 0.12.</p>\n\n<p>So, keeping track of the current number so far, and the maximum value it could ever take, we convert <em>both</em> numbers to base 7. If they agree on the first <code>k</code> digits, then we can safely output the next <code>k</code> digits -- regardless of what the infinite stream of base 5 digits are, they will never affect the next <code>k</code> digits of the base 7 representation!</p>\n\n<p>And that's the algorithm -- to generate the next output of <code>rand7()</code>, we generate only as many digits of <code>rand5()</code> as we need to ensure that we know with certainty the value of the next digit in the conversion of the random real number to base 7. Here is a Python implementation, with a test harness:</p>\n\n<pre><code>import random\n\nrand5_calls = 0\ndef rand5():\n global rand5_calls\n rand5_calls += 1\n return random.randint(0, 4)\n\ndef rand7_gen():\n state = 0\n pow5 = 1\n pow7 = 7\n while True:\n if state / pow5 == (state + pow7) / pow5:\n result = state / pow5\n state = (state - result * pow5) * 7\n pow7 *= 7\n yield result\n else:\n state = 5 * state + pow7 * rand5()\n pow5 *= 5\n\nif __name__ == '__main__':\n r7 = rand7_gen()\n N = 10000\n x = list(next(r7) for i in range(N))\n distr = [x.count(i) for i in range(7)]\n expmean = N / 7.0\n expstddev = math.sqrt(N * (1.0/7.0) * (6.0/7.0))\n\n print '%d TRIALS' % N\n print 'Expected mean: %.1f' % expmean\n print 'Expected standard deviation: %.1f' % expstddev\n print\n print 'DISTRIBUTION:'\n for i in range(7):\n print '%d: %d (%+.3f stddevs)' % (i, distr[i], (distr[i] - expmean) / expstddev)\n print\n print 'Calls to rand5: %d (average of %f per call to rand7)' % (rand5_calls, float(rand5_calls) / N)\n</code></pre>\n\n<p>Note that <code>rand7_gen()</code> returns a generator, since it has internal state involving the conversion of the number to base 7. The test harness calls <code>next(r7)</code> 10000 times to produce 10000 random numbers, and then it measures their distribution. Only integer math is used, so the results are exactly correct.</p>\n\n<p>Also note that the numbers here get <em>very</em> big, <em>very</em> fast. Powers of 5 and 7 grow quickly. Hence, performance will start to degrade noticeably after generating lots of random numbers, due to bignum arithmetic. But remember here, my goal was to maximize the usage of random bits, not to maximize performance (although that is a secondary goal).</p>\n\n<p>In one run of this, I made 12091 calls to <code>rand5()</code> for 10000 calls to <code>rand7()</code>, achieving the minimum of log(7)/log(5) calls on average to 4 significant figures, and the resulting output was uniform.</p>\n\n<p>In order to port this code to a language that doesn't have arbitrarily large integers built-in, you'll have to cap the values of <code>pow5</code> and <code>pow7</code> to the maximum value of your native integral type -- if they get too big, then reset everything and start over. This will increase the average number of calls to <code>rand5()</code> per call to <code>rand7()</code> very slightly, but hopefully it shouldn't increase too much even for 32- or 64-bit integers. </p>\n" }, { "answer_id": 1032834, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 3, "selected": false, "text": "<p>The premise behind Adam Rosenfield's correct answer is:</p>\n\n<ul>\n<li><strong>x</strong> = 5^n (in his case: <strong>n</strong>=2)</li>\n<li>manipulate n rand5 calls to get a number <strong>y</strong> within range [1, x]</li>\n<li><strong>z</strong> = ((int)(x / 7)) * 7</li>\n<li>if y > z, try again. else return y % 7 + 1</li>\n</ul>\n\n<p>When n equals 2, you have 4 throw-away possibilities: y = {22, 23, 24, 25}. If you use n equals 6, you only have 1 throw-away: y = {15625}.</p>\n\n<p>5^6 = 15625\n<br />7 * 2232 = 15624</p>\n\n<p>You call rand5 more times. However, you have a much lower chance of getting a throw-away value (or an infinite loop). If there is a way to get no possible throw-away value for y, I haven't found it yet.</p>\n" }, { "answer_id": 1397428, "author": "Chris Suter", "author_id": 116931, "author_profile": "https://Stackoverflow.com/users/116931", "pm_score": 3, "selected": false, "text": "<p>Here's my answer:</p>\n\n<pre><code>static struct rand_buffer {\n unsigned v, count;\n} buf2, buf3;\n\nvoid push (struct rand_buffer *buf, unsigned n, unsigned v)\n{\n buf-&gt;v = buf-&gt;v * n + v;\n ++buf-&gt;count;\n}\n\n#define PUSH(n, v) push (&amp;buf##n, n, v)\n\nint rand16 (void)\n{\n int v = buf2.v &amp; 0xf;\n buf2.v &gt;&gt;= 4;\n buf2.count -= 4;\n return v;\n}\n\nint rand9 (void)\n{\n int v = buf3.v % 9;\n buf3.v /= 9;\n buf3.count -= 2;\n return v;\n}\n\nint rand7 (void)\n{\n if (buf3.count &gt;= 2) {\n int v = rand9 ();\n\n if (v &lt; 7)\n return v % 7 + 1;\n\n PUSH (2, v - 7);\n }\n\n for (;;) {\n if (buf2.count &gt;= 4) {\n int v = rand16 ();\n\n if (v &lt; 14) {\n PUSH (2, v / 7);\n return v % 7 + 1;\n }\n\n PUSH (2, v - 14);\n }\n\n // Get a number between 0 &amp; 25\n int v = 5 * (rand5 () - 1) + rand5 () - 1;\n\n if (v &lt; 21) {\n PUSH (3, v / 7);\n return v % 7 + 1;\n }\n\n v -= 21;\n PUSH (2, v &amp; 1);\n PUSH (2, v &gt;&gt; 1);\n }\n}\n</code></pre>\n\n<p>It's a little more complicated than others, but I believe it minimises the calls to rand5. As with other solutions, there's a small probability that it could loop for a long time.</p>\n" }, { "answer_id": 1441828, "author": "Ashwin", "author_id": 174553, "author_profile": "https://Stackoverflow.com/users/174553", "pm_score": 2, "selected": false, "text": "<p>There are elegant algorithms cited above, but here's one way to approach it, although it might be roundabout. I am assuming values generated from 0.</p>\n\n<p>R2 = random number generator giving values less than 2 (sample space = {0, 1})<br>\nR8 = random number generator giving values less than 8 (sample space = {0, 1, 2, 3, 4, 5, 6, 7})</p>\n\n<p>In order to generate R8 from R2, you will run R2 thrice, and use the combined result of all 3 runs as a binary number with 3 digits. Here are the range of values when R2 is ran thrice:</p>\n\n<p>0 0 0 --> 0<br>\n.<br>\n.<br>\n1 1 1 --> 7</p>\n\n<p>Now to generate R7 from R8, we simply run R7 again if it returns 7:</p>\n\n<pre><code>int R7() {\n do {\n x = R8();\n } while (x &gt; 6)\n return x;\n}\n</code></pre>\n\n<p>The roundabout solution is to generate R2 from R5 (just like we generated R7 from R8), then R8 from R2 and then R7 from R8.</p>\n" }, { "answer_id": 1700617, "author": "Ante", "author_id": 206844, "author_profile": "https://Stackoverflow.com/users/206844", "pm_score": 3, "selected": false, "text": "<p>Why not do it simple?</p>\n\n<pre><code>int random7() {\n return random5() + (random5() % 3);\n}\n</code></pre>\n\n<p>The chances of getting 1 and 7 in this solution is lower due to the modulo, however, if you just want a quick and readable solution, this is the way to go.</p>\n" }, { "answer_id": 1850414, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>As long as there aren't seven possibilities left to choose from, draw another random number, which multiplies the number of possibilities by five. In Perl:</p>\n\n<pre><code>$num = 0;\n$possibilities = 1;\n\nsub rand7\n{\n while( $possibilities &lt; 7 )\n {\n $num = $num * 5 + int(rand(5));\n $possibilities *= 5;\n }\n my $result = $num % 7;\n $num = int( $num / 7 );\n $possibilities /= 7;\n return $result;\n}\n</code></pre>\n" }, { "answer_id": 1851459, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 2, "selected": false, "text": "<p>The function you need is <em>rand1_7()</em>, I wrote rand1_5() so that you can test it and plot it.</p>\n\n<pre><code>import numpy\ndef rand1_5():\n return numpy.random.randint(5)+1\n\ndef rand1_7():\n q = 0\n for i in xrange(7): q+= rand1_5()\n return q%7 + 1\n</code></pre>\n" }, { "answer_id": 1972518, "author": "Kugel", "author_id": 177591, "author_profile": "https://Stackoverflow.com/users/177591", "pm_score": 2, "selected": false, "text": "<p>There you go, uniform distribution and zero rand5 calls.</p>\n\n<pre><code>def rand7:\n seed += 1\n if seed &gt;= 7:\n seed = 0\n yield seed\n</code></pre>\n\n<p>Need to set seed beforehand.</p>\n" }, { "answer_id": 2420737, "author": "Rex Kerr", "author_id": 247533, "author_profile": "https://Stackoverflow.com/users/247533", "pm_score": 2, "selected": false, "text": "<p>Here's a solution that fits entirely within integers and is within about 4% of optimal (i.e. uses 1.26 random numbers in {0..4} for every one in {0..6}). The code's in Scala, but the math should be reasonably clear in any language: you take advantage of the fact that 7^9 + 7^8 is very close to 5^11. So you pick an 11 digit number in base 5, and then interpret it as a 9 digit number in base 7 if it's in range (giving 9 base 7 numbers), or as an 8 digit number if it's over the 9 digit number, etc.:</p>\n\n<pre><code>abstract class RNG {\n def apply(): Int\n}\n\nclass Random5 extends RNG {\n val rng = new scala.util.Random\n var count = 0\n def apply() = { count += 1 ; rng.nextInt(5) }\n}\n\nclass FiveSevener(five: RNG) {\n val sevens = new Array[Int](9)\n var nsevens = 0\n val to9 = 40353607;\n val to8 = 5764801;\n val to7 = 823543;\n def loadSevens(value: Int, count: Int) {\n nsevens = 0;\n var remaining = value;\n while (nsevens &lt; count) {\n sevens(nsevens) = remaining % 7\n remaining /= 7\n nsevens += 1\n }\n }\n def loadSevens {\n var fivepow11 = 0;\n var i=0\n while (i&lt;11) { i+=1 ; fivepow11 = five() + fivepow11*5 }\n if (fivepow11 &lt; to9) { loadSevens(fivepow11 , 9) ; return }\n fivepow11 -= to9\n if (fivepow11 &lt; to8) { loadSevens(fivepow11 , 8) ; return }\n fivepow11 -= to8\n if (fivepow11 &lt; 3*to7) loadSevens(fivepow11 % to7 , 7)\n else loadSevens\n }\n def apply() = {\n if (nsevens==0) loadSevens\n nsevens -= 1\n sevens(nsevens)\n }\n}\n</code></pre>\n\n<p>If you paste a test into the interpreter (REPL actually), you get:</p>\n\n<pre><code>scala&gt; val five = new Random5\nfive: Random5 = Random5@e9c592\n\nscala&gt; val seven = new FiveSevener(five)\nseven: FiveSevener = FiveSevener@143c423\n\nscala&gt; val counts = new Array[Int](7)\ncounts: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)\n\nscala&gt; var i=0 ; while (i &lt; 100000000) { counts( seven() ) += 1 ; i += 1 }\ni: Int = 100000000\n\nscala&gt; counts\nres0: Array[Int] = Array(14280662, 14293012, 14281286, 14284836, 14287188,\n14289332, 14283684)\n\nscala&gt; five.count\nres1: Int = 125902876\n</code></pre>\n\n<p>The distribution is nice and flat (within about 10k of 1/7 of 10^8 in each bin, as expected from an approximately-Gaussian distribution).</p>\n" }, { "answer_id": 2667241, "author": "philcolbourn", "author_id": 275052, "author_profile": "https://Stackoverflow.com/users/275052", "pm_score": 3, "selected": false, "text": "<p>I know it has been answered, but is this seems to work ok, but I can not tell you if it has a bias. My 'testing' suggests it is, at least, reasonable.</p>\n\n<p><em>Perhaps Adam Rosenfield would be kind enough to comment?</em></p>\n\n<p>My (naive?) idea is this:</p>\n\n<p>Accumulate rand5's until there is enough random bits to make a rand7. This takes at most 2 rand5's. To get the rand7 number I use the accumulated value mod 7.</p>\n\n<p>To avoid the accumulator overflowing, and since the accumulator is mod 7 then I take the mod 7 of the accumulator:</p>\n\n<pre><code>(5a + rand5) % 7 = (k*7 + (5a%7) + rand5) % 7 = ( (5a%7) + rand5) % 7\n</code></pre>\n\n<p>The rand7() function follows:</p>\n\n<p>(I let the range of rand5 be 0-4 and rand7 is likewise 0-6.)</p>\n\n<pre><code>int rand7(){\n static int a=0;\n static int e=0;\n int r;\n a = a * 5 + rand5();\n e = e + 5; // added 5/7ths of a rand7 number\n if ( e&lt;7 ){\n a = a * 5 + rand5();\n e = e + 5; // another 5/7ths\n }\n r = a % 7;\n e = e - 7; // removed a rand7 number\n a = a % 7;\n return r;\n}\n</code></pre>\n\n<p>Edit: Added results for 100 million trials.</p>\n\n<p>'Real' rand functions mod 5 or 7</p>\n\n<p>rand5 : avg=1.999802 0:20003944 1:19999889 2:20003690 3:19996938 4:19995539\nrand7 : avg=3.000111 0:14282851 1:14282879 2:14284554 3:14288546 4:14292388 5:14288736 6:14280046</p>\n\n<p>My rand7</p>\n\n<p>Average looks ok and number distributions look ok too.</p>\n\n<p>randt : avg=3.000080 0:14288793 1:14280135 2:14287848 3:14285277 4:14286341 5:14278663 6:14292943</p>\n" }, { "answer_id": 2919491, "author": "cartonn", "author_id": 350668, "author_profile": "https://Stackoverflow.com/users/350668", "pm_score": 2, "selected": false, "text": "<p>just scale your output from your first function</p>\n\n<pre><code>0) you have a number in range 1-5\n1) subtract 1 to make it in range 0-4\n2) multiply by (7-1)/(5-1) to make it in range 0-6\n3) add 1 to increment the range: Now your result is in between 1-7\n</code></pre>\n" }, { "answer_id": 3547853, "author": "chiccodoro", "author_id": 55787, "author_profile": "https://Stackoverflow.com/users/55787", "pm_score": 3, "selected": false, "text": "<p>Simple and efficient:</p>\n\n<pre><code>int rand7 ( void )\n{\n return 4; // this number has been calculated using\n // rand5() and is in the range 1..7\n}\n</code></pre>\n\n<p>(Inspired by <a href=\"https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon/84747#84747\">What&#39;s your favorite &quot;programmer&quot; cartoon?</a>).</p>\n" }, { "answer_id": 3761993, "author": "fredoverflow", "author_id": 252000, "author_profile": "https://Stackoverflow.com/users/252000", "pm_score": 3, "selected": false, "text": "<p>I don't like ranges starting from 1, so I'll start from 0 :-)</p>\n\n<pre><code>unsigned rand5()\n{\n return rand() % 5;\n}\n\nunsigned rand7()\n{\n int r;\n\n do\n {\n r = rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n r = r * 5 + rand5();\n } while (r &gt; 15623);\n\n return r / 2232;\n}\n</code></pre>\n" }, { "answer_id": 3895983, "author": "user470894", "author_id": 470894, "author_profile": "https://Stackoverflow.com/users/470894", "pm_score": 2, "selected": false, "text": "<pre><code>function Rand7\n put 200 into x\n repeat while x &gt; 118\n put ((random(5)-1) * 25) + ((random(5)-1) * 5) + (random(5)-1) into x\n end repeat\n return (x mod 7) + 1\nend Rand7\n</code></pre>\n\n<p>Three calls to Rand5, which only repeats 6 times out of 125, on average.</p>\n\n<p>Think of it as a 3D array, 5x5x5, filled with 1 to 7 over and over, and 6 blanks. Re-roll on the blanks. The rand5 calls create a three digit base-5 index into that array.</p>\n\n<p>There would be fewer repeats with a 4D, or higher N-dimensional arrays, but this means more calls to the rand5 function become standard. You'll start to get diminishing efficiency returns at higher dimensions. Three seems to me to be a good compromise, but I haven't tested them against each other to be sure. And it would be rand5-implementation specific.</p>\n" }, { "answer_id": 4179748, "author": "Anand", "author_id": 507613, "author_profile": "https://Stackoverflow.com/users/507613", "pm_score": 5, "selected": false, "text": "<p><strong>Algorithm:</strong></p>\n\n<p>7 can be represented in a sequence of 3 bits</p>\n\n<p>Use rand(5) to randomly fill each bit with 0 or 1.<br>\nFor e.g: call rand(5) and </p>\n\n<p>if the result is 1 or 2, fill the bit with 0<br>\nif the result is 4 or 5, fill the bit with 1<br>\nif the result is 3 , then ignore and do it again (rejection) </p>\n\n<p>This way we can fill 3 bits randomly with 0/1 and thus get a number from 1-7.</p>\n\n<p><strong>EDIT:</strong> This seems like the simplest and most efficient answer, so here's some code for it:</p>\n\n<pre><code>public static int random_7() {\n int returnValue = 0;\n while (returnValue == 0) {\n for (int i = 1; i &lt;= 3; i++) {\n returnValue = (returnValue &lt;&lt; 1) + random_5_output_2();\n }\n }\n return returnValue;\n}\n\nprivate static int random_5_output_2() {\n while (true) {\n int flip = random_5();\n\n if (flip &lt; 3) {\n return 0;\n }\n else if (flip &gt; 3) {\n return 1;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 4316537, "author": "pas1311", "author_id": 525505, "author_profile": "https://Stackoverflow.com/users/525505", "pm_score": 2, "selected": false, "text": "<pre><code>int getOneToSeven(){\n int added = 0;\n for(int i = 1; i&lt;=7; i++){\n added += getOneToFive();\n }\n return (added)%7+1;\n}\n</code></pre>\n" }, { "answer_id": 4327883, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 2, "selected": false, "text": "<p>This is the simplest answer I could create after reviewing others' answers:</p>\n\n<pre><code>def r5tor7():\n while True:\n cand = (5 * r5()) + r5()\n if cand &lt; 27:\n return cand\n</code></pre>\n\n<p><code>cand</code> is in the range [6, 27] and the possible outcomes are evenly distributed if the possible outcomes from r5() are evenly distributed. You can test my answer with this code:</p>\n\n<pre><code>from collections import defaultdict\n\ndef r5_outcome(n):\n if not n:\n yield []\n else:\n for i in range(1, 6):\n for j in r5_outcome(n-1):\n yield [i] + j\n\ndef test_r7():\n d = defaultdict(int)\n for x in r5_outcome(2):\n s = sum([x[i] * 5**i for i in range(len(x))])\n if s &lt; 27:\n d[s] += 1\n print len(d), d\n</code></pre>\n\n<p><code>r5_outcome(2)</code> generates all possible combinations of r5() results. I use the same filter to test as in my solution code. You can see that all of the outcomes are equally probably because they have the same value.</p>\n" }, { "answer_id": 4341713, "author": "maxchengcn", "author_id": 528789, "author_profile": "https://Stackoverflow.com/users/528789", "pm_score": 2, "selected": false, "text": "<pre><code>extern int r5();\n\nint r7() {\n return ((r5() &amp; 0x01) &lt;&lt; 2 ) | ((r5() &amp; 0x01) &lt;&lt; 1 ) | (r5() &amp; 0x01);\n}\n</code></pre>\n" }, { "answer_id": 4720026, "author": "DeWan", "author_id": 579349, "author_profile": "https://Stackoverflow.com/users/579349", "pm_score": 2, "selected": false, "text": "<pre><code>package CareerCup;\n\npublic class RangeTransform {\n static int counter = (int)(Math.random() * 5 + 1);\n\n private int func() {\n return (int) (Math.random() * 5 + 1);\n }\n\n private int getMultiplier() {\n return counter % 5 + 1;\n }\n\n public int rangeTransform() {\n counter++;\n int count = getMultiplier();\n int mult = func() + 5 * count;\n System.out.println(\"Mult is : \" + 5 * count);\n return (mult) % 7 + 1;\n }\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n RangeTransform rangeTransform = new RangeTransform();\n for (int i = 0; i &lt; 35; i++)\n System.out.println(\"Val is : \" + rangeTransform.rangeTransform());\n }\n}\n</code></pre>\n" }, { "answer_id": 4813754, "author": "Sam", "author_id": 591809, "author_profile": "https://Stackoverflow.com/users/591809", "pm_score": 2, "selected": false, "text": "<p>Why won't this work? Other then the one extra call to rand5()?</p>\n\n<pre><code>i = rand5() + rand5() + (rand5() - 1) //Random number between 1 and 14\n\ni = i % 7 + 1;\n</code></pre>\n" }, { "answer_id": 5037144, "author": "rich", "author_id": 622483, "author_profile": "https://Stackoverflow.com/users/622483", "pm_score": 1, "selected": false, "text": "<p>how about this</p>\n\n<p>rand5()%2+rand5()%2+rand5()%2+rand5()%2+rand5()%2+rand5()%2</p>\n\n<p>Not sure this is uniform distributed. Any suggestions?</p>\n" }, { "answer_id": 5328966, "author": "Rob Leclerc", "author_id": 606612, "author_profile": "https://Stackoverflow.com/users/606612", "pm_score": 2, "selected": false, "text": "<p>For values 0-7 you have the following:</p>\n\n<pre><code>0 000\n1 001\n2 010\n3 011\n4 100\n5 101\n6 110\n7 111\n</code></pre>\n\n<p>From bitwise from left to right Rand5() has p(1) = {2/5, 2/5, 3/5}. So if we complement those probability distributions (~Rand5()) we should be able to use that to produce our number. I'll try to report back later with a solution. Anyone have any thoughts?</p>\n\n<p>R</p>\n" }, { "answer_id": 5354261, "author": "ekr", "author_id": 666278, "author_profile": "https://Stackoverflow.com/users/666278", "pm_score": 2, "selected": false, "text": "<pre><code>rand25() =5*(rand5()-1) + rand5()\n\nrand7() { \n while(true) {\n int r = rand25();\n if (r &lt; 21) return r%3; \n }\n}\n</code></pre>\n\n<p>Why this works: probability that the loop will run forever is 0.</p>\n" }, { "answer_id": 5508688, "author": "Eric Rowell", "author_id": 686858, "author_profile": "https://Stackoverflow.com/users/686858", "pm_score": 1, "selected": false, "text": "<p>I thought of an interesting solution to this problem and wanted to share it.</p>\n\n<pre><code>function rand7() {\n\n var returnVal = 4;\n\n for (var n=0; n&lt;3; n++) {\n var rand = rand5();\n\n if (rand==1||rand==2){\n returnVal+=1;\n }\n else if (rand==3||rand==4) {\n returnVal-=1;\n }\n }\n\n return returnVal;\n}\n</code></pre>\n\n<p>I built a test function that loops through rand7() 10,000 times, sums up all of the return values, and divides it by 10,000. If rand7() is working correctly, our calculated average should be 4 - for example, (1+2+3+4+5+6+7 / 7) = 4. After doing multiple tests, the average is indeed right at 4 :)</p>\n" }, { "answer_id": 5509037, "author": "dqhendricks", "author_id": 512922, "author_profile": "https://Stackoverflow.com/users/512922", "pm_score": 2, "selected": false, "text": "<p>in php</p>\n\n<pre><code>function rand1to7() {\n do {\n $output_value = 0;\n for ($i = 0; $i &lt; 28; $i++) {\n $output_value += rand1to5();\n }\n while ($output_value != 140);\n $output_value -= 12;\n return floor($output_value / 16);\n}\n</code></pre>\n\n<p>loops to produce a random number between 16 and 127, divides by sixteen to create a float between 1 and 7.9375, then rounds down to get an int between 1 and 7. if I am not mistaken, there is a 16/112 chance of getting any one of the 7 outcomes.</p>\n" }, { "answer_id": 5537186, "author": "Ben", "author_id": 690910, "author_profile": "https://Stackoverflow.com/users/690910", "pm_score": 2, "selected": false, "text": "<p>Assuming <code>rand</code> gives equal weighting to all bits, then masks with the upper bound.</p>\n\n<pre><code>int i = rand(5) ^ (rand(5) &amp; 2);\n</code></pre>\n\n<p><code>rand(5)</code> can only return: <code>1b</code>, <code>10b</code>, <code>11b</code>, <code>100b</code>, <code>101b</code>. You only need to concern yourself with sometimes setting the 2 bit.</p>\n" }, { "answer_id": 7209458, "author": "ming_codes", "author_id": 387028, "author_profile": "https://Stackoverflow.com/users/387028", "pm_score": 2, "selected": false, "text": "<p>Here's what I've found:</p>\n\n<ol>\n<li>Random5 produces a range from 1~5, randomly distributed</li>\n<li>If we run it 3 times and add them together we'll get a range of 3~15, randomly distributed</li>\n<li>Perform arithmetic on the 3~15 range\n<ol>\n<li>(3~15) - 1 = (2~14)</li>\n<li>(2~14)/2 = (1~7)</li>\n</ol></li>\n</ol>\n\n<p>Then we get a range of 1~7, which is the Random7 we're looking for.</p>\n" }, { "answer_id": 10035519, "author": "Yatharth Agarwal", "author_id": 1292652, "author_profile": "https://Stackoverflow.com/users/1292652", "pm_score": 0, "selected": false, "text": "<p>Why don't you just divide by 5 and multiply by 7, and then round? (Granted, you would have to use floating-point no.s)</p>\n\n<p>It's much easier and more reliable (really?) than the other solutions. E.g. in Python:</p>\n\n<pre><code>def ranndomNo7():\n import random\n rand5 = random.randint(4) # Produces range: [0, 4]\n rand7 = int(rand5 / 5 * 7) # /5, *7, +0.5 and floor()\n return rand7\n</code></pre>\n\n<p>Wasn't that easy?</p>\n" }, { "answer_id": 10378532, "author": "ASKN", "author_id": 388331, "author_profile": "https://Stackoverflow.com/users/388331", "pm_score": 1, "selected": false, "text": "<p>First thing came on my mind is this. But i have no idea whether its uniformly distributed.\nImplemented in python</p>\n<blockquote>\n<p>import random</p>\n<p>def rand5():</p>\n<blockquote>\n<p>return random.randint(1,5)</p>\n</blockquote>\n<p>def rand7():</p>\n<blockquote>\n<p>return ( ( (rand5() -1) * rand5() ) %7 )+1</p>\n</blockquote>\n</blockquote>\n" }, { "answer_id": 12585928, "author": "coder", "author_id": 1122689, "author_profile": "https://Stackoverflow.com/users/1122689", "pm_score": 0, "selected": false, "text": "<pre><code>int rand7()\n{\n return ( rand5() + (rand5()%3) );\n}\n</code></pre>\n\n<ol>\n<li>rand5() - Returns values from 1-5</li>\n<li>rand5()%3 - Returns values from 0-2</li>\n<li>So, when summing up the total value will be between 1-7</li>\n</ol>\n" }, { "answer_id": 14528515, "author": "leonbloy", "author_id": 277304, "author_profile": "https://Stackoverflow.com/users/277304", "pm_score": 1, "selected": false, "text": "<p>Here's my general implementation, to generate a uniform in the range [0,N-1] given a uniform generator in the range [0,B-1]. </p>\n\n<pre><code>public class RandomUnif {\n\n public static final int BASE_NUMBER = 5;\n\n private static Random rand = new Random();\n\n /** given generator, returns uniform integer in the range 0.. BASE_NUMBER-1\n public static int randomBASE() {\n return rand.nextInt(BASE_NUMBER);\n }\n\n /** returns uniform integer in the range 0..n-1 using randomBASE() */\n public static int randomUnif(int n) {\n int rand, factor;\n if( n &lt;= 1 ) return 0;\n else if( n == BASE_NUMBER ) return randomBASE();\n if( n &lt; BASE_NUMBER ) {\n factor = BASE_NUMBER / n;\n do\n rand = randomBASE() / factor;\n while(rand &gt;= n);\n return rand;\n } else {\n factor = (n - 1) / BASE_NUMBER + 1;\n do {\n rand = factor * randomBASE() + randomUnif(factor);\n } while(rand &gt;= n);\n return rand;\n }\n }\n}\n</code></pre>\n\n<p>Not spectaculary efficient, but general and compact. Mean calls to base generator:</p>\n\n<pre><code> n calls\n 2 1.250 \n 3 1.644 \n 4 1.252 \n 5 1.000 \n 6 3.763 \n 7 3.185 \n 8 2.821 \n 9 2.495 \n10 2.250 \n11 3.646 \n12 3.316 \n13 3.060 \n14 2.853 \n15 2.650 \n16 2.814 \n17 2.644 \n18 2.502 \n19 2.361 \n20 2.248 \n21 2.382 \n22 2.277 \n23 2.175 \n24 2.082 \n25 2.000 \n26 5.472 \n27 5.280 \n28 5.119 \n29 4.899 \n</code></pre>\n" }, { "answer_id": 14630267, "author": "bernard paulus", "author_id": 1610553, "author_profile": "https://Stackoverflow.com/users/1610553", "pm_score": 2, "selected": false, "text": "<p><em>We are using the convention <code>rand(n) -&gt; [0, n - 1]</code> here</em></p>\n\n<p>From many of the answer I read, they provide either uniformity or halt guarantee, but not both (adam rosenfeld second answer might).</p>\n\n<p>It is, however, possible to do so. We basically have this distribution:</p>\n\n<p><img src=\"https://i.imgur.com/Ww0qPTP.png\" alt=\"rand5_proba.png\"></p>\n\n<p>This leaves us a hole in the distribution over <code>[0-6]</code>: 5 and 6 have no\nprobability of ocurrence. Imagine now we try to fill the hole it by shifting the\nprobability distribution and summing.</p>\n\n<p>Indeed, we can the initial distribution with itself shifted by one, and\nrepeating by summing the obtained distribution with the initial one shifted by\ntwo, then three and so on, until 7, not included (we covered the whole range).\nThis is shown on the following figure. The order of the colors, corresponding to\nthe steps, is blue -> green -> cyan -> white -> magenta -> yellow -> red.</p>\n\n<p><img src=\"https://i.imgur.com/EIfJCYr.png\" alt=\"fig_moving_average_proba.png\"></p>\n\n<p>Because each slot is covered by 5 of the 7 shifted distributions (shift varies from\n0 to 6), and because we assume the random numbers are independent from one\n<code>ran5()</code> call to another, we obtain</p>\n\n<pre><code>p(x) = 5 / 35 = 1 / 7 for all x in [0, 6]\n</code></pre>\n\n<p>This means that, given 7 independent random numbers from <code>ran5()</code>, we can\ncompute a random number with uniform probability in the <code>[0-6]</code> range.\nIn fact, the ran5() probability\ndistribution does not even need to be uniform, as long as the samples are\nindependent (so the distribution stays the same from trial to trial).\nAlso, this is valid for other numbers than 5 and 7.</p>\n\n<p>This gives us the following python function:</p>\n\n<pre><code>def rand_range_transform(rands):\n \"\"\"\n returns a uniform random number in [0, len(rands) - 1]\n if all r in rands are independent random numbers from the same uniform distribution\n \"\"\"\n return sum((x + i) for i, x in enumerate(rands)) % len(rands) # a single modulo outside the sum is enough in modulo arithmetic\n</code></pre>\n\n<p>This can be used like this:</p>\n\n<pre><code>rand5 = lambda : random.randrange(5)\n\ndef rand7():\n return rand_range_transform([rand5() for _ in range(7)])\n</code></pre>\n\n<p>If we call <code>rand7()</code> 70000 times, we can get:</p>\n\n<pre><code>max: 6 min: 0 mean: 2.99711428571 std: 2.00194697049\n0: 10019\n1: 10016\n2: 10071\n3: 10044\n4: 9775\n5: 10042\n6: 10033\n</code></pre>\n\n<p>This is good, although far from perfect. The fact is, one of our assumption is\nmost likely false in this implementation: we use a PRNG, and as such, the result\nof the next call is dependent from the last result.</p>\n\n<p>That said, using a truly random source of numbers, the output should also be\ntruly random. And this algorithm terminates in every case.</p>\n\n<p>But this comes with a cost: we need 7 calls to <code>rand5()</code> for a single <code>rand7()</code>\ncall.</p>\n" }, { "answer_id": 15148624, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 1, "selected": false, "text": "<p>There are a lot of solutions here that do not produce a uniform distribution and many comments pointing that out, but the <em>the question does not state that as a requirement</em>. The simplest solution is:</p>\n\n<pre><code>int rand_7() { return rand_5(); }\n</code></pre>\n\n<p>A random integer in the range 1 - 5 is clearly in the range 1 - 7. Well, technically, the simplest solution is to return a constant, but that's too trivial. </p>\n\n<p>However, I think the existence of the rand_5 function is a red herring. Suppose the question was asked as \"produce a uniformly distributed pseudo-random number generator with integer output in the range 1 - 7\". That's a simple problem (not technically simple, but already solved, so you can look it up.) </p>\n\n<p>On the other hand, if the question is interpreted to mean that you actually have a truly random number generator for integers in the range 1 - 5 (not pseudo random), then the solution is:</p>\n\n<pre><code>1) examine the rand_5 function\n2) understand how it works\n3) profit\n</code></pre>\n" }, { "answer_id": 18573436, "author": "user2713461", "author_id": 2713461, "author_profile": "https://Stackoverflow.com/users/2713461", "pm_score": 0, "selected": false, "text": "<p>This expression is sufficient to get random integers between 1 - 7</p>\n\n<pre><code>int j = ( rand5()*2 + 4 ) % 7 + 1;\n</code></pre>\n" }, { "answer_id": 20668588, "author": "dansalmo", "author_id": 1355221, "author_profile": "https://Stackoverflow.com/users/1355221", "pm_score": 1, "selected": false, "text": "<pre><code>function rand7() {\n while (true) { //lowest base 5 random number &gt; 7 reduces memory\n int num = (rand5()-1)*5 + rand5()-1;\n if (num &lt; 21) // improves performance\n return 1 + num%7;\n }\n}\n</code></pre>\n\n<p>Python code:</p>\n\n<pre><code>from random import randint\ndef rand7():\n while(True):\n num = (randint(1, 5)-1)*5 + randint(1, 5)-1\n if num &lt; 21:\n return 1 + num%7\n</code></pre>\n\n<p>Test distribution for 100000 runs:</p>\n\n<pre><code>&gt;&gt;&gt; rnums = []\n&gt;&gt;&gt; for _ in range(100000):\n rnums.append(rand7())\n&gt;&gt;&gt; {n:rnums.count(n) for n in set(rnums)}\n{1: 15648, 2: 15741, 3: 15681, 4: 15847, 5: 15642, 6: 15806, 7: 15635}\n</code></pre>\n" }, { "answer_id": 20957658, "author": "invisal", "author_id": 1332934, "author_profile": "https://Stackoverflow.com/users/1332934", "pm_score": 1, "selected": false, "text": "<p>This is similiarly to @RobMcAfee except that I use magic number instead of 2 dimensional array.</p>\n\n<pre><code>int rand7() {\n int m = 1203068;\n int r = (m &gt;&gt; (rand5() - 1) * 5 + rand5() - 1) &amp; 7;\n\n return (r &gt; 0) ? r : rand7();\n}\n</code></pre>\n" }, { "answer_id": 21252243, "author": "Martin", "author_id": 2306145, "author_profile": "https://Stackoverflow.com/users/2306145", "pm_score": 2, "selected": false, "text": "<p>This solution doesn't waste any entropy and gives the first available truly random number in range. <strong>With each iteration the probability of not getting an answer is provably decreased.</strong> The probability of getting an answer in N iterations is the probability that a random number between 0 and max (5^N) will be smaller than the largest multiple of seven in that range (max-max%7). Must iterate at least twice. But that's necessarily true for all solutions.</p>\n\n<pre><code>int random7() {\n range = 1;\n remainder = 0;\n\n while (1) {\n remainder = remainder * 5 + random5() - 1;\n range = range * 5;\n\n limit = range - (range % 7);\n if (remainder &lt; limit) return (remainder % 7) + 1;\n\n remainder = remainder % 7;\n range = range % 7;\n }\n}\n</code></pre>\n\n<p>Numerically equivalent to:</p>\n\n<pre><code>r5=5;\nnum=random5()-1;\nwhile (1) {\n num=num*5+random5()-1;\n r5=r5*5;\n r7=r5-r5%7;\n if (num&lt;r7) return num%7+1;\n}\n</code></pre>\n\n<p>The first code calculates it in modulo form. The second code is just plain math. Or I made a mistake somewhere. :-)</p>\n" }, { "answer_id": 22467753, "author": "jantimon", "author_id": 159319, "author_profile": "https://Stackoverflow.com/users/159319", "pm_score": 1, "selected": false, "text": "<p>This solution was inspired by Rob McAfee.<br>\nHowever it doesn't need a loop and the result is a uniform distribution:</p>\n\n<pre><code>// Returns 1-5\nvar rnd5 = function(){\n return parseInt(Math.random() * 5, 10) + 1;\n}\n// Helper\nvar lastEdge = 0;\n// Returns 1-7\nvar rnd7 = function () {\n var map = [\n [ 1, 2, 3, 4, 5 ],\n [ 6, 7, 1, 2, 3 ],\n [ 4, 5, 6, 7, 1 ],\n [ 2, 3, 4, 5, 6 ],\n [ 7, 0, 0, 0, 0 ]\n ];\n var result = map[rnd5() - 1][rnd5() - 1];\n if (result &gt; 0) {\n return result;\n }\n lastEdge++;\n if (lastEdge &gt; 7 ) {\n lastEdge = 1;\n }\n return lastEdge;\n};\n\n// Test the a uniform distribution\nresults = {}; for(i=0; i &lt; 700000;i++) { var rand = rnd7(); results[rand] = results[rand] ? results[rand] + 1 : 1;} \nconsole.log(results)\n</code></pre>\n\n<p>Result: <code>[1: 99560, 2: 99932, 3: 100355, 4: 100262, 5: 99603, 6: 100062, 7: 100226]</code></p>\n\n<p><kbd><a href=\"http://jsfiddle.net/ZkTbq/\" rel=\"nofollow\">jsFiddle</a></kbd></p>\n" }, { "answer_id": 22722546, "author": "Graham Toal", "author_id": 210830, "author_profile": "https://Stackoverflow.com/users/210830", "pm_score": 1, "selected": false, "text": "<p>I think y'all are overthinking this. Doesn't this simple solution work?</p>\n\n<pre><code>int rand7(void)\n{\n static int startpos = 0;\n startpos = (startpos+5) % (5*7);\n return (((startpos + rand5()-1)%7)+1);\n}\n</code></pre>\n" }, { "answer_id": 23854520, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": 1, "selected": false, "text": "<p>Given a function which produces a random integer in the range 1 to 5 <code>rand5()</code>, write a function which produces a random integer in the range 1 to 7 <code>rand7()</code></p>\n\n<p>In my proposed solution, I only call <code>rand5</code> once only</p>\n\n<p><strong>Real Solution</strong></p>\n\n<pre><code>float rand7()\n{\n return (rand5() * 7.0) / 5.0 ;\n}\n</code></pre>\n\n<p>The distribution here is scaled, so it depends directly on the distribution of <code>rand5</code></p>\n\n<p><strong>Integer Solution</strong></p>\n\n<pre><code>int rand7()\n{\n static int prev = 1;\n\n int cur = rand5();\n\n int r = cur * prev; // 1-25\n\n float f = r / 4.0; // 0.25-6.25\n\n f = f - 0.25; // 0-6\n\n f = f + 1.0; // 1-7\n\n prev = cur;\n\n return (int)f;\n}\n</code></pre>\n\n<p>The distribution here depends on the series <code>rand7(i) ~ rand5(i) * rand5(i-1)</code></p>\n\n<p>with <code>rand7(0) ~ rand5(0) * 1</code></p>\n" }, { "answer_id": 25703358, "author": "user515430", "author_id": 515430, "author_profile": "https://Stackoverflow.com/users/515430", "pm_score": 1, "selected": false, "text": "<p>Here is an answer taking advantage of features in C++ 11</p>\n\n<pre><code>#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;ostream&gt;\n#include &lt;random&gt;\n\nint main()\n{\n std::random_device rd;\n unsigned long seed = rd();\n std::cout &lt;&lt; \"seed = \" &lt;&lt; seed &lt;&lt; std::endl;\n\n std::mt19937 engine(seed);\n\n std::uniform_int_distribution&lt;&gt; dist(1, 5);\n auto rand5 = std::bind(dist, engine);\n\n const int n = 20;\n for (int i = 0; i != n; ++i)\n {\n std::cout &lt;&lt; rand5() &lt;&lt; \" \";\n }\n std::cout &lt;&lt; std::endl;\n\n // Use a lambda expression to define rand7\n auto rand7 = [&amp;rand5]()-&gt;int\n {\n for (int result = 0; ; result = 0)\n {\n // Take advantage of the fact that\n // 5**6 = 15625 = 15624 + 1 = 7 * (2232) + 1.\n // So we only have to discard one out of every 15625 numbers generated.\n\n // Generate a 6-digit number in base 5\n for (int i = 0; i != 6; ++i)\n {\n result = 5 * result + (rand5() - 1);\n }\n\n // result is in the range [0, 15625)\n if (result == 15625 - 1)\n {\n // Discard this number\n continue;\n }\n\n // We now know that result is in the range [0, 15624), a range that can\n // be divided evenly into 7 buckets guaranteeing uniformity\n result /= 2232;\n return 1 + result;\n }\n };\n\n for (int i = 0; i != n; ++i)\n {\n std::cout &lt;&lt; rand7() &lt;&lt; \" \";\n }\n std::cout &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 26373727, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>The simple solution has been well covered: take two <code>random5</code> samples for one <code>random7</code> result and do it over if the result is outside the range that generates a uniform distribution. If your goal is to reduce the number of calls to <code>random5</code> this is extremely wasteful - the average number of calls to <code>random5</code> for each <code>random7</code> output is 2.38 rather than 2 due to the number of thrown away samples.</p>\n\n<p>You can do better by using more <code>random5</code> inputs to generate more than one <code>random7</code> output at a time. For results calculated with a 31-bit integer, the optimum comes when using 12 calls to <code>random5</code> to generate 9 <code>random7</code> outputs, taking an average of 1.34 calls per output. It's efficient because only 2018983 out of 244140625 results need to be scrapped, or less than 1%.</p>\n\n<p>Demo in Python:</p>\n\n<pre><code>def random5():\n return random.randint(1, 5)\n\ndef random7gen(n):\n count = 0\n while n &gt; 0:\n samples = 6 * 7**9\n while samples &gt;= 6 * 7**9:\n samples = 0\n for i in range(12):\n samples = samples * 5 + random5() - 1\n count += 1\n samples //= 6\n for outputs in range(9):\n yield samples % 7 + 1, count\n samples //= 7\n count = 0\n n -= 1\n if n == 0: break\n\n&gt;&gt;&gt; from collections import Counter\n&gt;&gt;&gt; Counter(x for x,i in random7gen(10000000))\nCounter({2: 1430293, 4: 1429298, 1: 1428832, 7: 1428571, 3: 1428204, 5: 1428134, 6: 1426668})\n&gt;&gt;&gt; sum(i for x,i in random7gen(10000000)) / 10000000.0\n1.344606\n</code></pre>\n" }, { "answer_id": 26405409, "author": "Martin", "author_id": 2215617, "author_profile": "https://Stackoverflow.com/users/2215617", "pm_score": 1, "selected": false, "text": "<p>Would be cool if someone could give me feedback on this one, I used the JUNIT without assert Pattern because it's easy and fast to get it running in Eclipse, I could also have just defined a main method. By the way, I am assuming rand5 gives values 0-4, adding 1 would make it 1-5, same with rand7... So the discussion should be on the solution, it's distribution, not on wether it goes from 0-4 or 1-5...</p>\n\n<pre><code>package random;\n\nimport java.util.Random;\n\nimport org.junit.Test;\n\npublic class RandomTest {\n\n\n @Test\n public void testName() throws Exception {\n long times = 100000000;\n int indexes[] = new int[7];\n for(int i = 0; i &lt; times; i++) {\n int rand7 = rand7();\n indexes[rand7]++;\n }\n\n for(int i = 0; i &lt; 7; i++)\n System.out.println(\"Value \" + i + \": \" + indexes[i]);\n }\n\n\n public int rand7() {\n return (rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5()) % 7;\n }\n\n\n public int rand5() {\n return new Random().nextInt(5);\n }\n\n\n}\n</code></pre>\n\n<p>When I run it, I get this result:</p>\n\n<pre><code>Value 0: 14308087\nValue 1: 14298303\nValue 2: 14279731\nValue 3: 14262533\nValue 4: 14269749\nValue 5: 14277560\nValue 6: 14304037\n</code></pre>\n\n<p>This seems like a very fair distribution, doesn't it?</p>\n\n<p>If I add rand5() less or more times (where the amount of times is not divisible by 7), the distribution clearly shows offsets. For instance, adding <code>rand5()</code> 3 times:</p>\n\n<pre><code>Value 0: 15199685\nValue 1: 14402429\nValue 2: 12795649\nValue 3: 12796957\nValue 4: 14402252\nValue 5: 15202778\nValue 6: 15200250\n</code></pre>\n\n<p>So, this would lead to the following:</p>\n\n<pre><code>public int rand(int range) {\n int randomValue = 0;\n for(int i = 0; i &lt; range; i++) {\n randomValue += rand5();\n }\n return randomValue % range;\n\n}\n</code></pre>\n\n<p>And then, I could go further:</p>\n\n<pre><code>public static final int ORIGN_RANGE = 5;\npublic static final int DEST_RANGE = 7;\n\n@Test\npublic void testName() throws Exception {\n long times = 100000000;\n int indexes[] = new int[DEST_RANGE];\n for(int i = 0; i &lt; times; i++) {\n int rand7 = convertRand(DEST_RANGE, ORIGN_RANGE);\n indexes[rand7]++;\n }\n\n for(int i = 0; i &lt; DEST_RANGE; i++)\n System.out.println(\"Value \" + i + \": \" + indexes[i]);\n}\n\n\npublic int convertRand(int destRange, int originRange) {\n int randomValue = 0;\n for(int i = 0; i &lt; destRange; i++) {\n randomValue += rand(originRange);\n }\n return randomValue % destRange;\n\n}\n\n\npublic int rand(int range) {\n return new Random().nextInt(range);\n}\n</code></pre>\n\n<p>I tried this replacing the destRange and originRange with various values (even 7 for ORIGIN and 13 for DEST), and I get this distribution:</p>\n\n<pre><code>Value 0: 7713763\nValue 1: 7706552\nValue 2: 7694697\nValue 3: 7695319\nValue 4: 7688617\nValue 5: 7681691\nValue 6: 7674798\nValue 7: 7680348\nValue 8: 7685286\nValue 9: 7683943\nValue 10: 7690283\nValue 11: 7699142\nValue 12: 7705561\n</code></pre>\n\n<p>What I can conclude from here is that you can change any random to anyother by suming the origin random \"destination\" times. This will get a kind of gaussian distribution (being the middle values more likely, and the edge values more uncommon). However, the modulus of destination seems to distribute itself evenly across this gaussian distribution... It would be great to have feedback from a mathematician... </p>\n\n<p>What is cool is that the cost is 100% predictable and constant, whereas other solutions cause a small probability of infinite loop...</p>\n" }, { "answer_id": 26538543, "author": "Michael Katkov", "author_id": 955321, "author_profile": "https://Stackoverflow.com/users/955321", "pm_score": 0, "selected": false, "text": "<p>First, I move ramdom5() on the 1 point 6 times, to get 7 random numbers. \nSecond, I add 7 numbers to obtain common sum. \nThird, I get remainder of the division at 7.\nLast, I add 1 to get results from 1 till 7.\nThis method gives an equal probability of getting numbers in the range from 1 to 7, with the exception of 1. 1 has a slightly higher probability.</p>\n\n<pre><code>public int random7(){\n Random random = new Random();\n //function (1 + random.nextInt(5)) is given\n int random1_5 = 1 + random.nextInt(5); // 1,2,3,4,5\n int random2_6 = 2 + random.nextInt(5); // 2,3,4,5,6\n int random3_7 = 3 + random.nextInt(5); // 3,4,5,6,7\n int random4_8 = 4 + random.nextInt(5); // 4,5,6,7,8\n int random5_9 = 5 + random.nextInt(5); // 5,6,7,8,9\n int random6_10 = 6 + random.nextInt(5); //6,7,8,9,10\n int random7_11 = 7 + random.nextInt(5); //7,8,9,10,11\n\n //sumOfRandoms is between 28 and 56\n int sumOfRandoms = random1_5 + random2_6 + random3_7 + \n random4_8 + random5_9 + random6_10 + random7_11;\n //result is number between 0 and 6, and\n //equals 0 if sumOfRandoms = 28 or 35 or 42 or 49 or 56 , 5 options\n //equals 1 if sumOfRandoms = 29 or 36 or 43 or 50, 4 options\n //equals 2 if sumOfRandoms = 30 or 37 or 44 or 51, 4 options\n //equals 3 if sumOfRandoms = 31 or 38 or 45 or 52, 4 options\n //equals 4 if sumOfRandoms = 32 or 39 or 46 or 53, 4 options\n //equals 5 if sumOfRandoms = 33 or 40 or 47 or 54, 4 options\n //equals 6 if sumOfRandoms = 34 or 41 or 48 or 55, 4 options\n //It means that the probabilities of getting numbers between 0 and 6 are almost equal.\n int result = sumOfRandoms % 7;\n //we should add 1 to move the interval [0,6] to the interval [1,7]\n return 1 + result;\n}\n</code></pre>\n" }, { "answer_id": 26539070, "author": "jongo45", "author_id": 1447749, "author_profile": "https://Stackoverflow.com/users/1447749", "pm_score": 0, "selected": false, "text": "<p>Here's mine, this attempts to recreate <code>Math.random()</code> from multiple <code>rand5()</code> function calls, reconstructing a unit interval (the output range of <code>Math.random()</code>) by re-constructing it with &quot;weighted fractions&quot;(?). Then using this random unit interval to produce a random integer between 1 and 7:</p>\n<pre><code>function rand5(){\n return Math.floor(Math.random()*5)+1;\n}\nfunction rand7(){\n var uiRandom=0;\n var div=1;\n for(var i=0; i&lt;7; i++){\n div*=5;\n var term=(rand5()-1)/div;\n uiRandom+=term;\n }\n //return uiRandom;\n return Math.floor(uiRandom*7)+1; \n}\n</code></pre>\n<p>To paraphrase: We take a random integers between 0-4 (just <code>rand5()-1</code>) and multiply each result with 1/5, 1/25, 1/125, ... and then sum them together. It's similar to how binary weighted fractions work; I suppose instead, we'll call it a quinary (base-5) weighted fraction: Producing a number from 0 -- 0.999999 as a series of (1/5)^n terms.</p>\n<p>Modifying the function to take any input/output random integer range should be trivial. And the code above can be optimized when rewritten as a closure.</p>\n<hr />\n<p>Alternatively, we can also do this:</p>\n<pre><code>function rand5(){\n return Math.floor(Math.random()*5)+1;\n}\nfunction rand7(){\n var buffer=[];\n var div=1;\n for (var i=0; i&lt;7; i++){\n buffer.push((rand5()-1).toString(5));\n div*=5;\n }\n var n=parseInt(buffer.join(&quot;&quot;),5);\n var uiRandom=n/div;\n //return uiRandom;\n return Math.floor(uiRandom*7)+1; \n}\n</code></pre>\n<p>Instead of fiddling with constructing a quinary (base-5) weighted fractions, we'll actually make a quinary number and turn it into a fraction (0--0.9999... as before), then compute our random 1--7 digit from there.</p>\n<p>Results for above (code snippet #2: 3 runs of 100,000 calls each):</p>\n<blockquote>\n<p>1: 14263; 2: 14414; 3: 14249; 4: 14109; 5: 14217; 6: 14361; 7: 14387</p>\n<p>1: 14205; 2: 14394; 3: 14238; 4: 14187; 5: 14384; 6: 14224; 7: 14368</p>\n<p>1: 14425; 2: 14236; 3: 14334; 4: 14232; 5: 14160; 6: 14320; 7: 14293</p>\n</blockquote>\n" }, { "answer_id": 29886312, "author": "Colin Su", "author_id": 492611, "author_profile": "https://Stackoverflow.com/users/492611", "pm_score": 0, "selected": false, "text": "<p>the main conception of this problem is about normal distribution, here provided a simple and recursive solution to this problem</p>\n\n<p>presume we already have <code>rand5()</code> in our scope:</p>\n\n<pre><code>def rand7():\n # twoway = 0 or 1 in the same probability\n twoway = None\n while not twoway in (1, 2):\n twoway = rand5()\n twoway -= 1\n\n ans = rand5() + twoway * 5\n\n return ans if ans in range(1,8) else rand7()\n</code></pre>\n\n<h1>Explanation</h1>\n\n<p>We can divide this program into 2 parts:</p>\n\n<ol>\n<li>looping rand5() until we found 1 or 2, that means we have 1/2 probability to have 1 or 2 in the variable <code>twoway</code></li>\n<li>composite <code>ans</code> by <code>rand5() + twoway * 5</code>, this is exactly the result of <code>rand10()</code>, if this did not match our need (1~7), then we run rand7 again.</li>\n</ol>\n\n<p>P.S. we <strong>cannot</strong> directly run a while loop in the second part due to each probability of <code>twoway</code> need to be individual.</p>\n\n<p>But there is a trade-off, because of the while loop in the first section and the recursion in the return statement, this function doesn't guarantee the execution time, it is actually not effective.</p>\n\n<h1>Result</h1>\n\n<p>I've made a simple test for observing the distribution to my answer.</p>\n\n<pre><code>result = [ rand7() for x in xrange(777777) ]\n\nans = {\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n}\n\nfor i in result:\n ans[i] += 1\n\nprint ans\n</code></pre>\n\n<p>It gave</p>\n\n<pre><code>{1: 111170, 2: 110693, 3: 110651, 4: 111260, 5: 111197, 6: 111502, 7: 111304}\n</code></pre>\n\n<p>Therefore we could know this answer is in a normal distribution.</p>\n\n<h1>Simplified Answer</h1>\n\n<p>If you don't care about the execution time of this function, here's a simplified answer based on the above answer I gave:</p>\n\n<pre><code>def rand7():\n ans = rand5() + (rand5()-1) * 5\n return ans if ans &lt; 8 else rand7()\n</code></pre>\n\n<p>This augments the probability of value which is greater than 8 but probably will be the shortest answer to this problem.</p>\n" }, { "answer_id": 30189285, "author": "user2622350", "author_id": 2622350, "author_profile": "https://Stackoverflow.com/users/2622350", "pm_score": -1, "selected": false, "text": "<pre><code>def rand5():\n return random.randint(1,5) #return random integers from 1 to 5\n\ndef rand7():\n rand = rand5()+rand5()-1\n if rand &gt; 7: #if numbers &gt; 7, call rand7() again\n return rand7()\n print rand%7 + 1\n</code></pre>\n\n<p>I guess this will the easiest solution but everywhere people have suggested <code>5*rand5() + rand5() - 5</code> like in <a href=\"http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/\" rel=\"nofollow\">http://www.geeksforgeeks.org/generate-integer-from-1-to-7-with-equal-probability/</a>.\nCan someone explain what is wrong with <code>rand5()+rand5()-1</code></p>\n" }, { "answer_id": 30567290, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 1, "selected": false, "text": "<p>Similar to <a href=\"https://stackoverflow.com/a/21252243/2417578\">Martin's answer</a>, but resorts to throwing entropy away much less frequently:</p>\n\n<pre><code>int rand7(void) {\n static int m = 1;\n static int r = 0;\n\n for (;;) {\n while (m &lt;= INT_MAX / 5) {\n r = r + m * (rand5() - 1);\n m = m * 5;\n }\n int q = m / 7;\n if (r &lt; q * 7) {\n int i = r % 7;\n r = r / 7;\n m = q;\n return i + 1;\n }\n r = r - q * 7;\n m = m - q * 7;\n }\n}\n</code></pre>\n\n<p>Here we build up a random value between <code>0</code> and <code>m-1</code>, and try to maximise <code>m</code> by adding as much state as will fit without overflow (<code>INT_MAX</code> being the largest value that will fit in an <code>int</code> in C, or you can replace that with any large value that makes sense in your language and architecture).</p>\n\n<p>Then; if <code>r</code> falls within the largest possible interval evenly divisible by 7 then it contains a viable result and we can divide that interval by 7 and take the remainder as our result and return the rest of the value to our entropy pool. Otherwise <code>r</code> is in the other interval which doesn't divide evenly and we have to discard and restart our entropy pool from that ill-fitting interval.</p>\n\n<p>Compared with the popular answers in here, it calls <code>rand5()</code> about half as often on average.</p>\n\n<p>The divides can be factored out into trivial bit-twiddles and LUTs for performance.</p>\n" }, { "answer_id": 30569344, "author": "sh1", "author_id": 2417578, "author_profile": "https://Stackoverflow.com/users/2417578", "pm_score": 2, "selected": false, "text": "<p>Another answer which appears to have not been covered here:</p>\n\n<pre><code>int rand7() {\n int r = 7 / 2;\n for (int i = 0; i &lt; 28; i++)\n r = ((rand5() - 1) * 7 + r) / 5;\n return r + 1;\n}\n</code></pre>\n\n<p>On every iteration <code>r</code> is a random value between 0 and 6 inclusive. This is appended (base 7) to a random value between 0 and 4 inclusive, and the result is divided by 5, giving a new random value in the range of 0 to 6 inclusive. <code>r</code> starts with a substantial bias (<code>r = 3</code> is very biased!) but each iteration divides that bias by 5.</p>\n\n<p>This method is <em>not</em> perfectly uniform; however, the bias is vanishingly small. Something in the order of 1/(2**64). What's important about this approach is that it has constant execution time (assuming <code>rand5()</code> also has constant execution time). No theoretical concerns that an unlucky call could iterate forever picking bad values.</p>\n\n<hr>\n\n<p>Also, a sarcastic answer for good measure (deliberately or not, it has been covered):</p>\n\n<p>1-5 is already within the range 1-7, therefore the following is a valid implementation:</p>\n\n<pre><code>int rand7() {\n return rand5();\n}\n</code></pre>\n\n<p>Question did not ask for uniform distribution.</p>\n" }, { "answer_id": 31949527, "author": "robermorales", "author_id": 887427, "author_profile": "https://Stackoverflow.com/users/887427", "pm_score": 0, "selected": false, "text": "<p>This algorithm reduces the number of calls of rand5 to the theoretical minimum of 7/5. Calling it 7 times by produce the next 5 rand7 numbers.</p>\n\n<p>There are no rejection of any random bit, and there are NO possibility to keep waiting the result for always.</p>\n\n<pre><code>#!/usr/bin/env ruby\n\n# random integer from 1 to 5\ndef rand5\n STDERR.putc '.'\n 1 + rand( 5 )\nend\n\n@bucket = 0\n@bucket_size = 0\n\n# random integer from 1 to 7\ndef rand7\n if @bucket_size == 0\n @bucket = 7.times.collect{ |d| rand5 * 5**d }.reduce( &amp;:+ )\n @bucket_size = 5\n end\n\n next_rand7 = @bucket%7 + 1\n\n @bucket /= 7\n @bucket_size -= 1\n\n return next_rand7\nend\n\n35.times.each{ putc rand7.to_s }\n</code></pre>\n" }, { "answer_id": 33795768, "author": "Thirlan", "author_id": 590059, "author_profile": "https://Stackoverflow.com/users/590059", "pm_score": 4, "selected": false, "text": "<pre><code>int rand7() {\n int value = rand5()\n + rand5() * 2\n + rand5() * 3\n + rand5() * 4\n + rand5() * 5\n + rand5() * 6;\n return value%7;\n}\n</code></pre>\n\n<p>Unlike the chosen solution, the algorithm will run in constant time. It does however make 2 more calls to rand5 than the average run time of the chosen solution.</p>\n\n<p>Note that this generator is not perfect (the number 0 has 0.0064% more chance than any other number), but for most practical purposes the guarantee of constant time probably outweighs this inaccuracy.</p>\n\n<p><strong>Explanation</strong></p>\n\n<p>This solution is derived from the fact that the number 15,624 is divisible by 7 and thus if we can randomly and uniformly generate numbers from 0 to 15,624 and then take mod 7 we can get a near-uniform rand7 generator. Numbers from 0 to 15,624 can be uniformly generated by rolling rand5 6 times and using them to form the digits of a base 5 number as follows:</p>\n\n<pre><code>rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5\n</code></pre>\n\n<p>Properties of mod 7 however allow us to simplify the equation a bit:</p>\n\n<pre><code>5^5 = 3 mod 7\n5^4 = 2 mod 7\n5^3 = 6 mod 7\n5^2 = 4 mod 7\n5^1 = 5 mod 7\n</code></pre>\n\n<p>So</p>\n\n<pre><code>rand5 * 5^5 + rand5 * 5^4 + rand5 * 5^3 + rand5 * 5^2 + rand5 * 5 + rand5\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>rand5 * 3 + rand5 * 2 + rand5 * 6 + rand5 * 4 + rand5 * 5 + rand5\n</code></pre>\n\n<p><strong>Theory</strong></p>\n\n<p>The number 15,624 was not chosen randomly, but can be discovered using fermat's little theorem, which states that if p is a prime number then</p>\n\n<pre><code>a^(p-1) = 1 mod p\n</code></pre>\n\n<p>So this gives us,</p>\n\n<pre><code>(5^6)-1 = 0 mod 7\n</code></pre>\n\n<p>(5^6)-1 is equal to</p>\n\n<pre><code>4 * 5^5 + 4 * 5^4 + 4 * 5^3 + 4 * 5^2 + 4 * 5 + 4\n</code></pre>\n\n<p>This is a number in base 5 form and thus we can see that this method can be used to go from any random number generator to any other random number generator. Though a small bias towards 0 is always introduced when using the exponent p-1.</p>\n\n<p>To generalize this approach and to be more accurate we can have a function like this:</p>\n\n<pre><code>def getRandomconverted(frm, to):\n s = 0\n for i in range(to):\n s += getRandomUniform(frm)*frm**i\n mx = 0\n for i in range(to):\n mx = (to-1)*frm**i \n mx = int(mx/to)*to # maximum value till which we can take mod\n if s &lt; mx:\n return s%to\n else:\n return getRandomconverted(frm, to)\n</code></pre>\n" }, { "answer_id": 43161105, "author": "Devendra Lattu", "author_id": 2889297, "author_profile": "https://Stackoverflow.com/users/2889297", "pm_score": 1, "selected": false, "text": "<ol>\n<li>What is a simple solution? <code>(rand5() + rand5()) % 7 + 1</code>\n<br></li>\n<li>What is an effective solution to reduce memory usage or run on a slower CPU? <code>Yes, this is effective as it calls rand5() only twice and have O(1) space complexity</code>\n<br></li>\n</ol>\n\n<p>Consider <code>rand5()</code> gives out random numbers from 1 to 5(inclusive).<br>\n(1 + 1) % 7 + 1 = 3 <br>\n(1 + 2) % 7 + 1 = 4 <br>\n(1 + 3) % 7 + 1 = 5 <br>\n(1 + 4) % 7 + 1 = 6 <br>\n(1 + 5) % 7 + 1 = 7 <br></p>\n\n<p>(2 + 1) % 7 + 1 = 4 <br>\n(2 + 2) % 7 + 1 = 5 <br>\n(2 + 3) % 7 + 1 = 6 <br>\n(2 + 4) % 7 + 1 = 7 <br>\n(2 + 5) % 7 + 1 = 1 <br>\n...</p>\n\n<p>(5 + 1) % 7 + 1 = 7 <br>\n(5 + 2) % 7 + 1 = 1 <br>\n(5 + 3) % 7 + 1 = 2 <br>\n(5 + 4) % 7 + 1 = 3 <br>\n(5 + 5) % 7 + 1 = 4 <br>\n...</p>\n\n<p>and so on</p>\n" }, { "answer_id": 47603332, "author": "Shambho", "author_id": 3547167, "author_profile": "https://Stackoverflow.com/users/3547167", "pm_score": 2, "selected": false, "text": "<p>I think I have four answers, two giving exact solutions <a href=\"https://stackoverflow.com/a/137809/3547167\">like that of @Adam Rosenfield</a> but without the infinite loop problem, and other two with almost perfect solution but faster implementation than first one. </p>\n\n<p>The best exact solution requires 7 calls to <code>rand5</code>, but lets proceed in order to understand. </p>\n\n<h1>Method 1 - Exact</h1>\n\n<p>Strength of Adam's answer is that it gives a perfect uniform distribution, and there is very high probability (21/25) that only two calls to rand5() will be needed. However, worst case is infinite loop. </p>\n\n<p>The first solution below also gives a perfect uniform distribution, but requires a total of 42 calls to <code>rand5</code>. No infinite loops.</p>\n\n<p>Here is an R implementation:</p>\n\n<pre><code>rand5 &lt;- function() sample(1:5,1)\n\nrand7 &lt;- function() (sum(sapply(0:6, function(i) i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6)) %% 7) + 1\n</code></pre>\n\n<p>For people not familiar with R, here is a simplified version:</p>\n\n<pre><code>rand7 = function(){\n r = 0 \n for(i in 0:6){\n r = r + i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6\n }\n return r %% 7 + 1\n}\n</code></pre>\n\n<p>The distribution of <code>rand5</code> will be preserved. If we do the math, each of the 7 iterations of the loop has 5^6 possible combinations, thus total number of possible combinations are <code>(7 * 5^6) %% 7 = 0</code>. Thus we can divide the random numbers generated in equal groups of 7. See method two for more discussion on this.</p>\n\n<p>Here are all the possible combinations:</p>\n\n<pre><code>table(apply(expand.grid(c(outer(1:5,0:6,\"+\")),(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n15625 15625 15625 15625 15625 15625 15625 \n</code></pre>\n\n<p>I think it's straight forward to show that Adam's method will run much much faster. The probability that there are 42 or more calls to <code>rand5</code> in Adam's solution is very small (<code>(4/25)^21 ~ 10^(-17)</code>). </p>\n\n<h1>Method 2 - Not Exact</h1>\n\n<p>Now the second method, which is almost uniform, but requires 6 calls to <code>rand5</code>:</p>\n\n<pre><code>rand7 &lt;- function() (sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1\n</code></pre>\n\n<p>Here is a simplified version:</p>\n\n<pre><code>rand7 = function(){\n r = 0 \n for(i in 1:6){\n r = r + i*rand5()\n }\n return r %% 7 + 1\n}\n</code></pre>\n\n<p>This is essentially one iteration of method 1. If we generate all possible combinations, here is resulting counts:</p>\n\n<pre><code>table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n2233 2232 2232 2232 2232 2232 2232\n</code></pre>\n\n<p>One number will appear once more in <code>5^6 = 15625</code> trials.</p>\n\n<p>Now, in Method 1, by adding 1 to 6, we move the number 2233 to each of the successive point. Thus the total number of combinations will match up. This works because 5^6 %% 7 = 1, and then we do 7 appropriate variations, so (7 * 5^6 %% 7 = 0). </p>\n\n<h1>Method 3 - Exact</h1>\n\n<p>If the argument of method 1 and 2 is understood, method 3 follows, and requires only 7 calls to <code>rand5</code>. At this point, I feel this is the minimum number of calls needed for an exact solution.</p>\n\n<p>Here is an R implementation:</p>\n\n<pre><code>rand5 &lt;- function() sample(1:5,1)\n\nrand7 &lt;- function() (sum(sapply(1:7, function(i) i * rand5())) %% 7) + 1\n</code></pre>\n\n<p>For people not familiar with R, here is a simplified version:</p>\n\n<pre><code>rand7 = function(){\n r = 0 \n for(i in 1:7){\n r = r + i * rand5()\n }\n return r %% 7 + 1\n}\n</code></pre>\n\n<p>The distribution of <code>rand5</code> will be preserved. If we do the math, each of the 7 iterations of the loop has 5 possible outcomes, thus total number of possible combinations are <code>(7 * 5) %% 7 = 0</code>. Thus we can divide the random numbers generated in equal groups of 7. See method one and two for more discussion on this.</p>\n\n<p>Here are all the possible combinations:</p>\n\n<pre><code>table(apply(expand.grid(0:6,(1:5)),1,sum) %% 7 + 1)\n\n1 2 3 4 5 6 7 \n5 5 5 5 5 5 5 \n</code></pre>\n\n<p>I think it's straight forward to show that Adam's method will still run faster. The probability that there are 7 or more calls to <code>rand5</code> in Adam's solution is still small (<code>(4/25)^3 ~ 0.004</code>). </p>\n\n<h1>Method 4 - Not Exact</h1>\n\n<p>This is a minor variation of the the second method. It is almost uniform, but requires 7 calls to <code>rand5</code>, that is one additional to method 2:</p>\n\n<pre><code>rand7 &lt;- function() (rand5() + sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1\n</code></pre>\n\n<p>Here is a simplified version:</p>\n\n<pre><code>rand7 = function(){\n r = 0 \n for(i in 1:6){\n r = r + i*rand5()\n }\n return (r+rand5()) %% 7 + 1\n}\n</code></pre>\n\n<p>If we generate all possible combinations, here is resulting counts:</p>\n\n<pre><code>table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6,1:5),1,sum) %% 7 + 1)\n\n 1 2 3 4 5 6 7 \n11160 11161 11161 11161 11161 11161 11160\n</code></pre>\n\n<p>Two numbers will appear once less in <code>5^7 = 78125</code> trials. For most purposes, I can live with that.</p>\n" }, { "answer_id": 51996385, "author": "Hassan", "author_id": 9798613, "author_profile": "https://Stackoverflow.com/users/9798613", "pm_score": -1, "selected": false, "text": "<p>This is the answer I came up with but these complicated answers are making me think this is completely off/ :))</p>\n\n<pre><code>import random\n\ndef rand5():\n return float(random.randint(0,5))\n\ndef rand7():\n random_val = rand5()\n return float(random.randint((random_val-random_val),7))\n\nprint rand7()\n</code></pre>\n" }, { "answer_id": 52253512, "author": "ibrahim tanyalcin", "author_id": 9410412, "author_profile": "https://Stackoverflow.com/users/9410412", "pm_score": 1, "selected": false, "text": "<p>Came here from a link from expanding a float range. This one is more fun. Instead of how I got to the conclusion, it occurred to me that for a given random integer generating function <code>f</code> with \"base\" <em>b</em> (4 in this case,i'll tell why), it can be expanded like below:</p>\n\n<pre><code>(b^0 * f() + b^1 * f() + b^2 * f() .... b^p * f()) / (b^(p+1) - 1) * (b-1)\n</code></pre>\n\n<p>This will convert a random generator to a FLOAT generator. I will define 2 parameters here the <code>b</code> and the <code>p</code>. Although the \"base\" here is 4, b can in fact be anything, it can also be an irrational number etc. <code>p</code>, i call precision is a degree of how well grained you want your float generator to be. Think of this as the number of calls made to <code>rand5</code> for each call of <code>rand7</code>.</p>\n\n<p>But I realized if you set b to base+1 (which is 4+1 = 5 in this case), it's a sweet spot and you'll get a uniform distribution. First get rid of this 1-5 generator, it is in truth rand4() + 1:</p>\n\n<pre><code>function rand4(){\n return Math.random() * 5 | 0;\n}\n</code></pre>\n\n<p>To get there, you can substitute <code>rand4</code> with <code>rand5()-1</code></p>\n\n<p>Next is to convert rand4 from an integer generator to a float generator</p>\n\n<pre><code>function toFloat(f,b,p){\n b = b || 2;\n p = p || 3;\n return (Array.apply(null,Array(p))\n .map(function(d,i){return f()})\n .map(function(d,i){return Math.pow(b,i)*d})\n .reduce(function(ac,d,i){return ac += d;}))\n /\n (\n (Math.pow(b,p) - 1)\n /(b-1)\n )\n}\n</code></pre>\n\n<p>This will apply the first function I wrote to a given rand function. Try it:</p>\n\n<pre><code>toFloat(rand4) //1.4285714285714286 base = 2, precision = 3\ntoFloat(rand4,3,4) //0.75 base = 3, precision = 4\ntoFloat(rand4,4,5) //3.7507331378299122 base = 4, precision = 5\ntoFloat(rand4,5,6) //0.2012288786482335 base = 5, precision =6\n...\n</code></pre>\n\n<p>Now you can convert this float range (0-4 INCLUSIVE) to any other float range and then downgrade it to be an integer. Here our base is <code>4</code> because we are dealing with <code>rand4</code>, therefore a value <code>b=5</code> will give you a uniform distribution. As the b grows past 4, you will start introducing periodic gaps in the distribution. I tested for b values ranging from 2 to 8 with 3000 points each and compared to native Math.random of javascript, looks to me even better than the native one itself:</p>\n\n<p><a href=\"http://jsfiddle.net/ibowankenobi/r57v432t/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/ibowankenobi/r57v432t/</a></p>\n\n<p>For the above link, click on the \"bin\" button on the top side of the distributions to decrease the binning size. The last graph is native Math.random, the 4th one where d=5 is uniform.</p>\n\n<p>After you get your float range either multiply with 7 and throw the decimal part or multiply with 7, subtract 0.5 and round:</p>\n\n<pre><code>((toFloat(rand4,5,6)/4 * 7) | 0) + 1 ---&gt; occasionally you'll get 8 with 1/4^6 probability.\nMath.round((toFloat(rand4,5,6)/4 * 7) - 0.5) + 1 --&gt; between 1 and 7\n</code></pre>\n" }, { "answer_id": 56184907, "author": "Ishpreet", "author_id": 5811973, "author_profile": "https://Stackoverflow.com/users/5811973", "pm_score": -1, "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>// returns random number between 0-5 with equal probability\r\nfunction rand5() {\r\n return Math.floor(Math.random() * 6);\r\n}\r\n\r\n// returns random number between 0-7 with equal probability\r\nfunction rand7() {\r\n if(rand5() % 2 == 0 &amp;&amp; rand5() % 2 == 0) { \r\n return 6 + rand5() % 2;\r\n } else {\r\n return rand5();\r\n }\r\n}\r\n\r\nconsole.log(rand7());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57677538, "author": "Emil Jeřábek", "author_id": 516539, "author_profile": "https://Stackoverflow.com/users/516539", "pm_score": 0, "selected": false, "text": "<p>Here is a solution that tries to minimize the number of calls to rand5() while keeping the implementation simple and efficient; in particular, it does not require arbitrary large integers unlike Adam Rosenfield’s second answer. It exploits the fact that 23/19 = 1.21052... is a good rational approximation to log(7)/log(5) = 1.20906..., thus we can generate 19 random elements of {1,...,7} out of 23 random elements of {1,...,5} by rejection sampling with only a small rejection probability. On average, the algorithm below takes about 1.266 calls to rand5() for each call to rand7(). If the distribution of rand5() is uniform, so is rand7().</p>\n\n<pre><code>uint_fast64_t pool;\n\nint capacity = 0;\n\nvoid new_batch (void)\n{\n uint_fast64_t r;\n int i;\n\n do {\n r = 0;\n for (i = 0; i &lt; 23; i++)\n r = 5 * r + (rand5() - 1);\n } while (r &gt;= 11398895185373143ULL); /* 7**19, a bit less than 5**23 */\n\n pool = r;\n capacity = 19;\n}\n\nint rand7 (void)\n{\n int r;\n\n if (capacity == 0)\n new_batch();\n\n r = pool % 7;\n pool /= 7;\n capacity--;\n\n return r + 1;\n}\n</code></pre>\n" }, { "answer_id": 63679421, "author": "Peter O.", "author_id": 815724, "author_profile": "https://Stackoverflow.com/users/815724", "pm_score": 0, "selected": false, "text": "<p>For the range [1, 5] to [1, 7], this is equivalent to rolling a 7-sided die with a 5-sided one.</p>\n<p>However, this can't be done without &quot;wasting&quot; randomness (or running forever in the worst case), since all the prime factors of 7 (namely 7) don't divide 5. Thus, the best that can be done is to use rejection sampling to get arbitrarily close to no &quot;waste&quot; of randomness (such as by batching multiple rolls of the 5-sided die until 5^<em>n</em> is &quot;close enough&quot; to a power of 7). Solutions to this problem were already given in other answers.</p>\n<p>More generally, an algorithm to roll a <em>k</em>-sided die with a <em>p</em>-sided die will inevitably &quot;waste&quot; randomness (and run forever in the worst case) unless &quot;every prime number dividing <em>k</em> also divides <em>p</em>&quot;, according to Lemma 3 in &quot;<a href=\"https://perso.math.u-pem.fr/kloeckner.benoit/papiers/DiceSimulation.pdf\" rel=\"nofollow noreferrer\">Simulating a dice with a dice</a>&quot; by B. Kloeckner. For example, take the much more practical case that <em>p</em> is a power of 2 and <em>k</em> is arbitrary. In this case, this &quot;waste&quot; and indefinite running time are inevitable unless <em>k</em> is also a power of 2.</p>\n" }, { "answer_id": 71476397, "author": "ldmtwo", "author_id": 3746632, "author_profile": "https://Stackoverflow.com/users/3746632", "pm_score": 0, "selected": false, "text": "<p><strong>Python: There's a simple two line answer that uses a combination of spatial algebra and modulus. This is not intuitive. My explanation of it is confusing, but is correct.</strong></p>\n<p><code>Knowing that 5*7=35 and 7/5 = 1 remainder 2. How to guarantee that sum of remainders is always 0? 5*[7/5 = 1 remainder 2] --&gt; 35/5 = 7 remainder 0</code></p>\n<p>Imagine we had a ribbon that was wrapped around a pole with a perimeter=7. The ribbon would need to be 35 units to wrap evenly. Select 7 random ribbon pieces <code>len=[1...5]</code>. The effective length ignoring the wrap around is the same as this method of converting rand5() into rand7().</p>\n<pre><code>import numpy as np\nimport pandas as pd\n# display is a notebook function FYI\ndef rand5(): ## random uniform int [1...5]\n return np.random.randint(1,6)\n\nn_trials = 1000\nsamples = [rand5() for _ in range(n_trials)]\n\ndisplay(pd.Series(samples).value_counts(normalize=True))\n# 4 0.2042\n# 5 0.2041\n# 2 0.2010\n# 1 0.1981\n# 3 0.1926\n# dtype: float64\n \ndef rand7(): # magic algebra\n x = sum(rand5() for _ in range(7))\n return x%7 + 1\n\nsamples = [rand7() for _ in range(n_trials)]\n\ndisplay(pd.Series(samples).value_counts(normalize=False))\n# 6 1475\n# 2 1475\n# 3 1456\n# 1 1423\n# 7 1419\n# 4 1393\n# 5 1359\n# dtype: int64\n \ndf = pd.DataFrame([\n pd.Series([rand7() for _ in range(n_trials)]).value_counts(normalize=True)\n for _ in range(1000)\n])\ndf.describe()\n# 1 2 3 4 5 6 7\n# count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000\n# mean 0.142885 0.142928 0.142523 0.142266 0.142704 0.143048 0.143646\n# std 0.010807 0.011526 0.010966 0.011223 0.011052 0.010983 0.011153\n# min 0.112000 0.108000 0.101000 0.110000 0.100000 0.109000 0.110000\n# 25% 0.135000 0.135000 0.135000 0.135000 0.135000 0.135000 0.136000\n# 50% 0.143000 0.142000 0.143000 0.142000 0.143000 0.142000 0.143000\n# 75% 0.151000 0.151000 0.150000 0.150000 0.150000 0.150000 0.151000\n# max 0.174000 0.181000 0.175000 0.178000 0.189000 0.176000 0.179000\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22535/" ]
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.
There is no (exactly correct) solution which will run in a constant amount of time, since 1/7 is an infinite decimal in base 5. One simple solution would be to use rejection sampling, e.g.: ``` int i; do { i = 5 * (rand5() - 1) + rand5(); // i is now uniformly random between 1 and 25 } while(i > 21); // i is now uniformly random between 1 and 21 return i % 7 + 1; // result is now uniformly random between 1 and 7 ``` This has an expected runtime of 25/21 = 1.19 iterations of the loop, but there is an infinitesimally small probability of looping forever.
137,784
<p>I have a report in SSRS 2005 that's based on a query that's similar to this one: </p> <pre><code>SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE '%XYZ%' </code></pre> <p>I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!</p>
[ { "answer_id": 137856, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 1, "selected": false, "text": "<p>Perhaps this would work for you:</p>\n\n<pre><code>if @checked = 1\n select * from mytable (nolock) where col = 'ABC'\nelse\n select * from mytable (nolock) where col = 'ABC' AND colw Like '%XYZ%'\n</code></pre>\n\n<p>I'm sorry I don't use SSRS much, but if you can get the value of the checkbox into the @checked parameter this should work.</p>\n\n<p>Alternately you could use a CASE WHEN statement.</p>\n" }, { "answer_id": 137913, "author": "Anthony K", "author_id": 1682, "author_profile": "https://Stackoverflow.com/users/1682", "pm_score": 0, "selected": false, "text": "<p>You can also take another approach and use the Exec function:</p>\n\n<pre><code>DECLARE @CommonSelectText varchar(2000) \nDECLARE @CompleteSelectText varchar(2000) \nSELECT @CommonSelectText = 'SELECT * FROM MyTable (nolock) Where Col = ''ABC'' ' \n\nIF @checked = 1 \n SELECT @CompleteSelectText = @CommonSelectText + ' AND ColW LIKE ''%XYZ%'' ' \nELSE \n SELECT @CompleteSelectText = @CommonSelectText \n\nEXEC (@CompleteSelectText) \n\nGO \n</code></pre>\n\n<p>Note the use of two apostrophes <code>'</code> to mark the quoted text.</p>\n" }, { "answer_id": 137924, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>How about this. @checked is your bit variable.</p>\n\n<pre><code>SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\nAND (@checked &lt;&gt; 0 and col2 LIKE '%XYZ%')\n</code></pre>\n\n<p><strong>Edit:</strong> Also, if you aren't using a stored proc, then use one.</p>\n" }, { "answer_id": 137969, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\nAND col2 LIKE CASE @checked WHEN 1 THEN '%XYZ%' ELSE col2 END\n</code></pre>\n" }, { "answer_id": 138008, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "<p>This would work in SSRS 2000 but used as a last resort.</p>\n\n<p>(bad) PSEUDOCODE</p>\n\n<pre><code>=\"SELECT * FROM MyTable (NOLOCK)\nWHERE col1 = 'ABC'\"+\niff(condition,true,\"AND col2 LIKE '%XYZ%'\",\"\")\n</code></pre>\n\n<p>Check out <a href=\"http://books.google.com/books?id=EII8FmTumX0C&amp;pg=PA298&amp;lpg=PA298&amp;dq=SSRS+dynamic+sql&amp;source=web&amp;ots=0hZJH_gXja&amp;sig=sKy-537AmHki69qpIyTgBO1KM0g&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=4&amp;ct=result#PPA299,M1\" rel=\"nofollow noreferrer\">Executing \"Dynamic\" SQL Queries</a>. from the Hitchhiker's Guide to SQL Server 2000 Reporting Services</p>\n" }, { "answer_id": 138172, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>One way to do this is by generating the SSRS query as an expression. In the BIDS report designer, set your query up like so:</p>\n\n<pre><code>=\"SELECT * FROM MyTable WITH (NOLOCK) WHERE col1 = 'ABC'\" +\n Iif(Parameters!Checked.Value = true,\" AND col2 LIKE '%XYZ%'\",\"\")\n</code></pre>\n" }, { "answer_id": 138193, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "<p>Charles almost had the correct answer.</p>\n\n<p>It should be:</p>\n\n<pre><code>SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\n AND (@checked = 0 OR col2 LIKE '%XYZ%')\n</code></pre>\n\n<p>This is a classic \"pattern\" in SQL for conditional predicates. If <code>@checked = 0</code>, then it will return all rows matching the remainder of the predicate (<code>col1 = 'ABC'</code>). SQL Server won't even process the second half of the <code>OR</code>.</p>\n\n<p>If <code>@checked = 1</code> then it will evaluate the second part of the <code>OR</code> and return rows matching <code>col1 = 'ABC' AND col2 LIKE '%XYZ%'</code></p>\n\n<p>If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable).</p>\n\n<p>For example:</p>\n\n<pre><code>SELECT * FROM MyTable (NOLOCK) \nWHERE col1 = 'ABC'\n AND (@checked1 = 0 OR col2 LIKE '%XYZ%')\n AND (@checked2 = 0 OR col3 LIKE '%MNO%')\n</code></pre>\n\n<p>Don't use dynamic SQL, don't use IF or CASE.</p>\n" }, { "answer_id": 140582, "author": "ScaleOvenStove", "author_id": 12268, "author_profile": "https://Stackoverflow.com/users/12268", "pm_score": 0, "selected": false, "text": "<p>if you can use stored procedures, its probably easier to do it there. pass in your params. Create a SQL String based on your conditions and do an EXEC on the sql string, your stored proc will return the results you need. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11507/" ]
I have a report in SSRS 2005 that's based on a query that's similar to this one: ``` SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND col2 LIKE '%XYZ%' ``` I need to be able to dynamically include the AND part of the WHERE clause in the query based on whether the user has checked a checkbox. Basically, this is a dynamic SQL statement and that's the problem. I tried several approaches to no avail. Is this possible? Does SSRS 2005 supports dynamic SQL? Thanks!
Charles almost had the correct answer. It should be: ``` SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked = 0 OR col2 LIKE '%XYZ%') ``` This is a classic "pattern" in SQL for conditional predicates. If `@checked = 0`, then it will return all rows matching the remainder of the predicate (`col1 = 'ABC'`). SQL Server won't even process the second half of the `OR`. If `@checked = 1` then it will evaluate the second part of the `OR` and return rows matching `col1 = 'ABC' AND col2 LIKE '%XYZ%'` If you have multiple conditional predicates they can be chained together using this method (while the IF and CASE methods would quickly become unmanageable). For example: ``` SELECT * FROM MyTable (NOLOCK) WHERE col1 = 'ABC' AND (@checked1 = 0 OR col2 LIKE '%XYZ%') AND (@checked2 = 0 OR col3 LIKE '%MNO%') ``` Don't use dynamic SQL, don't use IF or CASE.
137,803
<p>Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.</p>
[ { "answer_id": 137818, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 5, "selected": true, "text": "<p>If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.</p>\n\n<pre><code>SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1\n</code></pre>\n\n<p>The newId() will generate a new GUID for you that you can use as your automatically generated id column.</p>\n" }, { "answer_id": 137822, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 0, "selected": false, "text": "<p>Is this perhaps what you are looking for?</p>\n\n<blockquote>\n <p>select NEWID() * from TABLE</p>\n</blockquote>\n" }, { "answer_id": 137825, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 4, "selected": false, "text": "<p>IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords.</p>\n" }, { "answer_id": 138524, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 1, "selected": false, "text": "<p>Do you want an incrementing integer column returned with your recordset? If so: -</p>\n\n<pre><code>--Check for existance \nif exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1) \ndrop table dbo.t\ngo\n\n--create dummy table and insert data \ncreate table dbo.t(x char(1) not null primary key, y char(1) not null) \ngo \nset nocount on \ninsert dbo.t (x,y) values ('A','B') \ninsert dbo.t (x,y) values ('C','D') \ninsert dbo.t (x,y) values ('E','F')\n\n--create temp table to add an identity column \ncreate table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null) \n\n--populate the temporary table \ninsert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t\n\n--return the data \nselect i,x,y from dbo.#TempWithIdentity\n\n--clean up \ndrop table dbo.#TempWithIdentity\n</code></pre>\n" }, { "answer_id": 140666, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 0, "selected": false, "text": "<p>You can do this directly in SQL2000, as per Microsoft's page: <a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;186133\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx?scid=kb;en-us;186133</a></p>\n\n<pre><code> select rank=count(*), a1.au_lname, a1.au_fname\n from authors a1, authors a2\n where a1.au_lname + a1.au_fname &gt;= a2.au_lname + a2.au_fname\n group by a1.au_lname, a1.au_fname\n order by rank\n</code></pre>\n\n<p>The only problem with this approach is that (As Jeff says on SQL Server Central) it's a triangular join. So, if you have ten records this will be quick, if you have a thousand records it will be slow, and with a million records it may never complete!</p>\n\n<p>See here for a better explanation of triangular joins: <a href=\"http://www.sqlservercentral.com/articles/T-SQL/61539/\" rel=\"nofollow noreferrer\">http://www.sqlservercentral.com/articles/T-SQL/61539/</a></p>\n\n<hr>\n" }, { "answer_id": 380821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>Select (Select count(y.au_lname) from dbo.authors y\nwhere y.au_lname + y.au_fname &lt;= x.au_lname + y.au_fname) as Counterid,\nx.au_lname,x.au_fname from authors x group by au_lname,au_fname\norder by Counterid --Alternatively that can be done which is equivalent as above..\n</code></pre>\n" }, { "answer_id": 9781014, "author": "codezombie", "author_id": 1279958, "author_profile": "https://Stackoverflow.com/users/1279958", "pm_score": 4, "selected": false, "text": "<p>This will work in SQL Server 2008.</p>\n\n<pre><code>select top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp\n</code></pre>\n\n<p>Cheers</p>\n" }, { "answer_id": 25076734, "author": "Martin Widlund", "author_id": 3898763, "author_profile": "https://Stackoverflow.com/users/3898763", "pm_score": 4, "selected": false, "text": "<p>Here is a simple method which ranks the rows after however they are ordered, i.e. inserted in your table. In your SELECT statement simply add the field </p>\n\n<pre><code>ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.\n</code></pre>\n" }, { "answer_id": 73395865, "author": "Leonardo Camargo", "author_id": 16308905, "author_profile": "https://Stackoverflow.com/users/16308905", "pm_score": 0, "selected": false, "text": "<p>If you are looking for an integer id</p>\n<p>This has worked for me:</p>\n<pre><code> SELECT \n ROW_NUMBER() OVER (ORDER BY newId())\n FROM anyTbl\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ]
Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.
If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer. ``` SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1 ``` The newId() will generate a new GUID for you that you can use as your automatically generated id column.
137,837
<p>Does your software handle newline characters from other systems?</p> <pre><code>Linux/BSD linefeed ^J 10 x0A Windows/IBM return linefeed ^M^J 13 10 x0D x0A old Macs return ^M 13 x0D others? </code></pre> <p>For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this?</p>
[ { "answer_id": 137841, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>I suspect you will find that most modern Windows programs (with the notable exception of Notepad) handle newline-only files just fine. However, files generated with windows programs still tend to have crlf endings.</p>\n\n<p>Most of the time, the line endings will automatically be handled in a platform-specific way by the runtime library. For example, a C program that opens a file with <code>fopen(..., \"r\")</code> will see the lines in a consistent way (linefeed only) on any platform regardless of the actual line endings.</p>\n" }, { "answer_id": 137842, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": -1, "selected": false, "text": "<p>Not sure what you mean when you say 'deal' with, but basically you can just say something like:</p>\n\n<pre><code>string convertLineBreaks(String line, String lineBreakYouWant) {\n replace all ^M^J or ^M or ^J in line with lineBreakYouWant\n\n return line\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> I suspect after re-reading your question you mean how do you deal with other peoples programs that can't handle incorrect (for the target system) line breaks.</p>\n\n<p>I would suggest either 1) using a program that can deal or 2) running your files through a script that finds line breaks of any type and then converts them into whatever type is right for your system.</p>\n" }, { "answer_id": 137843, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 3, "selected": true, "text": "<p>As they say, be strict in what you write and liberal in what you read.</p>\n\n<p>Your application should be able to work properly reading both line endings. If you want to use linefeeds, and potentially upset Windows users, that's fine.</p>\n\n<p>But save for Notepad, most programs I play with seem to be happy with both methods.</p>\n\n<p>(And I use Cygwin on Windows, which just makes everything interesting)</p>\n" }, { "answer_id": 137847, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>The standard Python distribution comes with two command-line scripts (in Tools/scripts) called crlf.py and lfcr.py that can convert between Windows and Unix/Linux line endings.</p>\n\n<p><a href=\"http://code.activestate.com/recipes/66434/\" rel=\"nofollow noreferrer\">[Source]</a></p>\n" }, { "answer_id": 137848, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>In .NET, new lines are denoted by <code>Environment.NewLine</code>, so the framework is designed in such a way as to take whatever the system's new line is (CR+LF or CR only or LF only) to use at runtime. Of course this is ultimately useful in Mono.</p>\n" }, { "answer_id": 137855, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "<p>As far as I know, it's only Notepad that has a problem with line separators. Virtually ever other piece of software in the world accepts any of those three types of separator, and possibility others as well. Unfortunately, Notepad is the editor of first resort for most computer users these days. I think it's extremely irresponsible of Microsoft to let this situation continue. I've never played with Vista, but I believe the problem still exists there, as it does in XP. Any body know about the next version?</p>\n" }, { "answer_id": 137910, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>As others said, there are lot of (quite trivial) converters around, should the need arise. Note that if you do the transfer with FTP in Ascii mode, it will do the conversion automatically...</p>\n\n<p>Indeed, Notepad is the most proeminent program having an issue with LF ending...</p>\n\n<p>The most annoying I saw is text files with mixed line ending, done essentially by people editing a Windows file on Unix, or utilities adding stuff without checking the proper format.</p>\n" }, { "answer_id": 8694886, "author": "eonil", "author_id": 246776, "author_profile": "https://Stackoverflow.com/users/246776", "pm_score": 0, "selected": false, "text": "<p>To be happy, just follow recommendation from the standard.</p>\n\n<p><a href=\"http://unicode.org/standard/reports/tr13/tr13-5.html\" rel=\"nofollow\">http://unicode.org/standard/reports/tr13/tr13-5.html</a></p>\n\n<p>And offer options for special cases like old MacOS. Or handle the case automatically if you can detect them reliably.</p>\n\n<p>I recommend formatting your text in Unix style. Forget about Windows users. Because no Windows users use plain-text for document or data. They will be upset if you pass plain-text. They always expect Word or Excel document. Even they use plain-text file, the only problem they will get is just weirdly displaying text.</p>\n\n<p>But Unix users will experience their all tools will work incorrectly. Especially for Unix, follow the standard strictly.</p>\n\n<p>PS.\nOh, if your Windows user is a developer, just format with text in Unix, and tell them that's the file from Unix.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19737/" ]
Does your software handle newline characters from other systems? ``` Linux/BSD linefeed ^J 10 x0A Windows/IBM return linefeed ^M^J 13 10 x0D x0A old Macs return ^M 13 x0D others? ``` For reasons of insanity, I am going with using the Linux version of the newline character in my text files. But, when I bring my text files over to say Windows, some programs do not play nicely with newline characters in my text. How would you deal with this?
As they say, be strict in what you write and liberal in what you read. Your application should be able to work properly reading both line endings. If you want to use linefeeds, and potentially upset Windows users, that's fine. But save for Notepad, most programs I play with seem to be happy with both methods. (And I use Cygwin on Windows, which just makes everything interesting)
137,872
<p>I am using the JQuery form plugin (<a href="http://malsup.com/jquery/form/" rel="noreferrer">http://malsup.com/jquery/form/</a>) to handle the ajax submission of a form. I also have JQuery.Validate (<a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">http://docs.jquery.com/Plugins/Validation</a>) plugged in for my client side validation.</p> <p>What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.</p> <p>I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.</p> <p>So what I am I missing that is preventing my desired behaviour? Sample code below....</p> <pre><code>&lt;form id="searchForm" method="post" action="/User/GetDetails"&gt; &lt;input id="username" name="username" type="text" value="user.name" /&gt; &lt;input id="submit" name="submit" type="submit" value="Search" /&gt; &lt;/form&gt; &lt;div id="detailsView"&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; var options = { target: '#detailsView' }; $('#searchForm').ajaxForm(options); $('#searchForm').validate({ rules: { username: {required:true}}, messages: { username: {required:"Username is a required field."}} }); &lt;/script&gt; </code></pre>
[ { "answer_id": 137881, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 1, "selected": false, "text": "<p>Just as a first pass, I'm wondering why the line</p>\n\n<pre><code>$(\"form\").validate({\n</code></pre>\n\n<p>doesn't refer to $(\"searchform\"). I haven't looked this up, or tried it, but that just seems to be a mismatch. Wouldn't you want to call validate on the appropriate form?</p>\n\n<p>Anyway, if this is completely wrong, then the error isn't immediately obvious. :)</p>\n" }, { "answer_id": 139336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>May be a \nreturn false;\non the form will help?\n:)\nI mean:</p>\n\n<pre><code>&lt;form id=\"searchForm\" method=\"post\" action=\"/User/GetDetails\" onSubmit=\"return false;\"&gt;\n</code></pre>\n" }, { "answer_id": 844582, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 4, "selected": false, "text": "<p>You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm():</p>\n\n<pre><code>var options = {\n beforeSubmit: function() {\n return $('#searchForm').validate().form();\n },\n target: '#detailsView'\n };\n</code></pre>\n\n<p>Now it knows to check the result of the validation before it will submit the page.</p>\n" }, { "answer_id": 999236, "author": "Aaron", "author_id": 104641, "author_profile": "https://Stackoverflow.com/users/104641", "pm_score": 1, "selected": false, "text": "<p>Also make sure all of your input fields have a \"name\" attribute as well as an \"id\" attribute. I noticed the jquery validation plugin doesn't function correctly without these.</p>\n" }, { "answer_id": 2069996, "author": "berko", "author_id": 4884, "author_profile": "https://Stackoverflow.com/users/4884", "pm_score": 2, "selected": false, "text": "<p>... well it's been a while so my situation has changed a little. Currently I have a submitHandler option passed to the Validate() plugin. In that handler I manually use ajaxSubmit. More a workaround than an answer I guess. Hope that helps.</p>\n\n<p><a href=\"http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html\" rel=\"nofollow noreferrer\">http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html</a></p>\n\n<pre><code>var v = jQuery(\"#form\").validate({\n submitHandler: function(form) {\n jQuery(form).ajaxSubmit({target: \"#result\"});\n }\n});\n</code></pre>\n" }, { "answer_id": 5007286, "author": "duggi", "author_id": 262942, "author_profile": "https://Stackoverflow.com/users/262942", "pm_score": 1, "selected": false, "text": "<p>ok, this is an old question but i will put our solution here for posterity. i personally classify this one as a hack-trocity, but at least it's not a hack-tacu-manjaro</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var options = {\n target: '#detailsView'\n };\n\n// -- \"solution\" --\n$('#searchForm').submit(function(event) {\n this.preventDefault(event); // our env actually monkey patches preventDefault\n // impl your own prevent default here\n // basically the idea is to bind a prevent default\n // stopper on the form's submit event\n});\n// -- end --\n\n $('#searchForm').ajaxForm(options);\n\n $('#searchForm').validate({\n rules: {\n username: {required:true}},\n messages: {\n username: {required:\"Username is a required field.\"}}\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 11282333, "author": "Manjula Srinath", "author_id": 1494295, "author_profile": "https://Stackoverflow.com/users/1494295", "pm_score": 2, "selected": false, "text": "<pre><code>$('#contactform').ajaxForm({\n success : FormSendResponse, \n beforeSubmit: function(){\n return $(\"#contactform\").valid();\n }\n});\n\n\n$(\"#contactform\").validate(); \n</code></pre>\n\n<p>Above code worked fine for me.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4884/" ]
I am using the JQuery form plugin (<http://malsup.com/jquery/form/>) to handle the ajax submission of a form. I also have JQuery.Validate (<http://docs.jquery.com/Plugins/Validation>) plugged in for my client side validation. What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour. I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened. So what I am I missing that is preventing my desired behaviour? Sample code below.... ``` <form id="searchForm" method="post" action="/User/GetDetails"> <input id="username" name="username" type="text" value="user.name" /> <input id="submit" name="submit" type="submit" value="Search" /> </form> <div id="detailsView"> </div> <script type="text/javascript"> var options = { target: '#detailsView' }; $('#searchForm').ajaxForm(options); $('#searchForm').validate({ rules: { username: {required:true}}, messages: { username: {required:"Username is a required field."}} }); </script> ```
You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm(): ``` var options = { beforeSubmit: function() { return $('#searchForm').validate().form(); }, target: '#detailsView' }; ``` Now it knows to check the result of the validation before it will submit the page.
137,911
<p>I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone?</p> <p>I understand that filling the head_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main_template.pt, which is my current solution, with it's huge drawbacks).</p>
[ { "answer_id": 139950, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": -1, "selected": false, "text": "<p>Plone documentation on supporting OpenID can be found here.</p>\n\n<p><a href=\"http://plone.org/documentation/how-to/openid-support/view?searchterm=openid\" rel=\"nofollow noreferrer\">http://plone.org/documentation/how-to/openid-support/view?searchterm=openid</a></p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 147805, "author": "michaeljoseph", "author_id": 5549, "author_profile": "https://Stackoverflow.com/users/5549", "pm_score": 3, "selected": false, "text": "<p>You need fill the <code>head_slot</code> defined in <code>main_template.pt</code></p>\n\n<p>In your base plone template, add the following:</p>\n\n<pre><code>&lt;head&gt;\n &lt;metal:block metal:fill-slot=\"head_slot\"&gt;\n &lt;link rel=\"openid.server\" href=\"http://your.provider\"&gt;\n &lt;link rel=\"openid.delegate\" href=\"http://your.url\"&gt;\n &lt;/metal:block&gt;\n&lt;/head&gt;\n</code></pre>\n" }, { "answer_id": 197777, "author": "Reinout van Rees", "author_id": 27401, "author_profile": "https://Stackoverflow.com/users/27401", "pm_score": 1, "selected": false, "text": "<p>In the end, you have to either place them directly in the main_template or you have to insert them in one of the slots in the mail_template.</p>\n\n<p>What I have puts them in the style slot, next to the rest of the css/javascript links:</p>\n\n<pre><code> &lt;metal:myopenid fill-slot=\"style_slot\"&gt;\n &lt;link rel=\"openid.server\" href=\"http://www.myopenid.com/server\" /&gt;\n &lt;link rel=\"openid.delegate\" href=\"http://reinout.myopenid.com/\" /&gt;\n &lt;/metal:myopenid&gt;\n</code></pre>\n\n<p>You have to put this in a template somewhere. I put it in a separate homepage.pt as I was customizing the homepage anyway. This puts the openid headers just on the homepage. If you don't want a custom template, you can customize the document_view template (assuming your homepage is a document) and enter above snippet of code into it.</p>\n\n<p>It would be best if there's an option for this in plone itself, similar to the \"add javascript for statistics here\" option.</p>\n" }, { "answer_id": 438254, "author": "pupeno", "author_id": 6068, "author_profile": "https://Stackoverflow.com/users/6068", "pm_score": 1, "selected": true, "text": "<p>I couldn't understand how to fill a slot without a product or anything. I understand that you can fill a slot from a template, but if Plone is not picking up that template, then the <em>filling code</em> would never be run. I ended up modifying main_template and putting my code directly in the . This is bad because different skins will have different main_templates and indeed it bit me because I've modified it for one template when I was using the other. That is not a harmless-nothing-happens experience but a nasty problem because main_template in on custom and it gets picked up so you have one skin working with the main_template of the other. End result: UI broken with a hard-to-find problem.</p>\n\n<p>This is the code I added:</p>\n\n<pre><code>&lt;head&gt;\n ...\n &lt;link rel=\"openid.server\" href=\"http://www.myopenid.com/server\" /&gt;\n &lt;link rel=\"openid.delegate\" href=\"http://pupeno.myopenid.com/\" /&gt;\n &lt;link rel=\"openid2.local_id\" href=\"http://pupeno.myopenid.com\" /&gt;\n &lt;link rel=\"openid2.provider\" href=\"http://www.myopenid.com/server\" /&gt;\n &lt;meta http-equiv=\"X-XRDS-Location\" content=\"http://www.myopenid.com/xrds?username=pupeno.myopenid.com\" /&gt;\n&lt;/head&gt;\n</code></pre>\n\n<p>I will probably mark this answer as accepted because it's what I'm currently using (and that's my policy, I mark solutions I end up using as accepted, nothing else is marked as accepted), but if any of the other questions become clear in how to inject this new template, I will use that and revert the acceptance (if StackOverflow allows it).</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone? I understand that filling the head\_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main\_template.pt, which is my current solution, with it's huge drawbacks).
I couldn't understand how to fill a slot without a product or anything. I understand that you can fill a slot from a template, but if Plone is not picking up that template, then the *filling code* would never be run. I ended up modifying main\_template and putting my code directly in the . This is bad because different skins will have different main\_templates and indeed it bit me because I've modified it for one template when I was using the other. That is not a harmless-nothing-happens experience but a nasty problem because main\_template in on custom and it gets picked up so you have one skin working with the main\_template of the other. End result: UI broken with a hard-to-find problem. This is the code I added: ``` <head> ... <link rel="openid.server" href="http://www.myopenid.com/server" /> <link rel="openid.delegate" href="http://pupeno.myopenid.com/" /> <link rel="openid2.local_id" href="http://pupeno.myopenid.com" /> <link rel="openid2.provider" href="http://www.myopenid.com/server" /> <meta http-equiv="X-XRDS-Location" content="http://www.myopenid.com/xrds?username=pupeno.myopenid.com" /> </head> ``` I will probably mark this answer as accepted because it's what I'm currently using (and that's my policy, I mark solutions I end up using as accepted, nothing else is marked as accepted), but if any of the other questions become clear in how to inject this new template, I will use that and revert the acceptance (if StackOverflow allows it).
137,935
<p>In Vim editor I opted <code>]I</code> on a function (in C++ code). This presented a list, which says <em>'Press ENTER or type command to continue'</em>.</p> <p>Now to jump to an occurrence say 6, I type <code>6</code> - but this is not working.</p> <p>What commands can I type in such a case, and how do I jump to Nth occurrence from this list?</p> <p><strong>Update:</strong></p> <p>Actually I tried <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> (eg :6) - but the moment I type <code>:</code> Vim enters Insert mode, and the colon gets inserted in the code instead.</p> <p><strong>Update</strong></p> <p>Assuming <a href="https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942">:N</a> approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing <code>:</code> does not switch Vim to insert mode.</p>
[ { "answer_id": 137942, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "<p>It should present you a list like:</p>\n\n<pre><code>1: 345 my_func (int var)\n2: 4523 my_func (int var)\n3: 10032 my_func (3);\n</code></pre>\n\n<p>The second column is line numbers. Type :345 to jump to line 345.</p>\n" }, { "answer_id": 137956, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 0, "selected": false, "text": "<p>When I use vim, and I jump to a tag, by doing for instance:</p>\n\n<pre><code> :tag getfirst\n</code></pre>\n\n<p>I get presented with something that looks like:</p>\n\n<pre><code> # pri kind tag file\n 1 F m getfirst /home/sthorne/work/.../FormData.py\n class:FakeFieldStorage\n def getfirst(self, k, default):\n ....\n 8 F m getfirst /home/sthorne/work/.../CGIForm.py\n class:CGIForm\n def getfirst(self, name):\nChoice number (&lt;Enter&gt; cancels):\n</code></pre>\n\n<p>I type '5' to go to the 5th occurrence.</p>\n\n<p>If you can't get your vim to have that behaviour (it seems to be on by default for my vim), you can use <strong>g]</strong> instead of <strong>ctrl-]</strong>, which is analagous to <strong>:tselect</strong> instead of <strong>:tag</strong></p>\n" }, { "answer_id": 138002, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 1, "selected": false, "text": "<p>Do :h tselect on vim to see the complete definition</p>\n\n<blockquote>\n <p>If you already see the tag you want to\n use, you can type 'q' and enter the\n number.</p>\n</blockquote>\n" }, { "answer_id": 138007, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": -1, "selected": false, "text": "<p>Try using <code>123G</code> to go to line 123 (see <code>:h G</code>).</p>\n" }, { "answer_id": 142348, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "<p>If you hit a jump button, and get a list of possible targets, select the number, and hit the jump again.</p>\n\n<p>So given</p>\n\n<pre><code>1: 345 my_func (int var)\n2: 4523 my_func (int var)\n3: 10032 my_func (3);\n</code></pre>\n\n<p>If you hit '2]|', it should jump directly to that line.</p>\n" }, { "answer_id": 258108, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "<p><code>[I</code> only lists the search results. To <em>jump</em> to the results use the sequence <code>[ CTRL+I</code>.</p>\n\n<p>You can see the full list of relevant jumps at:</p>\n\n<p><a href=\"http://www.vim.org/htmldoc/tagsrch.html#include-search\" rel=\"nofollow noreferrer\">http://www.vim.org/htmldoc/tagsrch.html#include-search</a></p>\n" }, { "answer_id": 1062547, "author": "thoughton", "author_id": 128264, "author_profile": "https://Stackoverflow.com/users/128264", "pm_score": 1, "selected": false, "text": "<p>I had the same problem, and cobbling together the previous answers and experimenting I came up with this solution:</p>\n\n<pre><code>[I // gives list of matches for word under cursor, potentially some matches are in headers. remember the number of the match you're interested in, eg. the 3rd\nq // quits the list of matches\n3[Ctrl-i // (with cursor in same position) jumps to third match\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14803/" ]
In Vim editor I opted `]I` on a function (in C++ code). This presented a list, which says *'Press ENTER or type command to continue'*. Now to jump to an occurrence say 6, I type `6` - but this is not working. What commands can I type in such a case, and how do I jump to Nth occurrence from this list? **Update:** Actually I tried [:N](https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942) (eg :6) - but the moment I type `:` Vim enters Insert mode, and the colon gets inserted in the code instead. **Update** Assuming [:N](https://stackoverflow.com/questions/137935/how-to-jump-to-an-occurrence-from-vim-search-list#137942) approach is correct, still complete uninstall and install of Vim, without any configuration, too did not help - though now typing `:` does not switch Vim to insert mode.
It should present you a list like: ``` 1: 345 my_func (int var) 2: 4523 my_func (int var) 3: 10032 my_func (3); ``` The second column is line numbers. Type :345 to jump to line 345.
137,951
<p>I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it?</p>
[ { "answer_id": 137993, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 2, "selected": false, "text": "<p>Easily done with jQuery. I don't recall what kind of markup the Datagrid creates but basically something like this will work in Jquery</p>\n\n<pre><code> $('#client_id_of_datagrid input, #client_id_of_datagrid select')\n.each(function() {val = this.value; /* Do Stuff */})\n</code></pre>\n" }, { "answer_id": 138093, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": true, "text": "<p>And here's an example using Microsoft AJAX framework:</p>\n\n<pre><code>var txts = $get('client_id_of_datagrid').getElementsByTagName('input');\nvar ddls = $get('client_id_of_datagrid').getElementsByTagName('select');\n\nfor(var i=0;i&lt;txts.length;i++){\n if(txts[i].type==='text'){\n /* do stuff */\n }\n}\n\nfor(var i=0;i&lt;ddls.length;i++){\n /* do stuff */\n}\n</code></pre>\n\n<p>And for no framework replace $get with document.getElementById.\nReally, jQuery is the best idea.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ASP.NET Datagrid with several text boxes and drop down boxes inside it. I want to read all the values in the grid using a JavaScript function. How do i go about it?
And here's an example using Microsoft AJAX framework: ``` var txts = $get('client_id_of_datagrid').getElementsByTagName('input'); var ddls = $get('client_id_of_datagrid').getElementsByTagName('select'); for(var i=0;i<txts.length;i++){ if(txts[i].type==='text'){ /* do stuff */ } } for(var i=0;i<ddls.length;i++){ /* do stuff */ } ``` And for no framework replace $get with document.getElementById. Really, jQuery is the best idea.
137,952
<p>I decide to learn more about vim and its syntax highlighting. Using examples for others, I am creating my own syntax file for Markdown. I have seen <a href="http://www.vim.org/scripts/script.php?script_id=1242" rel="noreferrer">mkd.vim</a> and it has this problem too. My issue is between list items and code block highlighting.</p> <p>Code Block <a href="http://daringfireball.net/projects/markdown/syntax#precode" rel="noreferrer">definition</a>:</p> <ul> <li>first line is blank</li> <li>second line begins with at least 4 spaces or 1 tab</li> <li>block is finished with a blank line</li> </ul> <p>Example:</p> <pre><code>Regular text this is code, monospaced and left untouched by markdown another line of code Regular Text </code></pre> <p>My Vim syntax for code block:</p> <pre><code>syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment </code></pre> <p>Unorder List item <a href="http://daringfireball.net/projects/markdown/syntax#list" rel="noreferrer">definition</a>:</p> <ul> <li>first line is blank</li> <li>second line begins with a [-+*] followed by a space</li> <li>the list is finished with a blank line then a normal (non-list) line</li> <li>in between line items any number of blank lines can be added</li> <li>a sub list is specified by indenting (4 space or 1 tab)</li> <li>a line of normal text after a list item is include as a continuation of that list item</li> </ul> <p>Example:</p> <pre><code>Regular text - item 1 - sub item 1 - sub item 2 - item 2 this is part of item 2 so is this - item 3, still in the same list - sub item 1 - sub item 2 Regular text, list ends above </code></pre> <p>My Vim syntax for unorder list item definition (I only highlight <code>[-+*]</code>):</p> <pre><code>syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator </code></pre> <p>I cannot get the highlighting to work with the last two rule for list and with a code block.</p> <p>This is an example that breaks my syntax highlighting:</p> <pre><code>Regular text - Item 1 - Item 2 part of item 2 - these 2 line should be highlighted as a list item - but they are highlighted as a code block </code></pre> <p>I currently cannot figure out how to get the highlighting to work the way I want it too</p> <hr> <p>Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line.</p> <pre><code>syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent </code></pre> <hr> <p>Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules</p> <hr>
[ { "answer_id": 138186, "author": "hcs42", "author_id": 17916, "author_profile": "https://Stackoverflow.com/users/17916", "pm_score": 4, "selected": true, "text": "<p>Just make sure that the definition of mkdListItem is after the definition of mkdCodeBlock, like this:</p>\n\n<pre><code>syn match mkdCodeBlock /\\(\\s\\{4,}\\|\\t\\{1,}\\).*\\n/ contained nextgroup=mkdCodeBlock \nhi link mkdCodeBlock comment\n\nsyn region mkdListItem start=/\\s*[-*+]\\s\\+/ matchgroup=pdcListText end=\".*\" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl \nsyn match mkdListSkipNL /\\s*\\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl\nhi link mkdListItem operator\n\nsyn match mkdBlankLine /^\\s*\\n/ nextgroup=mkdCodeBlock,mkdListItem transparent\n</code></pre>\n\n<p>Vim documentation says in <code>:help :syn-define</code>:</p>\n\n<p>\"In case more than one item matches at the same position, the one that was\ndefined LAST wins. Thus you can override previously defined syntax items by\nusing an item that matches the same text. But a keyword always goes before a\nmatch or region. And a keyword with matching case always goes before a\nkeyword with ignoring case.\"</p>\n" }, { "answer_id": 142292, "author": "Tao Zhyn", "author_id": 873, "author_profile": "https://Stackoverflow.com/users/873", "pm_score": 1, "selected": false, "text": "<p>hcs42 was correct. I do remember reading that section now, but I forgot about it until hcs24 reminded me about it.</p>\n\n<p>Here is my updated syntax (few other tweaks) that works:</p>\n\n<pre>\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" Code Blocks:\n\n\" Indent with at least 4 space or 1 tab\n\" This rule must appear for mkdListItem, or highlighting gets messed up\nsyn match mkdCodeBlock /\\(\\s\\{4,}\\|\\t\\{1,}\\).*\\n/ contained nextgroup=mkdCodeBlock \n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\" Lists:\n\n\" These first two rules need to be first or the highlighting will be\n\" incorrect\n\n\" Continue a list on the current line or next line\nsyn match mkdListCont /\\s*[^-+*].*/ contained nextgroup=mkdListCont,mkdListItem,mkdListSkipNL contains=@Spell skipnl transparent\n\n\" Skip empty lines\nsyn match mkdListSkipNL /\\s*\\n/ contained nextgroup=mkdListItem,mkdListSkipNL \n\n\" Unorder list\nsyn match mkdListItem /\\s*[-*+]\\s\\+/ contained nextgroup=mkdListSkipNL,mkdListCont skipnl \n</pre>\n" }, { "answer_id": 22593998, "author": "Gabriele Lana", "author_id": 3187671, "author_profile": "https://Stackoverflow.com/users/3187671", "pm_score": 0, "selected": false, "text": "<p>Tao Zhyn, that maybe covers your use cases but it doesn't cover the Markdown syntax. In Markdown a list item <strong>could</strong> contain a code block. You could take a look at my solution <a href=\"https://github.com/gabrielelana/vim-markdown\" rel=\"nofollow\">here</a></p>\n\n<p>TL;DR; the problem is that vim doesn't let you say something like: <em>a block that have the same indentation as its container + 4 spaces</em>. The only solution I found is to generate rules for each kind of blocks that could be contained in a list items for each level of indentation (actually I support 42 level of indentation but it's an arbitrary number)</p>\n\n<p>So I have markdownCodeBlockInListItemAtLevel1 that <strong>must</strong> be contained in a markdownListItemAtLevel1 and it needs to have at least 8 leading spaces, an then markdownCodeBlockInListItemAtLevel2 that <strong>must</strong> be contained in a markdownListItemAtLevel2 that must be contained in a markdownListItemAtLevel1 ant needs to have at least 10 leading spaces, ecc...</p>\n\n<p>I know that a few years have passed but maybe someone would consider this answer helpful since all syntax based on indentation suffers of the same problem</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873/" ]
I decide to learn more about vim and its syntax highlighting. Using examples for others, I am creating my own syntax file for Markdown. I have seen [mkd.vim](http://www.vim.org/scripts/script.php?script_id=1242) and it has this problem too. My issue is between list items and code block highlighting. Code Block [definition](http://daringfireball.net/projects/markdown/syntax#precode): * first line is blank * second line begins with at least 4 spaces or 1 tab * block is finished with a blank line Example: ``` Regular text this is code, monospaced and left untouched by markdown another line of code Regular Text ``` My Vim syntax for code block: ``` syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment ``` Unorder List item [definition](http://daringfireball.net/projects/markdown/syntax#list): * first line is blank * second line begins with a [-+\*] followed by a space * the list is finished with a blank line then a normal (non-list) line * in between line items any number of blank lines can be added * a sub list is specified by indenting (4 space or 1 tab) * a line of normal text after a list item is include as a continuation of that list item Example: ``` Regular text - item 1 - sub item 1 - sub item 2 - item 2 this is part of item 2 so is this - item 3, still in the same list - sub item 1 - sub item 2 Regular text, list ends above ``` My Vim syntax for unorder list item definition (I only highlight `[-+*]`): ``` syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator ``` I cannot get the highlighting to work with the last two rule for list and with a code block. This is an example that breaks my syntax highlighting: ``` Regular text - Item 1 - Item 2 part of item 2 - these 2 line should be highlighted as a list item - but they are highlighted as a code block ``` I currently cannot figure out how to get the highlighting to work the way I want it too --- Forgot to add a "global" syntax rule used in both rules listed below. It is to ensure a that they start with a blank line. ``` syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent ``` --- Another Note: I should have been more clear. In my syntax file, the List rules appear before the Blockquote Rules ---
Just make sure that the definition of mkdListItem is after the definition of mkdCodeBlock, like this: ``` syn match mkdCodeBlock /\(\s\{4,}\|\t\{1,}\).*\n/ contained nextgroup=mkdCodeBlock hi link mkdCodeBlock comment syn region mkdListItem start=/\s*[-*+]\s\+/ matchgroup=pdcListText end=".*" contained nextgroup=mkdListItem,mkdListSkipNL contains=@Spell skipnl syn match mkdListSkipNL /\s*\n/ contained nextgroup=mkdListItem,mkdListSkipNL skipnl hi link mkdListItem operator syn match mkdBlankLine /^\s*\n/ nextgroup=mkdCodeBlock,mkdListItem transparent ``` Vim documentation says in `:help :syn-define`: "In case more than one item matches at the same position, the one that was defined LAST wins. Thus you can override previously defined syntax items by using an item that matches the same text. But a keyword always goes before a match or region. And a keyword with matching case always goes before a keyword with ignoring case."
137,998
<p>I'm a newbie to pgsql. I have few questionss on it:</p> <p>1) I know it is possible to access columns by <code>&lt;schema&gt;.&lt;table_name&gt;</code>, but when I try to access columns like <code>&lt;db_name&gt;.&lt;schema&gt;.&lt;table_name&gt;</code> it throwing error like</p> <pre><code>Cross-database references are not implemented </code></pre> <p>How do I implement it?</p> <p>2) We have 10+ tables and 6 of have 2000+ rows. Is it fine to maintain all of them in one database? Or should I create dbs to maintain them?</p> <p>3) From above questions tables which have over 2000+ rows, for a particular process I need a few rows of data. I have created views to get those rows. For example: a table contains details of employees, they divide into 3 types; manager, architect, and engineer. Very obvious thing this table not getting each every process... process use to read data from it... I think there are two ways to get data <code>SELECT * FROM emp WHERE type='manager'</code>, or I can create views for manager, architect n engineer and get data <code>SELECT * FROM view_manager</code></p> <p>Can you suggest any better way to do this?</p> <p>4) Do views also require storage space, like tables do?</p> <p>Thanx in advance.</p>
[ { "answer_id": 138022, "author": "Michael Ratanapintha", "author_id": 1879, "author_profile": "https://Stackoverflow.com/users/1879", "pm_score": 0, "selected": false, "text": "<p>1: A workaround is to open a connection to the other database, and (if using psql(1)) set that as your current connection. However, this will work only if you don't try to join tables in both databases.</p>\n" }, { "answer_id": 156320, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<p>1) That means it's not a feature Postgres supports. I do not know any way to create a query that runs on more than one database.</p>\n\n<p>2) That's fine for one database. Single databases can contains billions of rows.</p>\n\n<p>3) Don't bother creating views, the queries are simple enough anyway.</p>\n\n<p>4) Views don't require space in the database except their query definition.</p>\n" }, { "answer_id": 156332, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": true, "text": "<ol>\n<li><p>Cross Database exists in PostGreSQL for years now. You must prefix the name of the database by the database name (and, of course, have the right to query on it). You'll come with something like this:</p>\n\n<p>SELECT alias_1.col1, alias_2.col3 FROM table_1 as alias_1, database_b.table_2 as alias_2 WHERE ...</p>\n\n<p>If your database is on another instance, then you'll need to use the dblink contrib.</p></li>\n<li>This question doe not make sens. Please refine.</li>\n<li>Generally, views are use to simplify the writing of other queries that reuse them. In your case, as you describe it, maybe that stored proceudre would better fits you needs.</li>\n<li>No, expect the view definition.</li>\n</ol>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22554/" ]
I'm a newbie to pgsql. I have few questionss on it: 1) I know it is possible to access columns by `<schema>.<table_name>`, but when I try to access columns like `<db_name>.<schema>.<table_name>` it throwing error like ``` Cross-database references are not implemented ``` How do I implement it? 2) We have 10+ tables and 6 of have 2000+ rows. Is it fine to maintain all of them in one database? Or should I create dbs to maintain them? 3) From above questions tables which have over 2000+ rows, for a particular process I need a few rows of data. I have created views to get those rows. For example: a table contains details of employees, they divide into 3 types; manager, architect, and engineer. Very obvious thing this table not getting each every process... process use to read data from it... I think there are two ways to get data `SELECT * FROM emp WHERE type='manager'`, or I can create views for manager, architect n engineer and get data `SELECT * FROM view_manager` Can you suggest any better way to do this? 4) Do views also require storage space, like tables do? Thanx in advance.
1. Cross Database exists in PostGreSQL for years now. You must prefix the name of the database by the database name (and, of course, have the right to query on it). You'll come with something like this: SELECT alias\_1.col1, alias\_2.col3 FROM table\_1 as alias\_1, database\_b.table\_2 as alias\_2 WHERE ... If your database is on another instance, then you'll need to use the dblink contrib. 2. This question doe not make sens. Please refine. 3. Generally, views are use to simplify the writing of other queries that reuse them. In your case, as you describe it, maybe that stored proceudre would better fits you needs. 4. No, expect the view definition.
138,000
<p>When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP.</p> <p>But when sent over HTTPS, different browsers gave different results:</p> <p>On Firefox 3.0.2: - The GET request doesn't reach the web server.</p> <p>On IE 7: - The GET request reached the web server.</p> <p>Does this have something to do with Firefox 3 getting stricter with untrusted certificates? Is there a way around this?</p> <p>I've already added the URL as an exception in Firefox's Certificate Manager. The error console doesn't report any error. I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown.</p> <p>Using both absolute and relative URL path doesn't work.</p> <p>Here's the code snippet:</p> <pre><code> var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); xmlHttp.send(null); } catch (e) { alert('Error sending HTTP GET request!'); return false; } </code></pre> <p>Thanks, Kenneth</p>
[ { "answer_id": 138011, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<p>By any chance, are you requesting a non-HTTPS URL in an HTTPS page? Do any messages appear in the error log/console?</p>\n" }, { "answer_id": 161889, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 1, "selected": false, "text": "<p>Try placing your closure after the open:</p>\n\n<pre><code>// send HTTP GET request\ntry\n{\n xmlHttp.open(\"GET\", \"/[relative path to request]\", true);\n}\ncatch (e)\n{\n alert('Error sending HTTP GET request!');\n return false;\n}\n// we won't be handling any HTTP response\nxmlHttp.onreadystatechange=function()\n{\n // do nothing..\n}\n\n// Then send it.\nxmlHttp.send(null);\n</code></pre>\n\n<p>A little googling found confirmation:\n<a href=\"http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html\" rel=\"nofollow noreferrer\">http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html</a></p>\n\n<p>Although that document says to attach the function after .send(null), I've\nalways attached after open.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16139/" ]
When I try to send an HTTP GET request through XMLHttpRequest it works on non-secure HTTP. But when sent over HTTPS, different browsers gave different results: On Firefox 3.0.2: - The GET request doesn't reach the web server. On IE 7: - The GET request reached the web server. Does this have something to do with Firefox 3 getting stricter with untrusted certificates? Is there a way around this? I've already added the URL as an exception in Firefox's Certificate Manager. The error console doesn't report any error. I've added a try-catch around XMLHttpRequest's open() and send. No exception is thrown. Using both absolute and relative URL path doesn't work. Here's the code snippet: ``` var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); xmlHttp.send(null); } catch (e) { alert('Error sending HTTP GET request!'); return false; } ``` Thanks, Kenneth
Try placing your closure after the open: ``` // send HTTP GET request try { xmlHttp.open("GET", "/[relative path to request]", true); } catch (e) { alert('Error sending HTTP GET request!'); return false; } // we won't be handling any HTTP response xmlHttp.onreadystatechange=function() { // do nothing.. } // Then send it. xmlHttp.send(null); ``` A little googling found confirmation: <http://www.ghastlyfop.com/blog/2007/01/onreadystate-changes-in-firefox.html> Although that document says to attach the function after .send(null), I've always attached after open.
138,029
<p>After a bind a method to an event of a Tkinter element is there a way to get the method back?</p> <pre><code>&gt;&gt;&gt; root = Tkinter.Tk() &gt;&gt;&gt; frame = Tkinter.Frame(root, width=100, height=100) &gt;&gt;&gt; frame.bind('&lt;Button-1&gt;', lambda e: pprint('Click')) # function needed &gt;&gt;&gt; frame.pack() &gt;&gt;&gt; bound_event_method = frame.??? </code></pre>
[ { "answer_id": 138039, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 0, "selected": false, "text": "<p>Doesn't appear to be... why not just save it yourself if you're going to need it, or use a non-anonymous function?</p>\n\n<p>Also, your code doesn't work as written: <code>lambda</code> functions can only contain expressions, not statements, so <code>print</code> is a no-go (this will change in Python 3.0 when <code>print()</code> becomes a function).</p>\n" }, { "answer_id": 138258, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 3, "selected": true, "text": "<p>The associated call to do that for the tk C API would be <a href=\"http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm\" rel=\"nofollow noreferrer\">Get_GetCommandInfo</a> which</p>\n\n<blockquote>\n <p>places information about the command\n in the Tcl_CmdInfo structure pointed\n to by infoPtr</p>\n</blockquote>\n\n<p>However this function is not used anywhere in <a href=\"http://svn.python.org/projects/python/trunk/Modules/_tkinter.c\" rel=\"nofollow noreferrer\">_tkinter.c</a> which is the binding for tk used by python trough <a href=\"http://svn.python.org/projects/python/trunk/Lib/lib-tk/Tkinter.py\" rel=\"nofollow noreferrer\">Tkinter.py</a>.</p>\n\n<p>Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself.</p>\n" }, { "answer_id": 226141, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "<p>The standard way to do this in Tcl/Tk is trivial: you use the same bind command but without the final argument. </p>\n\n<pre><code>bind .b &lt;Button-1&gt; doSomething\nputs \"the function is [bind .b &lt;Button-1&gt;]\"\n=&gt; the function is doSomething\n</code></pre>\n\n<p>You can do something similar with Tkinter but the results are, unfortunately, not quite as usable:</p>\n\n<pre><code>e1.bind(\"&lt;Button-1&gt;\",doSomething)\ne1.bind(\"&lt;Button-1&gt;\")\n=&gt; 'if {\"[-1208974516doSomething %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]\" == \"break\"} break\\n'\n</code></pre>\n\n<p>Obviously, Tkinter is doing a lot of juggling below the covers. One solution would be to write a little helper procedure that remembers this for you:</p>\n\n<pre><code>def bindWidget(widget,event,func=None):\n '''Set or retrieve the binding for an event on a widget'''\n\n if not widget.__dict__.has_key(\"bindings\"): widget.bindings=dict()\n\n if func:\n widget.bind(event,func)\n widget.bindings[event] = func\n else:\n return(widget.bindings.setdefault(event,None))\n</code></pre>\n\n<p>You would use it like this:</p>\n\n<pre><code>e1=Entry()\nprint \"before, binding for &lt;Button-1&gt;: %s\" % bindWidget(e1,\"&lt;Button-1&gt;\")\nbindWidget(e1,\"&lt;Button-1&gt;\",doSomething)\nprint \" after, binding for &lt;Button-1&gt;: %s\" % bindWidget(e1,\"&lt;Button-1&gt;\")\n</code></pre>\n\n<p>When I run the above code I get:</p>\n\n<pre><code>before, binding for &lt;Button-1&gt;: None\n after, binding for &lt;Button-1&gt;: &lt;function doSomething at 0xb7f2e79c&gt;\n</code></pre>\n\n<p>As a final caveat, I don't use Tkinter much so I'm not sure what the ramifications are of dynamically adding an attribute to a widget instance. It seems to be harmless, but if not you can always create a global dictionary to keep track of the bindings.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
After a bind a method to an event of a Tkinter element is there a way to get the method back? ``` >>> root = Tkinter.Tk() >>> frame = Tkinter.Frame(root, width=100, height=100) >>> frame.bind('<Button-1>', lambda e: pprint('Click')) # function needed >>> frame.pack() >>> bound_event_method = frame.??? ```
The associated call to do that for the tk C API would be [Get\_GetCommandInfo](http://linux.about.com/library/cmd/blcmdl3_Tcl_GetCommandInfo.htm) which > > places information about the command > in the Tcl\_CmdInfo structure pointed > to by infoPtr > > > However this function is not used anywhere in [\_tkinter.c](http://svn.python.org/projects/python/trunk/Modules/_tkinter.c) which is the binding for tk used by python trough [Tkinter.py](http://svn.python.org/projects/python/trunk/Lib/lib-tk/Tkinter.py). Therefore it is impossible to get the bound function out of tkinter. You need to remember that function yourself.
138,040
<p>I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?</p>
[ { "answer_id": 138052, "author": "user22044", "author_id": 22044, "author_profile": "https://Stackoverflow.com/users/22044", "pm_score": 2, "selected": false, "text": "<p>There is no easy way to do this. Basically, you will need to dynamically layout controls when the window size is changed.</p>\n\n<p>See <a href=\"http://www.codeproject.com/KB/dialog/resizabledialog.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dialog/resizabledialog.aspx</a> for an example</p>\n" }, { "answer_id": 138062, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 6, "selected": true, "text": "<p>In the RC resource file if the dialog has this style similar to this it will be fixed size:</p>\n\n<pre><code>IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201\nSTYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU\n</code></pre>\n\n<p>If the dialog has this style it will be sizeable:</p>\n\n<pre><code>IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201\nSTYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME\n</code></pre>\n\n<p>With these sizable frame options the dialog will be re-sizeable but you will still need to do a lot of work handling the <strong>WM_SIZE</strong> message to manage the sizing an positioning of the controls within the dialog.</p>\n" }, { "answer_id": 139643, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 0, "selected": false, "text": "<p>I've tried many MFC layout libraries and found this one the best: <a href=\"http://www.codeproject.com/KB/dialog/layoutmgr.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dialog/layoutmgr.aspx</a>. Check out the comments there for some bug fixes and improvements (disclaimer: some of them by me ;) ). When you use this library, setting the correct resize flags on your window will be handled for you.</p>\n" }, { "answer_id": 5739386, "author": "steinybot", "author_id": 367796, "author_profile": "https://Stackoverflow.com/users/367796", "pm_score": 2, "selected": false, "text": "<p>If your using a dialog template then open the dialog template in the resource editor and set the <strong>Style</strong> property to <strong>Popup</strong> and the <strong>Border</strong> property to <strong>Resizing</strong>. I'm pretty sure this will do the same as what <em>jussij</em> said and set the WS_POPUP and WS_THICKFRAME styles. To set these dynamically then override the PreCreateWindow function and add the following:</p>\n\n<pre><code>cs.style |= WS_POPUP | WS_THICKFRAME;\n</code></pre>\n" }, { "answer_id": 5739620, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>In addition to setting the style to <code>WS_THICKFRAME</code>, you'll probably also want to have a system to move and resize the controls in a dialog as the dialog is resized. For my own personal use I've created a base class to replace CDialog that has this capability. Derive from this class and in your <code>InitDialog</code> function call the <code>AutoMove</code> function for each child control to define how much it should move and how much it should resize relative to the parent dialog. The size of the dialog in the resource file is used as a minimum size.</p>\n\n<p>BaseDialog.h:</p>\n\n<pre><code>#if !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_)\n#define AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_\n\n#if _MSC_VER &gt; 1000\n#pragma once\n#endif // _MSC_VER &gt; 1000\n\n#include &lt;vector&gt;\n\nclass CBaseDialog : public CDialog\n{\n// Construction\npublic:\n CBaseDialog(UINT nIDTemplate, CWnd* pParent = NULL); // standard constructor\n\n void AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct);\n\n// Overrides\n // ClassWizard generated virtual function overrides\n //{{AFX_VIRTUAL(CBaseDialog)\nprotected:\n //}}AFX_VIRTUAL\n\nprotected:\n //{{AFX_MSG(CBaseDialog)\n virtual BOOL OnInitDialog();\n afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);\n afx_msg void OnSize(UINT nType, int cx, int cy);\n //}}AFX_MSG\n DECLARE_MESSAGE_MAP()\n\npublic:\n bool m_bShowGripper; // ignored if not WS_THICKFRAME\n\nprivate:\n struct SMovingChild\n {\n HWND m_hWnd;\n double m_dXMoveFrac;\n double m_dYMoveFrac;\n double m_dXSizeFrac;\n double m_dYSizeFrac;\n CRect m_rcInitial;\n };\n typedef std::vector&lt;SMovingChild&gt; MovingChildren;\n\n MovingChildren m_MovingChildren;\n CSize m_szInitial;\n CSize m_szMinimum;\n HWND m_hGripper;\n};\n\n//{{AFX_INSERT_LOCATION}}\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\n\n#endif // !defined(AFX_BASEDIALOG_H__DF4DE489_4474_4759_A14E_EB3FF0CDFBDA__INCLUDED_)\n</code></pre>\n\n<p>BaseDialog.cpp:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include \"BaseDialog.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nCBaseDialog::CBaseDialog(UINT nIDTemplate, CWnd* pParent /*=NULL*/)\n : CDialog(nIDTemplate, pParent),\n m_bShowGripper(true),\n m_szMinimum(0, 0),\n m_hGripper(NULL)\n{\n}\n\n\nBEGIN_MESSAGE_MAP(CBaseDialog, CDialog)\n //{{AFX_MSG_MAP(CBaseDialog)\n ON_WM_GETMINMAXINFO()\n ON_WM_SIZE()\n //}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\nvoid CBaseDialog::AutoMove(int iID, double dXMovePct, double dYMovePct, double dXSizePct, double dYSizePct)\n{\n ASSERT((dXMovePct + dXSizePct) &lt;= 100.0); // can't use more than 100% of the resize for the child\n ASSERT((dYMovePct + dYSizePct) &lt;= 100.0); // can't use more than 100% of the resize for the child\n SMovingChild s;\n GetDlgItem(iID, &amp;s.m_hWnd);\n ASSERT(s.m_hWnd != NULL);\n s.m_dXMoveFrac = dXMovePct / 100.0;\n s.m_dYMoveFrac = dYMovePct / 100.0;\n s.m_dXSizeFrac = dXSizePct / 100.0;\n s.m_dYSizeFrac = dYSizePct / 100.0;\n ::GetWindowRect(s.m_hWnd, &amp;s.m_rcInitial);\n ScreenToClient(s.m_rcInitial);\n m_MovingChildren.push_back(s);\n}\n\nBOOL CBaseDialog::OnInitDialog()\n{\n CDialog::OnInitDialog();\n\n // use the initial dialog size as the default minimum\n if ((m_szMinimum.cx == 0) &amp;&amp; (m_szMinimum.cy == 0))\n {\n CRect rcWindow;\n GetWindowRect(rcWindow);\n m_szMinimum = rcWindow.Size();\n }\n\n // keep the initial size of the client area as a baseline for moving/sizing controls\n CRect rcClient;\n GetClientRect(rcClient);\n m_szInitial = rcClient.Size();\n\n // create a gripper in the bottom-right corner\n if (m_bShowGripper &amp;&amp; ((GetStyle() &amp; WS_THICKFRAME) != 0))\n {\n SMovingChild s;\n s.m_rcInitial.SetRect(-GetSystemMetrics(SM_CXVSCROLL), -GetSystemMetrics(SM_CYHSCROLL), 0, 0);\n s.m_rcInitial.OffsetRect(rcClient.BottomRight());\n m_hGripper = CreateWindow(_T(\"Scrollbar\"), _T(\"size\"), WS_CHILD | WS_VISIBLE | SBS_SIZEGRIP,\n s.m_rcInitial.left, s.m_rcInitial.top, s.m_rcInitial.Width(), s.m_rcInitial.Height(),\n m_hWnd, NULL, AfxGetInstanceHandle(), NULL);\n ASSERT(m_hGripper != NULL);\n if (m_hGripper != NULL)\n {\n s.m_hWnd = m_hGripper;\n s.m_dXMoveFrac = 1.0;\n s.m_dYMoveFrac = 1.0;\n s.m_dXSizeFrac = 0.0;\n s.m_dYSizeFrac = 0.0;\n m_MovingChildren.push_back(s);\n\n // put the gripper first in the z-order so it paints first and doesn't obscure other controls\n ::SetWindowPos(m_hGripper, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);\n }\n }\n\n return TRUE; // return TRUE unless you set the focus to a control\n}\n\nvoid CBaseDialog::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) \n{\n CDialog::OnGetMinMaxInfo(lpMMI);\n\n if (lpMMI-&gt;ptMinTrackSize.x &lt; m_szMinimum.cx)\n lpMMI-&gt;ptMinTrackSize.x = m_szMinimum.cx;\n if (lpMMI-&gt;ptMinTrackSize.y &lt; m_szMinimum.cy)\n lpMMI-&gt;ptMinTrackSize.y = m_szMinimum.cy;\n}\n\nvoid CBaseDialog::OnSize(UINT nType, int cx, int cy) \n{\n CDialog::OnSize(nType, cx, cy);\n\n int iXDelta = cx - m_szInitial.cx;\n int iYDelta = cy - m_szInitial.cy;\n HDWP hDefer = NULL;\n for (MovingChildren::iterator p = m_MovingChildren.begin(); p != m_MovingChildren.end(); ++p)\n {\n if (p-&gt;m_hWnd != NULL)\n {\n CRect rcNew(p-&gt;m_rcInitial);\n rcNew.OffsetRect(int(iXDelta * p-&gt;m_dXMoveFrac), int(iYDelta * p-&gt;m_dYMoveFrac));\n rcNew.right += int(iXDelta * p-&gt;m_dXSizeFrac);\n rcNew.bottom += int(iYDelta * p-&gt;m_dYSizeFrac);\n if (hDefer == NULL)\n hDefer = BeginDeferWindowPos(m_MovingChildren.size());\n UINT uFlags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER;\n if ((p-&gt;m_dXSizeFrac != 0.0) || (p-&gt;m_dYSizeFrac != 0.0))\n uFlags |= SWP_NOCOPYBITS;\n DeferWindowPos(hDefer, p-&gt;m_hWnd, NULL, rcNew.left, rcNew.top, rcNew.Width(), rcNew.Height(), uFlags);\n }\n }\n if (hDefer != NULL)\n EndDeferWindowPos(hDefer);\n\n if (m_hGripper != NULL)\n ::ShowWindow(m_hGripper, (nType == SIZE_MAXIMIZED) ? SW_HIDE : SW_SHOW);\n}\n</code></pre>\n" }, { "answer_id": 7022943, "author": "AndyUK", "author_id": 6795, "author_profile": "https://Stackoverflow.com/users/6795", "pm_score": 1, "selected": false, "text": "<p>I have some <a href=\"http://www.technical-recipes.com/2011/how-to-create-resizable-dialogs-in-mfc/\" rel=\"nofollow\">blog instructions</a> on how to create a very minimalist re-sizeable dialog in MFC.</p>\n\n<p>It is basically an implementation of <a href=\"http://www.codeproject.com/KB/dialog/resizabledialog.aspx\" rel=\"nofollow\">Paulo Messina's posting at CodeProject</a>\nbut with as much extraneous stuff removed as possible, just to help clarify how to do it better.</p>\n\n<p>It is fairly straightforward to implement once you've had a bit of practice: the important bits are to:</p>\n\n<p>i. ensure you have his CodeProject libraries etc pulled into your project and it all compiles correctly.</p>\n\n<p>ii. do the extra initialization required inside the OnInitDialog method: make the gripper visible, set the maximum dilog size, add anchor points to the dialog control items that you wish to 'stretch' etc.</p>\n\n<p>iii. Replace usage of CDialog with CResizableDialog at the appropriate points: in the dialog class definition, constructor, DoDataExchange, BEGIN_MESSAGE_MAP, OnInitDialog etc. </p>\n" }, { "answer_id": 43074472, "author": "tibx", "author_id": 5557538, "author_profile": "https://Stackoverflow.com/users/5557538", "pm_score": 3, "selected": false, "text": "<p>Since <strong>Visual Studio 2015</strong>, you can use <a href=\"https://devblogs.microsoft.com/cppblog/mfc-dynamic-dialog-layout/\" rel=\"nofollow noreferrer\">MFC Dynamic Dialog Layout</a>, but it seems, there is no way to restrict dialog size to minimal size (still only the old way by <a href=\"https://forums.codeguru.com/showthread.php?318933-MFC-General-How-to-prevent-a-resizable-window-to-be-smaller-than\" rel=\"nofollow noreferrer\">handling</a> <strong>WM_GETMINMAXINFO</strong>).</p>\n<p>Dynamic layout can be done:</p>\n<ul>\n<li>at design time in resource editor by selecting the control and setting the <strong>Moving Type</strong> and <strong>Sizing Type</strong> properties (this emits new <strong>AFX_DIALOG_LAYOUT</strong> section into .rc file);</li>\n<li>or programatically using the <strong>CMFCDynamicLayout</strong> <a href=\"https://learn.microsoft.com/en-us/cpp/mfc/reference/cmfcdynamiclayout-class\" rel=\"nofollow noreferrer\">class</a>.</li>\n</ul>\n<p>Documentation: <a href=\"https://learn.microsoft.com/en-us/cpp/mfc/dynamic-layout\" rel=\"nofollow noreferrer\">Dynamic Layout</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have to create a dialog based application, instead of old CFormView type of design. But CDialog produces fixed-size dialogs. How can I create dialog based applications with resizable dialogs?
In the RC resource file if the dialog has this style similar to this it will be fixed size: ``` IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU ``` If the dialog has this style it will be sizeable: ``` IDD_DIALOG_DIALOG DIALOGEX 0, 0, 320, 201 STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME ``` With these sizable frame options the dialog will be re-sizeable but you will still need to do a lot of work handling the **WM\_SIZE** message to manage the sizing an positioning of the controls within the dialog.
138,043
<p>I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.</p> <p>I know that TcpClient will assign a new client side port when I open a connection to a given server.</p> <p>Is there a simple way to find the next open TCP port in .NET?</p> <p>I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.</p>
[ { "answer_id": 138044, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 5, "selected": false, "text": "<p>Use a port number of 0. The TCP stack will allocate the next free one.</p>\n" }, { "answer_id": 138220, "author": "jan.vdbergh", "author_id": 9540, "author_profile": "https://Stackoverflow.com/users/9540", "pm_score": 3, "selected": false, "text": "<p>First open the port, then give the correct port number to the other process.</p>\n\n<p>Otherwise it is still possible that some other process opens the port first and you still have a different one.</p>\n" }, { "answer_id": 150974, "author": "TheSeeker", "author_id": 4829, "author_profile": "https://Stackoverflow.com/users/4829", "pm_score": 8, "selected": true, "text": "<p>Here is what I was looking for:</p>\n\n<pre><code>static int FreeTcpPort()\n{\n TcpListener l = new TcpListener(IPAddress.Loopback, 0);\n l.Start();\n int port = ((IPEndPoint)l.LocalEndpoint).Port;\n l.Stop();\n return port;\n}\n</code></pre>\n" }, { "answer_id": 38969868, "author": "yoavs", "author_id": 6313865, "author_profile": "https://Stackoverflow.com/users/6313865", "pm_score": 1, "selected": false, "text": "<p>If you want to get a free port in a specific range in order to use it as local port / end point:</p>\n\n<pre><code>private int GetFreePortInRange(int PortStartIndex, int PortEndIndex)\n{\n DevUtils.LogDebugMessage(string.Format(\"GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}\", PortStartIndex, PortEndIndex));\n try\n {\n IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();\n\n IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners();\n List&lt;int&gt; usedServerTCpPorts = tcpEndPoints.Select(p =&gt; p.Port).ToList&lt;int&gt;();\n\n IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners();\n List&lt;int&gt; usedServerUdpPorts = udpEndPoints.Select(p =&gt; p.Port).ToList&lt;int&gt;();\n\n TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();\n List&lt;int&gt; usedPorts = tcpConnInfoArray.Where(p=&gt; p.State != TcpState.Closed).Select(p =&gt; p.LocalEndPoint.Port).ToList&lt;int&gt;();\n\n usedPorts.AddRange(usedServerTCpPorts.ToArray());\n usedPorts.AddRange(usedServerUdpPorts.ToArray());\n\n int unusedPort = 0;\n\n for (int port = PortStartIndex; port &lt; PortEndIndex; port++)\n {\n if (!usedPorts.Contains(port))\n {\n unusedPort = port;\n break;\n }\n }\n DevUtils.LogDebugMessage(string.Format(\"Local unused Port:{0}\", unusedPort.ToString()));\n\n if (unusedPort == 0)\n {\n DevUtils.LogErrorMessage(\"Out of ports\");\n throw new ApplicationException(\"GetFreePortInRange, Out of ports\");\n }\n\n return unusedPort;\n }\n catch (Exception ex)\n {\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n throw;\n }\n}\n\n\nprivate int GetLocalFreePort()\n{\n int hemoStartLocalPort = int.Parse(DBConfig.GetField(\"Site.Config.hemoStartLocalPort\"));\n int hemoEndLocalPort = int.Parse(DBConfig.GetField(\"Site.Config.hemoEndLocalPort\"));\n int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort);\n DevUtils.LogDebugMessage(string.Format(\"Local Free Port:{0}\", localPort.ToString()));\n return localPort;\n}\n\n\npublic void Connect(string host, int port)\n{\n try\n {\n // Create socket\n Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\n\n var localPort = GetLocalFreePort();\n // Create an endpoint for the specified IP on any port\n IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);\n\n // Bind the socket to the endpoint\n socket.Bind(bindEndPoint);\n\n // Connect to host\n socket.Connect(IPAddress.Parse(host), port);\n\n socket.Dispose();\n }\n catch (SocketException ex)\n {\n // Get the error message\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n }\n}\n\n\npublic void Connect2(string host, int port)\n{\n try\n {\n // Create socket\n\n var localPort = GetLocalFreePort();\n\n // Create an endpoint for the specified IP on any port\n IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);\n\n var client = new TcpClient(bindEndPoint);\n //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done\n\n // Connect to the host\n client.Connect(IPAddress.Parse(host), port);\n\n client.Close();\n }\n catch (SocketException ex)\n {\n // Get the error message\n string errorMessage = ex.Message;\n DevUtils.LogErrorMessage(errorMessage);\n }\n}\n</code></pre>\n" }, { "answer_id": 45384984, "author": "zumalifeguard", "author_id": 75129, "author_profile": "https://Stackoverflow.com/users/75129", "pm_score": 4, "selected": false, "text": "<p>If you just want to give a starting port, and let it return to you the next TCP port available, use code like this:</p>\n\n<pre><code>public static int GetAvailablePort(int startingPort)\n{\n var portArray = new List&lt;int&gt;();\n\n var properties = IPGlobalProperties.GetIPGlobalProperties();\n\n // Ignore active connections\n var connections = properties.GetActiveTcpConnections();\n portArray.AddRange(from n in connections\n where n.LocalEndPoint.Port &gt;= startingPort\n select n.LocalEndPoint.Port);\n\n // Ignore active tcp listners\n var endPoints = properties.GetActiveTcpListeners();\n portArray.AddRange(from n in endPoints\n where n.Port &gt;= startingPort\n select n.Port);\n\n // Ignore active UDP listeners\n endPoints = properties.GetActiveUdpListeners();\n portArray.AddRange(from n in endPoints\n where n.Port &gt;= startingPort\n select n.Port);\n\n portArray.Sort();\n\n for (var i = startingPort; i &lt; UInt16.MaxValue; i++)\n if (!portArray.Contains(i))\n return i;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 49408267, "author": "Eric Boumendil", "author_id": 249742, "author_profile": "https://Stackoverflow.com/users/249742", "pm_score": 4, "selected": false, "text": "<p>It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable:</p>\n\n<pre><code>using System;\nusing System.Net;\nusing System.Net.Sockets;\n\n private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);\n\n public static int GetAvailablePort()\n {\n using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n socket.Bind(DefaultLoopbackEndpoint);\n return ((IPEndPoint)socket.LocalEndPoint).Port;\n }\n }\n</code></pre>\n" }, { "answer_id": 58526893, "author": "Daniel Rosenberg", "author_id": 6275530, "author_profile": "https://Stackoverflow.com/users/6275530", "pm_score": 2, "selected": false, "text": "<p>Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private int GetNextUnusedPort(int min, int max)\n{\n if (max &lt; min)\n throw new ArgumentException(\"Max cannot be less than min.\");\n\n var ipProperties = IPGlobalProperties.GetIPGlobalProperties();\n\n var usedPorts =\n ipProperties.GetActiveTcpConnections()\n .Where(connection =&gt; connection.State != TcpState.Closed)\n .Select(connection =&gt; connection.LocalEndPoint)\n .Concat(ipProperties.GetActiveTcpListeners())\n .Concat(ipProperties.GetActiveUdpListeners())\n .Select(endpoint =&gt; endpoint.Port)\n .ToArray();\n\n var firstUnused =\n Enumerable.Range(min, max - min)\n .Where(port =&gt; !usedPorts.Contains(port))\n .Select(port =&gt; new int?(port))\n .FirstOrDefault();\n\n if (!firstUnused.HasValue)\n throw new Exception($\"All local TCP ports between {min} and {max} are currently in use.\");\n\n return firstUnused.Value;\n}\n</code></pre>\n" }, { "answer_id": 58924521, "author": "Fatih TAN", "author_id": 6322573, "author_profile": "https://Stackoverflow.com/users/6322573", "pm_score": 4, "selected": false, "text": "<p>I found the following code from <strong>Selenium.WebDriver DLL</strong></p>\n\n<p><strong>Namespace</strong>: OpenQA.Selenium.Internal</p>\n\n<p><strong>Class</strong>: PortUtility</p>\n\n<pre><code>public static int FindFreePort()\n{\n int port = 0;\n Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n try\n {\n IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);\n socket.Bind(localEP);\n localEP = (IPEndPoint)socket.LocalEndPoint;\n port = localEP.Port;\n }\n finally\n {\n socket.Close();\n }\n return port;\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
Here is what I was looking for: ``` static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } ```
138,045
<p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm" rel="noreferrer">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
[ { "answer_id": 138053, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 3, "selected": false, "text": "<p>Use reflection for this.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx\" rel=\"noreferrer\"><code>Type.GetProperty()</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx\" rel=\"noreferrer\"><code>Type.GetProperties()</code></a> each return <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx\" rel=\"noreferrer\"><code>PropertyInfo</code></a> instances, which can be used to read a property value on an object.</p>\n\n<pre><code>var result = typeof(DateTime).GetProperty(\"Year\").GetValue(dt, null)\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx\" rel=\"noreferrer\"><code>Type.GetMethod()</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getmethods.aspx\" rel=\"noreferrer\"><code>Type.GetMethods()</code></a> each return <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx\" rel=\"noreferrer\"><code>MethodInfo</code></a> instances, which can be used to execute a method on an object.</p>\n\n<pre><code>var result = typeof(DateTime).GetMethod(\"ToLongDateString\").Invoke(dt, null);\n</code></pre>\n\n<p>If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well.</p>\n\n<pre><code>var result = dt.GetType().GetProperty(\"Year\").Invoke(dt, null);\n</code></pre>\n" }, { "answer_id": 138054, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 1, "selected": false, "text": "<p>Yes, you can do this...</p>\n\n<pre><code>typeof(YourObjectType).GetProperty(\"PropertyName\").GetValue(instanceObjectToGetPropFrom, null);\n</code></pre>\n" }, { "answer_id": 138063, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 0, "selected": false, "text": "<p>There's the System.Reflection.PropertyInfo class that can be created using object.GetType().GetProperties(). That can be used to probe an object's properties using strings. (Similar methods exist for object methods, fields, etc.)</p>\n\n<p>I don't think that will help you accomplish your goals though. You should probably just create and manipulate the objects directly. Controls have a Name property that you can set, for example.</p>\n" }, { "answer_id": 138079, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "<p>There is also <a href=\"http://msdn.microsoft.com/en-us/library/66btctbe.aspx\" rel=\"noreferrer\">Type.InvokeMember</a>.</p>\n\n<pre><code>public static class ReflectionExt\n{\n public static object GetAttr(this object obj, string name)\n {\n Type type = obj.GetType();\n BindingFlags flags = BindingFlags.Instance | \n BindingFlags.Public | \n BindingFlags.GetProperty;\n\n return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);\n }\n}\n</code></pre>\n\n<p>Which could be used like:</p>\n\n<pre><code>object value = ReflectionExt.GetAttr(obj, \"PropertyName\");\n</code></pre>\n\n<p>or (as an extension method):</p>\n\n<pre><code>object value = obj.GetAttr(\"PropertyName\");\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22562/" ]
Is there something like [Python's getattr()](http://effbot.org/zone/python-getattr.htm) in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.
There is also [Type.InvokeMember](http://msdn.microsoft.com/en-us/library/66btctbe.aspx). ``` public static class ReflectionExt { public static object GetAttr(this object obj, string name) { Type type = obj.GetType(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty; return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); } } ``` Which could be used like: ``` object value = ReflectionExt.GetAttr(obj, "PropertyName"); ``` or (as an extension method): ``` object value = obj.GetAttr("PropertyName"); ```
138,056
<p>In other words, a block of code like this:</p> <pre><code>(setq initial-major-mode (lambda () (text-mode) (font-lock-mode) )) </code></pre> <p>... would come out looking like something like this:</p> <p><img src="https://i.stack.imgur.com/kiaIG.gif" alt="alt text"></p> <p>If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it?</p>
[ { "answer_id": 138357, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 5, "selected": true, "text": "<p>I think you are looking for something like <a href=\"http://www.foldr.org/~michaelw/emacs/mwe-color-box.el\" rel=\"noreferrer\">mwe-color-box.el</a></p>\n" }, { "answer_id": 139423, "author": "Levente Mészáros", "author_id": 20993, "author_profile": "https://Stackoverflow.com/users/20993", "pm_score": 2, "selected": false, "text": "<p>If you need this to help editing, then I suggest turning on coloring the <em>innermost</em> sexp which contains the cursor with a different background color. At least I'm used to this and it is sufficient.</p>\n" }, { "answer_id": 1099688, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://nschum.de/src/emacs/highlight-parentheses/\" rel=\"nofollow noreferrer\">http://nschum.de/src/emacs/highlight-parentheses/</a> lets you highlight just the parentheses.</p>\n" }, { "answer_id": 6035524, "author": "Trey Jackson", "author_id": 6148, "author_profile": "https://Stackoverflow.com/users/6148", "pm_score": 2, "selected": false, "text": "<p>There is the package <a href=\"http://www.emacswiki.org/emacs/RainbowDelimiters\" rel=\"nofollow\">rainbow-delimiters</a>, which doesn't do exactly what you want, but does just colorize the parentheses - which is a nice subset and allows you to still see the other syntax highlighting provided by the major mode. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
In other words, a block of code like this: ``` (setq initial-major-mode (lambda () (text-mode) (font-lock-mode) )) ``` ... would come out looking like something like this: ![alt text](https://i.stack.imgur.com/kiaIG.gif) If something like this already exists, what is it? And if it doesn't exist, how should I go about writing it?
I think you are looking for something like [mwe-color-box.el](http://www.foldr.org/~michaelw/emacs/mwe-color-box.el)
138,071
<p>The questions says everything, take this example code: </p> <pre><code>&lt;ul id="css-id"&gt; &lt;li&gt; &lt;something:CustomControl ID="SomeThingElse" runat="server" /&gt; &lt;something:OtherCustomControl runat="server" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?</p>
[ { "answer_id": 138082, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 4, "selected": true, "text": "<p>You can catch all exception not handled elswhere in the Global.asax page / class. \nLook at:</p>\n\n<pre><code>protected void Application_Error(Object sender, EventArgs e)\n</code></pre>\n\n<p>method.</p>\n" }, { "answer_id": 138083, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 1, "selected": false, "text": "<p>Add a global.asax en implement the Application_Error handler. Use the Server.GetLastError() function to get a handle on the exception thrown.</p>\n" }, { "answer_id": 138084, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 2, "selected": false, "text": "<p>Unfortunately an unhandled exception will always error your site.\nYOu can prevent this a few ways though.</p>\n\n<ul>\n<li>Use the section in your web.config to show a user friendly message</li>\n<li>In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - <a href=\"http://www.webdude.co.za/archive/2008/09/17/creating-your-own-unhandled-error-logging-module.aspx\" rel=\"nofollow noreferrer\">like this</a></li>\n</ul>\n\n<p><strong>best solution</strong></p>\n\n<ul>\n<li>Make sure you controls don't throw unhandled exceptions!</li>\n</ul>\n" }, { "answer_id": 138088, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>Using the global.asax Application_Error method, as described in <a href=\"http://support.microsoft.com/kb/306355\" rel=\"nofollow noreferrer\">How to create custom error reporting pages in ASP.NET by using Visual C# .NET</a>.</p>\n\n<p>An alternative approach would be to use a <a href=\"http://msdn.microsoft.com/en-us/library/aa479332.aspx\" rel=\"nofollow noreferrer\">HTTP module</a>; this gives you some more flexibility (you can handle errors from multiple applications, for example).</p>\n" }, { "answer_id": 138092, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 1, "selected": false, "text": "<p>Do you want to catch the exception and handle it?</p>\n\n<p>Or do you want to prevent the Yellow Screen Of Death? If you are trying to prevent the Yellow Screen Of Death, look at handling the <code>Error</code> event on the <code>HttpApplication</code> (in other words, in your Global.asax).</p>\n\n<p>See the following MSDN page for more details:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx</a></p>\n\n<p>Specifically this paragraph:</p>\n\n<blockquote>\n <p>The exception that raises the Error event can be accessed by a call to the GetLastError method. If your application generates custom error output, suppress the default error message that is generated by ASP.NET by a call to the ClearError method.</p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
The questions says everything, take this example code: ``` <ul id="css-id"> <li> <something:CustomControl ID="SomeThingElse" runat="server" /> <something:OtherCustomControl runat="server" /> </li> </ul> ``` Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?
You can catch all exception not handled elswhere in the Global.asax page / class. Look at: ``` protected void Application_Error(Object sender, EventArgs e) ``` method.
138,073
<p><strong>Scenario:</strong> C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. </p> <p><strong>Q:</strong> How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error &lt;> 0' does fire. I try to store the @@Error number, but it is always 0.</p> <p>Please help.</p>
[ { "answer_id": 138111, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 2, "selected": false, "text": "<p>Haven't got an example to hand, but look at using</p>\n\n<pre><code>RAISERROR ... WITH LOG\n</code></pre>\n\n<p>see: <a href=\"http://msdn.microsoft.com/en-us/library/aa238452(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa238452(SQL.80).aspx</a> for more on this.</p>\n\n<p>Or use: </p>\n\n<pre><code>xp_logevent {error_number, 'message'} [, 'severity']\n</code></pre>\n\n<p>to write to the event log. More details at <a href=\"http://msdn.microsoft.com/en-us/library/aa260695(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa260695(SQL.80).aspx</a></p>\n" }, { "answer_id": 138114, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "<p><code>@@ERROR</code> is reset to 0 when you check it. Why? Because it reflects the status of the last statement executed.</p>\n\n<pre><code>IF @@ERROR &lt;&gt; 0 ...\n</code></pre>\n\n<p>is a statement, and that statement succeeds, causing <code>@@ERROR</code> to be set to 0.</p>\n\n<p>The proper way to examine and operate on <code>@@ERROR</code> values is as follows:</p>\n\n<pre><code>DECLARE @ErrorCode INT\n\nINSERT INTO Table ...\n\nSET @ErrorCode = @@ERROR\nIF @ErrorCode &lt;&gt; 0\nBEGIN\n INSERT INTO ErrorLog (ErrorCode, Message)\n VALUES (@ErrorCode, 'The INSERT operation failed.')\nEND\n</code></pre>\n" }, { "answer_id": 138173, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "<p>Didn't try it myself but I guess you can monitor the errors with <strong>Sql Server Profiler</strong>.</p>\n" }, { "answer_id": 5868727, "author": "Sai Sherlekar", "author_id": 730593, "author_profile": "https://Stackoverflow.com/users/730593", "pm_score": 1, "selected": false, "text": "<pre><code>ALTER PROCEDURE [dbo].[StoreProcedureName] \n(\nparameters \n)\nAS\nBEGIN\n SET NOCOUNT On\n BEGIN TRY \n --type your query \n\n End Try\n BEGIN CATCH\n SELECT\n ERROR_NUMBER() AS ErrorNumber,\n ERROR_SEVERITY() AS ErrorSeverity,\n ERROR_STATE() AS ErrorState,\n ERROR_PROCEDURE() AS ErrorProcedure,\n ERROR_LINE() AS ErrorLine,\n ERROR_MESSAGE() AS ErrorMessage\n RETURN -1\n END CATCH\nEnd\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**Scenario:** C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. **Q:** How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0. Please help.
`@@ERROR` is reset to 0 when you check it. Why? Because it reflects the status of the last statement executed. ``` IF @@ERROR <> 0 ... ``` is a statement, and that statement succeeds, causing `@@ERROR` to be set to 0. The proper way to examine and operate on `@@ERROR` values is as follows: ``` DECLARE @ErrorCode INT INSERT INTO Table ... SET @ErrorCode = @@ERROR IF @ErrorCode <> 0 BEGIN INSERT INTO ErrorLog (ErrorCode, Message) VALUES (@ErrorCode, 'The INSERT operation failed.') END ```
138,096
<p>I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame.</p> <p>Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. </p> <p>I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (<a href="http://dnrtv.com/default.aspx?showID=115" rel="noreferrer">http://dnrtv.com/default.aspx?showID=115</a>). </p>
[ { "answer_id": 138315, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 5, "selected": true, "text": "<p>the Frame class exposes a method named \"Navigate\" that takes the content you want to show in your frame as parameter.\ntry calling </p>\n\n<pre><code>myFrame.Navigate(myPageObject);\n</code></pre>\n\n<p>this should work</p>\n" }, { "answer_id": 24053558, "author": "BASIR ALMAS", "author_id": 3709951, "author_profile": "https://Stackoverflow.com/users/3709951", "pm_score": -1, "selected": false, "text": "<p>yourFramName.NavigationService.Navigate(yourPageObject)</p>\n\n<p>e.g \nFrame1.NavigationService.Navigate(new Page1());</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
I have a Window where I have put a Frame. I would like to add a Page to the Frame when I click a button that is also on the Window but not in the Frame. There are several buttons in the Window and each click on a button should load a different Page in the Frame. Since I'm a total newbie on this WPF stuff it's quite possible that this approach is not the best and I have thought about replacing the Frame with a Canvas and then make UserControls instead of Pages that will be added to the Canvas. I welcome any ideas and suggestions on how to best solve this. I aiming for a functionality that is similar to the application Billy Hollis demonstrated in dnrtv episode 115. (<http://dnrtv.com/default.aspx?showID=115>).
the Frame class exposes a method named "Navigate" that takes the content you want to show in your frame as parameter. try calling ``` myFrame.Navigate(myPageObject); ``` this should work
138,097
<p>I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.</p> <p>Is there another way to obtain the PID?</p>
[ { "answer_id": 138098, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 6, "selected": true, "text": "<p>If you have <a href=\"http://en.wikipedia.org/wiki/Procfs\" rel=\"nofollow noreferrer\">procfs</a> installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case).</p>\n\n<p>Thus, with Java, you can do:</p>\n\n<pre><code>String pid = new File(\"/proc/self\").getCanonicalFile().getName();\n</code></pre>\n\n<p>In JRuby, you can use the same solution:</p>\n\n<pre><code>pid = java.io.File.new(\"/proc/self\").canonical_file.name\n</code></pre>\n\n<p>Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, <a href=\"https://stackoverflow.com/users/14648/jerub\">Jerub</a>, <a href=\"https://stackoverflow.com/users/893/greg-hewgill\">gregh</a>, and <a href=\"https://stackoverflow.com/users/1057/harley\">Topdeck</a>)</p>\n" }, { "answer_id": 138332, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 3, "selected": false, "text": "<p>Only tested in Linux using Sun JVM. Might not work with other JMX implementations.</p>\n\n<pre><code>String pid = ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0];\n</code></pre>\n" }, { "answer_id": 11396935, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 2, "selected": false, "text": "<p>You can use the JNI interface to call the POSIX function <a href=\"http://www.kernel.org/doc/man-pages/online/pages/man2/getpid.2.html\" rel=\"nofollow\">getpid</a>(). It is quite straight forward. You start with a class for the POSIX functions you need. I call it <code>POSIX.java</code>:</p>\n\n<pre><code>import java.util.*;\n\nclass POSIX\n{\n static { System.loadLibrary (\"POSIX\"); }\n native static int getpid ();\n}\n</code></pre>\n\n<p>Compile it with </p>\n\n<pre><code>$ javac POSIX.java\n</code></pre>\n\n<p>After that you generate a header file <code>POSIX.h</code> with</p>\n\n<pre><code>$ javah -jni POSIX\n</code></pre>\n\n<p>The header file contains the C prototype for the function with wraps the getpid function. Now you have to implement the function, which is quite easy. I did it in <code>POSIX.c</code>:</p>\n\n<pre><code>#include \"POSIX.h\"\n\n#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\n\nJNIEXPORT jint JNICALL Java_POSIX_getpid (JNIEnv *env, jclass cls)\n{\n return getpid ();\n}\n</code></pre>\n\n<p>Now you can compile it using gcc:</p>\n\n<pre><code>$ gcc -Wall -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include/linux -o libPOSIX.so -shared -Wl,-soname,libPOSIX.so POSIX.c -static -lc\n</code></pre>\n\n<p>You have to specify the location where your Java is installed. That's all. Now you can use it. Create a simple getpid program:</p>\n\n<pre><code>public class getpid\n{\n public static void main (String argv[])\n {\n System.out.println (POSIX.getpid ());\n }\n}\n</code></pre>\n\n<p>Compile it with <code>javac getpid.java</code> and run it:</p>\n\n<pre><code>$ java getpid &amp;\n[1] 21983\n$ 21983\n</code></pre>\n\n<p>The first pid is written by the shell and the second is written by the Java program after shell prompt has returned. ∎</p>\n" }, { "answer_id": 12886699, "author": "Jarekczek", "author_id": 772981, "author_profile": "https://Stackoverflow.com/users/772981", "pm_score": 2, "selected": false, "text": "<p>Spawn a shell process that will read its parent's pid. That must be our pid. Here is the running code, without exception and error handling.</p>\n\n<pre><code>import java.io.*;\nimport java.util.Scanner;\n\npublic class Pid2\n{\n public static void main(String sArgs[])\n throws java.io.IOException, InterruptedException\n {\n Process p = Runtime.getRuntime().exec(\n new String[] { \"sh\", \"-c\", \"ps h -o ppid $$\" });\n p.waitFor();\n Scanner sc = new Scanner(p.getInputStream());\n System.out.println(\"My pid: \" + sc.nextInt()); \n Thread.sleep(5000);\n }\n}\n</code></pre>\n\n<p>This solution seems to be the best if the PID is to be obtained only to issue another shell command. It's enough to wrap the command in back quotes to pass it as an argument to another command, for example:</p>\n\n<pre><code>nice `ps h -o ppid $$`\n</code></pre>\n\n<p>This may substitue the last string in the array given to <code>exec</code> call.</p>\n" }, { "answer_id": 28992841, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 0, "selected": false, "text": "<p>You can try getpid() in <a href=\"https://github.com/jnr/jnr-posix\" rel=\"nofollow\">JNR-Posix</a>.</p>\n\n<p>It also has a Windows POSIX wrapper that calls getpid() off of libc. No JNI needed.</p>\n" }, { "answer_id": 52526755, "author": "Xavier Guihot", "author_id": 9297144, "author_profile": "https://Stackoverflow.com/users/9297144", "pm_score": 1, "selected": false, "text": "<p><code>Java 9</code> finally offers an official way to do so with <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html\" rel=\"nofollow noreferrer\">ProcessHandle</a>:</p>\n\n<pre><code>ProcessHandle.current().pid();\n</code></pre>\n\n<p>This:</p>\n\n<ul>\n<li><p>First gets a <code>ProcessHandle</code> reference for the current process.</p></li>\n<li><p>In order to access its <code>pid</code>.</p></li>\n</ul>\n\n<p>No import necessary as <code>ProcessHandle</code> is part of <code>java.lang</code>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid. Is there another way to obtain the PID?
If you have [procfs](http://en.wikipedia.org/wiki/Procfs) installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case). Thus, with Java, you can do: ``` String pid = new File("/proc/self").getCanonicalFile().getName(); ``` In JRuby, you can use the same solution: ``` pid = java.io.File.new("/proc/self").canonical_file.name ``` Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, [Jerub](https://stackoverflow.com/users/14648/jerub), [gregh](https://stackoverflow.com/users/893/greg-hewgill), and [Topdeck](https://stackoverflow.com/users/1057/harley))
138,099
<p>GWT's serializer has limited <code>java.io.Serializable</code> support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example <a href="http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable" rel="noreferrer">this FAQ entry</a> says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist.</p> <p>The generated list contains a number of types that are part of the standard library, such as <code>java.lang.String</code> and <code>java.util.HashMap</code>. I get an error when trying to serialize <code>java.sql.Date</code>, which implements the <code>Serializable</code> interface, but is not on the whitelist. How can I add this type to the list?</p>
[ { "answer_id": 138965, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 3, "selected": false, "text": "<p>The whitelist is generated by the GWT compiler and contains all the entries that are designated by the IsSerializable marker interface. </p>\n\n<p>To add a type to the list you just need to make sure that the class implements the IsSerializable interface.</p>\n\n<p>Additionally for serialization to work correctly the class must have a default no arg constructor (constructor can be private if needed). Also if the class is an inner it must be marked as static.</p>\n" }, { "answer_id": 144894, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 5, "selected": true, "text": "<p>Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg:</p>\n\n<pre><code>public String getStringForDates(ArrayList&lt;java.util.Date&gt; dates);\n</code></pre>\n\n<p>Will result in ArrayList and Date both being included on the whitelist.</p>\n\n<p>It gets trickier if you try and use java.lang.Object instead of specific types:</p>\n\n<pre><code>public Object getObjectForString(String str);\n</code></pre>\n\n<p>Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism.</p>\n" }, { "answer_id": 992745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>There's a workaround: define a new <code>Dummy</code> class with member fields of all the types that you want to be included in serialization. Then add a method to your RPC interface:</p>\n\n<pre><code>Dummy dummy(Dummy d);\n</code></pre>\n\n<p>The implementation is just this:</p>\n\n<pre><code>Dummy dummy(Dummy d) { return d; }\n</code></pre>\n\n<p>And the async interface will have this:</p>\n\n<pre><code>void dummy(Dummy d, AsyncCallback&lt; Dummy&gt; callback);\n</code></pre>\n\n<p>The GWT compiler will pick this up, and because the <code>Dummy</code> class references those types, it will include them in the white list.</p>\n\n<p>Example <code>Dummy</code> class:</p>\n\n<pre><code>public class Dummy implements IsSerializable {\n private java.sql.Date d;\n}\n</code></pre>\n" }, { "answer_id": 1230180, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>IMHO the simpliest way to access whitelist programmatically is to create a class similar to this:</p>\n\n<pre><code>public class SerializableWhitelist implements IsSerializable {\n String[] dummy1;\n SomeOtherThingsIWishToSerialize dummy2;\n}\n</code></pre>\n\n<p>Then include it in the <code>.client</code> package and reference from the RPC service (so it gets analyzed by the compiler).</p>\n\n<p>I couldn't find a better way to enable tranfer of unparameterized maps, which is obviously what you sometimes need in order to create more generic services...</p>\n" }, { "answer_id": 1533719, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>to ensure the desired result delete all <code>war/&lt;app&gt;/gwt/*.gwt.rpc</code></p>\n" }, { "answer_id": 1627181, "author": "Domchi", "author_id": 29192, "author_profile": "https://Stackoverflow.com/users/29192", "pm_score": 0, "selected": false, "text": "<p>To anyone who will have the same question and doesn't find previous answers satisfactory...</p>\n\n<p>I'm using GWT with GWTController, since I'm using Spring, which I modified as described <a href=\"http://markmail.org/message/k5j2vni6yzcokjsw\" rel=\"nofollow noreferrer\">in this message</a>. The message explains how to modify GrailsRemoteServiceServlet, but GWTController calls RPC.decodeRequest() and RPC.encodeResponseForSuccess() in the same way.</p>\n\n<p>This is the final version of GWTController I'm using:</p>\n\n<pre><code>/**\n * Used to instantiate GWT server in Spring context.\n *\n * Original version from &lt;a href=\"http://docs.google.com/Doc?docid=dw2zgx2_25492p5qxfq&amp;hl=en\"&gt;this tutorial&lt;/a&gt;.\n * \n * ...fixed to work as explained &lt;a href=\"http://blog.js-development.com/2009/09/gwt-meets-spring.html\"&gt;in this tutorial&lt;/a&gt;.\n * \n * ...and then fixed to use StandardSerializationPolicy as explained in\n * &lt;a href=\"http://markmail.org/message/k5j2vni6yzcokjsw\"&gt;this message&lt;/a&gt; to allow\n * using Serializable instead of IsSerializable in model.\n */\npublic class GWTController extends RemoteServiceServlet implements Controller, ServletContextAware {\n\n // Instance fields\n\n private RemoteService remoteService;\n\n private Class&lt;? extends RemoteService&gt; remoteServiceClass;\n\n private ServletContext servletContext;\n\n // Public methods\n\n /**\n * Call GWT's RemoteService doPost() method and return null.\n * \n * @param request\n * The current HTTP request\n * @param response\n * The current HTTP response\n * @return A ModelAndView to render, or null if handled directly\n * @throws Exception\n * In case of errors\n */\n public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {\n doPost(request, response);\n return null; // response handled by GWT RPC over XmlHttpRequest\n }\n\n /**\n * Process the RPC request encoded into the payload string and return a string that encodes either the method return\n * or an exception thrown by it.\n * \n * @param payload\n * The RPC payload\n */\n public String processCall(String payload) throws SerializationException {\n try {\n RPCRequest rpcRequest = RPC.decodeRequest(payload, this.remoteServiceClass, this);\n\n // delegate work to the spring injected service\n return RPC.invokeAndEncodeResponse(this.remoteService, rpcRequest.getMethod(), rpcRequest.getParameters(), rpcRequest.getSerializationPolicy());\n } catch (IncompatibleRemoteServiceException e) {\n return RPC.encodeResponseForFailure(null, e);\n }\n }\n\n /**\n * Setter for Spring injection of the GWT RemoteService object.\n * \n * @param RemoteService\n * The GWT RemoteService implementation that will be delegated to by the {@code GWTController}.\n */\n public void setRemoteService(RemoteService remoteService) {\n this.remoteService = remoteService;\n this.remoteServiceClass = this.remoteService.getClass();\n }\n\n @Override\n public ServletContext getServletContext() {\n return servletContext;\n }\n\n public void setServletContext(ServletContext servletContext) {\n this.servletContext = servletContext;\n }\n}\n</code></pre>\n" }, { "answer_id": 2614308, "author": "Asif Sheikh", "author_id": 313568, "author_profile": "https://Stackoverflow.com/users/313568", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>The whitelist is generated by the gwt compiler and contains all the entries that are designated by the IsSerializable marker interface.</p>\n<p>To add a type to the list you just need to make sure that the class implements the IsSerializable interface.</p>\n<p>-- Andrej</p>\n</blockquote>\n<p>This is probably the easiest solution.\nThe only thing to remember with this is that all the classes that you want to serialize should have &quot;public, no-argument&quot; constructor, and (depending upon requirements) setter methods for the member fields.</p>\n" }, { "answer_id": 7532213, "author": "Glenn", "author_id": 924369, "author_profile": "https://Stackoverflow.com/users/924369", "pm_score": 0, "selected": false, "text": "<p>I found that just putting it in the client package or using it in a dummy service interface was not sufficient as it seemed the system optimized it away.</p>\n\n<p>I found it easiest to create a class that derived from one of the types already used in the service interface and stick it in the client package. Nothing else needed.</p>\n\n<pre><code>public class GWTSerializableTypes extends SomeTypeInServiceInterface implements IsSerializable {\n Long l;\n Double d;\n private GWTSerializableTypes() {}\n}\n</code></pre>\n" }, { "answer_id": 14733419, "author": "Dominic Tracey", "author_id": 1211550, "author_profile": "https://Stackoverflow.com/users/1211550", "pm_score": 0, "selected": false, "text": "<p>I had this problem but ended up tracing the problem back to a line of code in my Serializable object:</p>\n\n<pre><code>Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO, \"Foo\");\n</code></pre>\n\n<p>There were no other complaints before the exception gets caught in:</p>\n\n<pre><code> @Override\n protected void serialize(Object instance, String typeSignature)\n throws SerializationException {\n assert (instance != null);\n\n Class&lt;?&gt; clazz = getClassForSerialization(instance);\n\n try {\n serializationPolicy.validateSerialize(clazz);\n } catch (SerializationException e) {\n throw new SerializationException(e.getMessage() + \": instance = \" + instance);\n }\n serializeImpl(instance, clazz);\n }\n</code></pre>\n\n<p>And the business end of the stack trace is:</p>\n\n<pre><code>com.google.gwt.user.client.rpc.SerializationException: Type 'net.your.class' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = net.your.class@9c7edce\n at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:619)\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562/" ]
GWT's serializer has limited `java.io.Serializable` support, but for security reasons there is a whitelist of types it supports. The documentation I've found, for example [this FAQ entry](http://www.gwtproject.org/doc/latest/FAQ_Server.html#Does_the_GWT_RPC_system_support_the_use_of_java.io.Serializable) says that any types you want to serialize "must be included in the serialization policy whitelist", and that the list is generated at compile time, but doesn't explain how the compiler decides what goes on the whitelist. The generated list contains a number of types that are part of the standard library, such as `java.lang.String` and `java.util.HashMap`. I get an error when trying to serialize `java.sql.Date`, which implements the `Serializable` interface, but is not on the whitelist. How can I add this type to the list?
Any specific types that you include in your service interface and any types that they reference will be automatically whitelisted, as long as they implement java.io.Serializable, eg: ``` public String getStringForDates(ArrayList<java.util.Date> dates); ``` Will result in ArrayList and Date both being included on the whitelist. It gets trickier if you try and use java.lang.Object instead of specific types: ``` public Object getObjectForString(String str); ``` Because the compiler doesn't know what to whitelist. In that case if the objects are not referenced anywhere in your service interface, you have to mark them explicitly with the IsSerializable interface, otherwise it won't let you pass them through the RPC mechanism.
138,117
<p>how to send rich text message in system.net.mail need code for send a mail as html</p>
[ { "answer_id": 138128, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 2, "selected": false, "text": "<pre><code>System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();\nmm.Body = \"&lt;html&gt;...&lt;/html&gt;\";\nmm.IsBodyHtml = true;\n</code></pre>\n" }, { "answer_id": 138134, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": true, "text": "<pre><code>//create the mail message\n MailMessage mail = new MailMessage();\n\n //set the addresses\n mail.From = new MailAddress(\"[email protected]\");\n mail.To.Add(\"[email protected]\");\n\n //set the content\n mail.Subject = \"This is an email\";\n mail.Body = \"&lt;b&gt;This is bold&lt;/b&gt; &lt;font color=#336699&gt;This is blue&lt;/font&gt;\";\n mail.IsBodyHtml = true;\n\n //send the message\n SmtpClient smtp = new SmtpClient(\"127.0.0.1\");\n smtp.Send(mail);\n</code></pre>\n" }, { "answer_id": 138141, "author": "GvS", "author_id": 11492, "author_profile": "https://Stackoverflow.com/users/11492", "pm_score": 1, "selected": false, "text": "<p>You should be aware, that not every person/mailclient can present a message formatted in HTML. If you rely on layout to make your message clear this can be a problem. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
how to send rich text message in system.net.mail need code for send a mail as html
``` //create the mail message MailMessage mail = new MailMessage(); //set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); //set the content mail.Subject = "This is an email"; mail.Body = "<b>This is bold</b> <font color=#336699>This is blue</font>"; mail.IsBodyHtml = true; //send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail); ```
138,122
<p>I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.</p> <p>I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.</p> <p>The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.</p> <p>I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.</p> <p>any thoughts?</p>
[ { "answer_id": 138126, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 1, "selected": false, "text": "<p>This is unusual as I often created a DC based on the screen that will be used for a bitmap image that is much larger than the screen - 3000 pixels plus in some cases - with no problems at all. Do you have some sample code showing this problem in action?</p>\n" }, { "answer_id": 138143, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 3, "selected": true, "text": "<p>CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with <a href=\"http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx\" rel=\"nofollow noreferrer\">::CreateDIBSection</a>, then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.</p>\n\n<p>You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp:</p>\n\n<pre><code>BITMAPINFOHEADER bmi = { sizeof(bmi) };\nbmi.biWidth = 20000;\nbmi.biHeight = 20000;\nbmi.biPlanes = 1;\nbmi.biBitCount = 16;\nHDC hdc = CreateCompatibleDC(NULL);\nBYTE* pbData = 0;\nHBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&amp;bmi, DIB_RGB_COLORS, (void**)&amp;pbData, NULL, 0);\nDeleteObject(SelectObject(hdc, hbm));\n</code></pre>\n" }, { "answer_id": 138180, "author": "xoreax", "author_id": 22573, "author_profile": "https://Stackoverflow.com/users/22573", "pm_score": 1, "selected": false, "text": "<p>Considering such a big image resolution, you cannot create the image using compatible bitmaps.</p>\n\n<p>Example:</p>\n\n<p>pixel depth = 32 bits = 4 bytes per pixel</p>\n\n<p>pixel count = 20.000 * 20.000 = 400.000.000</p>\n\n<p>total bytes = pixel count * 4 = 1.600.000.000 bytes = 1.562.500 kb ~= 1525 MB ~= 1.5GB</p>\n\n<p>I'm speculating about the final intentions, but suppose you want to create and allow users to explore an immense map with very detailed zooms.\nYou should create a custom image file format; you can put inside that file various layers containing grids of bitmaps for example, to speedup rendering. The render process can use GDI DIBs or GDI+ to create partial images and then render them together. Of course this need some experimenting/optimizing to reach the perfect user feeling.</p>\n\n<p>good luck</p>\n" }, { "answer_id": 138236, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 0, "selected": false, "text": "<p>If the image has to be this resolution - say a hi-res scan of an x-ray - then you might want to look at writing custom spooling routines for it - 1.5 gb is very expensive - even for modern desktops.</p>\n\n<p>If it is vector based then you can look at SVG as it supports view ports and most allow you to render to other formats. I use SVG to JPG via Batik (java) so it is possible to do.</p>\n" }, { "answer_id": 138272, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 1, "selected": false, "text": "<p>To keep your memory usage within acceptable limits, you'll have to use your 'divide and conquer' strategy. It's not a hack, if implemented right it's actually a very elegant way of dealing with bitmaps of unlimited size. If you design it right, you can combine the 'only render/show part of the image', 'render the whole image at low resolution for on-screen display' and 'render the whole thing to an on-disk bitmap' approaches in one engine and shield users of your code (most likely yourself in two weeks ;) ) from the internals. I work on a product with the same issues: rendering (potentially large) maps either to the screen or to .bmp files.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver. I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information. The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render. I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique. any thoughts?
CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with [::CreateDIBSection](http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx), then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately. You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp: ``` BITMAPINFOHEADER bmi = { sizeof(bmi) }; bmi.biWidth = 20000; bmi.biHeight = 20000; bmi.biPlanes = 1; bmi.biBitCount = 16; HDC hdc = CreateCompatibleDC(NULL); BYTE* pbData = 0; HBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pbData, NULL, 0); DeleteObject(SelectObject(hdc, hbm)); ```
138,132
<p><strong>Here's the situation</strong>: I'm trying my hand at some MySpace page customisations. If you've <a href="https://stackoverflow.com/questions/116610/myspace-dom">ever tried</a> [stackoverflow], I'm sure you understand how frustrating it can be.<br> Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!).<br> Have a look at this <a href="http://www.mikeindustries.com/blog/archive/2006/04/hacking-myspace-layouts" rel="nofollow noreferrer">blog</a> if you want more info, I used it as the basis for my customisations</p> <p>So the only problem is with the comments section, where 'friends' post whatever they feel like. It already has...</p> <pre><code>max-width:423px; </code></pre> <p>...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting!</p> <p><strong>Question</strong>: Is there a way to manage text that is going to push the width of the table?<br> Perhaps splitting/chopping the string? Or is there more I should be doing..?<br> The URLs are posted as text, not hrefs.</p> <p>Using Firefox and Firebug btw.</p> <p><strong>Edit</strong>: Also javascript is not allowed ;)</p> <p><strong>Another edit</strong> Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case..</p>
[ { "answer_id": 138145, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>Have you tried the various values for the \"overflow\" css property? I think that may do what you need in some permutation.</p>\n" }, { "answer_id": 138151, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 0, "selected": false, "text": "<p>Your options are pretty limited, if you are using only CSS. You can try</p>\n\n<pre><code> overflow: hidden\n</code></pre>\n\n<p>to hide the offending parts. CSS 3 supports <a href=\"http://www.w3.org/TR/css3-text/#wrapping\" rel=\"nofollow noreferrer\">text-wrap</a>, but support for it is probably non-existent. IIRC there is an IE-only css-property for doing the same thing, but I can't remember it at the moment and my Google-Fu fails me.</p>\n" }, { "answer_id": 138154, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<p>a few browsers support <a href=\"http://www.css3.info/preview/word-wrap/\" rel=\"nofollow noreferrer\">word-wrap</a></p>\n\n<p>ex.</p>\n\n<pre><code>&lt;div style=\"width: 50px; word-wrap: break-word\"&gt;insertsuperlongwordhereplease&lt;/div&gt;\n</code></pre>\n\n<p>browser support currently is IE / Safari / Firefox 3.1 (Alpha)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
**Here's the situation**: I'm trying my hand at some MySpace page customisations. If you've [ever tried](https://stackoverflow.com/questions/116610/myspace-dom) [stackoverflow], I'm sure you understand how frustrating it can be. Basically it can be all customised via CSS, within a certain set of rules (e.g. the '#' character is not allowed...how useful!). Have a look at this [blog](http://www.mikeindustries.com/blog/archive/2006/04/hacking-myspace-layouts) if you want more info, I used it as the basis for my customisations So the only problem is with the comments section, where 'friends' post whatever they feel like. It already has... ``` max-width:423px; ``` ...set on the table, but I've discovered if long URLs are posted in the comment section, it blows out the table width, regardless of the max setting! **Question**: Is there a way to manage text that is going to push the width of the table? Perhaps splitting/chopping the string? Or is there more I should be doing..? The URLs are posted as text, not hrefs. Using Firefox and Firebug btw. **Edit**: Also javascript is not allowed ;) **Another edit** Just checked with IE7, and it seems to work.. so firefox is being the hassle in this case..
Have you tried the various values for the "overflow" css property? I think that may do what you need in some permutation.
138,133
<p>Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?</p>
[ { "answer_id": 138152, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/aspnet/Wiki/View.aspx?title=Dynamic%20Data&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">Dynamic Data</a> for ASP.NET (and ASP.NET MVC) lets you do validation for model properties using attributes.</p>\n" }, { "answer_id": 138156, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 3, "selected": false, "text": "<p>The Microsoft Enterprise Library has the Microsoft.Practices.EnterpriseLibrary.Validation library/namespace which allows validation using attributes.</p>\n" }, { "answer_id": 138294, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could also use <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">postsharp</a> and implement your own attributes for validation.</p>\n" }, { "answer_id": 1438327, "author": "Christian", "author_id": 54193, "author_profile": "https://Stackoverflow.com/users/54193", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx\" rel=\"nofollow noreferrer\">Microsoft Code Contracts</a>, which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters.</p>\n<p>An example use for parameter checking would be (copied from <a href=\"http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf\" rel=\"nofollow noreferrer\">Code Contracts documentation</a>):</p>\n<pre><code>public Rational(int numerator, int denominator)\n{\n Contract.Requires(denominator ! = 0);\n \n this.numerator = numerator;\n this.denominator = denominator;\n}\n</code></pre>\n<p>The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application.</p>\n<p><strong>EDIT:</strong> Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their <a href=\"http://research.microsoft.com/en-us/projects/contracts/faq.aspx\" rel=\"nofollow noreferrer\">FAQ</a>:</p>\n<blockquote>\n<p>The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes:</p>\n<p><strong>Runtime support:</strong> Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation.</p>\n<p><strong>Need for parsing:</strong> Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses.</p>\n<p><strong>Lack of IDE support:</strong> Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code.</p>\n</blockquote>\n" }, { "answer_id": 2359257, "author": "Kevin Castle", "author_id": 228413, "author_profile": "https://Stackoverflow.com/users/228413", "pm_score": 1, "selected": false, "text": "<p>Here is an example using PostSharp\n<a href=\"http://dpatrickcaldwell.blogspot.com/2009/03/validate-parameters-using-attributes.html\" rel=\"nofollow noreferrer\">http://dpatrickcaldwell.blogspot.com/2009/03/validate-parameters-using-attributes.html</a></p>\n" }, { "answer_id": 3784166, "author": "Sven Erik", "author_id": 456886, "author_profile": "https://Stackoverflow.com/users/456886", "pm_score": 2, "selected": false, "text": "<p>While Microsoft Code Contracts are out for a while, they are still hosted in MS Research and you cannot use configuration (app.config/database etc.) to switch on/off or even change rules. My library <a href=\"http://bouncer.codeplex.com/\" rel=\"nofollow\">Bouncer</a> does provide declarive rule definition: attributes in source code or app.config entries for rules at the entity class/property level. The library is opensource under LGPL (you can freely use it in commercial products). If you configure the rules via app.config you can adjust the rule settings without the need of a recompile.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?
[Microsoft Code Contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx), which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters. An example use for parameter checking would be (copied from [Code Contracts documentation](http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf)): ``` public Rational(int numerator, int denominator) { Contract.Requires(denominator ! = 0); this.numerator = numerator; this.denominator = denominator; } ``` The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application. **EDIT:** Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their [FAQ](http://research.microsoft.com/en-us/projects/contracts/faq.aspx): > > The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes: > > > **Runtime support:** Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation. > > > **Need for parsing:** Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses. > > > **Lack of IDE support:** Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code. > > >
138,144
<p>What essential things (functions, aliases, start up scripts) do you have in your profile?</p>
[ { "answer_id": 138224, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "<pre><code>############################################################################## \n# Get an XPath Navigator object based on the input string containing xml\nfunction get-xpn ($text) { \n $rdr = [System.IO.StringReader] $text\n $trdr = [system.io.textreader]$rdr\n $xpdoc = [System.XML.XPath.XPathDocument] $trdr\n $xpdoc.CreateNavigator()\n}\n</code></pre>\n\n<p>Useful for working with xml, such as output from svn commands with --xml.</p>\n" }, { "answer_id": 138229, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 3, "selected": false, "text": "<p>apropos.</p>\n\n<p>Although I think this has been superseded by a recent or upcoming release.</p>\n\n<pre><code>############################################################################## \n## Search the PowerShell help documentation for a given keyword or regular \n## expression.\n## \n## Example:\n## Get-HelpMatch hashtable\n## Get-HelpMatch \"(datetime|ticks)\"\n############################################################################## \nfunction apropos {\n\n param($searchWord = $(throw \"Please specify content to search for\"))\n\n $helpNames = $(get-help *)\n\n foreach($helpTopic in $helpNames)\n {\n $content = get-help -Full $helpTopic.Name | out-string\n if($content -match $searchWord)\n { \n $helpTopic | select Name,Synopsis\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 139102, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 1, "selected": false, "text": "<pre><code>$MaximumHistoryCount=1024 \nfunction hist {get-history -count 256 | %{$_.commandline}}\n\nNew-Alias which get-command\n\nfunction guidConverter([byte[]] $gross){ $GUID = \"{\" + $gross[3].ToString(\"X2\") + `\n$gross[2].ToString(\"X2\") + $gross[1].ToString(\"X2\") + $gross[0].ToString(\"X2\") + \"-\" + `\n$gross[5].ToString(\"X2\") + $gross[4].ToString(\"X2\") + \"-\" + $gross[7].ToString(\"X2\") + `\n$gross[6].ToString(\"X2\") + \"-\" + $gross[8].ToString(\"X2\") + $gross[9].ToString(\"X2\") + \"-\" +` \n$gross[10].ToString(\"X2\") + $gross[11].ToString(\"X2\") + $gross[12].ToString(\"X2\") + `\n$gross[13].ToString(\"X2\") + $gross[14].ToString(\"X2\") + $gross[15].ToString(\"X2\") + \"}\" $GUID }\n</code></pre>\n" }, { "answer_id": 139997, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 4, "selected": false, "text": "<p>To setup my Visual Studio build environment from PowerShell I took the VsVars32 from <a href=\"http://www.tavaresstudios.com/Blog/post/The-last-vsvars32ps1-Ill-ever-need.aspx\" rel=\"noreferrer\">here</a>. and use it all the time. </p>\n\n<pre>\n###############################################################################\n# Exposes the environment vars in a batch and sets them in this PS session\n###############################################################################\nfunction Get-Batchfile($file) \n{\n $theCmd = \"`\"$file`\" & set\" \n cmd /c $theCmd | Foreach-Object {\n $thePath, $theValue = $_.split('=')\n Set-Item -path env:$thePath -value $theValue\n }\n}\n\n\n###############################################################################\n# Sets the VS variables for this PS session to use\n###############################################################################\nfunction VsVars32($version = \"9.0\")\n{\n $theKey = \"HKLM:SOFTWARE\\Microsoft\\VisualStudio\\\" + $version\n $theVsKey = get-ItemProperty $theKey\n $theVsInstallPath = [System.IO.Path]::GetDirectoryName($theVsKey.InstallDir)\n $theVsToolsDir = [System.IO.Path]::GetDirectoryName($theVsInstallPath)\n $theVsToolsDir = [System.IO.Path]::Combine($theVsToolsDir, \"Tools\")\n $theBatchFile = [System.IO.Path]::Combine($theVsToolsDir, \"vsvars32.bat\")\n Get-Batchfile $theBatchFile\n [System.Console]::Title = \"Visual Studio \" + $version + \" Windows Powershell\"\n}\n</pre>\n" }, { "answer_id": 145882, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 3, "selected": false, "text": "<p>I keep a little bit of everything. Mostly, my profile sets up all the environment (including calling scripts to set up my .NET/VS and Java development environment).</p>\n\n<p>I also redefine the <code>prompt()</code> function with my own style (<a href=\"http://www.winterdom.com/weblog/2008/08/14/MyPowerShellPrompt.aspx\" rel=\"nofollow noreferrer\">see it in action</a>), set up several aliases to other scripts and commands. and change what <code>$HOME</code> points to.</p>\n\n<p>Here's my complete <a href=\"http://github.com/tomasr/dotfiles/tree/master/.profile.ps1\" rel=\"nofollow noreferrer\">profile script</a>.</p>\n" }, { "answer_id": 145893, "author": "user15071", "author_id": 15071, "author_profile": "https://Stackoverflow.com/users/15071", "pm_score": 3, "selected": false, "text": "<pre><code># ----------------------------------------------------------\n# msdn search for win32 APIs.\n# ----------------------------------------------------------\n\nfunction Search-MSDNWin32\n{\n\n $url = 'http://search.msdn.microsoft.com/?query=';\n\n $url += $args[0];\n\n for ($i = 1; $i -lt $args.count; $i++) {\n $url += '+';\n $url += $args[$i];\n }\n\n $url += '&amp;locale=en-us&amp;refinement=86&amp;ac=3';\n\n Open-IE($url);\n}\n\n# ----------------------------------------------------------\n# Open Internet Explorer given the url.\n# ----------------------------------------------------------\n\nfunction Open-IE ($url)\n{ \n $ie = new-object -comobject internetexplorer.application;\n\n $ie.Navigate($url);\n\n $ie.Visible = $true;\n}\n</code></pre>\n" }, { "answer_id": 146937, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 4, "selected": false, "text": "<p>This iterates through a scripts PSDrive and dot-sources everything that begins with \"lib-\".</p>\n\n<pre><code>### ---------------------------------------------------------------------------\n### Load function / filter definition library\n### ---------------------------------------------------------------------------\n\n Get-ChildItem scripts:\\lib-*.ps1 | % { \n . $_\n write-host \"Loading library file:`t$($_.name)\"\n }\n</code></pre>\n" }, { "answer_id": 146945, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "<p>This creates a scripts: drive and adds it to your path. Note, you must create the folder yourself. Next time you need to get back to it, just type \"scripts:\" and hit enter, just like any drive letter in Windows.</p>\n\n<pre><code>$env:path += \";$profiledir\\scripts\"\nNew-PSDrive -Name Scripts -PSProvider FileSystem -Root $profiledir\\scripts\n</code></pre>\n" }, { "answer_id": 146952, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "<p>This will add snapins you have installed into your powershell session. The reason you may want to do something like this is that it's easy to maintain, and works well if you sync your profile across multiple systems. If a snapin isn't installed, you won't see an error message.</p>\n\n<h3>---------------------------------------------------------------------------</h3>\n\n<h3>Add third-party snapins</h3>\n\n<h3>---------------------------------------------------------------------------</h3>\n\n<pre><code>$snapins = @(\n \"Quest.ActiveRoles.ADManagement\",\n \"PowerGadgets\",\n \"VMware.VimAutomation.Core\",\n \"NetCmdlets\"\n)\n$snapins | ForEach-Object { \n if ( Get-PSSnapin -Registered $_ -ErrorAction SilentlyContinue ) {\n Add-PSSnapin $_\n }\n}\n</code></pre>\n" }, { "answer_id": 158779, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "<p>Here's my not so subtle profile</p>\n\n<pre><code>\n #==============================================================================\n# Jared Parsons PowerShell Profile ([email protected]) \n#==============================================================================\n\n#==============================================================================\n# Common Variables Start\n#==============================================================================\n$global:Jsh = new-object psobject \n$Jsh | add-member NoteProperty \"ScriptPath\" $(split-path -parent $MyInvocation.MyCommand.Definition) \n$Jsh | add-member NoteProperty \"ConfigPath\" $(split-path -parent $Jsh.ScriptPath)\n$Jsh | add-member NoteProperty \"UtilsRawPath\" $(join-path $Jsh.ConfigPath \"Utils\")\n$Jsh | add-member NoteProperty \"UtilsPath\" $(join-path $Jsh.UtilsRawPath $env:PROCESSOR_ARCHITECTURE)\n$Jsh | add-member NoteProperty \"GoMap\" @{}\n$Jsh | add-member NoteProperty \"ScriptMap\" @{}\n\n#==============================================================================\n\n#==============================================================================\n# Functions \n#==============================================================================\n\n# Load snapin's if they are available\nfunction Jsh.Load-Snapin([string]$name) {\n $list = @( get-pssnapin | ? { $_.Name -eq $name })\n if ( $list.Length -gt 0 ) {\n return; \n }\n\n $snapin = get-pssnapin -registered | ? { $_.Name -eq $name }\n if ( $snapin -ne $null ) {\n add-pssnapin $name\n }\n}\n\n# Update the configuration from the source code server\nfunction Jsh.Update-WinConfig([bool]$force=$false) {\n\n # First see if we've updated in the last day \n $target = join-path $env:temp \"Jsh.Update.txt\"\n $update = $false\n if ( test-path $target ) {\n $last = [datetime] (gc $target)\n if ( ([DateTime]::Now - $last).Days -gt 1) {\n $update = $true\n }\n } else {\n $update = $true;\n }\n\n if ( $update -or $force ) {\n write-host \"Checking for winconfig updates\"\n pushd $Jsh.ConfigPath\n $output = @(& svn update)\n if ( $output.Length -gt 1 ) {\n write-host \"WinConfig updated. Re-running configuration\"\n cd $Jsh.ScriptPath\n & .\\ConfigureAll.ps1\n . .\\Profile.ps1\n }\n\n sc $target $([DateTime]::Now)\n popd\n }\n}\n\nfunction Jsh.Push-Path([string] $location) { \n go $location $true \n}\nfunction Jsh.Go-Path([string] $location, [bool]$push = $false) {\n if ( $location -eq \"\" ) {\n write-output $Jsh.GoMap\n } elseif ( $Jsh.GoMap.ContainsKey($location) ) {\n if ( $push ) {\n push-location $Jsh.GoMap[$location]\n } else {\n set-location $Jsh.GoMap[$location]\n }\n } elseif ( test-path $location ) {\n if ( $push ) {\n push-location $location\n } else {\n set-location $location\n }\n } else {\n write-output \"$loctaion is not a valid go location\"\n write-output \"Current defined locations\"\n write-output $Jsh.GoMap\n }\n}\n\nfunction Jsh.Run-Script([string] $name) {\n if ( $Jsh.ScriptMap.ContainsKey($name) ) {\n . $Jsh.ScriptMap[$name]\n } else {\n write-output \"$name is not a valid script location\"\n write-output $Jsh.ScriptMap\n }\n}\n\n\n# Set the prompt\nfunction prompt() {\n if ( Test-Admin ) { \n write-host -NoNewLine -f red \"Admin \"\n }\n write-host -NoNewLine -ForegroundColor Green $(get-location)\n foreach ( $entry in (get-location -stack)) {\n write-host -NoNewLine -ForegroundColor Red '+';\n }\n write-host -NoNewLine -ForegroundColor Green '>'\n ' '\n}\n\n#==============================================================================\n\n#==============================================================================\n# Alias \n#==============================================================================\nset-alias gcid Get-ChildItemDirectory\nset-alias wget Get-WebItem\nset-alias ss select-string\nset-alias ssr Select-StringRecurse \nset-alias go Jsh.Go-Path\nset-alias gop Jsh.Push-Path\nset-alias script Jsh.Run-Script\nset-alias ia Invoke-Admin\nset-alias ica Invoke-CommandAdmin\nset-alias isa Invoke-ScriptAdmin\n#==============================================================================\n\npushd $Jsh.ScriptPath\n\n# Setup the go locations\n$Jsh.GoMap[\"ps\"] = $Jsh.ScriptPath\n$Jsh.GoMap[\"config\"] = $Jsh.ConfigPath\n$Jsh.GoMap[\"~\"] = \"~\"\n\n# Setup load locations\n$Jsh.ScriptMap[\"profile\"] = join-path $Jsh.ScriptPath \"Profile.ps1\"\n$Jsh.ScriptMap[\"common\"] = $(join-path $Jsh.ScriptPath \"LibraryCommon.ps1\")\n$Jsh.ScriptMap[\"svn\"] = $(join-path $Jsh.ScriptPath \"LibrarySubversion.ps1\")\n$Jsh.ScriptMap[\"subversion\"] = $(join-path $Jsh.ScriptPath \"LibrarySubversion.ps1\")\n$Jsh.ScriptMap[\"favorites\"] = $(join-path $Jsh.ScriptPath \"LibraryFavorites.ps1\")\n$Jsh.ScriptMap[\"registry\"] = $(join-path $Jsh.ScriptPath \"LibraryRegistry.ps1\")\n$Jsh.ScriptMap[\"reg\"] = $(join-path $Jsh.ScriptPath \"LibraryRegistry.ps1\")\n$Jsh.ScriptMap[\"token\"] = $(join-path $Jsh.ScriptPath \"LibraryTokenize.ps1\")\n$Jsh.ScriptMap[\"unit\"] = $(join-path $Jsh.ScriptPath \"LibraryUnitTest.ps1\")\n$Jsh.ScriptMap[\"tfs\"] = $(join-path $Jsh.ScriptPath \"LibraryTfs.ps1\")\n$Jsh.ScriptMap[\"tab\"] = $(join-path $Jsh.ScriptPath \"TabExpansion.ps1\")\n\n# Load the common functions\n. script common\n. script tab\n$global:libCommonCertPath = (join-path $Jsh.ConfigPath \"Data\\Certs\\jaredp_code.pfx\")\n\n# Load the snapin's we want\nJsh.Load-Snapin \"pscx\"\nJsh.Load-Snapin \"JshCmdlet\" \n\n# Setup the Console look and feel\n$host.UI.RawUI.ForegroundColor = \"Yellow\"\nif ( Test-Admin ) {\n $title = \"Administrator Shell - {0}\" -f $host.UI.RawUI.WindowTitle\n $host.UI.RawUI.WindowTitle = $title;\n}\n\n# Call the computer specific profile\n$compProfile = join-path \"Computers\" ($env:ComputerName + \"_Profile.ps1\")\nif ( -not (test-path $compProfile)) { ni $compProfile -type File | out-null }\nwrite-host \"Computer profile: $compProfile\"\n. \".\\$compProfile\"\n$Jsh.ScriptMap[\"cprofile\"] = resolve-path ($compProfile)\n\n# If the computer name is the same as the domain then we are not \n# joined to active directory\nif ($env:UserDomain -ne $env:ComputerName ) {\n # Call the domain specific profile data\n write-host \"Domain $env:UserDomain\"\n $domainProfile = join-path $env:UserDomain \"Profile.ps1\"\n if ( -not (test-path $domainProfile)) { ni $domainProfile -type File | out-null }\n . \".\\$domainProfile\"\n}\n\n# Run the get-fortune command if JshCmdlet was loaded\nif ( get-command \"get-fortune\" -ea SilentlyContinue ) {\n get-fortune -timeout 1000\n}\n\n# Finished with the profile, go back to the original directory\npopd\n\n# Look for updates\nJsh.Update-WinConfig\n\n# Because this profile is run in the same context, we need to remove any \n# variables manually that we don't want exposed outside this script\n</code>\n</pre>\n" }, { "answer_id": 174693, "author": "Jeffery Hicks", "author_id": 25508, "author_profile": "https://Stackoverflow.com/users/25508", "pm_score": 2, "selected": false, "text": "<p>I put all my functions and aliases in separate script files and then dot source them in my profile:</p>\n\n<p>. c:\\scripts\\posh\\jdh-functions.ps1</p>\n" }, { "answer_id": 227382, "author": "jwmiller5", "author_id": 7824, "author_profile": "https://Stackoverflow.com/users/7824", "pm_score": 3, "selected": false, "text": "<p><strong><em>start-transcript</em></strong>. This will write out your entire session to a text file. Great for training new hires on how to use Powershell in the environment.</p>\n" }, { "answer_id": 255709, "author": "Alex", "author_id": 19081, "author_profile": "https://Stackoverflow.com/users/19081", "pm_score": 2, "selected": false, "text": "<p>The function to view the entire history of typed command (Get-History, and his alias h show default only 32 last commands): </p>\n\n<pre><code>function ha {\n Get-History -count $MaximumHistoryCount\n}\n</code></pre>\n" }, { "answer_id": 385718, "author": "nabiy", "author_id": 48286, "author_profile": "https://Stackoverflow.com/users/48286", "pm_score": 3, "selected": false, "text": "<p>i add this function so that i can see disk usage easily:</p>\n\n<pre><code>function df {\n $colItems = Get-wmiObject -class \"Win32_LogicalDisk\" -namespace \"root\\CIMV2\" `\n -computername localhost\n\n foreach ($objItem in $colItems) {\n write $objItem.DeviceID $objItem.Description $objItem.FileSystem `\n ($objItem.Size / 1GB).ToString(\"f3\") ($objItem.FreeSpace / 1GB).ToString(\"f3\")\n\n }\n}\n</code></pre>\n" }, { "answer_id": 394187, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>My prompt contains:</p>\n\n<pre><code>$width = ($Host.UI.RawUI.WindowSize.Width - 2 - $(Get-Location).ToString().Length)\n$hr = New-Object System.String @('-',$width)\nWrite-Host -ForegroundColor Red $(Get-Location) $hr\n</code></pre>\n\n<p>Which gives me a divider between commands that's easy to see when scrolling back. It also shows me the current directory without using horizontal space on the line that I'm typing on.</p>\n\n<p>For example:</p>\n\n<p><PRE>\nC:\\Users\\Jay ----------------------------------------------------------------------------------------------------------\n[1] PS>\n</PRE></p>\n" }, { "answer_id": 1435515, "author": "Precipitous", "author_id": 77784, "author_profile": "https://Stackoverflow.com/users/77784", "pm_score": 1, "selected": false, "text": "<p>I keep my profile empty. Instead, I have folders of scripts I can navigate to load functionality and aliases into the session. A folder will be modular, with libraries of functions and assemblies. For ad hoc work, I'll have a script to loads aliases and functions. If I want to munge event logs, I'd navigate to a folder scripts\\eventlogs and execute</p>\n\n<pre><code>PS &gt; . .\\DotSourceThisToLoadSomeHandyEventLogMonitoringFunctions.ps1\n</code></pre>\n\n<p>I do this because I need to share scripts with others or move them from machine to machine. I like to be able to copy a folder of scripts and assemblies and have it just work on any machine for any user. </p>\n\n<p>But you want a fun collection of tricks. Here's a script that many of my \"profiles\" depend on. It allows calls to web services that use self signed SSL for ad hoc exploration of web services in development. Yes, I freely mix C# in my powershell scripts. </p>\n\n<pre><code># Using a target web service that requires SSL, but server is self-signed. \n# Without this, we'll fail unable to establish trust relationship. \nfunction Set-CertificateValidationCallback\n{\n try\n {\n Add-Type @'\n using System;\n\n public static class CertificateAcceptor{\n\n public static void SetAccept()\n {\n System.Net.ServicePointManager.ServerCertificateValidationCallback = AcceptCertificate;\n }\n\n private static bool AcceptCertificate(Object sender,\n System.Security.Cryptography.X509Certificates.X509Certificate certificate,\n System.Security.Cryptography.X509Certificates.X509Chain chain,\n System.Net.Security.SslPolicyErrors policyErrors)\n {\n Console.WriteLine(\"Accepting certificate and ignoring any SSL errors.\");\n return true;\n }\n }\n'@\n }\n catch {} # Already exists? Find a better way to check.\n\n [CertificateAcceptor]::SetAccept()\n}\n</code></pre>\n" }, { "answer_id": 1913201, "author": "icnivad", "author_id": 232756, "author_profile": "https://Stackoverflow.com/users/232756", "pm_score": 2, "selected": false, "text": "<pre><code>Set-PSDebug -Strict \n</code></pre>\n\n<p>You will benefit i you ever searched for a stupid Typo eg. outputting $varsometext instead $var sometext </p>\n" }, { "answer_id": 1995576, "author": "Raoul Supercopter", "author_id": 57123, "author_profile": "https://Stackoverflow.com/users/57123", "pm_score": 5, "selected": false, "text": "<p>I often find myself needing needing some basic agregates to count/sum some things., I've defined these functions and use them often, they work really nicely at the end of a pipeline :</p>\n\n<pre><code>#\n# useful agregate\n#\nfunction count\n{\n BEGIN { $x = 0 }\n PROCESS { $x += 1 }\n END { $x }\n}\n\nfunction product\n{\n BEGIN { $x = 1 }\n PROCESS { $x *= $_ }\n END { $x }\n}\n\nfunction sum\n{\n BEGIN { $x = 0 }\n PROCESS { $x += $_ }\n END { $x }\n}\n\nfunction average\n{\n BEGIN { $max = 0; $curr = 0 }\n PROCESS { $max += $_; $curr += 1 }\n END { $max / $curr }\n}\n</code></pre>\n\n<p>To be able to get time and path with colors in my prompt :</p>\n\n<pre><code>function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }\nfunction prompt\n{\n # Write the time \n write-host \"[\" -noNewLine\n write-host $(Get-Time) -foreground yellow -noNewLine\n write-host \"] \" -noNewLine\n # Write the path\n write-host $($(Get-Location).Path.replace($home,\"~\").replace(\"\\\",\"/\")) -foreground green -noNewLine\n write-host $(if ($nestedpromptlevel -ge 1) { '&gt;&gt;' }) -noNewLine\n return \"&gt; \"\n}\n</code></pre>\n\n<p>The following functions are stolen from a blog and modified to fit my taste, but ls with colors is very nice :</p>\n\n<pre><code># LS.MSH \n# Colorized LS function replacement \n# /\\/\\o\\/\\/ 2006 \n# http://mow001.blogspot.com \nfunction LL\n{\n param ($dir = \".\", $all = $false) \n\n $origFg = $host.ui.rawui.foregroundColor \n if ( $all ) { $toList = ls -force $dir }\n else { $toList = ls $dir }\n\n foreach ($Item in $toList) \n { \n Switch ($Item.Extension) \n { \n \".Exe\" {$host.ui.rawui.foregroundColor = \"Yellow\"} \n \".cmd\" {$host.ui.rawui.foregroundColor = \"Red\"} \n \".msh\" {$host.ui.rawui.foregroundColor = \"Red\"} \n \".vbs\" {$host.ui.rawui.foregroundColor = \"Red\"} \n Default {$host.ui.rawui.foregroundColor = $origFg} \n } \n if ($item.Mode.StartsWith(\"d\")) {$host.ui.rawui.foregroundColor = \"Green\"}\n $item \n } \n $host.ui.rawui.foregroundColor = $origFg \n}\n\nfunction lla\n{\n param ( $dir=\".\")\n ll $dir $true\n}\n\nfunction la { ls -force }\n</code></pre>\n\n<p>And some shortcuts to avoid really repetitive filtering tasks :</p>\n\n<pre><code># behave like a grep command\n# but work on objects, used\n# to be still be allowed to use grep\nfilter match( $reg )\n{\n if ($_.tostring() -match $reg)\n { $_ }\n}\n\n# behave like a grep -v command\n# but work on objects\nfilter exclude( $reg )\n{\n if (-not ($_.tostring() -match $reg))\n { $_ }\n}\n\n# behave like match but use only -like\nfilter like( $glob )\n{\n if ($_.toString() -like $glob)\n { $_ }\n}\n\nfilter unlike( $glob )\n{\n if (-not ($_.tostring() -like $glob))\n { $_ }\n}\n</code></pre>\n" }, { "answer_id": 2191475, "author": "JMS", "author_id": 56876, "author_profile": "https://Stackoverflow.com/users/56876", "pm_score": 2, "selected": false, "text": "<p>You can see my PowerShell profile at <a href=\"http://github.com/jamesottaway/windowspowershell\" rel=\"nofollow noreferrer\">http://github.com/jamesottaway/windowspowershell</a></p>\n\n<p>If you use Git to clone my repo into your Documents folder (or whatever folder is above 'WindowsPowerShell' in your $PROFILE variable), you'll get all of my goodness.</p>\n\n<p>The main <code>profile.ps1</code> sets the subfolder with the name <code>Addons</code> as a <code>PSDrive</code>, and then finds all .ps1 files underneath that folder to load.</p>\n\n<p>I quite like the <code>go</code> command, which stores a dictionary of shorthand locations to visit easily. For example, <code>go vsp</code> will take me to <code>C:\\Visual Studio 2008\\Projects</code>.</p>\n\n<p>I also like overriding the <code>Set-Location</code> cmdlet to run both <code>Set-Location</code> and <code>Get-ChildItem</code>.</p>\n\n<p>My other favourite is being able to do a <code>mkdir</code> which does <code>Set-Location xyz</code> after running <code>New-Item xyz -Type Directory</code>.</p>\n" }, { "answer_id": 6888009, "author": "Scott Muc", "author_id": 1894, "author_profile": "https://Stackoverflow.com/users/1894", "pm_score": 2, "selected": false, "text": "<p>I actually keep mine on <a href=\"https://github.com/scottmuc/poshfiles\" rel=\"nofollow\">github</a>. </p>\n" }, { "answer_id": 7668105, "author": "Stisfa", "author_id": 595317, "author_profile": "https://Stackoverflow.com/users/595317", "pm_score": 2, "selected": false, "text": "<pre><code>Function funcOpenPowerShellProfile\n{\n Notepad $PROFILE\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n</code></pre>\n<p>Only a <a href=\"https://web.archive.org/web/20170222194554/http://www.undefined.com/ia/2006/10/24/the-fourteen-types-of-programmers-type-4-lazy-ones/\" rel=\"nofollow noreferrer\">sagaciously-lazy individual</a> would tell you that <code>fop</code> is so much easier to type than <code>Notepad $PROFILE</code> at the prompt, unless, of course, you associate &quot;fop&quot; with a <a href=\"http://en.wikipedia.org/wiki/Fop\" rel=\"nofollow noreferrer\">17th century English ninny</a>.</p>\n<hr />\n<p>If you wanted, you could take it a step further and make it somewhat useful:</p>\n<pre><code>Function funcOpenPowerShellProfile\n{\n $fileProfileBackup = $PROFILE + '.bak'\n cp $PROFILE $fileProfileBackup\n PowerShell_ISE $PROFILE # Replace with Desired IDE/ISE for Syntax Highlighting\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n</code></pre>\n<hr />\n<p>For satisfying survivalist-paranoia:</p>\n<pre><code>Function funcOpenPowerShellProfile\n{\n $fileProfilePathParts = @($PROFILE.Split('\\'))\n $fileProfileName = $fileProfilePathParts[-1]\n $fileProfilePathPartNum = 0\n $fileProfileHostPath = $fileProfilePathParts[$fileProfilePathPartNum] + '\\'\n $fileProfileHostPathPartsCount = $fileProfilePathParts.Count - 2\n # Arrays start at 0, but the Count starts at 1; if both started at 0 or 1, \n # then a -1 would be fine, but the realized discrepancy is 2\n Do\n {\n $fileProfilePathPartNum++\n $fileProfileHostPath = $fileProfileHostPath + `\n $fileProfilePathParts[$fileProfilePathPartNum] + '\\'\n }\n While\n (\n $fileProfilePathPartNum -LT $fileProfileHostPathPartsCount\n )\n $fileProfileBackupTime = [string](date -format u) -replace &quot;:&quot;, &quot;&quot;\n $fileProfileBackup = $fileProfileHostPath + `\n $fileProfileBackupTime + ' - ' + $fileProfileName + '.bak'\n cp $PROFILE $fileProfileBackup\n\n cd $fileProfileHostPath\n $fileProfileBackupNamePattern = $fileProfileName + '.bak'\n $fileProfileBackups = @(ls | Where {$_.Name -Match $fileProfileBackupNamePattern} | `\n Sort Name)\n $fileProfileBackupsCount = $fileProfileBackups.Count\n $fileProfileBackupThreshold = 5 # Change as Desired\n If\n (\n $fileProfileBackupsCount -GT $fileProfileBackupThreshold\n )\n {\n $fileProfileBackupsDeleteNum = $fileProfileBackupsCount - `\n $fileProfileBackupThreshold\n $fileProfileBackupsIndexNum = 0\n Do\n {\n\n rm $fileProfileBackups[$fileProfileBackupsIndexNum]\n $fileProfileBackupsIndexNum++;\n $fileProfileBackupsDeleteNum--\n }\n While\n (\n $fileProfileBackupsDeleteNum -NE 0\n )\n }\n\n PowerShell_ISE $PROFILE\n # Replace 'PowerShell_ISE' with Desired IDE (IDE's path may be needed in \n # '$Env:PATH' for this to work; if you can start it from the &quot;Run&quot; window, \n # you should be fine)\n}\n\nSet-Alias fop funcOpenPowerShellProfile\n</code></pre>\n" }, { "answer_id": 10337172, "author": "Bill Barry", "author_id": 108993, "author_profile": "https://Stackoverflow.com/users/108993", "pm_score": 2, "selected": false, "text": "<p>amongst many other things:</p>\n\n<pre><code>function w {\n explorer .\n}\n</code></pre>\n\n<p>opens an explorer window in the current directory</p>\n\n<pre><code>function startover {\n iisreset /restart\n iisreset /stop\n\n rm \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\\*.*\" -recurse -force -Verbose\n\n iisreset /start\n}\n</code></pre>\n\n<p>gets rid of everything in my temporary asp.net files (useful for working on managed code that has dependencies on buggy unmanaged code)</p>\n\n<pre><code>function edit($x) {\n . 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe' $x\n}\n</code></pre>\n\n<p>edits $x in notepad++</p>\n" }, { "answer_id": 15710210, "author": "Christopher Douglas", "author_id": 1304390, "author_profile": "https://Stackoverflow.com/users/1304390", "pm_score": 3, "selected": false, "text": "<p>I rock a few functions, and since I'm a module author I typically load a console and desperately need to know what's where.</p>\n\n<pre><code>write-host \"Your modules are...\" -ForegroundColor Red\nGet-module -li\n</code></pre>\n\n<p>Die hard nerding:</p>\n\n<pre><code>function prompt\n{\n $host.UI.RawUI.WindowTitle = \"ShellPower\"\n # Need to still show the working directory.\n #Write-Host \"You landed in $PWD\"\n\n # Nerd up, yo.\n $Str = \"Root@The Matrix\"\n \"$str&gt; \"\n}\n</code></pre>\n\n<p>The mandatory anything I can PowerShell I will functions go here...</p>\n\n<pre><code># Explorer command\nfunction Explore\n{\n param\n (\n [Parameter(\n Position = 0,\n ValueFromPipeline = $true,\n Mandatory = $true,\n HelpMessage = \"This is the path to explore...\"\n )]\n [ValidateNotNullOrEmpty()]\n [string]\n # First parameter is the path you're going to explore.\n $Target\n )\n $exploration = New-Object -ComObject shell.application\n $exploration.Explore($Target)\n}\n</code></pre>\n\n<p>I am STILL an administrator so I do need...</p>\n\n<pre><code>Function RDP\n{\n param\n (\n [Parameter(\n Position = 0,\n ValueFromPipeline = $true,\n Mandatory = $true,\n HelpMessage = \"Server Friendly name\"\n )]\n [ValidateNotNullOrEmpty()]\n [string]\n $server\n )\n\n cmdkey /generic:TERMSRV/$server /user:$UserName /pass:($Password.GetNetworkCredential().Password)\n mstsc /v:$Server /f /admin\n Wait-Event -Timeout 5\n cmdkey /Delete:TERMSRV/$server\n}\n</code></pre>\n\n<p>Sometimes I want to start explorer as someone other than the logged in user...</p>\n\n<pre><code># Restarts explorer as the user in $UserName\nfunction New-Explorer\n{\n # CLI prompt for password\n\n taskkill /f /IM Explorer.exe\n runas /noprofile /netonly /user:$UserName explorer\n}\n</code></pre>\n\n<p>This is just because it's funny.</p>\n\n<pre><code>Function Lock-RemoteWorkstation\n{\n param(\n $Computername,\n $Credential\n )\n\n if(!(get-module taskscheduler))\n {\n Import-Module TaskScheduler\n }\n New-task -ComputerName $Computername -credential:$Credential |\n Add-TaskTrigger -In (New-TimeSpan -Seconds 30) |\n Add-TaskAction -Script `\n {\n $signature = @\"\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern bool LockWorkStation();\n \"@\n $LockWorkStation = Add-Type -memberDefinition $signature -name \"Win32LockWorkStation\" -namespace Win32Functions -passthru\n $LockWorkStation::LockWorkStation() | Out-Null\n } | Register-ScheduledTask TestTask -ComputerName $Computername -credential:$Credential\n}\n</code></pre>\n\n<p>I also have one for me, since <kbd>Win</kbd> + <kbd>L</kbd> is too far away...</p>\n\n<pre><code>Function llm # Lock Local machine\n{\n $signature = @\"\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern bool LockWorkStation();\n \"@\n $LockWorkStation = Add-Type -memberDefinition $signature -name \"Win32LockWorkStation\" -namespace Win32Functions -passthru\n\n $LockWorkStation::LockWorkStation() | Out-Null\n}\n</code></pre>\n\n<p>A few filters? I think so...</p>\n\n<pre><code> filter FileSizeBelow($size){if($_.length -le $size){ $_ }}\n filter FileSizeAbove($size){if($_.Length -ge $size){$_}}\n</code></pre>\n\n<p>I also have a few I can't post yet, because they're not done but they're basically a way to persist credentials between sessions without writing them out as an encrypted file.</p>\n" }, { "answer_id": 24091871, "author": "noam", "author_id": 1751302, "author_profile": "https://Stackoverflow.com/users/1751302", "pm_score": 2, "selected": false, "text": "<p>Jeffrey Snover's <a href=\"http://blogs.msdn.com/b/powershell/archive/2006/04/25/583268.aspx\" rel=\"nofollow noreferrer\">Start-NewScope</a> because re-launching the shell can be a drag.</p>\n<p>I never got comfortable with the <a href=\"http://ss64.com/nt/diruse.html\" rel=\"nofollow noreferrer\">diruse</a> options, <a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/05/weekend-scripter-sorting-folders-by-size.aspx\" rel=\"nofollow noreferrer\">so</a>:</p>\n<pre><code>function Get-FolderSizes { # poor man's du\n [cmdletBinding()]\n param(\n [parameter(mandatory=$true)]$Path,\n [parameter(mandatory=$false)]$SizeMB,\n [parameter(mandatory=$false)]$ExcludeFolders,\n [parameter(mandatory=$false)][switch]$AsObject\n ) #close param\n # http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/05/weekend-scripter-sorting-folders-by-size.aspx\n # uses Christoph Schneegans' Find-Files https://schneegans.de/windows/find-files/ because &quot;gci -rec&quot; follows junctions in &quot;special&quot; folders\n $pathCheck = test-path $path\n if (!$pathcheck) { Write-Error &quot;Invalid path. Wants gci's -path parameter.&quot;; return }\n if (!(Get-Command Find-Files)) { Write-Error &quot;Required function Find-Files not found&quot;; return }\n $fso = New-Object -ComObject scripting.filesystemobject\n $parents = Get-ChildItem $path -Force | where { $_.PSisContainer -and $ExcludeFolders -notContains $_.name -and !$_.LinkType }\n $folders = Foreach ($folder in $parents)\n {\n $getFolder = $fso.getFolder( $folder.fullname.tostring() )\n if (!$getFolder.Size)\n { \n #for &quot;special folders&quot; like appdata\n # maybe &quot;-Attributes !ReparsePoint&quot; works in v6? https://stackoverflow.com/a/59952913/\n # what about https://superuser.com/a/650476/ ?\n # abandoned because it follows junctions, distorting results # $length = gci $folder.FullName -Recurse -Force -EA SilentlyContinue | Measure -Property Length -Sum\n $length = Find-Files $folder.FullName -EA SilentlyContinue | Measure -Property Length -Sum -EA SilentlyContinue\n $sizeMBs = &quot;{0:N0}&quot; -f ($length.Sum /1mb)\n } #close if size property is null\n else { $sizeMBs = &quot;{0:N0}&quot; -f ($getFolder.size /1mb) }\n New-Object -TypeName psobject -Property @{\n Name = $getFolder.Path\n SizeMB = $sizeMBs\n } #close new obj property\n } #close foreach folder\n #here's the output\n $foldersObj = $folders | Sort @{E={[decimal]$_.SizeMB}} -Descending | ? {[Decimal]$_.SizeMB -gt $SizeMB}\n if (!$AsObject) { $foldersObj | Format-Table -AutoSize } else { $foldersObj }\n #calculate the total including contents\n $sum = $folders | Select -Expand SizeMB | Measure -Sum | Select -Expand Sum\n $sum += ( gci $path | where {!$_.psIsContainer} | Measure -Property Length -Sum | Select -Expand Sum ) / 1mb\n $sumString = &quot;{0:n2}&quot; -f ($sum /1kb)\n $sumString + &quot; GB total&quot; \n} #end function\nSet-Alias gfs Get-FolderSizes\n\nfunction Find-Files\n{\n &lt;# by Christoph Schneegans https://schneegans.de/windows/find-files/ - used in Get-FolderSizes aka gfs\n .SYNOPSIS\n Lists the contents of a directory. Unlike Get-ChildItem, this function does not recurse into symbolic links or junctions in order to avoid infinite loops.\n #&gt;\n\n param (\n [Parameter( Mandatory=$false )]\n [string]\n # Specifies the path to the directory whose contents are to be listed. By default, the current working directory is used.\n $LiteralPath = (Get-Location),\n\n [Parameter( Mandatory=$false )]\n # Specifies a filter that is applied to each file or directory. Wildcards ? and * are supported.\n $Filter,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if file objects should be returned. By default, all file system objects are returned.\n $File = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if directory objects should be returned. By default, all file system objects are returned.\n $Directory = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if reparse point objects should be returned. By default, all file system objects are returned.\n $ReparsePoint = $true,\n\n [Parameter( Mandatory=$false )]\n [boolean]\n # Specifies if the top directory should be returned. By default, all file system objects are returned.\n $Self = $true\n )\n\n function Enumerate( [System.IO.FileSystemInfo] $Item ) {\n $Item;\n if ( $Item.GetType() -eq [System.IO.DirectoryInfo] -and ! $Item.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {\n foreach ($ChildItem in $Item.EnumerateFileSystemInfos() ) {\n Enumerate $ChildItem;\n }\n }\n }\n\n function FilterByName {\n process {\n if ( ( $Filter -eq $null ) -or ( $_.Name -ilike $Filter ) ) {\n $_;\n }\n }\n }\n\n function FilterByType {\n process {\n if ( $_.GetType() -eq [System.IO.FileInfo] ) {\n if ( $File ) { $_; }\n } elseif ( $_.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {\n if ( $ReparsePoint ) { $_; }\n } else {\n if ( $Directory ) { $_; }\n }\n }\n }\n \n $Skip = if ($Self) { 0 } else { 1 };\n Enumerate ( Get-Item -LiteralPath $LiteralPath -Force ) | Select-Object -Skip $Skip | FilterByName | FilterByType;\n} # end function find-files\n</code></pre>\n<p>The most valuable bit above is Christoph Schneegans' <code>Find-Files</code> <a href=\"https://schneegans.de/windows/find-files\" rel=\"nofollow noreferrer\">https://schneegans.de/windows/find-files</a></p>\n<p>For pointing at stuff:</p>\n<pre><code>function New-URLfile {\n param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )\n if ($target -match &quot;^\\.&quot; -or $link -match &quot;^\\.&quot;) {&quot;Full paths plz.&quot;; break}\n $content = @()\n $header = '[InternetShortcut]'\n $content += $header\n $content += &quot;URL=&quot; + $target\n $content | out-file $link \n ii $link\n} #end function\n\nfunction New-LNKFile {\n param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )\n if ($target -match &quot;^\\.&quot; -or $link -match &quot;^\\.&quot;) {&quot;Full paths plz.&quot;; break}\n $WshShell = New-Object -comObject WScript.Shell\n $Shortcut = $WshShell.CreateShortcut($link)\n $Shortcut.TargetPath = $target\n $shortCut.save()\n} #end function new-lnkfile\n</code></pre>\n<p>Poor man's grep? For searching large txt files.</p>\n<pre><code>function Search-TextFile {\n param( \n [parameter(mandatory=$true)]$File,\n [parameter(mandatory=$true)]$SearchText\n ) #close param\n if ( !(Test-path $File) )\n { \n Write-Error &quot;File not found: $file&quot; \n return\n }\n $fullPath = Resolve-Path $file | select -Expand ProviderPath\n $lines = [System.IO.File]::ReadLines($fullPath)\n foreach ($line in $lines) { if ($line -match $SearchText) {$line} }\n} #end function Search-TextFile\nSet-Alias stf Search-TextFile\n</code></pre>\n<p>Lists programs installed on a remote computer.</p>\n<pre><code>function Get-InstalledProgram { [cmdletBinding()] #http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/13/use-powershell-to-quickly-find-installed-software.aspx\n param( [parameter(mandatory=$true)]$Comp,[parameter(mandatory=$false)]$Name )\n $keys = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall','SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall'\n TRY { $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp) }\n CATCH {\n $rrSvc = gwmi win32_service -comp $comp -Filter {name='RemoteRegistry'}\n if (!$rrSvc) {&quot;Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service.&quot;; break}\n #Enable and start RemoteRegistry service\n if ($rrSvc.State -ne 'Running') {\n if ($rrSvc.StartMode -eq 'Disabled') { $null = $rrSvc.ChangeStartMode('Manual'); $undoMe2 = $true }\n $null = $rrSvc.StartService() ; $undoMe = $true \n } #close if rrsvc not running\n else {&quot;Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service.&quot;; break}\n $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp) \n } #close if failed to connect regbase\n $out = @()\n foreach ($key in $keys) {\n if ( $RegBase.OpenSubKey($Key) ) { #avoids errors on 32bit OS\n foreach ( $entry in $RegBase.OpenSubKey($Key).GetSubkeyNames() ) {\n $sub = $RegBase.OpenSubKey( ($key + '\\' + $entry) )\n if ($sub) { $row = $null\n $row = [pscustomobject]@{\n Name = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('DisplayName')\n InstallDate = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('InstallDate')\n Version = $RegBase.OpenSubKey( ($key + '\\' + $entry) ).GetValue('DisplayVersion')\n } #close row\n $out += $row\n } #close if sub\n } #close foreach entry\n } #close if key exists\n } #close foreach key\n $out | where {$_.name -and $_.name -match $Name}\n if ($undoMe) { $null = $rrSvc.StopService() }\n if ($undoMe2) { $null = $rrSvc.ChangeStartMode('Disabled') }\n } #end function\n</code></pre>\n<p>Going meta, spreading the gospel, whatnot</p>\n<pre><code>function Copy-ProfilePS1 ($Comp,$User) {\n if (!$User) {$User = $env:USERNAME}\n $targ = &quot;\\\\$comp\\c$\\users\\$User\\Documents\\WindowsPowershell\\&quot;\n if (Test-Path $targ)\n {\n $cmd = &quot;copy /-Y $profile $targ&quot;\n cmd /c $cmd\n } else {&quot;Path not found! $targ&quot;}\n} #end function CopyProfilePS1\n</code></pre>\n" }, { "answer_id": 24871440, "author": "Burt_Harris", "author_id": 3776535, "author_profile": "https://Stackoverflow.com/users/3776535", "pm_score": 0, "selected": false, "text": "<p>Great question. Because I deal with several different PowerShell hosts, I do a little logging in each of several profiles, just to make the context of any other messages clearer. In <code>profile.ps1</code>, I currently only have that, but I sometimes change it based on context:</p>\n\n<pre><code>if ($PSVersionTable.PsVersion.Major -ge 3) {\n Write-Host \"Executing $PSCommandPath\"\n}\n</code></pre>\n\n<p>My favorite host is the ISE, in <code>Microsoft.PowerShellIse_profile.ps1</code>, I have:</p>\n\n<pre><code>if ($PSVersionTable.PsVersion.Major -ge 3) {\n Write-Host \"Executing $PSCommandPath\"\n}\n\nif ( New-PSDrive -ErrorAction Ignore One FileSystem `\n (Get-ItemProperty hkcu:\\Software\\Microsoft\\SkyDrive UserFolder).UserFolder) { \n Write-Host -ForegroundColor Green \"PSDrive One: mapped to local OneDrive/SkyDrive folder\"\n }\n\nImport-Module PSCX\n\n$PSCX:TextEditor = (get-command Powershell_ISE).Path\n\n$PSDefaultParameterValues = @{\n \"Get-Help:ShowWindow\" = $true\n \"Help:ShowWindow\" = $true\n \"Out-Default:OutVariable\" = \"0\"\n}\n\n\n#Script Browser Begin\n#Version: 1.2.1\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\System.Windows.Interactivity.dll'\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\ScriptBrowser.dll'\nAdd-Type -Path 'C:\\Program Files (x86)\\Microsoft Corporation\\Microsoft Script Browser\\BestPractices.dll'\n$scriptBrowser = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Browser', [ScriptExplorer.Views.MainView], $true)\n$scriptAnalyzer = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Analyzer', [BestPractices.Views.BestPracticesView], $true)\n$psISE.CurrentPowerShellTab.VisibleVerticalAddOnTools.SelectedAddOnTool = $scriptBrowser\n#Script Browser End\n</code></pre>\n" }, { "answer_id": 38385059, "author": "gparis", "author_id": 6557796, "author_profile": "https://Stackoverflow.com/users/6557796", "pm_score": 0, "selected": false, "text": "<p>Of everything not already listed, <strong><em>Start-Steroids</em></strong> has to be my favorite, except for maybe Start-Transcript.</p>\n\n<p>(<a href=\"http://www.powertheshell.com/isesteroids2-2/\" rel=\"nofollow\">http://www.powertheshell.com/isesteroids2-2/</a>)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20911/" ]
What essential things (functions, aliases, start up scripts) do you have in your profile?
I often find myself needing needing some basic agregates to count/sum some things., I've defined these functions and use them often, they work really nicely at the end of a pipeline : ``` # # useful agregate # function count { BEGIN { $x = 0 } PROCESS { $x += 1 } END { $x } } function product { BEGIN { $x = 1 } PROCESS { $x *= $_ } END { $x } } function sum { BEGIN { $x = 0 } PROCESS { $x += $_ } END { $x } } function average { BEGIN { $max = 0; $curr = 0 } PROCESS { $max += $_; $curr += 1 } END { $max / $curr } } ``` To be able to get time and path with colors in my prompt : ``` function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) } function prompt { # Write the time write-host "[" -noNewLine write-host $(Get-Time) -foreground yellow -noNewLine write-host "] " -noNewLine # Write the path write-host $($(Get-Location).Path.replace($home,"~").replace("\","/")) -foreground green -noNewLine write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine return "> " } ``` The following functions are stolen from a blog and modified to fit my taste, but ls with colors is very nice : ``` # LS.MSH # Colorized LS function replacement # /\/\o\/\/ 2006 # http://mow001.blogspot.com function LL { param ($dir = ".", $all = $false) $origFg = $host.ui.rawui.foregroundColor if ( $all ) { $toList = ls -force $dir } else { $toList = ls $dir } foreach ($Item in $toList) { Switch ($Item.Extension) { ".Exe" {$host.ui.rawui.foregroundColor = "Yellow"} ".cmd" {$host.ui.rawui.foregroundColor = "Red"} ".msh" {$host.ui.rawui.foregroundColor = "Red"} ".vbs" {$host.ui.rawui.foregroundColor = "Red"} Default {$host.ui.rawui.foregroundColor = $origFg} } if ($item.Mode.StartsWith("d")) {$host.ui.rawui.foregroundColor = "Green"} $item } $host.ui.rawui.foregroundColor = $origFg } function lla { param ( $dir=".") ll $dir $true } function la { ls -force } ``` And some shortcuts to avoid really repetitive filtering tasks : ``` # behave like a grep command # but work on objects, used # to be still be allowed to use grep filter match( $reg ) { if ($_.tostring() -match $reg) { $_ } } # behave like a grep -v command # but work on objects filter exclude( $reg ) { if (-not ($_.tostring() -match $reg)) { $_ } } # behave like match but use only -like filter like( $glob ) { if ($_.toString() -like $glob) { $_ } } filter unlike( $glob ) { if (-not ($_.tostring() -like $glob)) { $_ } } ```
138,162
<p>I want to setup my local development machine so that any requests for <code>*.local</code> are redirected to <code>localhost</code>. The idea is that as I develop multiple sites, I can just add vhosts to Apache called <code>site1.local</code>, <code>site2.local</code> etc, and have them all resolve to <code>localhost</code>, while Apache serves a different site accordingly.</p> <p>I am on Windows XP.</p> <p>I tried adding </p> <pre><code>127.0.0.1 *.local </code></pre> <p>to my <code>c:\windows\system32\drivers\etc\hosts</code> file, also tried:</p> <pre><code>127.0.0.1 .local </code></pre> <p>Neither of which seem to work.</p> <p>I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which.</p> <p>I don't want to have to setup a local DNS server or anything hard, any suggestions?</p>
[ { "answer_id": 138181, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 5, "selected": false, "text": "<p>I don't think that it is possible.</p>\n\n<p>You anyway have to modify the apache virtualroot entries every time you add a new site and location, so it's not a big work to syncronise the new name to the Windows vhost file.</p>\n\n<p>Update: please check the next answer and the comments on this answer. This answer is 6 years old and not correct anymore.</p>\n" }, { "answer_id": 138228, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 2, "selected": false, "text": "<p>You could talk your network administrator into setting up a domain for you (say 'evilpuppetmaster.hell') and having the wildcard there so that everything (*.evilpuppetmaster.hell') resolves to your IP</p>\n" }, { "answer_id": 144796, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 3, "selected": false, "text": "<p>I found a posting about <a href=\"http://vlaurie.com/computers2/Articles/hosts.htm\" rel=\"noreferrer\">Using the Windows Hosts File</a> that also says \"No wildcards are allowed.\"</p>\n\n<p>In the past, I have just added the additional entries to the hosts file, because (as previously said), it's not that much extra work when you already are editing the apache config file.</p>\n" }, { "answer_id": 272092, "author": "jeremyasnyder", "author_id": 33143, "author_profile": "https://Stackoverflow.com/users/33143", "pm_score": 6, "selected": false, "text": "<p>To answer your question, you cannot use wildcards in the hosts file under Windows.</p>\n\n<p>However, if you want to only change the hosts file to make new sites work.... you can configure your Apache like this and you don't have to keep editing it's config:</p>\n\n<p><a href=\"http://postpostmodern.com/instructional/a-smarter-mamp/\" rel=\"noreferrer\">http://postpostmodern.com/instructional/a-smarter-mamp/</a></p>\n\n<p>Basically a quick summary based on my setup, add the following to your apache.conf file:</p>\n\n<pre><code> LoadModule vhost_alias_module modules/mod_vhost_alias.so\n\n NameVirtualHost *:80\n\n &lt;Directory \"/xampp/sites\"&gt;\n Options Indexes FollowSymLinks Includes ExecCGI\n AllowOverride All\n Order allow,deny\n Allow from all \n &lt;/Directory&gt;\n\n &lt;VirtualHost *:80&gt;\n VirtualDocumentRoot c:/xampp/sites/%-1/%-2+/\n &lt;/VirtualHost&gt;\n</code></pre>\n\n<p>This allows me to add an entry like:</p>\n\n<pre><code>127.0.0.1 test.dev\n</code></pre>\n\n<p>and then make the directory, c:\\xampp\\sites\\dev\\test and place the necessary files in there and it just works.</p>\n\n<p>The other option is to use <code>&lt;Directory&gt;</code> tags in apache.conf and reference the pages from <a href=\"http://localhost/project/\" rel=\"noreferrer\">http://localhost/project/</a>.</p>\n" }, { "answer_id": 342562, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.</p>\n\n<p>If you read the man page, it says:</p>\n\n<pre><code>DESCRIPTION\n The hosts file contains information regarding the known hosts on the net-\n work. For each host a single line should be present with the following\n information:\n\n Internet address\n Official host name\n Aliases\n</code></pre>\n\n<p>Although it does say,</p>\n\n<pre><code> Host names may contain any printable character other than a field delim-\n iter, newline, or comment character.\n</code></pre>\n\n<p>that is not true from a practical level.</p>\n\n<p>Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.</p>\n\n<p>The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.</p>\n" }, { "answer_id": 809070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You can use a dynamic DNS client such as <a href=\"http://www.no-ip.com\" rel=\"nofollow noreferrer\">http://www.no-ip.com</a>. Then, with an external DNS server CNAME *.mydomain.com to mydomain.no-ip.com.</p>\n" }, { "answer_id": 3954440, "author": "Joe", "author_id": 478674, "author_profile": "https://Stackoverflow.com/users/478674", "pm_score": 3, "selected": false, "text": "<p>Editing the hosts file is less of a pain when you run \"ipconfig /flushdns\" from the windows command prompt, instead of restarting your computer.</p>\n" }, { "answer_id": 5855537, "author": "marlonyao", "author_id": 576832, "author_profile": "https://Stackoverflow.com/users/576832", "pm_score": 2, "selected": false, "text": "<p>I have written a simple dns proxy in Python. It will read wildcard entries in /etc/hosts. See here: <a href=\"http://code.google.com/p/marlon-tools/source/browse/tools/dnsproxy/dnsproxy.py\" rel=\"nofollow\">http://code.google.com/p/marlon-tools/source/browse/tools/dnsproxy/dnsproxy.py</a></p>\n\n<p>I have tested in Linux &amp; Mac OS X, but not yet in Windows.</p>\n" }, { "answer_id": 9567632, "author": "iloahz", "author_id": 782114, "author_profile": "https://Stackoverflow.com/users/782114", "pm_score": 2, "selected": false, "text": "<p>You may try <a href=\"http://angryhosts.com/\" rel=\"nofollow\">AngryHosts</a>, which provided a way to support wildcard and regular expression. Actually, it's a hosts file enhancement and management software.<br>\nMore features can be seen @ <a href=\"http://angryhosts.com/features/\" rel=\"nofollow\">http://angryhosts.com/features/</a></p>\n" }, { "answer_id": 9695861, "author": "Petah", "author_id": 268074, "author_profile": "https://Stackoverflow.com/users/268074", "pm_score": 10, "selected": true, "text": "<p>Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.</p>\n\n<p><strong>Download from the offical website</strong></p>\n\n<p><a href=\"http://mayakron.altervista.org/support/browse.php?path=Acrylic&amp;name=Home\">http://mayakron.altervista.org/support/browse.php?path=Acrylic&amp;name=Home</a></p>\n\n<h2>Configuring Acrylic DNS Proxy</h2>\n\n<p><strong>To configure Acrylic DNS Proxy, install it from the above link then go to:</strong></p>\n\n<ol>\n<li>Start</li>\n<li>Programs</li>\n<li>Acrylic DNS Proxy</li>\n<li>Config</li>\n<li>Edit Custom Hosts File (AcrylicHosts.txt)</li>\n</ol>\n\n<p><strong>Add the folowing lines on the end of the file:</strong></p>\n\n<pre><code>127.0.0.1 *.localhost\n127.0.0.1 *.local\n127.0.0.1 *.lc\n</code></pre>\n\n<p><strong>Restart the Acrylic DNS Proxy service:</strong></p>\n\n<ol>\n<li>Start</li>\n<li>Programs</li>\n<li>Acrilic DNS Proxy</li>\n<li>Config</li>\n<li>Restart Acrylic Service</li>\n</ol>\n\n<p><strong>You will also need to adjust your DNS setting in you network interface settings:</strong></p>\n\n<ol>\n<li>Start</li>\n<li>Control Panel </li>\n<li>Network and Internet </li>\n<li>Network Connections </li>\n<li>Local Area Connection Properties</li>\n<li>TCP/IPv4</li>\n</ol>\n\n<p><strong>Set \"Use the following DNS server address\":</strong></p>\n\n<pre><code>Preferred DNS Server: 127.0.0.1\n</code></pre>\n\n<p><em>If you then combine this answer with jeremyasnyder's answer (using <code>VirtualDocumentRoot</code>) you can then automatically setup domains/virtual hosts by simply creating a directory.</em></p>\n" }, { "answer_id": 11252276, "author": "BlackTigerX", "author_id": 8411, "author_profile": "https://Stackoverflow.com/users/8411", "pm_score": 0, "selected": false, "text": "<p>While you can't add a wildcard like that, you could add the full list of sites that you need, at least for testing, that works well enough for me, in your hosts file, you just add:</p>\n\n<p>127.0.0.1 site1.local<br>\n127.0.0.1 site2.local<br>\n127.0.0.1 site3.local<br>\n...</p>\n" }, { "answer_id": 17812067, "author": "Matthew Skelton", "author_id": 1253233, "author_profile": "https://Stackoverflow.com/users/1253233", "pm_score": 2, "selected": false, "text": "<p>We have this working using wildcard DNS in our local DNS server: add an <code>A</code> record something like <code>*.local -&gt; 127.0.0.1</code></p>\n\n<p>I think that your network settings will need to have the chosen domain suffix in the domain suffix search list for machines on the network, so you might want to replace <code>.local</code> with your company's internal domain (e.g. <code>.int</code>) and then add a subdomain like <code>.localhost.int</code> to make it clear what it's for.</p>\n\n<p>So <code>*.localhost.int</code> would resolve to <code>127.0.0.1</code> for everybody on the network, and config file settings for all developers would \"just work\" if endpoints hang off that subdomain e.g. <code>site1.localhost.int</code>, <code>site2.localhost.int</code> This is pretty much the scheme we have introduced.</p>\n\n<p><strong>dnsmasq</strong> also looks nice, but I have not tried it yet:\n<a href=\"http://ihaveabackup.net/2012/06/28/using-wildcards-in-the-hosts-file/\" rel=\"nofollow\">http://ihaveabackup.net/2012/06/28/using-wildcards-in-the-hosts-file/</a></p>\n" }, { "answer_id": 21153552, "author": "oucil", "author_id": 1058733, "author_profile": "https://Stackoverflow.com/users/1058733", "pm_score": 1, "selected": false, "text": "<p>@petah and Acrylic DNS Proxy is the best answer, and at the end he references the ability to do multi-site using an Apache which @jeremyasnyder describes a little further down...</p>\n\n<p>... however, in our case we're testing a multi-tenant hosting system and so <em>most</em> domains we want to test go to the same <code>virtualhost</code>, while a couple others are directed elsewhere.</p>\n\n<p>So in our case, you simply use regex wildcards in the <code>ServerAlias</code> directive, like so...</p>\n\n<pre><code>ServerAlias *.foo.local\n</code></pre>\n" }, { "answer_id": 22097400, "author": "casivaagustin", "author_id": 1582216, "author_profile": "https://Stackoverflow.com/users/1582216", "pm_score": 2, "selected": false, "text": "<p>I'm using DNSChef to do that.</p>\n\n<p><a href=\"https://thesprawl.org/projects/dnschef/\" rel=\"nofollow\">https://thesprawl.org/projects/dnschef/</a></p>\n\n<p>You have to download the app, in Linux or Mac you need python to run it. Windows have their own exe.</p>\n\n<p>You must create a ini file with your dns entries, for example </p>\n\n<pre><code>[A]\n*.google.com=192.0.2.1\n*.local=127.0.0.1\n*.devServer1.com=192.0.2.3\n</code></pre>\n\n<p>Then you must launch the dns application with admin privileges</p>\n\n<pre><code>sudo python dnschef.py --file myfile.ini -q\n</code></pre>\n\n<p>or in windows</p>\n\n<pre><code>runas dnschef.exe --file myfile.ini -q\n</code></pre>\n\n<p>Finally you need to setup as your only DNS your local host environment (network, interface, dns or similar or in linux /etc/resolv.conf).</p>\n\n<p>That's it</p>\n" }, { "answer_id": 25391952, "author": "Daniel Jordi", "author_id": 3765399, "author_profile": "https://Stackoverflow.com/users/3765399", "pm_score": 1, "selected": false, "text": "<p>Here is the total configuration for those trying to accomplish the goal (wildcards in dev environment ie, XAMPP -- this example assumes all sites pointing to same codebase)</p>\n<h1>hosts file (add an entry)</h1>\n<p>file: %SystemRoot%\\system32\\drivers\\etc\\hosts</p>\n<pre><code>127.0.0.1 example.local\n</code></pre>\n<h1>httpd.conf configuration (enable vhosts)</h1>\n<p>file: \\XAMPP\\etc\\httpd.conf</p>\n<pre><code># Virtual hosts\nInclude etc\\extra\\httpd-vhosts.conf\n</code></pre>\n<h1>httpd-vhosts.conf configuration</h1>\n<p>file: XAMPP\\etc\\extra\\httpd-vhosts.conf</p>\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n DocumentRoot &quot;\\path_to_XAMPP\\htdocs&quot;\n ServerName example.local\n ServerAlias *.example.local\n# SetEnv APP_ENVIRONMENT development\n# ErrorLog &quot;logs\\example.local-error_log&quot;\n# CustomLog &quot;logs\\example.local-access_log&quot; common\n&lt;/VirtualHost&gt;\n</code></pre>\n<p>restart apache</p>\n<h1>create pac file:</h1>\n<p>save as whatever.pac wherever you want to and then load the file in the browser's network&gt;proxy&gt;auto_configuration settings (reload if you alter this)</p>\n<pre><code>function FindProxyForURL(url, host) {\n if (shExpMatch(host, &quot;*example.local&quot;)) {\n return &quot;PROXY example.local&quot;;\n }\n return &quot;DIRECT&quot;;\n}\n</code></pre>\n" }, { "answer_id": 27858259, "author": "arva", "author_id": 2659230, "author_profile": "https://Stackoverflow.com/users/2659230", "pm_score": 1, "selected": false, "text": "<p>You can use echoipdns for this (<a href=\"https://github.com/zapty/echoipdns\" rel=\"nofollow\">https://github.com/zapty/echoipdns</a>). </p>\n\n<p>By running <code>echoipdns local</code> all requests for .local subdomains are redirected to 127.0.0.1, so any domain with xyz.local etc will resolve to 127.0.0.1. You can use any other suffix also just replace local with name you want.</p>\n\n<p>Echoipdns is even more powerful, when you want to use your url from other machines in network you can still use it with zero configuration. </p>\n\n<p>For e.g. If your machine ip address is 192.168.1.100 you could now use a domain name xyz.192-168-1-100.local which will always resolve to 192.168.1.100. This magic is done by the echoipdns by looking at the ip address in the second part of the domain name and returning the same ip address on DNS query. You will have to run the echoipdns on the machine from which you want to access the remote system.</p>\n\n<p>echoipdns also can be setup as a standalone DNS proxy, so by just point to this DNS, you can now use all the above benefits without running a special command every time, and you can even use it from mobile devices.</p>\n\n<p>So essentially this simplifies the wildcard domain based DNS development for local as well as team environment.</p>\n\n<p>echoipdns works on Mac, Linux and Windows.</p>\n\n<p>NOTE: I am author for echoipdns.</p>\n" }, { "answer_id": 28846477, "author": "Stackia", "author_id": 3542546, "author_profile": "https://Stackoverflow.com/users/3542546", "pm_score": 2, "selected": false, "text": "<p>I made this simple tool to take the place of hosts. Regular expressions are supported.\n<a href=\"https://github.com/stackia/DNSAgent\" rel=\"nofollow\">https://github.com/stackia/DNSAgent</a></p>\n\n<p>A sample configuration:</p>\n\n<pre><code>[\n {\n \"Pattern\": \"^.*$\",\n \"NameServer\": \"8.8.8.8\"\n },\n {\n \"Pattern\": \"^(.*\\\\.googlevideo\\\\.com)|((.*\\\\.)?(youtube|ytimg)\\\\.com)$\",\n \"Address\": \"203.66.168.119\"\n },\n {\n \"Pattern\": \"^.*\\\\.cn$\",\n \"NameServer\": \"114.114.114.114\"\n },\n {\n \"Pattern\": \"baidu.com$\",\n \"Address\": \"127.0.0.1\"\n }\n]\n</code></pre>\n" }, { "answer_id": 29159000, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 3, "selected": false, "text": "<p>To add to the great suggestions already here, <a href=\"http://xip.io\" rel=\"noreferrer\"><strong>XIP.IO</strong></a> is a fantastic wildcard DNS server that's publicly available.</p>\n\n<pre><code> myproject.127.0.0.1.xip.io -- resolves to --&gt; 127.0.0.1\n other.project.127.0.0.1.xip.io -- resolves to --&gt; 127.0.0.1\n other.machine.10.0.0.1.xip.io -- resolves to --&gt; 10.0.0.1\n</code></pre>\n\n<p>(The ability to specify non-loopback addresses is fantastic for testing sites on iOS devices where you cannot access a hosts file.)</p>\n\n<p>If you combine this with some of the Apache configuration mentioned in other answers, you can potentially add VirtualHosts with <em>zero setup</em>.</p>\n" }, { "answer_id": 54423117, "author": "Davron Achilov", "author_id": 8182972, "author_profile": "https://Stackoverflow.com/users/8182972", "pm_score": 0, "selected": false, "text": "<p>Configuration for nginx config auto subdomain with Acrylic DNS Proxy</p>\n\n<blockquote>\n <p>auto.conf file for your nginx sites folder</p>\n</blockquote>\n\n<pre><code>server {\n listen 80;\n server_name ~^(?&lt;branch&gt;.*)\\.example\\.com;\n root /var/www/html/$branch/public; \n\n index index.html index.htm index.php;\n\n charset utf-8;\n\n location / {\n try_files $uri $uri/ /index.php$is_args$args;\n }\n\n location = /favicon.ico { access_log off; log_not_found off; }\n location = /robots.txt { access_log off; log_not_found off; }\n\n error_log /var/log/nginx/$branch.error.log error;\n\n sendfile off;\n\n client_max_body_size 100m;\n\n location ~ \\.php$ {\n try_files $uri /index.php =404;\n fastcgi_pass php-fpm:9000;\n fastcgi_index index.php;\n fastcgi_buffers 16 16k;\n fastcgi_buffer_size 32k;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n include fastcgi_params;\n }\n\n location ~ /\\.ht {\n deny all;\n }\n}\n</code></pre>\n\n<p>Add to Acrylic hosts file <code>127.0.0.1 example.com *.example.com</code> and restart Acrylic service.\n<strong>$branch</strong> - your subdomain name.</p>\n\n<p>Set instead of <em>root /var/www/html/$branch/public;</em> your project path</p>\n" }, { "answer_id": 58622224, "author": "davidjimenez75", "author_id": 8208892, "author_profile": "https://Stackoverflow.com/users/8208892", "pm_score": 0, "selected": false, "text": "<p>This can be done using <a href=\"https://pi-hole.net\" rel=\"nofollow noreferrer\">Pi-Hole</a>, just edit the \"/etc/hosts\" and restart dns service.</p>\n\n<pre><code>nano /etc/hosts\npihole restartdns\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>127.0.1.1 raspberrypi\n192.168.1.1 w1.dev.net\n192.168.1.2 w2.dev.net\n192.168.1.3 w3.dev.net\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
I want to setup my local development machine so that any requests for `*.local` are redirected to `localhost`. The idea is that as I develop multiple sites, I can just add vhosts to Apache called `site1.local`, `site2.local` etc, and have them all resolve to `localhost`, while Apache serves a different site accordingly. I am on Windows XP. I tried adding ``` 127.0.0.1 *.local ``` to my `c:\windows\system32\drivers\etc\hosts` file, also tried: ``` 127.0.0.1 .local ``` Neither of which seem to work. I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which. I don't want to have to setup a local DNS server or anything hard, any suggestions?
Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards. **Download from the offical website** <http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home> Configuring Acrylic DNS Proxy ----------------------------- **To configure Acrylic DNS Proxy, install it from the above link then go to:** 1. Start 2. Programs 3. Acrylic DNS Proxy 4. Config 5. Edit Custom Hosts File (AcrylicHosts.txt) **Add the folowing lines on the end of the file:** ``` 127.0.0.1 *.localhost 127.0.0.1 *.local 127.0.0.1 *.lc ``` **Restart the Acrylic DNS Proxy service:** 1. Start 2. Programs 3. Acrilic DNS Proxy 4. Config 5. Restart Acrylic Service **You will also need to adjust your DNS setting in you network interface settings:** 1. Start 2. Control Panel 3. Network and Internet 4. Network Connections 5. Local Area Connection Properties 6. TCP/IPv4 **Set "Use the following DNS server address":** ``` Preferred DNS Server: 127.0.0.1 ``` *If you then combine this answer with jeremyasnyder's answer (using `VirtualDocumentRoot`) you can then automatically setup domains/virtual hosts by simply creating a directory.*
138,194
<p>In the Flex framework a custom preloader can be used while the site is loading.</p> <p>In the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html" rel="nofollow noreferrer">Adobe docs</a> it specifies that '<strong>the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.</strong>'</p> <p>However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear.</p> <p>I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before.</p> <p>Anybody help?</p>
[ { "answer_id": 138247, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 1, "selected": false, "text": "<p>This is in mx.preloaders::DownloadProgressBar.as, line 1205 in the <code>showDisplayForDownloading</code> function.</p>\n\n<p>Old school monkey-patching is out with AS3, but you can either edit the Flex source and compile yourself a new framework.swc (apparently a pain), or just include it in your source path (source paths override .swcs); or derive your own preloader class from DownloadProgressBar that just overrides <code>showDisplayForDownloading</code> and returns true.</p>\n\n<p>You can find the framework source in '%PROGRAMFILES%\\Adobe\\Flex Builder 3[ Plug-in]\\sdks\\3.0.0\\frameworks\\projects\\framework\\src', then the package path. Change the sdk version if you are using 3.1, or whatever.</p>\n" }, { "answer_id": 138373, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You should just extend the DownloadProgressBar, try the following code. i've used this before and I've found jesse warden site <a href=\"http://jessewarden.com/2007/07/making-a-cooler-preloader-in-flex-part-1-of-3.html\" rel=\"nofollow noreferrer\">click here </a>usful for info on this (where I found out about it and this is a cut down version of his code)</p>\n\n<pre><code>package{\nimport flash.display.MovieClip;\nimport flash.display.Sprite;\nimport flash.events.Event;\nimport flash.events.ProgressEvent;\n\nimport mx.events.FlexEvent;\nimport mx.preloaders.DownloadProgressBar;\n\npublic class Preloader extends DownloadProgressBar\n{\n\n /**\n * The Flash 8 MovieClip embedded as a Class.\n */ \n [Embed(source=\"yourPreloaderFile.swf\")]\n private var FlashPreloaderSymbol:Class;\n\n private var clip:MovieClip;\n\n public function Preloader()\n {\n super();\n clip = new FlashPreloaderSymbol();\n addChild(clip);\n }\n\n public override function set preloader(preloader:Sprite):void \n { \n preloader.addEventListener( FlexEvent.INIT_COMPLETE , onFlexInitComplete );\n\n centerPreloader();\n }\n\n private function centerPreloader():void\n {\n x = (stageWidth / 2) - (clip.width / 2);\n y = (stageHeight / 2) - (clip.height / 2);\n }\n\n private function onFlexInitComplete( event:FlexEvent ):void \n {\n dispatchEvent( new Event( Event.COMPLETE ) ); \n }\n\n\n protected override function showDisplayForDownloading(time : int, event : ProgressEvent) : Boolean {\n return true;\n }\n\n}\n</code></pre>\n\n<p>}</p>\n\n<p>after that just change the preloader property in the main application tag to the Preloader class.</p>\n" }, { "answer_id": 138777, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 0, "selected": false, "text": "<p>I'd guess that delay is there for two reasons:</p>\n\n<ol>\n<li>You don't want the preloader to\n\"blink\" in once the page is already\ncached </li>\n<li>The preloader itself has to\nload</li>\n</ol>\n\n<p>When I need to make absolutely sure a preloader is shown instantly I make a small wrapper swf that has <em>just</em> the preloader and load the main swf from there.</p>\n" }, { "answer_id": 751103, "author": "Bryson", "author_id": 89367, "author_profile": "https://Stackoverflow.com/users/89367", "pm_score": -1, "selected": false, "text": "<p>its not possible to make preloader show instantly , since some classes needs to be downloaded before progress can be displayed . other alternative can be that you display a progress in html and when flash movie is loaded it shows up but here .</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
In the Flex framework a custom preloader can be used while the site is loading. In the [Adobe docs](http://livedocs.adobe.com/flex/3/html/help.html?content=app_container_4.html) it specifies that '**the progress bar [preloader] is displayed if less than half of the application is downloaded after 700 milliseconds of downloading.**' However I ALWAYS want the preloader to appear instantly since I know that 95% of our users are first time visitors and the site is over 500kb. I dont want people to have to wait .7 seconds for the preloader animation to appear. I would think in theory that it is possible to 'monkey patch' the framework to remove this .7 second limitation. I dont have time to figure out how, and I've never done it before. Anybody help?
You should just extend the DownloadProgressBar, try the following code. i've used this before and I've found jesse warden site [click here](http://jessewarden.com/2007/07/making-a-cooler-preloader-in-flex-part-1-of-3.html) usful for info on this (where I found out about it and this is a cut down version of his code) ``` package{ import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.ProgressEvent; import mx.events.FlexEvent; import mx.preloaders.DownloadProgressBar; public class Preloader extends DownloadProgressBar { /** * The Flash 8 MovieClip embedded as a Class. */ [Embed(source="yourPreloaderFile.swf")] private var FlashPreloaderSymbol:Class; private var clip:MovieClip; public function Preloader() { super(); clip = new FlashPreloaderSymbol(); addChild(clip); } public override function set preloader(preloader:Sprite):void { preloader.addEventListener( FlexEvent.INIT_COMPLETE , onFlexInitComplete ); centerPreloader(); } private function centerPreloader():void { x = (stageWidth / 2) - (clip.width / 2); y = (stageHeight / 2) - (clip.height / 2); } private function onFlexInitComplete( event:FlexEvent ):void { dispatchEvent( new Event( Event.COMPLETE ) ); } protected override function showDisplayForDownloading(time : int, event : ProgressEvent) : Boolean { return true; } } ``` } after that just change the preloader property in the main application tag to the Preloader class.
138,203
<p>Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control? </p> <p>The report definition should be embedded in the executable and should not use the Reporting Services web service.</p>
[ { "answer_id": 138222, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>You don't have to show the control itself.</p>\n\n<pre><code>ReportViewer rv = new ReportViewer();\nrv.LocalReport.ReportPath = \"templatepath\";\n// or use file from resource with rv.LocalReport.ReportEmbeddedResource\n\n// add parameters, datasource, etc.\n\nWarning[] warnings;\nstring[] streamids;\nstring mimeType;\nstring encoding;\nstring filenameExtension;\n\nbyte[] bytes;\nbytes = rv.LocalReport.Render(\"PDF\", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);\n\n// save byte[] to file with FileStream or something else\n</code></pre>\n\n<p>However it can render only PDF and XLS (as ReportViewer control cannot export to Word and others as Reportig Service can).</p>\n\n<p>I forgot to mention that the above code is C#, using .NET framework and ReportViewer control. Check out <a href=\"http://www.gotreportviewer.com/\" rel=\"nofollow noreferrer\">GotReportViewer</a> for a quickstart.</p>\n" }, { "answer_id": 138339, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 4, "selected": true, "text": "<p>Actually you don't need a ReportViewer at all, you can directly instantiate and use a LocalReport:</p>\n\n<pre><code>LocalReport report = new LocalReport();\nreport.ReportPath = \"templatepath\";\n// or use file from resource with report.ReportEmbeddedResource\n\n// add parameters, datasource, etc.\n\nWarning[] warnings;\nstring[] streamids;\nstring mimeType;\nstring encoding;\nstring filenameExtension;\n\nbyte[] bytes;\nbytes =report.Render(\"PDF\", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);\n\n// save byte[] to file with FileStream or something else\n</code></pre>\n" }, { "answer_id": 354394, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Can you pass a .rdlc report directly to pdf with parameters? I have two dropdownlists that i pull my report with. I can't get the parameters to work when automatically exporting to pdf. Here is the error I get: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.</p>\n\n<p>The dropdownlists work when I use the reportviewer, but i want to skip this step. I can also get my data to go directly to a pdf if it doesn't have any parameters. My dropdownlists are called ddlyear and ddlmonth.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/966/" ]
Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control? The report definition should be embedded in the executable and should not use the Reporting Services web service.
Actually you don't need a ReportViewer at all, you can directly instantiate and use a LocalReport: ``` LocalReport report = new LocalReport(); report.ReportPath = "templatepath"; // or use file from resource with report.ReportEmbeddedResource // add parameters, datasource, etc. Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtension; byte[] bytes; bytes =report.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); // save byte[] to file with FileStream or something else ```
138,245
<p>currently I'm dealing with a video processing software in which the picture data (8bit signed and unsigned) is stored in arrays of 16-aligned integers allocated as</p> <pre><code>__declspec(align(16)) int *pData = (__declspec(align(16)) int *)_mm_malloc(width*height*sizeof(int),16); </code></pre> <p>Generally, wouldn't it enable faster reading and writing if one used signed/unsigned char arrays like this?:</p> <pre><code>__declspec(align(16)) int *pData = (__declspec(align(16)) unsigned char *)_mm_malloc(width*height*sizeof(unsigned char),16); </code></pre> <p>I know little about cache line size and data transfer optimization, but at least I know that it is an issue. Beyond that, SSE will be used in future, and in that case char-arrays - unlike int arrays - are already in a <em>packed</em> format. So which version would be faster?</p>
[ { "answer_id": 138297, "author": "akiva", "author_id": 65724, "author_profile": "https://Stackoverflow.com/users/65724", "pm_score": -1, "selected": false, "text": "<p>on the contrary, packing and unpacking is CPU commands expensive.</p>\n\n<p>if you want to make a lot of a random pixel operations - it is faster to make it an array of int so that each pixel has its own address. </p>\n\n<p>but if you iterate through your image sequencly you want to make a chars array so that it is small in size and reduces the chances to have a page fault (Especially for large images)</p>\n" }, { "answer_id": 138306, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 3, "selected": false, "text": "<p>If you're planning to use SSE, storing the data in its native size (8-bit) is almost certainly a better choice, since loads of operations can be done without unpacking, and even if you need to unpack for pmaddwd or other similar instructions, its still faster because you have to load less data.</p>\n\n<p>Even in scalar code, loading 8-bit or 16-bit values is no slower than loading 32-bit, since movzx/movsx is no different in speed from mov. So you just save memory, which surely can't hurt.</p>\n" }, { "answer_id": 138350, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>It really depends on your target CPU -- you should read up on its specs and run some benchmarks as everyone has already suggested. Many factors could influence performance. The first obvious one that comes to my mind is that your array of ints is 2 to 4 times larger than an array of chars and, hence, if the array is big enough, you'll get fewer data cache hits, which will definitely slow down the performance.</p>\n" }, { "answer_id": 506876, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": -1, "selected": false, "text": "<p>Char arrays can be slower in some cases. As a very general rule of thumb, the native word size is the best to go for, which will more than likely be 4-byte (32-bit) or 8-byte (64-bit). Even better is to have everything aligned to 16-bytes as you have already done... this will enable faster copies if you use SSE instructions (MOVNTA). If you are only concerned with moving items around this will have a much greater impact than the type used by the array...</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
currently I'm dealing with a video processing software in which the picture data (8bit signed and unsigned) is stored in arrays of 16-aligned integers allocated as ``` __declspec(align(16)) int *pData = (__declspec(align(16)) int *)_mm_malloc(width*height*sizeof(int),16); ``` Generally, wouldn't it enable faster reading and writing if one used signed/unsigned char arrays like this?: ``` __declspec(align(16)) int *pData = (__declspec(align(16)) unsigned char *)_mm_malloc(width*height*sizeof(unsigned char),16); ``` I know little about cache line size and data transfer optimization, but at least I know that it is an issue. Beyond that, SSE will be used in future, and in that case char-arrays - unlike int arrays - are already in a *packed* format. So which version would be faster?
If you're planning to use SSE, storing the data in its native size (8-bit) is almost certainly a better choice, since loads of operations can be done without unpacking, and even if you need to unpack for pmaddwd or other similar instructions, its still faster because you have to load less data. Even in scalar code, loading 8-bit or 16-bit values is no slower than loading 32-bit, since movzx/movsx is no different in speed from mov. So you just save memory, which surely can't hurt.
138,250
<p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?</p> <p>Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p> <p>I would prefer if I didn't have to download any additional libraries.</p>
[ { "answer_id": 138254, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>Image manipulation is a complex topic, and it's best if you <em>do</em> use a library. I can recommend <a href=\"http://newcenturycomputers.net/projects/gdmodule.html\" rel=\"nofollow noreferrer\">gdmodule</a> which provides easy access to many different image formats from within Python.</p>\n" }, { "answer_id": 138260, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 9, "selected": true, "text": "<p>It's probably best to use the <a href=\"http://www.pythonware.com/products/pil/\" rel=\"noreferrer\">Python Image Library</a> to do this which I'm afraid is a separate download.</p>\n\n<p>The easiest way to do what you want is via the <a href=\"http://effbot.org/imagingbook/image.htm\" rel=\"noreferrer\">load() method on the Image object</a> which returns a pixel access object which you can manipulate like an array:</p>\n\n<pre><code>from PIL import Image\n\nim = Image.open('dead_parrot.jpg') # Can be many different formats.\npix = im.load()\nprint im.size # Get the width and hight of the image for iterating over\nprint pix[x,y] # Get the RGBA Value of the a pixel of an image\npix[x,y] = value # Set the RGBA Value of the image (tuple)\nim.save('alive_parrot.png') # Save the modified pixels as .png\n</code></pre>\n\n<p>Alternatively, look at <a href=\"http://effbot.org/imagingbook/imagedraw.htm\" rel=\"noreferrer\">ImageDraw</a> which gives a much richer API for creating images.</p>\n" }, { "answer_id": 138300, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 2, "selected": false, "text": "<p>There's a really good article on wiki.wxpython.org entitled <a href=\"http://wiki.wxpython.org/index.cgi/WorkingWithImages\" rel=\"nofollow noreferrer\">Working With Images</a>. The article mentions the possiblity of using wxWidgets (wxImage), PIL or PythonMagick. Personally, I've used PIL and wxWidgets and both make image manipulation fairly easy.</p>\n" }, { "answer_id": 139070, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 5, "selected": false, "text": "<p><strong>PyPNG - lightweight PNG decoder/encoder</strong></p>\n\n<p>Although the question hints at JPG, I hope my answer will be useful to some people.</p>\n\n<p>Here's how to read and write PNG pixels using <a href=\"https://pypi.python.org/pypi/pypng/0.0.18\" rel=\"noreferrer\">PyPNG module</a>:</p>\n\n<pre><code>import png, array\n\npoint = (2, 10) # coordinates of pixel to be painted red\n\nreader = png.Reader(filename='image.png')\nw, h, pixels, metadata = reader.read_flat()\npixel_byte_width = 4 if metadata['alpha'] else 3\npixel_position = point[0] + point[1] * w\nnew_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)\npixels[\n pixel_position * pixel_byte_width :\n (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)\n\noutput = open('image-with-red-dot.png', 'wb')\nwriter = png.Writer(w, h, **metadata)\nwriter.write_array(output, pixels)\noutput.close()\n</code></pre>\n\n<p>PyPNG is a single pure Python module less than 4000 lines long, including tests and comments.</p>\n\n<p><a href=\"http://www.pythonware.com/products/pil/\" rel=\"noreferrer\">PIL</a> is a more comprehensive imaging library, but it's also significantly heavier.</p>\n" }, { "answer_id": 663861, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://www.pygame.org\" rel=\"nofollow noreferrer\">pygame</a>'s surfarray module. This module has a 3d pixel array returning method called pixels3d(surface). I've shown usage below:</p>\n\n<pre><code>from pygame import surfarray, image, display\nimport pygame\nimport numpy #important to import\n\npygame.init()\nimage = image.load(\"myimagefile.jpg\") #surface to render\nresolution = (image.get_width(),image.get_height())\nscreen = display.set_mode(resolution) #create space for display\nscreen.blit(image, (0,0)) #superpose image on screen\ndisplay.flip()\nsurfarray.use_arraytype(\"numpy\") #important!\nscreenpix = surfarray.pixels3d(image) #pixels in 3d array:\n#[x][y][rgb]\nfor y in range(resolution[1]):\n for x in range(resolution[0]):\n for color in range(3):\n screenpix[x][y][color] += 128\n #reverting colors\nscreen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen\ndisplay.flip() #update display\nwhile 1:\n print finished\n</code></pre>\n\n<p>I hope been helpful. Last word: screen is locked for lifetime of screenpix.</p>\n" }, { "answer_id": 5365853, "author": "Lachlan Phillips", "author_id": 667814, "author_profile": "https://Stackoverflow.com/users/667814", "pm_score": 4, "selected": false, "text": "<p>As Dave Webb said:</p>\n\n<blockquote>\n <p>Here is my working code snippet printing the pixel colours from an\n image:</p>\n\n<pre><code>import os, sys\nimport Image\n\nim = Image.open(\"image.jpg\")\nx = 3\ny = 4\n\npix = im.load()\nprint pix[x,y]\n</code></pre>\n</blockquote>\n" }, { "answer_id": 22877878, "author": "user3423024", "author_id": 3423024, "author_profile": "https://Stackoverflow.com/users/3423024", "pm_score": 2, "selected": false, "text": "<p>install PIL using the command \"sudo apt-get install python-imaging\" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values</p>\n\n<pre><code>import PIL\nimport Image\nFILENAME='fn.gif' #image can be in gif jpeg or png format \nim=Image.open(FILENAME).convert('RGB')\npix=im.load()\nw=im.size[0]\nh=im.size[1]\nfor i in range(w):\n for j in range(h):\n print pix[i,j]\n</code></pre>\n" }, { "answer_id": 27370477, "author": "chenlian", "author_id": 4268078, "author_profile": "https://Stackoverflow.com/users/4268078", "pm_score": 2, "selected": false, "text": "<p>You could use the Tkinter module, which is the standard Python interface to the Tk GUI toolkit and you don't need extra download. See <a href=\"https://docs.python.org/2/library/tkinter.html\" rel=\"nofollow\">https://docs.python.org/2/library/tkinter.html</a>.</p>\n\n<p>(For Python 3, Tkinter is renamed to tkinter)</p>\n\n<p>Here is how to set RGB values:</p>\n\n<pre><code>#from http://tkinter.unpythonic.net/wiki/PhotoImage\nfrom Tkinter import *\n\nroot = Tk()\n\ndef pixel(image, pos, color):\n \"\"\"Place pixel at pos=(x,y) on image, with color=(r,g,b).\"\"\"\n r,g,b = color\n x,y = pos\n image.put(\"#%02x%02x%02x\" % (r,g,b), (y, x))\n\nphoto = PhotoImage(width=32, height=32)\n\npixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle...\n\nlabel = Label(root, image=photo)\nlabel.grid()\nroot.mainloop()\n</code></pre>\n\n<p>And get RGB:</p>\n\n<pre><code>#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py\ndef getRGB(image, x, y):\n value = image.get(x, y)\n return tuple(map(int, value.split(\" \")))\n</code></pre>\n" }, { "answer_id": 27960627, "author": "Martin Thoma", "author_id": 562769, "author_profile": "https://Stackoverflow.com/users/562769", "pm_score": 6, "selected": false, "text": "<p>Using <a href=\"http://python-pillow.github.io/\" rel=\"noreferrer\">Pillow</a> (which works with Python 3.X as well as Python 2.7+), you can do the following:</p>\n<pre><code>from PIL import Image\nim = Image.open('image.jpg', 'r')\nwidth, height = im.size\npixel_values = list(im.getdata())\n</code></pre>\n<p>Now you have all pixel values. If it is RGB or another mode can be read by <code>im.mode</code>. Then you can get pixel <code>(x, y)</code> by:</p>\n<pre><code>pixel_values[width*y+x]\n</code></pre>\n<p>Alternatively, you can use Numpy and reshape the array:</p>\n<pre><code>&gt;&gt;&gt; pixel_values = numpy.array(pixel_values).reshape((width, height, 3))\n&gt;&gt;&gt; x, y = 0, 1\n&gt;&gt;&gt; pixel_values[x][y]\n[ 18 18 12]\n</code></pre>\n<p>A complete, simple to use solution is</p>\n<pre class=\"lang-py prettyprint-override\"><code># Third party modules\nimport numpy\nfrom PIL import Image\n\n\ndef get_image(image_path):\n &quot;&quot;&quot;Get a numpy array of an image so that one can access values[x][y].&quot;&quot;&quot;\n image = Image.open(image_path, &quot;r&quot;)\n width, height = image.size\n pixel_values = list(image.getdata())\n if image.mode == &quot;RGB&quot;:\n channels = 3\n elif image.mode == &quot;L&quot;:\n channels = 1\n else:\n print(&quot;Unknown mode: %s&quot; % image.mode)\n return None\n pixel_values = numpy.array(pixel_values).reshape((width, height, channels))\n return pixel_values\n\n\nimage = get_image(&quot;gradient.png&quot;)\n\nprint(image[0])\nprint(image.shape)\n</code></pre>\n<h2>Smoke testing the code</h2>\n<p>You might be uncertain about the order of width / height / channel. For this reason I've created this gradient:</p>\n<p><a href=\"https://i.stack.imgur.com/H70ww.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/H70ww.png\" alt=\"enter image description here\" /></a></p>\n<p>The image has a width of 100px and a height of 26px. It has a color gradient going from <code>#ffaa00</code> (yellow) to <code>#ffffff</code> (white). The output is:</p>\n<pre><code>[[255 172 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 172 5]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 4]\n [255 172 5]\n [255 171 5]\n [255 171 5]\n [255 172 5]]\n(100, 26, 3)\n</code></pre>\n<p>Things to note:</p>\n<ul>\n<li>The shape is (width, height, channels)</li>\n<li>The <code>image[0]</code>, hence the first row, has 26 triples of the same color</li>\n</ul>\n" }, { "answer_id": 33630650, "author": "Peter V", "author_id": 916859, "author_profile": "https://Stackoverflow.com/users/916859", "pm_score": 3, "selected": false, "text": "<pre><code>photo = Image.open('IN.jpg') #your image\nphoto = photo.convert('RGB')\n\nwidth = photo.size[0] #define W and H\nheight = photo.size[1]\n\nfor y in range(0, height): #each pixel has coordinates\n row = \"\"\n for x in range(0, width):\n\n RGB = photo.getpixel((x,y))\n R,G,B = RGB #now you can use the RGB value\n</code></pre>\n" }, { "answer_id": 45342958, "author": "user8374199", "author_id": 8374199, "author_profile": "https://Stackoverflow.com/users/8374199", "pm_score": 1, "selected": false, "text": "<pre><code>import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimg=mpimg.imread('Cricket_ACT_official_logo.png')\nimgplot = plt.imshow(img)\n</code></pre>\n" }, { "answer_id": 49242185, "author": "Anupam Hayat Shawon", "author_id": 6760464, "author_profile": "https://Stackoverflow.com/users/6760464", "pm_score": 1, "selected": false, "text": "<p>If you are looking to have three digits in the form of an RGB colour code, the following code should do just that.</p>\n\n<pre><code>i = Image.open(path)\npixels = i.load() # this is not a list, nor is it list()'able\nwidth, height = i.size\n\nall_pixels = []\nfor x in range(width):\n for y in range(height):\n cpixel = pixels[x, y]\n all_pixels.append(cpixel)\n</code></pre>\n\n<p>This may work for you.</p>\n" }, { "answer_id": 50894365, "author": "Idan Rotbart", "author_id": 6941443, "author_profile": "https://Stackoverflow.com/users/6941443", "pm_score": 3, "selected": false, "text": "<p>Using a library called Pillow, you can make this into a function, for ease of use later in your program, and if you have to use it multiple times.\nThe function simply takes in the path of an image and the coordinates of the pixel you want to &quot;grab.&quot; It opens the image, converts it to an RGB color space, and returns the R, G, and B of the requested pixel.</p>\n<pre><code>from PIL import Image\ndef rgb_of_pixel(img_path, x, y):\n im = Image.open(img_path).convert('RGB')\n r, g, b = im.getpixel((x, y))\n a = (r, g, b)\n return a\n</code></pre>\n<blockquote>\n<p><em>*Note: I was not the original author of this code; it was left without an explanation. As it is fairly easy to explain, I am simply providing said explanation, just in case someone down the line does not understand it.</em></p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel? Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value? I would prefer if I didn't have to download any additional libraries.
It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download. The easiest way to do what you want is via the [load() method on the Image object](http://effbot.org/imagingbook/image.htm) which returns a pixel access object which you can manipulate like an array: ``` from PIL import Image im = Image.open('dead_parrot.jpg') # Can be many different formats. pix = im.load() print im.size # Get the width and hight of the image for iterating over print pix[x,y] # Get the RGBA Value of the a pixel of an image pix[x,y] = value # Set the RGBA Value of the image (tuple) im.save('alive_parrot.png') # Save the modified pixels as .png ``` Alternatively, look at [ImageDraw](http://effbot.org/imagingbook/imagedraw.htm) which gives a much richer API for creating images.
138,251
<p>I am trying to access a Windows Media Player library from ASP.NET.</p> <p>The following code:</p> <p>WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer();</p> <p>WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio");</p> <p>Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS.</p> <p>Setting impersonation with:</p> <p>System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();</p> <p>Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library. </p> <p>Is there a way to get around this?</p>
[ { "answer_id": 140939, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 1, "selected": false, "text": "<p>Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probably) running code as yourself, but when under IIS you'll be running it as IUSR_<em>machinename</em> or another low-permission system account.</p>\n\n<p>Try adding something like this to your web.config file:</p>\n\n<pre><code>&lt;system.web&gt;\n&lt;identity impersonate=\"true\" userName=\"MYDOMAIN\\myuser\" password=\"p@ssw0rd\" /&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>No idea whether this works with Media Player specifically, but it works for other identity/security related problems like this. </p>\n" }, { "answer_id": 229677, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 0, "selected": false, "text": "<p>I've run into a similar problem: the code works fine on my local machine, but once deployed on my home server, it can not pull anything out of the media library (I can open media player to verify there are songs in the library)</p>\n\n<p>At first I thought it was a process issue as well, so I tried both setting the application pool to run under my own account, and to set it via the identity impersonate tags; neither resolved the issue.</p>\n\n<p>I'm not sure of what other differences would cause the issue</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22590/" ]
I am trying to access a Windows Media Player library from ASP.NET. The following code: WMPLib.WindowsMediaPlayer mplayer = new WMPLib.WindowsMediaPlayer(); WMPLib.IWMPStringCollection list = mplayer.mediaCollection.getAttributeStringCollection("artist", "audio"); Returns an non-empty list when run using the VS2005 development web server but an empty list when using IIS. Setting impersonation with: System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate(); Doesn't help. It seems that WMPLib still doesn't thinks its running as a user who has a library. Is there a way to get around this?
Have you tried configuration via web.config in ASP.NET? When you're running in the VS2005 debugger, you're (probably) running code as yourself, but when under IIS you'll be running it as IUSR\_*machinename* or another low-permission system account. Try adding something like this to your web.config file: ``` <system.web> <identity impersonate="true" userName="MYDOMAIN\myuser" password="p@ssw0rd" /> </system.web> ``` No idea whether this works with Media Player specifically, but it works for other identity/security related problems like this.
138,261
<p>I am having a table Table1 with columns id1, id2, id3 all the columns are nullable</p> <p>I may enter null or value to all columns in rows.</p> <p>My question is I need to select the rows whose all the column values should not be null.</p> <p>Thanks</p> <hr> <p>There are totally around 300 columns in the table. I can't do the <code>is null</code> property for all the columns in <code>where</code> condition.</p>
[ { "answer_id": 138274, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>The answer to use a \"function\" to test the null-values is correct. The syntax depends on the database. If ISNULL() does not exist in your database then try:</p>\n\n<p>SELECT * FROM Table1 WHERE id1 IS NOT NULL AND id2 IS NOT NULL AND id3 IS NOT NULL</p>\n\n<p>And there is no way to short this down even if you have 300 fields in your table.</p>\n" }, { "answer_id": 138276, "author": "James", "author_id": 7837, "author_profile": "https://Stackoverflow.com/users/7837", "pm_score": 1, "selected": false, "text": "<p>Are you saying you want to select the rows where none of the columns are null?</p>\n\n<p><code></p>\n\n<pre>\nSELECT id1, id2, id3 \nFROM Table1 \nWHERE id1 IS NOT NULL AND id2 IS NOT NULL AND id3 IS NOT NULL\n</pre>\n\n<p></code></p>\n" }, { "answer_id": 138301, "author": "Robinb", "author_id": 22064, "author_profile": "https://Stackoverflow.com/users/22064", "pm_score": 2, "selected": false, "text": "<p>Best bet is to either rethink the design of your tables, splitting them if required. </p>\n\n<p>otherwise best bet is do it progmatically - grab the table metadata, itterate through the columns and drynamically create the SQL from there. Most coding languages have access to the tables metadata, failing that a second SQL is required for it.</p>\n\n<p>But, best bet is to think how can I design the table better. </p>\n" }, { "answer_id": 138312, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 0, "selected": false, "text": "<p>you can try CLR stored procedure (if you're using SQL Server) or move this logic to the other layer of your application using C# or whatever language you're using.</p>\n\n<p>another option is to create the query dynamically, concatenating your WHERE clause and EXECute your dynamically generated query.</p>\n" }, { "answer_id": 138326, "author": "Robinb", "author_id": 22064, "author_profile": "https://Stackoverflow.com/users/22064", "pm_score": 2, "selected": false, "text": "<p>Don't understand why this question is getting negitive reviews - This question can be extended to people who inherited a large table from a non-programmer in a community (I know from previous experience), and likewise if the table is unknown. To downgrade this because its '300' columns is pointless IMO. </p>\n" }, { "answer_id": 138352, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 0, "selected": false, "text": "<p>Are you just reading the data, or will you want to try and update the rows in question?</p>\n\n<p>I'm just wondering if there's something you can go by making a half-dozen views, each one based on say 50 columns being NOT NULL, and then linking them with some kind of EXISTS or UNION statement?</p>\n\n<p>Can you tell us a bit more about what you want to do with your result set?</p>\n" }, { "answer_id": 138792, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": true, "text": "<p>You need to do this:</p>\n\n<pre><code>SELECT *\nFROM yourtable\nWHERE\n column1 IS NOT NULL\nAND column2 IS NOT NULL\nAND column3 IS NOT NULL\nAND ....\n</code></pre>\n" }, { "answer_id": 140107, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 1, "selected": false, "text": "<p>Sorry - I might be being a bit thick here. You're trying to get back the rows that have got SOMETHING in one of the columns (other than the id column)?</p>\n\n<p>Can't you do;</p>\n\n<pre>\ncreate vw_View_Fields1to5 as \n select id from employees \n where name is not null or description is not null or field3 is not null \n or field4 is not null or field5 is not null;\ncreate vw_View_Fields6to10 as \n select id from employees \n where field6 is not null or field7 is not null or field8 is not null \n or field 9 is not null or field10 is not null;\n(etc)\n\nselect id from vw_View_Fields1to5\nunion \nselect id from vw_View_Fields6to10 .... (etc)\n\n</pre>\n\n<p>You'd have to take a DISTINCT or something to cut down the rows that fall into more than one view, of course.</p>\n\n<p>If you want the rows back that have NOTHING in any column other than id, you'd switch '<strong>or blah is not null</strong>' to be '<strong>and blah is null</strong>' (etc).</p>\n\n<p>Does that make sense... or am I missing something? :-)</p>\n\n<p>EDIT: Actually, I believe the UNION process will only bring back distinct rows anyway (as opposed to UNION ALL), but I could be wrong - I haven't actually tried this.... (yet!)</p>\n" }, { "answer_id": 147609, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 0, "selected": false, "text": "<p>For the first time whatever Georgi or engram or robsoft is the way. However for subsequent stuff you can if possible alter the table and add one more column, called CSELECTFLAG, and initially updated this to Y for all columns that have values and N for others. Everytime there is an insert this needs to be updated. This would help make your subsequent queries faster and easier.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I am having a table Table1 with columns id1, id2, id3 all the columns are nullable I may enter null or value to all columns in rows. My question is I need to select the rows whose all the column values should not be null. Thanks --- There are totally around 300 columns in the table. I can't do the `is null` property for all the columns in `where` condition.
You need to do this: ``` SELECT * FROM yourtable WHERE column1 IS NOT NULL AND column2 IS NOT NULL AND column3 IS NOT NULL AND .... ```
138,302
<p>When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid()</p> <p>e.g</p> <pre><code>CREATE TABLE [dbo].[MyTable]( [MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()), [Status] [int] NULL, [Priority] [int] NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED ( [MyPrimaryKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] </code></pre> <p>wIth the C# code</p> <pre><code> tran = connection.BeginTransaction(); SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran); sqlCopy.DestinationTableName = "MyTable"; sqlCopy.WriteToServer(dataTable); </code></pre> <p>Gives you an error...</p> <p>Column 'MyPrimaryKey' does not allow DBNull.Value</p> <p>I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key.</p> <p>Anyone know if there is a workaround for this issue? Or can you verify that there is no workaround (other than changing the table structure)?</p>
[ { "answer_id": 139804, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 0, "selected": false, "text": "<p>You're only options are to remove the MyPrimaryKey field from the data that is being loaded or to modify the table structure.</p>\n\n<p>With the field being there with no values you are telling SQL that you want to force a null into the field, which, obviously, is not allowed.</p>\n" }, { "answer_id": 139850, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>You need to set up the column mappings. First call</p>\n\n<pre><code>sqlCopy.ColumnMappings.Clear();\n</code></pre>\n\n<p>Then call</p>\n\n<pre><code>sqlBulkCopy.ColumnMappings.Add(\"Status\", \"Status\");\nsqlBulkCopy.ColumnMappings.Add(\"Priority\", \"Priority\");\n</code></pre>\n\n<p>This means the bulk copy will stop trying to insert into MyPrimaryKey column and will only insert into the status and Priority columns.</p>\n" }, { "answer_id": 30249522, "author": "DCShannon", "author_id": 2449863, "author_profile": "https://Stackoverflow.com/users/2449863", "pm_score": 0, "selected": false, "text": "<p>Removing the database generated columns from the column set before writing is what you need to do.</p>\n\n<p>We use LINQ-to-SQL for most of our database operations, but use another method for inserting many records at once, as L2S is a bit slow for this.</p>\n\n<p>We have a generic method called <code>BulkInsertAll&lt;&gt;</code> that we can use on any table, which uses <code>SqlBulkCopy</code> internally. We dynamically generate the columns using reflection based on the generic type's properties. The <code>ColumnAttribute</code> is found in the .cs file generated from our .dbml file, where we have specified the guid primary key column as <code>IsDbGenerated=\"true\"</code>.</p>\n\n<pre><code>public void BulkInsertAll&lt;T&gt;( IEnumerable&lt;T&gt; entities ) {\n entities = entities.ToArray();\n\n string cs = Connection.ConnectionString;\n var conn = new SqlConnection( cs );\n conn.Open();\n\n Type t = typeof( T );\n\n var tableAttribute = (TableAttribute) t.GetCustomAttributes(\n typeof( TableAttribute ), false\n ).Single();\n\n var bulkCopy = new SqlBulkCopy( conn ) {\n DestinationTableName = tableAttribute.Name\n };\n\n var properties = t.GetProperties().Where( EventTypeFilter );\n\n // This will prevent the bulk insert from attempting to update DBGenerated columns\n // Without, inserts with a guid pk will fail to get the generated sequential id\n // If uninitialized guids are passed to the DB, it will throw duplicate key exceptions\n properties = properties.Where( \n x =&gt; !x.GetCustomAttributes( typeof( ColumnAttribute ), false )\n .Cast&lt;ColumnAttribute&gt;().Any( attr =&gt; attr.IsDbGenerated )\n );\n\n var table = new DataTable();\n\n foreach( var property in properties ) {\n Type propertyType = property.PropertyType;\n if( propertyType.IsGenericType &amp;&amp;\n propertyType.GetGenericTypeDefinition() == typeof( Nullable&lt;&gt; ) ) {\n propertyType = Nullable.GetUnderlyingType( propertyType );\n }\n\n table.Columns.Add( new DataColumn( property.Name, propertyType ) );\n }\n\n foreach( var entity in entities ) {\n table.Rows.Add( \n properties.Select( \n property =&gt; GetPropertyValue( property.GetValue( entity, null ) ) \n ).ToArray()\n );\n }\n\n //specify the mapping for SqlBulk Upload\n foreach( var col in properties ) {\n bulkCopy.ColumnMappings.Add( col.Name, col.Name );\n }\n\n bulkCopy.WriteToServer( table );\n\n conn.Close();\n}\n\n\nprivate bool EventTypeFilter( System.Reflection.PropertyInfo p ) {\n var attribute = Attribute.GetCustomAttribute( p,\n typeof( AssociationAttribute ) ) as AssociationAttribute;\n\n if( attribute == null ) return true;\n if( attribute.IsForeignKey == false ) return true;\n\n return false;\n}\n\nprivate object GetPropertyValue( object o ) {\n if( o == null )\n return DBNull.Value;\n return o;\n}\n</code></pre>\n\n<p>And this works just fine. The entities won't be updated with the newly assigned Guid, so you'll have to make another query to get those, but the new rows have property generated guids in the database.</p>\n\n<p>We could wrap that <code>.Where</code> filter into the EventTypeFilter method, but I'm not the one who wrote most of this, and I haven't gone through it to tune everything up.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using SQLBulkCopy on a table with a GUID primary key and default newsequentialid() e.g ``` CREATE TABLE [dbo].[MyTable]( [MyPrimaryKey] [uniqueidentifier] NOT NULL CONSTRAINT [MyConstraint] DEFAULT (newsequentialid()), [Status] [int] NULL, [Priority] [int] NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY NONCLUSTERED ( [MyPrimaryKey] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] ``` wIth the C# code ``` tran = connection.BeginTransaction(); SqlBulkCopy sqlCopy = new SqlBulkCopy(connection,SqlBulkCopyOptions.Default, tran); sqlCopy.DestinationTableName = "MyTable"; sqlCopy.WriteToServer(dataTable); ``` Gives you an error... Column 'MyPrimaryKey' does not allow DBNull.Value I've tried fiddling the the SqlBulkCopyOptions. The only thing that works is setting the MyPrimaryKey field to allow nulls and removing the primary key. Anyone know if there is a workaround for this issue? Or can you verify that there is no workaround (other than changing the table structure)?
You need to set up the column mappings. First call ``` sqlCopy.ColumnMappings.Clear(); ``` Then call ``` sqlBulkCopy.ColumnMappings.Add("Status", "Status"); sqlBulkCopy.ColumnMappings.Add("Priority", "Priority"); ``` This means the bulk copy will stop trying to insert into MyPrimaryKey column and will only insert into the status and Priority columns.
138,309
<p>I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.</p> <p>Example:</p> <pre><code>&lt;object id="img" data="image.svg" width="500" height="300"/&gt; &lt;script&gt;document.getElementById("img").addData([1,23,4]);&lt;/script&gt; </code></pre> <p>Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?</p>
[ { "answer_id": 138358, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 5, "selected": true, "text": "<p>Solution:</p>\n\n<p>in svg:</p>\n\n<pre><code>&lt;script&gt;document.method = function() {}&lt;/script&gt;\n</code></pre>\n\n<p>in html (using prototype to add event listeners):</p>\n\n<pre><code>&lt;script&gt;$(\"img\").observe(\"load\", function() {$(\"img\").contentDocument.method()});\n</code></pre>\n\n<p>You need to listen to the load event on the image. Once the image is loaded, you can use the <code>element.contentDocument</code> to access the document variable on the svg document. Any methods added to that, will be available.</p>\n" }, { "answer_id": 144236, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 3, "selected": false, "text": "<p>A few years ago, I was asked to create a 2-player Ajax-based game using SVG. It may not be precisely the solution you're looking for, but it may help you listen for events in your SVG. Here's the SVG controller:</p>\n\n<p><em>fyi, the SVG was being dragged and dropped (it was Stratego)</em></p>\n\n<pre><code>/****************** Track and handle SVG object movement *************/\nvar svgDoc;\nvar svgRoot;\nvar mover=''; //keeps track of what I'm dragging\n\n///start function////\n//do this onload\nfunction start(evt){\n //set up the svg document elements\n svgDoc=evt.target.ownerDocument;\n svgRoot=svgDoc.documentElement;\n //add the mousemove event to the whole thing\n svgRoot.addEventListener('mousemove',go,false);\n //do this when the mouse is released\n svgRoot.addEventListener('mouseup',releaseMouse,false); \n}\n\n// set the id of the target to drag\nfunction setMove(id){ mover=id; }\n\n// clear the id of the dragging object\nfunction releaseMouse(){ \n if(allowMoves == true){ sendMove(mover); }\n mover=''; \n}\n\n// this is launched every mousemove on the doc\n// if we are dragging something, move it\nfunction go(evt){\n if(mover != '' &amp;&amp; allowMoves != false) {\n //init it\n var me=document.getElementById(mover);\n\n //actually change the location\n moveX = evt.clientX-135; //css positioning minus 1/2 the width of the piece\n moveY = evt.clientY-65;\n me.setAttributeNS(null, 'x', evt.clientX-135);\n me.setAttributeNS(null, 'y', evt.clientY-65);\n }\n}\n\nfunction moveThis(pieceID, x, y) {\n $(pieceID).setAttributeNS(null, 'x', x);\n $(pieceID).setAttributeNS(null, 'y', y);\n}\n</code></pre>\n\n<p>My app was pure SVG + JavaScript, but this is the gist of it.</p>\n" }, { "answer_id": 257771, "author": "David.Chu.ca", "author_id": 62776, "author_profile": "https://Stackoverflow.com/users/62776", "pm_score": 1, "selected": false, "text": "<p>I have explored the svg by JavaScripts. See the blog: <a href=\"http://davidchuprogramming.blogspot.com/2008/10/scaling-svg-graphics-with-javascript.html\" rel=\"nofollow noreferrer\">Scaling SVG Graphics with JavaScripts</a></p>\n" }, { "answer_id": 257785, "author": "Ris Adams", "author_id": 15683, "author_profile": "https://Stackoverflow.com/users/15683", "pm_score": 3, "selected": false, "text": "<p>I would reference Dr. David Dailey as the most awesome SVG / JS info you will find \n<a href=\"http://srufaculty.sru.edu/david.dailey/svg/\" rel=\"noreferrer\">http://srufaculty.sru.edu/david.dailey/svg/</a></p>\n" }, { "answer_id": 361342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Also see the <a href=\"http://keith-wood.name/svg.html\" rel=\"nofollow noreferrer\">jQuery SVG plugin</a></p>\n" }, { "answer_id": 3899965, "author": "Matt Ellen", "author_id": 204723, "author_profile": "https://Stackoverflow.com/users/204723", "pm_score": 0, "selected": false, "text": "<p>For support in IE6, have a look at <a href=\"http://code.google.com/p/svgweb/\" rel=\"nofollow\">SVGWeb</a>.</p>\n\n<p>There are examples on how to manipulate SVG with JavaScript in the sample code supplied with the library.</p>\n\n<p>There is also a fair amount of information in the archives of the mailing list.</p>\n" }, { "answer_id": 7183632, "author": "Temperage", "author_id": 657087, "author_profile": "https://Stackoverflow.com/users/657087", "pm_score": 3, "selected": false, "text": "<p>Things are actually simpler than you expect. You do not really need to read convoluted tutorial to understand the concept, neither do you have to use JQuery. Here is the basic layout:</p>\n\n<ul>\n<li><p>A JavaScript function in your html document.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction change(){\n var s=document.getElementById(\"cube\");\n s.setAttribute(\"stroke\",\"0000FF\");\n}\n&lt;/script&gt;\n</code></pre></li>\n<li><p>An SVG element that we are trying to manipulate.</p>\n\n<pre><code>&lt;svg width=100 height=100 style='float: left;'&gt;\n &lt;rect x=\"10\" y=\"10\" width=\"60\" height=\"60\" id=\"cube\" onclick=\"change()\" stroke=#F53F0C stroke-width=10 fill=#F5C60C /&gt;\n&lt;/svg&gt;\n</code></pre></li>\n<li><p>An inline Button that would trigger the change. Notice that in my example the event can also be triggered by clicking on the cube itself.</p>\n\n<pre><code>&lt;button onclick=\"change()\"&gt;Click&lt;/button&gt;\n</code></pre></li>\n</ul>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image. Example: ``` <object id="img" data="image.svg" width="500" height="300"/> <script>document.getElementById("img").addData([1,23,4]);</script> ``` Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?
Solution: in svg: ``` <script>document.method = function() {}</script> ``` in html (using prototype to add event listeners): ``` <script>$("img").observe("load", function() {$("img").contentDocument.method()}); ``` You need to listen to the load event on the image. Once the image is loaded, you can use the `element.contentDocument` to access the document variable on the svg document. Any methods added to that, will be available.
138,311
<p>The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?</p>
[ { "answer_id": 138372, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 6, "selected": true, "text": "<p>I love simple questions with clear answers.</p>\n\n<pre><code>#I go in application.rb\nself.allow_forgery_protection = false\n</code></pre>\n\n<p>If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching <code>Application</code> then rather than <code>self</code>). You could also write something like:</p>\n\n<pre><code>#I still go in application.rb\nself.allow_forgery_protection = false unless ENV[\"RAILS_ENV\"] == \"production\"\n</code></pre>\n\n<p>See <a href=\"http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-cross-site-request-forging-prevention\" rel=\"noreferrer\">here</a> for details. (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.)</p>\n" }, { "answer_id": 7564903, "author": "Jeff Dickey", "author_id": 43055, "author_profile": "https://Stackoverflow.com/users/43055", "pm_score": 2, "selected": false, "text": "<p>In Rails 3, remove the <code>protect_from_forgery</code> command in <code>app/controllers/application_controller.rb</code></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?
I love simple questions with clear answers. ``` #I go in application.rb self.allow_forgery_protection = false ``` If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching `Application` then rather than `self`). You could also write something like: ``` #I still go in application.rb self.allow_forgery_protection = false unless ENV["RAILS_ENV"] == "production" ``` See [here](http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-cross-site-request-forging-prevention) for details. (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.)
138,313
<p>I would like to create a page where all images which reside on my website are listed with title and alternative representation.</p> <p>I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract <code>src</code>, <code>title</code> and <code>alt</code> from this HTML:</p> <pre><code>&lt;img <b>src</b>="/image/fluffybunny.jpg" <b>title</b>="Harvey the bunny" <b>alt</b>="a cute little fluffy bunny" /></code></pre> <p>I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).</p>
[ { "answer_id": 138614, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": false, "text": "<p>Just to give a small example of using PHP's XML functionality for the task:</p>\n\n<pre><code>$doc=new DOMDocument();\n$doc-&gt;loadHTML(\"&lt;html&gt;&lt;body&gt;Test&lt;br&gt;&lt;img src=\\\"myimage.jpg\\\" title=\\\"title\\\" alt=\\\"alt\\\"&gt;&lt;/body&gt;&lt;/html&gt;\");\n$xml=simplexml_import_dom($doc); // just to make xpath more simple\n$images=$xml-&gt;xpath('//img');\nforeach ($images as $img) {\n echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];\n}\n</code></pre>\n\n<p>I did use the <code>DOMDocument::loadHTML()</code> method because this method can cope with HTML-syntax and does not force the input document to be XHTML. Strictly speaking the conversion to a <code>SimpleXMLElement</code> is not necessary - it just makes using xpath and the xpath results more simple.</p>\n" }, { "answer_id": 138649, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 3, "selected": false, "text": "<p>If it's XHTML, your example is, you need only simpleXML.</p>\n\n<pre><code>&lt;?php\n$input = '&lt;img src=\"/image/fluffybunny.jpg\" title=\"Harvey the bunny\" alt=\"a cute little fluffy bunny\"/&gt;';\n$sx = simplexml_load_string($input);\nvar_dump($sx);\n?&gt;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>object(SimpleXMLElement)#1 (1) {\n [\"@attributes\"]=&gt;\n array(3) {\n [\"src\"]=&gt;\n string(22) \"/image/fluffybunny.jpg\"\n [\"title\"]=&gt;\n string(16) \"Harvey the bunny\"\n [\"alt\"]=&gt;\n string(26) \"a cute little fluffy bunny\"\n }\n}\n</code></pre>\n" }, { "answer_id": 143455, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 9, "selected": true, "text": "<h2>EDIT : now that I know better</h2>\n\n<p>Using regexp to solve this kind of problem is <a href=\"https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454\">a bad idea</a> and will likely lead in unmaintainable and unreliable code. Better use an <a href=\"http://simplehtmldom.sourceforge.net/\" rel=\"noreferrer\">HTML parser</a>. </p>\n\n<h2>Solution With regexp</h2>\n\n<p>In that case it's better to split the process into two parts :</p>\n\n<ul>\n<li>get all the img tag</li>\n<li>extract their metadata</li>\n</ul>\n\n<p>I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :</p>\n\n<pre><code>/* preg_match_all match the regexp in all the $html string and output everything as \nan array in $result. \"i\" option is used to make it case insensitive */\n\npreg_match_all('/&lt;img[^&gt;]+&gt;/i',$html, $result); \n\nprint_r($result);\nArray\n(\n [0] =&gt; Array\n (\n [0] =&gt; &lt;img src=\"/Content/Img/stackoverflow-logo-250.png\" width=\"250\" height=\"70\" alt=\"logo link to homepage\" /&gt;\n [1] =&gt; &lt;img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" /&gt;\n [2] =&gt; &lt;img class=\"vote-down\" src=\"/content/img/vote-arrow-down.png\" alt=\"vote down\" title=\"This was not helpful (click again to undo)\" /&gt;\n [3] =&gt; &lt;img src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&amp;d=identicon&amp;r=PG\" height=32 width=32 alt=\"gravatar image\" /&gt;\n [4] =&gt; &lt;img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" /&gt;\n\n[...]\n )\n\n)\n</code></pre>\n\n<p>Then we get all the img tag attributes with a loop :</p>\n\n<pre><code>$img = array();\nforeach( $result as $img_tag)\n{\n preg_match_all('/(alt|title|src)=(\"[^\"]*\")/i',$img_tag, $img[$img_tag]);\n}\n\nprint_r($img);\n\nArray\n(\n [&lt;img src=\"/Content/Img/stackoverflow-logo-250.png\" width=\"250\" height=\"70\" alt=\"logo link to homepage\" /&gt;] =&gt; Array\n (\n [0] =&gt; Array\n (\n [0] =&gt; src=\"/Content/Img/stackoverflow-logo-250.png\"\n [1] =&gt; alt=\"logo link to homepage\"\n )\n\n [1] =&gt; Array\n (\n [0] =&gt; src\n [1] =&gt; alt\n )\n\n [2] =&gt; Array\n (\n [0] =&gt; \"/Content/Img/stackoverflow-logo-250.png\"\n [1] =&gt; \"logo link to homepage\"\n )\n\n )\n\n [&lt;img class=\"vote-up\" src=\"/content/img/vote-arrow-up.png\" alt=\"vote up\" title=\"This was helpful (click again to undo)\" /&gt;] =&gt; Array\n (\n [0] =&gt; Array\n (\n [0] =&gt; src=\"/content/img/vote-arrow-up.png\"\n [1] =&gt; alt=\"vote up\"\n [2] =&gt; title=\"This was helpful (click again to undo)\"\n )\n\n [1] =&gt; Array\n (\n [0] =&gt; src\n [1] =&gt; alt\n [2] =&gt; title\n )\n\n [2] =&gt; Array\n (\n [0] =&gt; \"/content/img/vote-arrow-up.png\"\n [1] =&gt; \"vote up\"\n [2] =&gt; \"This was helpful (click again to undo)\"\n )\n\n )\n\n [&lt;img class=\"vote-down\" src=\"/content/img/vote-arrow-down.png\" alt=\"vote down\" title=\"This was not helpful (click again to undo)\" /&gt;] =&gt; Array\n (\n [0] =&gt; Array\n (\n [0] =&gt; src=\"/content/img/vote-arrow-down.png\"\n [1] =&gt; alt=\"vote down\"\n [2] =&gt; title=\"This was not helpful (click again to undo)\"\n )\n\n [1] =&gt; Array\n (\n [0] =&gt; src\n [1] =&gt; alt\n [2] =&gt; title\n )\n\n [2] =&gt; Array\n (\n [0] =&gt; \"/content/img/vote-arrow-down.png\"\n [1] =&gt; \"vote down\"\n [2] =&gt; \"This was not helpful (click again to undo)\"\n )\n\n )\n\n [&lt;img src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&amp;d=identicon&amp;r=PG\" height=32 width=32 alt=\"gravatar image\" /&gt;] =&gt; Array\n (\n [0] =&gt; Array\n (\n [0] =&gt; src=\"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&amp;d=identicon&amp;r=PG\"\n [1] =&gt; alt=\"gravatar image\"\n )\n\n [1] =&gt; Array\n (\n [0] =&gt; src\n [1] =&gt; alt\n )\n\n [2] =&gt; Array\n (\n [0] =&gt; \"http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&amp;d=identicon&amp;r=PG\"\n [1] =&gt; \"gravatar image\"\n )\n\n )\n\n [..]\n )\n\n)\n</code></pre>\n\n<p>Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using <a href=\"http://fr2.php.net/manual/fr/function.ob-start.php\" rel=\"noreferrer\">ob_start</a> and loading / saving from a text file.</p>\n\n<h2>How does this stuff work ?</h2>\n\n<p>First, we use <a href=\"http://fr2.php.net/manual/fr/function.preg-match-all.php\" rel=\"noreferrer\">preg_ match_ all</a>, a function that gets every string matching the pattern and ouput it in it's third parameter.</p>\n\n<p>The regexps :</p>\n\n<pre><code>&lt;img[^&gt;]+&gt;\n</code></pre>\n\n<p>We apply it on all html web pages. It can be read as <em>every string that starts with \"<code>&lt;img</code>\", contains non \">\" char and ends with a ></em>.</p>\n\n<pre><code>(alt|title|src)=(\"[^\"]*\")\n</code></pre>\n\n<p>We apply it successively on each img tag. It can be read as <em>every string starting with \"alt\", \"title\" or \"src\", then a \"=\", then a ' \" ', a bunch of stuff that are not ' \" ' and ends with a ' \" '. Isolate the sub-strings between ()</em>. </p>\n\n<p>Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this <a href=\"http://regex.larsolavtorvik.com/\" rel=\"noreferrer\">online regexp tester</a>.</p>\n\n<p>EDIT : answer to the first comment.</p>\n\n<p>It's true that I did not think about the (hopefully few) people using single quotes.</p>\n\n<p>Well, if you use only ', just replace all the \" by '. </p>\n\n<p>If you mix both. First you should slap yourself :-), then try to use (\"|') instead or \" and [^ø] to replace [^\"].</p>\n" }, { "answer_id": 1482842, "author": "Bakudan", "author_id": 179669, "author_profile": "https://Stackoverflow.com/users/179669", "pm_score": 3, "selected": false, "text": "<p>The script must be edited like this</p>\n\n<p><code>foreach( $result[0] as $img_tag)</code></p>\n\n<p>because preg_match_all return array of arrays</p>\n" }, { "answer_id": 2937682, "author": "karim", "author_id": 353868, "author_profile": "https://Stackoverflow.com/users/353868", "pm_score": 8, "selected": false, "text": "<pre><code>$url=\"http://example.com\";\n\n$html = file_get_contents($url);\n\n$doc = new DOMDocument();\n@$doc-&gt;loadHTML($html);\n\n$tags = $doc-&gt;getElementsByTagName('img');\n\nforeach ($tags as $tag) {\n echo $tag-&gt;getAttribute('src');\n}\n</code></pre>\n" }, { "answer_id": 3815188, "author": "WNRosenberg", "author_id": 332472, "author_profile": "https://Stackoverflow.com/users/332472", "pm_score": 3, "selected": false, "text": "<p>I used preg_match to do it.</p>\n\n<p>In my case, I had a string containing exactly one <code>&lt;img&gt;</code> tag (and no other markup) that I got from Wordpress and I was trying to get the <code>src</code> attribute so I could run it through timthumb.</p>\n\n<pre><code>// get the featured image\n$image = get_the_post_thumbnail($photos[$i]-&gt;ID);\n\n// get the src for that image\n$pattern = '/src=\"([^\"]*)\"/';\npreg_match($pattern, $image, $matches);\n$src = $matches[1];\nunset($matches);\n</code></pre>\n\n<p>In the pattern to grab the title or the alt, you could simply use <code>$pattern = '/title=\"([^\"]*)\"/';</code> to grab the title or <code>$pattern = '/title=\"([^\"]*)\"/';</code> to grab the alt. Sadly, my regex isn't good enough to grab all three (alt/title/src) with one pass though.</p>\n" }, { "answer_id": 4172834, "author": "Xavier", "author_id": 506742, "author_profile": "https://Stackoverflow.com/users/506742", "pm_score": -1, "selected": false, "text": "<p>Here is THE solution, in PHP:</p>\n\n<p>Just download QueryPath, and then do as follows:</p>\n\n<pre><code>$doc= qp($myHtmlDoc);\n\nforeach($doc-&gt;xpath('//img') as $img) {\n\n $src= $img-&gt;attr('src');\n $title= $img-&gt;attr('title');\n $alt= $img-&gt;attr('alt');\n\n}\n</code></pre>\n\n<p>That's it, you're done !</p>\n" }, { "answer_id": 8061770, "author": "John Daliani", "author_id": 1037139, "author_profile": "https://Stackoverflow.com/users/1037139", "pm_score": 1, "selected": false, "text": "<p>Here's A PHP Function I hobbled together from all of the above info for a similar purpose, namely adjusting image tag width and length properties on the fly ... a bit clunky, perhaps, but seems to work dependably:</p>\n\n<pre><code>function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {\n\n// find image tags\npreg_match_all('/&lt;img[^&gt;]+&gt;/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER); \n\n// put image tags in a simpler array\n$imagearray = array();\nfor ($i = 0; $i &lt; count($rawimagearray); $i++) {\n array_push($imagearray, $rawimagearray[$i][0]);\n}\n\n// put image attributes in another array\n$imageinfo = array();\nforeach($imagearray as $img_tag) {\n\n preg_match_all('/(src|width|height)=(\"[^\"]*\")/i',$img_tag, $imageinfo[$img_tag]);\n}\n\n// combine everything into one array\n$AllImageInfo = array();\nforeach($imagearray as $img_tag) {\n\n $ImageSource = str_replace('\"', '', $imageinfo[$img_tag][2][0]);\n $OrignialWidth = str_replace('\"', '', $imageinfo[$img_tag][2][1]);\n $OrignialHeight = str_replace('\"', '', $imageinfo[$img_tag][2][2]);\n\n $NewWidth = $OrignialWidth; \n $NewHeight = $OrignialHeight;\n $AdjustDimensions = \"F\";\n\n if($OrignialWidth &gt; $MaximumWidth) { \n $diff = $OrignialWidth-$MaximumHeight; \n $percnt_reduced = (($diff/$OrignialWidth)*100); \n $NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100)); \n $NewWidth = floor($OrignialWidth-$diff); \n $AdjustDimensions = \"T\";\n }\n\n if($OrignialHeight &gt; $MaximumHeight) { \n $diff = $OrignialHeight-$MaximumWidth; \n $percnt_reduced = (($diff/$OrignialHeight)*100); \n $NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100)); \n $NewHeight= floor($OrignialHeight-$diff); \n $AdjustDimensions = \"T\";\n } \n\n $thisImageInfo = array('OriginalImageTag' =&gt; $img_tag , 'ImageSource' =&gt; $ImageSource , 'OrignialWidth' =&gt; $OrignialWidth , 'OrignialHeight' =&gt; $OrignialHeight , 'NewWidth' =&gt; $NewWidth , 'NewHeight' =&gt; $NewHeight, 'AdjustDimensions' =&gt; $AdjustDimensions);\n array_push($AllImageInfo, $thisImageInfo);\n}\n\n// build array of before and after tags\n$ImageBeforeAndAfter = array();\nfor ($i = 0; $i &lt; count($AllImageInfo); $i++) {\n\n if($AllImageInfo[$i]['AdjustDimensions'] == \"T\") {\n $NewImageTag = str_ireplace('width=\"' . $AllImageInfo[$i]['OrignialWidth'] . '\"', 'width=\"' . $AllImageInfo[$i]['NewWidth'] . '\"', $AllImageInfo[$i]['OriginalImageTag']);\n $NewImageTag = str_ireplace('height=\"' . $AllImageInfo[$i]['OrignialHeight'] . '\"', 'height=\"' . $AllImageInfo[$i]['NewHeight'] . '\"', $NewImageTag);\n\n $thisImageBeforeAndAfter = array('OriginalImageTag' =&gt; $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' =&gt; $NewImageTag);\n array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);\n }\n}\n\n// execute search and replace\nfor ($i = 0; $i &lt; count($ImageBeforeAndAfter); $i++) {\n $HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);\n}\n\nreturn $HTMLContent;\n\n}\n</code></pre>\n" }, { "answer_id": 21375115, "author": "Nauphal", "author_id": 932319, "author_profile": "https://Stackoverflow.com/users/932319", "pm_score": 3, "selected": false, "text": "<p>You may use <a href=\"http://simplehtmldom.sourceforge.net/\" rel=\"noreferrer\">simplehtmldom</a>. Most of the jQuery selectors are supported in simplehtmldom. An example is given below</p>\n\n<pre><code>// Create DOM from URL or file\n$html = file_get_html('http://www.google.com/');\n\n// Find all images\nforeach($html-&gt;find('img') as $element)\n echo $element-&gt;src . '&lt;br&gt;';\n\n// Find all links\nforeach($html-&gt;find('a') as $element)\n echo $element-&gt;href . '&lt;br&gt;'; \n</code></pre>\n" }, { "answer_id": 56151147, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "<p>I have read the many comments on this page that complain that using a dom parser is unnecessary overhead. Well, it may be more expensive than a mere regex call, but the OP has stated that there is no control over the order of the attributes in the img tags. This fact leads to unnecessary regex pattern convolution. Beyond that, using a dom parser provides the additional benefits of readability, maintainability, and dom-awareness (regex is not dom-aware).</p>\n\n<p>I love regex and I answer lots of regex questions, but when dealing with valid HTML there is seldom a good reason to regex over a parser.</p>\n\n<p>In the demonstration below, see how easy and clean DOMDocument handles img tag attributes in any order with a mixture of quoting (and no quoting at all). Also notice that tags without a targeted attribute are not disruptive at all -- an empty string is provided as a value.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/jsNCc\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$test = &lt;&lt;&lt;HTML\n&lt;img src=\"/image/fluffybunny.jpg\" title=\"Harvey the bunny\" alt=\"a cute little fluffy bunny\" /&gt;\n&lt;img src='/image/pricklycactus.jpg' title='Roger the cactus' alt='a big green prickly cactus' /&gt;\n&lt;p&gt;This is irrelevant text.&lt;/p&gt;\n&lt;img alt=\"an annoying white cockatoo\" title=\"Polly the cockatoo\" src=\"/image/noisycockatoo.jpg\"&gt;\n&lt;img title=something src=somethingelse&gt;\nHTML;\n\nlibxml_use_internal_errors(true); // silences/forgives complaints from the parser (remove to see what is generated)\n$dom = new DOMDocument();\n$dom-&gt;loadHTML($test);\nforeach ($dom-&gt;getElementsByTagName('img') as $i =&gt; $img) {\n echo \"IMG#{$i}:\\n\";\n echo \"\\tsrc = \" , $img-&gt;getAttribute('src') , \"\\n\";\n echo \"\\ttitle = \" , $img-&gt;getAttribute('title') , \"\\n\";\n echo \"\\talt = \" , $img-&gt;getAttribute('alt') , \"\\n\";\n echo \"---\\n\";\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>IMG#0:\n src = /image/fluffybunny.jpg\n title = Harvey the bunny\n alt = a cute little fluffy bunny\n---\nIMG#1:\n src = /image/pricklycactus.jpg\n title = Roger the cactus\n alt = a big green prickly cactus\n---\nIMG#2:\n src = /image/noisycockatoo.jpg\n title = Polly the cockatoo\n alt = an annoying white cockatoo\n---\nIMG#3:\n src = somethingelse\n title = something\n alt = \n---\n</code></pre>\n\n<p>Using this technique in professional code will leave you with a clean script, fewer hiccups to contend with, and fewer colleagues that wish you worked somewhere else.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
I would like to create a page where all images which reside on my website are listed with title and alternative representation. I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract `src`, `title` and `alt` from this HTML: ``` <img **src**="/image/fluffybunny.jpg" **title**="Harvey the bunny" **alt**="a cute little fluffy bunny" /> ``` I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).
EDIT : now that I know better ----------------------------- Using regexp to solve this kind of problem is [a bad idea](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) and will likely lead in unmaintainable and unreliable code. Better use an [HTML parser](http://simplehtmldom.sourceforge.net/). Solution With regexp -------------------- In that case it's better to split the process into two parts : * get all the img tag * extract their metadata I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code : ``` /* preg_match_all match the regexp in all the $html string and output everything as an array in $result. "i" option is used to make it case insensitive */ preg_match_all('/<img[^>]+>/i',$html, $result); print_r($result); Array ( [0] => Array ( [0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" /> [1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" /> [2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" /> [3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" /> [4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" /> [...] ) ) ``` Then we get all the img tag attributes with a loop : ``` $img = array(); foreach( $result as $img_tag) { preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]); } print_r($img); Array ( [<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array ( [0] => Array ( [0] => src="/Content/Img/stackoverflow-logo-250.png" [1] => alt="logo link to homepage" ) [1] => Array ( [0] => src [1] => alt ) [2] => Array ( [0] => "/Content/Img/stackoverflow-logo-250.png" [1] => "logo link to homepage" ) ) [<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array ( [0] => Array ( [0] => src="/content/img/vote-arrow-up.png" [1] => alt="vote up" [2] => title="This was helpful (click again to undo)" ) [1] => Array ( [0] => src [1] => alt [2] => title ) [2] => Array ( [0] => "/content/img/vote-arrow-up.png" [1] => "vote up" [2] => "This was helpful (click again to undo)" ) ) [<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array ( [0] => Array ( [0] => src="/content/img/vote-arrow-down.png" [1] => alt="vote down" [2] => title="This was not helpful (click again to undo)" ) [1] => Array ( [0] => src [1] => alt [2] => title ) [2] => Array ( [0] => "/content/img/vote-arrow-down.png" [1] => "vote down" [2] => "This was not helpful (click again to undo)" ) ) [<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array ( [0] => Array ( [0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" [1] => alt="gravatar image" ) [1] => Array ( [0] => src [1] => alt ) [2] => Array ( [0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" [1] => "gravatar image" ) ) [..] ) ) ``` Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using [ob\_start](http://fr2.php.net/manual/fr/function.ob-start.php) and loading / saving from a text file. How does this stuff work ? -------------------------- First, we use [preg\_ match\_ all](http://fr2.php.net/manual/fr/function.preg-match-all.php), a function that gets every string matching the pattern and ouput it in it's third parameter. The regexps : ``` <img[^>]+> ``` We apply it on all html web pages. It can be read as *every string that starts with "`<img`", contains non ">" char and ends with a >*. ``` (alt|title|src)=("[^"]*") ``` We apply it successively on each img tag. It can be read as *every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ()*. Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this [online regexp tester](http://regex.larsolavtorvik.com/). EDIT : answer to the first comment. It's true that I did not think about the (hopefully few) people using single quotes. Well, if you use only ', just replace all the " by '. If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].
138,318
<p>here is my directory structure.</p> <p>/user/a /user/b /user/b</p> <p>inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification.</p> <p>now, on my shell, im on my /user/ directory and i try to do </p> <pre><code> javac */person.java </code></pre> <p>the shell returns the following error,</p> <p>person.java:14: duplicate class: person</p> <p>Is there anything to resolve this?</p>
[ { "answer_id": 138329, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 4, "selected": true, "text": "<p>I think the problem here might be, that javac tries to compile everything in one go, which naturally results in duplicated class definitions. </p>\n\n<p>A simple way to resolve this would be </p>\n\n<p><code>find . -name '*.java' -exec javac {} \\;</code></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Or to be more precise <code>find . -name 'person.java' -maxdepth 2 -exec javac {} \\;</code> </p>\n" }, { "answer_id": 138354, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "<p>I would go for the small shell script:</p>\n\n<pre><code>for f in */person.java; do\n javac $file\ndone\n</code></pre>\n\n<p>First line find all the files person.java in a sub-directory, second line compile the file.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ]
here is my directory structure. /user/a /user/b /user/b inside folder a,b,c there is a file person.java (it is the Same file, just a one line modification. now, on my shell, im on my /user/ directory and i try to do ``` javac */person.java ``` the shell returns the following error, person.java:14: duplicate class: person Is there anything to resolve this?
I think the problem here might be, that javac tries to compile everything in one go, which naturally results in duplicated class definitions. A simple way to resolve this would be `find . -name '*.java' -exec javac {} \;` **Edit:** Or to be more precise `find . -name 'person.java' -maxdepth 2 -exec javac {} \;`
138,321
<p>I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?</p> <p>(I'm on a Windows system, but have Cygwin installed.)</p>
[ { "answer_id": 138325, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 2, "selected": false, "text": "<p>You have to use the commandline. The Context menu in Explorer doesnt do this recursively!</p>\n\n<pre><code>clearfsimport –recurse /usr/src/projectx /vobs/projectx/src\n</code></pre>\n" }, { "answer_id": 138397, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 2, "selected": false, "text": "<p>Heres a script to do it\nAnd tips to integrate the script from Explorer</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/rational/library/4687.html\" rel=\"nofollow noreferrer\">http://www.ibm.com/developerworks/rational/library/4687.html</a></p>\n" }, { "answer_id": 144310, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "<p>I would rather go with the clearfsimport script, better equipped to import multiple times the same set of files, and automatically:</p>\n\n<ul>\n<li>add new files,</li>\n<li>make new version of existing files previously imported (but modified in the source set of files re-imported)</li>\n<li>remove files already imported but no longer present in the source set of files.</li>\n<li>make a clear log of all operations made during the import process.</li>\n</ul>\n\n<p>So if your 'zip-file delivery needs to be updated on a regularly basis, clearfsimport is the way to go, but with the following options:</p>\n\n<pre><code>clearfsimport -preview -rec -nset c:\\sourceDir\\* m:\\MyView\\MyVob\\MyDestinationDirectory\n</code></pre>\n\n<p>Note the :</p>\n\n<ul>\n<li>-preview option: it will allow to check <em>what would happen</em> without actually doing anything.</li>\n<li>'*' used only in Windows environment, in order to import the content of a directory</li>\n<li>-nset option.</li>\n</ul>\n\n<p>From <a href=\"http://www.cmcrossroads.com/cgi-bin/cmwiki/view/CM/ClearFsImport\" rel=\"noreferrer\">CMWiki</a>, about that 'nset' option:</p>\n\n<blockquote>\n <p>By default, clearfsimport is meant to be used by the vob owner or a privileged user, but users often overlook the -nsetevent option, with which it may be used by any user.<br>\n This option drives clearfsimport not to set the time stamps of elements to this of the source file object outside the vob (which requires privileged access).<br>\n There is a minor non-obvious side-effect with this: once a version will have been created with a current time stamp, even the vob owner will not be able to import on top of it a version with an older (as it would be) time stamp, without this -nsetevent option. I.e. once you use this option, normal or privileged user, you are more or less bound to use it in the continuation. </p>\n</blockquote>\n" }, { "answer_id": 147899, "author": "Markus Schnell", "author_id": 20668, "author_profile": "https://Stackoverflow.com/users/20668", "pm_score": 5, "selected": false, "text": "<p>Here is one other way I found by using the Windows Explorer:</p>\n\n<ol>\n<li>Select <code>Search...</code> from the context menu on the target directory.</li>\n<li>Search for <code>*</code>.</li>\n<li>Select all (<code>Ctrl-A</code>) files/directories in the result list.</li>\n<li>Select <code>ClearCase</code> > <code>Add to source control...</code> from the context menu on an item in the result list.</li>\n</ol>\n\n<p>There you go ...</p>\n" }, { "answer_id": 352739, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can also add this command to your context menu with a small script...</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/rational/library/4687.html\" rel=\"nofollow noreferrer\">Ten best Triggers</a></p>\n\n<p><strong>edit</strong>: oh, sorry. didn't saw that this was already suggested...</p>\n" }, { "answer_id": 2712944, "author": "GP.", "author_id": 325919, "author_profile": "https://Stackoverflow.com/users/325919", "pm_score": 0, "selected": false, "text": "<p>I agree,\nfind+select+add-to-source-control from Windows explorer is not a good option if the number of files to be version controlled is huge. As already mentioned above, explorer.exe crashes if we try to add a large number of files.</p>\n\n<p>clearfsimport is the best and the most hassle free utility for this task.</p>\n\n<p>-GP</p>\n" }, { "answer_id": 4091968, "author": "rudeboy", "author_id": 496519, "author_profile": "https://Stackoverflow.com/users/496519", "pm_score": 1, "selected": false, "text": "<p>you can get a fix at</p>\n\n<p><a href=\"http://www-01.ibm.com/support/docview.wss?ratlid=cctocbody&amp;rs=984&amp;uid=swg21117629\" rel=\"nofollow\">http://www-01.ibm.com/support/docview.wss?ratlid=cctocbody&amp;rs=984&amp;uid=swg21117629</a></p>\n" }, { "answer_id": 8517904, "author": "PrasadB", "author_id": 1049657, "author_profile": "https://Stackoverflow.com/users/1049657", "pm_score": 2, "selected": false, "text": "<p>Had a similar requirement to add a directory recursively to ClearCase. Since I did not have access to clearfsimport tool nor do I have ClearCase integrated with Windows Explorer, found an easy solution within ClearCase GUI.</p>\n\n<p>1) Add the root directory using \"Add to Source Control\" menu option.\n2) Click on this directory and then use \"ClearCase Search\" to search for all Private Files in this directory. \n3) Select all from the Search Results and \"Add to Source Control\"</p>\n\n<p>There you go ! The entire directory is recursively added from within ClearCase GUI</p>\n" }, { "answer_id": 17305293, "author": "kevin zamora", "author_id": 2521386, "author_profile": "https://Stackoverflow.com/users/2521386", "pm_score": 3, "selected": false, "text": "<p>ClearTeam Explorer, version 8 (maybe earlier as well), has recursive add of subdirectories/files when you select \"Add to Source Control\". When the \"Add to Source Control\" dialog box appears, check the \"Include descendant artifacts of the selected directories\" checkbox and uncheck the \"Checkout descendant files only, do not checkout descendant directories\" checkbox.</p>\n" }, { "answer_id": 36550173, "author": "Amit Kumar", "author_id": 2123715, "author_profile": "https://Stackoverflow.com/users/2123715", "pm_score": 3, "selected": false, "text": "<p>Since I did not have access to clearfsimport , I added the files/directories in a two step process:</p>\n\n<p>1.) <code>find . ! -path . -type d | xargs cleartool mkelem -mkpath -nc</code></p>\n\n<p>This will create nodes for all new directories recursively</p>\n\n<p>2.) <code>find ./ -type f | xargs cleartool mkelem -nc</code></p>\n\n<p>This will create nodes for all new files recursively</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668/" ]
I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree? (I'm on a Windows system, but have Cygwin installed.)
I would rather go with the clearfsimport script, better equipped to import multiple times the same set of files, and automatically: * add new files, * make new version of existing files previously imported (but modified in the source set of files re-imported) * remove files already imported but no longer present in the source set of files. * make a clear log of all operations made during the import process. So if your 'zip-file delivery needs to be updated on a regularly basis, clearfsimport is the way to go, but with the following options: ``` clearfsimport -preview -rec -nset c:\sourceDir\* m:\MyView\MyVob\MyDestinationDirectory ``` Note the : * -preview option: it will allow to check *what would happen* without actually doing anything. * '\*' used only in Windows environment, in order to import the content of a directory * -nset option. From [CMWiki](http://www.cmcrossroads.com/cgi-bin/cmwiki/view/CM/ClearFsImport), about that 'nset' option: > > By default, clearfsimport is meant to be used by the vob owner or a privileged user, but users often overlook the -nsetevent option, with which it may be used by any user. > > This option drives clearfsimport not to set the time stamps of elements to this of the source file object outside the vob (which requires privileged access). > > There is a minor non-obvious side-effect with this: once a version will have been created with a current time stamp, even the vob owner will not be able to import on top of it a version with an older (as it would be) time stamp, without this -nsetevent option. I.e. once you use this option, normal or privileged user, you are more or less bound to use it in the continuation. > > >
138,353
<p>In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?</p> <p>For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class.</p> <p>However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel.</p> <p>I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience.</p> <pre><code> class Job(wiz.WizardPageSimple): """Character's job class.""" def __init__(self, parent, title, attribs): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) self.charAttribs = attribs #---Create widgets self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"] box1_title = wx.StaticBox( self, -1, "" ) box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL ) grid1 = wx.BoxSizer(wx.VERTICAL) for item in self.Job_list: radio = wx.RadioButton(self, -1, item) grid1.Add(radio) ##Debugging self.btn = wx.Button(self, -1, "click") self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn) #---Place widgets self.sizer.Add(self.Job_intro) self.sizer.Add(self.btn) box1.Add(grid1) self.sizer.Add(box1) def eligibleJob(self, event): """Determine which Jobs a character is eligible for.""" if self.charAttribs.intelligence &gt;= 12: skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"] for skill in skillList: self.Job_list.append(skill) print self.Job_list ##Debugging #return self.Job_list </code></pre>
[ { "answer_id": 138479, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 0, "selected": false, "text": "<p>Two possible solutions</p>\n\n<ol>\n<li>Rebuild the sizer with the radio widgets each time you have to make a change</li>\n<li>Hold the radio button widgets in a list, and call SetLabel each time you have to change their labels.</li>\n</ol>\n" }, { "answer_id": 139009, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 2, "selected": true, "text": "<p>To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call:</p>\n\n<pre><code>def addNewSkills(self, newSkillList):\n '''newSkillList is a list of skill names you want to add'''\n for skillName in newSkillList:\n newRadioButton = wx.RadioButton(self, -1, skillName)\n self.grid1.Add(newRadioButton) # appears in top-left corner of the panel\n self.Layout() # all newly added radio buttons appear where they should be\n self.Fit() # if you need to resize the panel to fit new items, this will help\n</code></pre>\n\n<p>where <code>self.grid1</code> is the sizer you keep all your radio buttons on.</p>\n" }, { "answer_id": 145580, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 0, "selected": false, "text": "<p>I was able to fix it by using the info DzinX provided, with some modification.</p>\n\n<p>It appears that posting the radio buttons box first \"locked in\" the box to the sizer. If I tried to add a new box, I would get an error message stating that I was trying to add the widget to the same sizer twice.</p>\n\n<p>By simply removing the radio buttons initially and having the user click a button to call a method, I could simply add a the list of radio buttons without a problem.</p>\n\n<p>Additionally, by having the user click a button, I did not run into errors of \"class Foo has no attribute 'bar'\". Apparently, when the wizard initalizes, the attributes aren't available to the rest of the wizard pages. I had thought the wizard pages were dynamically created with each click of \"Next\" but they are all created at the same time.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later? For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like to dynamically change the list based on variables from another class. However, once the list is placed in the sizer, it's effectively "locked"; I can't just modify the list and have the changes appear. If I try re-adding the list to the sizer, it just gets put in the top left corner of the panel. I'm sure I could hide the original list and manually place the new list in the same position but that feels like a kludge. I'm sure I'm making this harder than it is. I'm probably using the wrong widgets for this, much less the wrong approach, but I'm building this as a learning experience. ``` class Job(wiz.WizardPageSimple): """Character's job class.""" def __init__(self, parent, title, attribs): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) self.charAttribs = attribs #---Create widgets self.Job_list = ["Aircraft Mechanic", "Vehicle Mechanic", "Electronics Specialist"] box1_title = wx.StaticBox( self, -1, "" ) box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL ) grid1 = wx.BoxSizer(wx.VERTICAL) for item in self.Job_list: radio = wx.RadioButton(self, -1, item) grid1.Add(radio) ##Debugging self.btn = wx.Button(self, -1, "click") self.Bind(wx.EVT_BUTTON, self.eligibleJob, self.btn) #---Place widgets self.sizer.Add(self.Job_intro) self.sizer.Add(self.btn) box1.Add(grid1) self.sizer.Add(box1) def eligibleJob(self, event): """Determine which Jobs a character is eligible for.""" if self.charAttribs.intelligence >= 12: skillList = ["Analyst", "Interrogator", "Fire Specialist", "Aircraft Pilot"] for skill in skillList: self.Job_list.append(skill) print self.Job_list ##Debugging #return self.Job_list ```
To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call: ``` def addNewSkills(self, newSkillList): '''newSkillList is a list of skill names you want to add''' for skillName in newSkillList: newRadioButton = wx.RadioButton(self, -1, skillName) self.grid1.Add(newRadioButton) # appears in top-left corner of the panel self.Layout() # all newly added radio buttons appear where they should be self.Fit() # if you need to resize the panel to fit new items, this will help ``` where `self.grid1` is the sizer you keep all your radio buttons on.
138,355
<p>I have a third party .NET Assembly and a large Java application. I need to call mothods provided by the .NET class library from the Java application. The assembly is not COM-enabled. I have searched the net and so far i have the following:</p> <p>C# code (cslib.cs):</p> <pre><code>using System; namespace CSLib { public class CSClass { public static void SayHi() { System.Console.WriteLine("Hi"); } } } </code></pre> <p>compiled with (using .net 3.5, but the same happens when 2.0 is used):</p> <pre><code>csc /target:library cslib.cs </code></pre> <p>C++ code (clib.cpp):</p> <pre><code>#include &lt;jni.h&gt; #using &lt;CSLib.dll&gt; using namespace CSLib; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { CSLib::CSClass::SayHi(); } </code></pre> <p>compiled with (using VC 2008 tools, but the same happens when 2003 tools are used):</p> <pre><code>cl /clr /LD clib.cpp mt -manifest clib.dll.manifest -outputresource:clib.dll;2 </code></pre> <p>Java code (CallCS.java):</p> <pre><code>class CallCS { static { System.loadLibrary("clib"); } private static native void callCS(); public static void main(String[] args) { callCS(); } } </code></pre> <p>When I try to run the java class, the Java VM crashes while invoking the method (it is able to load the library):</p> <pre> # # An unexpected error has been detected by Java Runtime Environment: # # Internal Error (0xe0434f4d), pid=3144, tid=3484 # # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86) # Problematic frame: # C [kernel32.dll+0x22366] # ... Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j CallCS.callCS()V+0 j CallCS.main([Ljava/lang/String;)V+0 v ~StubRoutines::call_stub </pre> <p>However, if I create a plain cpp application that loads clib.dll and calls the exported function Java_CallCS_callCS, everything is OK. I have tried this on both x86 and x64 environments and the result is the same. I have not tried other versions of Java, but I need the code to run on 1.5.0.</p> <p>Moreover, if I modify clib.cpp to call only System methods everything works fine even from Java:</p> <pre><code>#include &lt;jni.h&gt; #using &lt;mscorlib.dll&gt; using namespace System; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { System::Console::WriteLine("It works"); } </code></pre> <p>To wrap up:</p> <ol> <li>I am ABLE to call System methods from Java -> clib.dll -> mscorlib.dll</li> <li>I am ABLE to call any methods from CPPApp -> clib.dll -> cslib.dll</li> <li>I am UNABLE to call any methods from Java -> clib.dll -> cslib.dll</li> </ol> <p>I am aware of a workaround that uses 1. above - I can use reflection to load the assmebly and invoke desired methods using only System calls, but the code gets messy and I am hoping for a better solution. </p> <p>I know about dotnetfromjava project, which uses the reflection method, but prefer not to add more complexity than needed. I'll use something like this if there is no other way, however.</p> <p>I have looked at ikvm.net also, but my understanding is that it uses its own JVM (written in C#) to do the magic. However, running the entire Java application under its VM is no option for me.</p> <p>Thanks.</p>
[ { "answer_id": 138359, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 2, "selected": false, "text": "<p>Have you looked at ikvm.NET, which allows calls between .NET and Java code?</p>\n" }, { "answer_id": 138763, "author": "Kcats", "author_id": 22602, "author_profile": "https://Stackoverflow.com/users/22602", "pm_score": 4, "selected": true, "text": "<p>OK, the mystery is solved. </p>\n\n<p>The JVM crash is caused by unhandled System.IO.FileNotFoundException. The exception is thrown because the .NET assembly is searched in the folder where the calling exe file resides. </p>\n\n<ol>\n<li>The mscorlib.dll is in the Global Assembly Cache, so it works. </li>\n<li>The CPP application exe is in the same folder as the assembly, so it works also. </li>\n<li>The cslib.dll assembly is NEITHER in the folder of java.exe, NOR in the GAC, so it doesn't work.</li>\n</ol>\n\n<p>It seems my only option is to install the .NET assembly in GAC (the third-party dll does have a strong name). </p>\n" }, { "answer_id": 1655112, "author": "user200245", "author_id": 200245, "author_profile": "https://Stackoverflow.com/users/200245", "pm_score": 2, "selected": false, "text": "<p>Look at <a href=\"https://github.com/jni4net/jni4net\" rel=\"nofollow noreferrer\">jni4net</a>, it will do the hard work for you.</p>\n" }, { "answer_id": 17556542, "author": "dusselduck22", "author_id": 2565905, "author_profile": "https://Stackoverflow.com/users/2565905", "pm_score": 0, "selected": false, "text": "<p>I was so glad to find this article since I got stuck and had exactly that problem.\nI want to contribute some code, which helps to overcome this problem.\nIn your Java constructor call the init method, which adds the resolve event.\nMy experience it is necessary to call init NOT just before the call into your library in c++ code, since due to timing problems it may crash nonetheless.\nI've put the init call into my java class constructor of mapping the JNI calls, which works great.</p>\n\n<pre><code> //C# code\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Security.Permissions;\nusing System.Runtime.InteropServices;\n\nnamespace JNIBridge\n{\n public class Temperature\n {\n\n [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution)]\n [ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]\n [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]\n\n public static double toFahrenheit(double value)\n {\n return (value * 9) / 5 + 32;\n }\n\n [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution)]\n [ReflectionPermission(SecurityAction.Assert, Unrestricted = true)]\n [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]\n\n public static double toCelsius(double value)\n {\n return (value - 32) * 5 / 9; \n }\n\n\n }\n}\n</code></pre>\n\n<p>C++ Code</p>\n\n<pre><code> // C++ Code\n\n#include \"stdafx.h\"\n\n#include \"JNIMapper.h\"\n#include \"DotNet.h\"\n#include \"stdio.h\"\n#include \"stdlib.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/*\n * Class: DotNet\n * Method: toFahrenheit\n * Signature: (D)D\n */\n\nstatic bool initialized = false;\nusing namespace System;\nusing namespace System::Reflection;\n\n/*** \n This is procedure is always needed when the .NET dll's arent in the actual directory of the calling exe!!!\n It loads the needed assembly from a predefined path, if found in the directory and returns the assembly.\n*/\n\nAssembly ^OnAssemblyResolve(Object ^obj, ResolveEventArgs ^args)\n{\n //System::Console::WriteLine(\"In OnAssemblyResolve\");\n#ifdef _DEBUG\n /// Change to your .NET DLL paths here\n String ^path = gcnew String(\"d:\\\\WORK\\\\JNIBridge\\\\x64\\\\Debug\");\n#else\n String ^path = gcnew String(_T(\"d:\\\\WORK\\\\JNIBridge\\\\x64\\\\Release\"));\n#endif\n array&lt;String^&gt;^ assemblies =\n System::IO::Directory::GetFiles(path, \"*.dll\");\n for (long ii = 0; ii &lt; assemblies-&gt;Length; ii++) {\n AssemblyName ^name = AssemblyName::GetAssemblyName(assemblies[ii]);\n if (AssemblyName::ReferenceMatchesDefinition(gcnew AssemblyName(args-&gt;Name), name)) {\n // System::Console::WriteLine(\"Try to resolve \"+ name);\n Assembly ^a = Assembly::Load(name);\n //System::Console::WriteLine(\"Resolved \"+ name);\n return a;\n }\n }\n return nullptr;\n}\n\n/**\n This procedure adds the Assembly resolve event handler\n*/\nvoid AddResolveEvent()\n{\n AppDomain::CurrentDomain-&gt;AssemblyResolve +=\n gcnew ResolveEventHandler(OnAssemblyResolve);\n}\n/*\n * Class: DotNet\n * Method: init\n * Signature: ()Z\n */\nJNIEXPORT jboolean JNICALL Java_DotNet_init\n (JNIEnv *, jobject)\n\n{\n printf(\"In init\\n\"); \n AddResolveEvent(); \n printf(\"init - done.\\n\"); \n return true;\n\n}\n\n/*\n * Class: DotNet\n * Method: toFahrenheit\n * Signature: (D)D\n */\n\nJNIEXPORT jdouble JNICALL Java_DotNet_toFahrenheit\n (JNIEnv * je, jobject jo, jdouble value)\n{\n printf(\"In Java_DotNet_toFahrenheit\\n\"); \n\n double result = 47;\n\n try{ \n result = JNIBridge::Temperature::toFahrenheit(value);\n } catch (...){\n printf(\"Error caught\");\n }\n return result;\n}\n\n/*\n * Class: DotNet\n * Method: toCelsius\n * Signature: (D)D\n */\nJNIEXPORT jdouble JNICALL Java_DotNet_toCelsius\n (JNIEnv * je, jobject jo , jdouble value){\n\n printf(\"In Java_DotNet_toCelsius\\n\");\n\n double result = 11;\n\n try{\n\n result = JNIBridge::Temperature::toCelsius(value);\n } catch (...){\n printf(\"Error caught\");\n }\n\n return result;\n}\n\n\n#ifdef __cplusplus\n\n}\n</code></pre>\n\n<p>Java code</p>\n\n<pre><code> /***\n ** Java class file\n **/\npublic class DotNet { \n public native double toFahrenheit (double d);\n public native double toCelsius (double d);\n public native boolean init();\n\n static {\n try{ \n System.loadLibrary(\"JNIMapper\");\n } catch(Exception ex){\n ex.printStackTrace();\n }\n } \n\n public DotNet(){\n init();\n }\n\n public double fahrenheit (double v) {\n return toFahrenheit(v);\n }\n\n public double celsius (double v) {\n return toCelsius(v);\n }\n\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22602/" ]
I have a third party .NET Assembly and a large Java application. I need to call mothods provided by the .NET class library from the Java application. The assembly is not COM-enabled. I have searched the net and so far i have the following: C# code (cslib.cs): ``` using System; namespace CSLib { public class CSClass { public static void SayHi() { System.Console.WriteLine("Hi"); } } } ``` compiled with (using .net 3.5, but the same happens when 2.0 is used): ``` csc /target:library cslib.cs ``` C++ code (clib.cpp): ``` #include <jni.h> #using <CSLib.dll> using namespace CSLib; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { CSLib::CSClass::SayHi(); } ``` compiled with (using VC 2008 tools, but the same happens when 2003 tools are used): ``` cl /clr /LD clib.cpp mt -manifest clib.dll.manifest -outputresource:clib.dll;2 ``` Java code (CallCS.java): ``` class CallCS { static { System.loadLibrary("clib"); } private static native void callCS(); public static void main(String[] args) { callCS(); } } ``` When I try to run the java class, the Java VM crashes while invoking the method (it is able to load the library): ``` # # An unexpected error has been detected by Java Runtime Environment: # # Internal Error (0xe0434f4d), pid=3144, tid=3484 # # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86) # Problematic frame: # C [kernel32.dll+0x22366] # ... Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j CallCS.callCS()V+0 j CallCS.main([Ljava/lang/String;)V+0 v ~StubRoutines::call_stub ``` However, if I create a plain cpp application that loads clib.dll and calls the exported function Java\_CallCS\_callCS, everything is OK. I have tried this on both x86 and x64 environments and the result is the same. I have not tried other versions of Java, but I need the code to run on 1.5.0. Moreover, if I modify clib.cpp to call only System methods everything works fine even from Java: ``` #include <jni.h> #using <mscorlib.dll> using namespace System; extern "C" _declspec(dllexport) void Java_CallCS_callCS(JNIEnv* env, jclass cls) { System::Console::WriteLine("It works"); } ``` To wrap up: 1. I am ABLE to call System methods from Java -> clib.dll -> mscorlib.dll 2. I am ABLE to call any methods from CPPApp -> clib.dll -> cslib.dll 3. I am UNABLE to call any methods from Java -> clib.dll -> cslib.dll I am aware of a workaround that uses 1. above - I can use reflection to load the assmebly and invoke desired methods using only System calls, but the code gets messy and I am hoping for a better solution. I know about dotnetfromjava project, which uses the reflection method, but prefer not to add more complexity than needed. I'll use something like this if there is no other way, however. I have looked at ikvm.net also, but my understanding is that it uses its own JVM (written in C#) to do the magic. However, running the entire Java application under its VM is no option for me. Thanks.
OK, the mystery is solved. The JVM crash is caused by unhandled System.IO.FileNotFoundException. The exception is thrown because the .NET assembly is searched in the folder where the calling exe file resides. 1. The mscorlib.dll is in the Global Assembly Cache, so it works. 2. The CPP application exe is in the same folder as the assembly, so it works also. 3. The cslib.dll assembly is NEITHER in the folder of java.exe, NOR in the GAC, so it doesn't work. It seems my only option is to install the .NET assembly in GAC (the third-party dll does have a strong name).
138,371
<p>What are (if any)the implied assumptions or restrictions and the differences of designing like:</p> <p>A) this:</p> <pre><code>class SampleClass1 { IWorker workerA; IWorker workerB; void setWorkerA(IWorker w); void setWorkerB(IWorker w); WorkResult doWork(); } </code></pre> <p>B) versus this:</p> <pre><code>class SampleClass2 { WorkResult doWork(IWorker workerA, IWorker workerB); } </code></pre> <p>I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.</p> <p>Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.</p>
[ { "answer_id": 138376, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>Another Option:</p>\n\n<p>IWorker class:</p>\n\n<p>static WorkResult doWork(Iworker a, Iworker b);</p>\n" }, { "answer_id": 138386, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>If more than one method depends on IWorker a and IWorker b, I say do sample A.</p>\n\n<p>If only doWork() uses both IWorker a and IWorker b, then do sample B.</p>\n\n<p>Also, what is the real purpose of your SampleClass? doWork looks a bit like a utility method mroe than anything else.</p>\n" }, { "answer_id": 138399, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 1, "selected": false, "text": "<p>A) is a bad design because it allows the object to be defective (one or both of the worker classes might not have been set). </p>\n\n<p>B) can be good. Make it static though if you do not depend on the internal state of SampleClass2</p>\n" }, { "answer_id": 138402, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>IMO 2nd approach looks better, it requires caller to use less code to perform a task. 2nd approach is less error prone, caller don't need to worry that object might be not initialized completely.</p>\n" }, { "answer_id": 138403, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>How about instead defining a <code>WorkDelegate</code> (or alternatively an interface having a single <code>doWork</code> method without argument) that simply returns a <code>WorkResult</code> and letting individual classes decide how they implement it? This way, you don't confine yourself to premature decisions.</p>\n" }, { "answer_id": 138410, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 3, "selected": false, "text": "<p><strong>SampleClass1</strong></p>\n\n<ul>\n<li>I may need to maintain state of the workers between doWork</li>\n<li>I might need the capability to set Workers individually. (doWork with 1 and 2, then with 2 and 3)</li>\n<li>I want to maintain the workers because it might be expected to run doWork multiple times on the same workers.</li>\n<li>I'm not a utility class. An instance of me is important.</li>\n</ul>\n\n<p><strong>SampleClass2</strong></p>\n\n<ul>\n<li>Give me two workers and I will do work with them.</li>\n<li>I don't care who they are and I don't want to maintain them.</li>\n<li>It's someone else's job to maintain any pairing between workers.</li>\n<li>I may be more of a utility class. Maybe I can just be static.</li>\n</ul>\n" }, { "answer_id": 138450, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 4, "selected": true, "text": "<p>In option (A) you are creating what is known as a Function Object or Functor, this is a design pattern that is <a href=\"http://en.wikipedia.org/wiki/Function_object\" rel=\"noreferrer\">well documented</a>. </p>\n\n<p>The two main advantages are:</p>\n\n<ul>\n<li>The workers can be set by in one place and then the object used elsewhere</li>\n<li>The object can retain state between calls</li>\n</ul>\n\n<p>Also if you are using a dependency injection framework (Spring, Guice etc...) the functor can be automatically initialized and injected wherever required.</p>\n\n<p>Function objects are extensively used in libraries e.g. the C++ Standard Template Library</p>\n" }, { "answer_id": 138556, "author": "Andy Balaam", "author_id": 22610, "author_profile": "https://Stackoverflow.com/users/22610", "pm_score": 2, "selected": false, "text": "<p>Another option, a variant of case A, is the following:</p>\n\n<pre>\nclass SampleClass3\n{\n SampleClass3( IWorker workerA, IWorker workerB );\n WorkResult doWork();\n}\n</pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li><p>It's harder to make the object defective, since you are required to supply all the workers that are needed at construction time (in contrast to case A).</p></li>\n<li><p>You can still carry state inside SampleClass3 and/or one of the workers. (This is impossible in case B.)</p></li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>You have to have all your workers ready before you construct SampleClass3, instead of being able to provide them later. Of course, you could also provide the setters, so that they can be changed later.</li>\n</ul>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11906/" ]
What are (if any)the implied assumptions or restrictions and the differences of designing like: A) this: ``` class SampleClass1 { IWorker workerA; IWorker workerB; void setWorkerA(IWorker w); void setWorkerB(IWorker w); WorkResult doWork(); } ``` B) versus this: ``` class SampleClass2 { WorkResult doWork(IWorker workerA, IWorker workerB); } ``` I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called. Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.
In option (A) you are creating what is known as a Function Object or Functor, this is a design pattern that is [well documented](http://en.wikipedia.org/wiki/Function_object). The two main advantages are: * The workers can be set by in one place and then the object used elsewhere * The object can retain state between calls Also if you are using a dependency injection framework (Spring, Guice etc...) the functor can be automatically initialized and injected wherever required. Function objects are extensively used in libraries e.g. the C++ Standard Template Library
138,374
<p>I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.</p> <p>I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?</p> <pre><code>&lt;?php echo( "We'll email you as soon as this is done." ); header( "Connection: Close" ); // do some stuff that will take a while mail( '[email protected]', "okay I'm done", 'Yup, all done.' ); ?&gt; </code></pre>
[ { "answer_id": 138409, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 1, "selected": false, "text": "<p>You could try to do multithreading.</p>\n\n<p>you could whip up a script that makes a system call ( using <a href=\"http://my.php.net/manual/en/function.shell-exec.php\" rel=\"nofollow noreferrer\">shell_exec</a> ) that calls the php binary with the script to do your work as the parameter. But I don't think that is the most secure way. Maybe you can thighten stuff up by chrooting the php process and other stuff</p>\n\n<p>Alternatively, there's a class at phpclasses that do that <a href=\"http://www.phpclasses.org/browse/package/3953.html\" rel=\"nofollow noreferrer\">http://www.phpclasses.org/browse/package/3953.html</a>. But I don't know the specifics of the implementation</p>\n" }, { "answer_id": 138512, "author": "Steve Obbayi", "author_id": 11190, "author_profile": "https://Stackoverflow.com/users/11190", "pm_score": 0, "selected": false, "text": "<p>Your problem can be solved by doing some parallel programming in php. I asked a question about it a few weeks ago here: <a href=\"https://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications\">How can one use multi threading in PHP applications</a></p>\n\n<p>And got great answers. I liked one in particular very much. The writer made a reference <a href=\"http://phplens.com/phpeverywhere/?q=node/view/254\" rel=\"nofollow noreferrer\">to the <em>Easy Parallel Processing in PHP</em> (Sep 2008; by johnlim) tutorial</a> which can actually solve your problem very well as I have used it already to deal with a similar problem that came up a couple of days ago.</p>\n" }, { "answer_id": 138750, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 2, "selected": false, "text": "<p>Assuming you have a Linux server and root access, try this. It is the simplest solution I have found.</p>\n\n<p>Create a new directory for the following files and give it full permissions. (We can make it more secure later.)</p>\n\n<pre><code>mkdir test\nchmod -R 777 test\ncd test\n</code></pre>\n\n<p>Put this in a file called <code>bgping</code>.</p>\n\n<pre><code>echo starting bgping\nping -c 15 www.google.com &gt; dump.txt &amp;\necho ending bgping\n</code></pre>\n\n<p>Note the <code>&amp;</code>. The ping command will run in the background while the current process moves on to the echo command.\nIt will ping www.google.com 15 times, which will take about 15 seconds.</p>\n\n<p>Make it executable.</p>\n\n<pre><code>chmod 777 bgping\n</code></pre>\n\n<p>Put this in a file called <code>bgtest.php</code>.</p>\n\n<pre><code>&lt;?php\n\necho \"start bgtest.php\\n\";\nexec('./bgping', $output, $result).\"\\n\";\necho \"output:\".print_r($output,true).\"\\n\";\necho \"result:\".print_r($result,true).\"\\n\";\necho \"end bgtest.php\\n\";\n\n?&gt;\n</code></pre>\n\n<p>When you request bgtest.php in your browser, you should get the following response quickly, without waiting about\n15 seconds for the ping command to complete.</p>\n\n<pre><code>start bgtest.php\noutput:Array\n(\n [0] =&gt; starting bgping\n [1] =&gt; ending bgping\n)\n\nresult:0\nend bgtest.php\n</code></pre>\n\n<p>The ping command should now be running on the server. Instead of the ping command, you could run a PHP script:</p>\n\n<pre><code>php -n -f largejob.php &gt; dump.txt &amp;\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 139306, "author": "Morgan ARR Allen", "author_id": 22474, "author_profile": "https://Stackoverflow.com/users/22474", "pm_score": 0, "selected": false, "text": "<p>Ok, so basically the way jQuery does the XHR request, even the ob_flush method will not work because you are unable to run a function on each onreadystatechange. jQuery checks the state, then chooses the proper actions to take (complete,error,success,timeout). And although I was unable to find a reference, I recall hearing that this does not work with all XHR implementations.\nA method that I believe should work for you is a cross between the ob_flush and forever-frame polling.</p>\n\n<pre><code>&lt;?php\n function wrap($str)\n {\n return \"&lt;script&gt;{$str}&lt;/script&gt;\";\n };\n\n ob_start(); // begin buffering output\n echo wrap(\"console.log('test1');\");\n ob_flush(); // push current buffer\n flush(); // this flush actually pushed to the browser\n $t = time();\n while($t &gt; (time() - 3)) {} // wait 3 seconds\n echo wrap(\"console.log('test2');\");\n?&gt;\n\n&lt;html&gt;\n &lt;body&gt;\n &lt;iframe src=\"ob.php\"&gt;&lt;/iframe&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>And because the scripts are executed inline, as the buffers are flushed, you get execution. To make this useful, change the console.log to a callback method defined in you main script setup to receive data and act on it. Hope this helps. Cheers, Morgan.</p>\n" }, { "answer_id": 140883, "author": "Ole Helgesen", "author_id": 21892, "author_profile": "https://Stackoverflow.com/users/21892", "pm_score": 0, "selected": false, "text": "<p>An alternative solution is to add the job to a queue and make a cron script which checks for new jobs and runs them.</p>\n\n<p>I had to do it that way recently to circumvent limits imposed by a shared host - exec() et al was disabled for PHP run by the webserver but could run in a shell script.</p>\n" }, { "answer_id": 141026, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": 8, "selected": true, "text": "<p>The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script:</p>\n\n<ul>\n<li><a href=\"http://php.net/features.connection-handling\" rel=\"noreferrer\">Connection handling <sup><em>Docs</em></sup></a></li>\n</ul>\n\n<p>Supposedly it requires a bit more than sending a close header.</p>\n\n<hr>\n\n<p>OP then confirms: <em>yup, this did the trick:</em> <a href=\"http://php.net/manual/en/features.connection-handling.php#71172\" rel=\"noreferrer\">pointing to user-note #71172 (Nov 2006)</a> copied here:</p>\n\n<blockquote>\n <p>Closing the users browser connection whilst keeping your php script running has been an issue since [PHP] 4.1, when the behaviour of <code>register_shutdown_function()</code> was modified so that it would not automatically close the users connection.</p>\n \n <p>sts at mail dot xubion dot hu Posted the original solution:</p>\n\n<pre><code>&lt;?php\nheader(\"Connection: close\");\nob_start();\nphpinfo();\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush();\nflush();\nsleep(13);\nerror_log(\"do something in the background\");\n?&gt;\n</code></pre>\n \n <p>Which works fine until you substitute <code>phpinfo()</code> for <code>echo('text I want user to see');</code> in which case the headers are never sent!</p>\n \n <p>The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. Example:</p>\n\n<pre><code>&lt;?php\nob_end_clean();\nheader(\"Connection: close\");\nignore_user_abort(true); // just to be safe\nob_start();\necho('Text the user will see');\n$size = ob_get_length();\nheader(\"Content-Length: $size\");\nob_end_flush(); // Strange behaviour, will not work\nflush(); // Unless both are called !\n// Do processing here \nsleep(30);\necho('Text user will never see');\n?&gt;\n</code></pre>\n \n <p>Just spent 3 hours trying to figure this one out, hope it helps someone :)</p>\n \n <p>Tested in:</p>\n \n <ul>\n <li>IE 7.5730.11</li>\n <li>Mozilla Firefox 1.81</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<p>Later on in July 2010 in a <a href=\"https://stackoverflow.com/a/3270882/367456\">related answer</a> <a href=\"https://stackoverflow.com/users/347655/arctic-fire\"><em>Arctic Fire</em></a> then linked two further user-notes that were-follow-ups to the one above:</p>\n\n<ul>\n<li><a href=\"http://www.php.net/manual/en/features.connection-handling.php#89177\" rel=\"noreferrer\">Connection Handling user-note #89177 (Feb 2009)</a></li>\n<li><a href=\"http://www.php.net/manual/en/features.connection-handling.php#93441\" rel=\"noreferrer\">Connection Handling user-note #93441 (Sep 2009)</a></li>\n</ul>\n" }, { "answer_id": 1773248, "author": "Timbo White", "author_id": 215773, "author_profile": "https://Stackoverflow.com/users/215773", "pm_score": 6, "selected": false, "text": "<p>It's necessary to send these 2 headers:</p>\n<pre><code>Connection: close\nContent-Length: n (n = size of output in bytes )\n</code></pre>\n<p>Since you need know the size of your output, you'll need to buffer your output, then flush it to the browser:</p>\n<pre><code>// buffer all upcoming output\nob_start();\necho 'We\\'ll email you as soon as this is done.';\n\n// get the size of the output\n$size = ob_get_length();\n\n// send headers to tell the browser to close the connection\nheader('Content-Length: '.$size);\nheader('Connection: close');\n\n// flush all output\nob_end_flush();\nob_flush();\nflush();\n\n// if you're using sessions, this prevents subsequent requests\n// from hanging while the background process executes\nif (session_id()) {session_write_close();}\n\n/******** background process starts here ********/\n</code></pre>\n<p>Also, if your web server is using automatic gzip compression on the output (ie. Apache with mod_deflate), this won't work because actual size of the output is changed, and the Content-Length is no longer accurate. Disable gzip compression the particular script.</p>\n<p>For more details, visit <a href=\"http://www.zulius.com/how-to/close-browser-connection-continue-execution/\" rel=\"nofollow noreferrer\">http://www.zulius.com/how-to/close-browser-connection-continue-execution</a></p>\n" }, { "answer_id": 7120170, "author": "diyism", "author_id": 264181, "author_profile": "https://Stackoverflow.com/users/264181", "pm_score": 4, "selected": false, "text": "<p>Complete version:</p>\n\n<pre><code>ignore_user_abort(true);//avoid apache to kill the php running\nob_start();//start buffer output\n\necho \"show something to user\";\nsession_write_close();//close session file on server side to avoid blocking other requests\n\nheader(\"Content-Encoding: none\");//send header to avoid the browser side to take content as gzip format\nheader(\"Content-Length: \".ob_get_length());//send length header\nheader(\"Connection: close\");//or redirect to some url: header('Location: http://www.google.com');\nob_end_flush();flush();//really send content, can't change the order:1.ob buffer to normal buffer, 2.normal buffer to output\n\n//continue do something on server side\nob_start();\nsleep(5);//the user won't wait for the 5 seconds\necho 'for diyism';//user can't see this\nfile_put_contents('/tmp/process.log', ob_get_contents());\nob_end_clean();\n</code></pre>\n" }, { "answer_id": 10101623, "author": "Jorrit Schippers", "author_id": 261747, "author_profile": "https://Stackoverflow.com/users/261747", "pm_score": 5, "selected": false, "text": "<p>You can use Fast-CGI with PHP-FPM to use the <a href=\"http://php-fpm.org/wiki/Features#fastcgi_finish_request.28.29\" rel=\"noreferrer\"><code>fastcgi_end_request()</code> function</a>. In this way, you can continue to do some processing while the response has already been sent to the client.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/4236040/367456\">example of how to use fastcgi_finish_request() (Nov 2010)</a></li>\n</ul>\n\n<p>You find this in the PHP manual here: <a href=\"http://php.net/manual/install.fpm.php\" rel=\"noreferrer\">FastCGI Process Manager (FPM)</a>; But that function specifically is not further documented in the manual. Here the excerpt from the <a href=\"http://php-fpm.org/wiki/Main_Page\" rel=\"noreferrer\">PHP-FPM: PHP FastCGI Process Manager Wiki</a>:</p>\n\n<hr>\n\n<h2>fastcgi_finish_request()</h2>\n\n<p>Scope: php function</p>\n\n<p>Category: Optimization</p>\n\n<p>This feature allows you to speed up implementation of some php queries. Acceleration is possible when there are actions in the process of script execution that do not affect server response. For example, saving the session in memcached can occur after the page has been formed and passed to a web server. <code>fastcgi_finish_request()</code> is a php feature, that stops the response output. Web server immediately starts to transfer response \"slowly and sadly\" to the client, and php at the same time can do a lot of useful things in the context of a query, such as saving the session, converting the downloaded video, handling all kinds of statistics, etc.</p>\n\n<p><code>fastcgi_finish_request()</code> can invoke executing shutdown function.</p>\n\n<hr>\n\n<p><strong>Note:</strong> <code>fastcgi_finish_request()</code> has <a href=\"https://bugs.php.net/bug.php?id=68772\" rel=\"noreferrer\">a quirk</a> where calls to <code>flush</code>, <code>print</code>, or <code>echo</code> will terminate the script early.</p>\n\n<p>To avoid that issue, you can call <a href=\"https://www.php.net/manual/en/function.ignore-user-abort.php\" rel=\"noreferrer\"><code>ignore_user_abort(true)</code></a> right before or after the <code>fastcgi_finish_request</code> call:</p>\n\n<pre><code>ignore_user_abort(true);\nfastcgi_finish_request();\n</code></pre>\n" }, { "answer_id": 10465055, "author": "Nir O.", "author_id": 582821, "author_profile": "https://Stackoverflow.com/users/582821", "pm_score": 0, "selected": false, "text": "<p>If <code>flush()</code> function does not work. You must set next options in <strong><em>php.ini</em></strong> like:</p>\n\n<pre><code>output_buffering = Off \nzlib.output_compression = Off \n</code></pre>\n" }, { "answer_id": 14950738, "author": "Andrew Winter", "author_id": 206001, "author_profile": "https://Stackoverflow.com/users/206001", "pm_score": 2, "selected": false, "text": "<p>Here's a modification to Timbo's code that works with gzip compression.</p>\n\n<pre><code>// buffer all upcoming output\nif(!ob_start(\"ob_gzhandler\")){\n define('NO_GZ_BUFFER', true);\n ob_start();\n}\necho \"We'll email you as soon as this is done.\";\n\n//Flush here before getting content length if ob_gzhandler was used.\nif(!defined('NO_GZ_BUFFER')){\n ob_end_flush();\n}\n\n// get the size of the output\n$size = ob_get_length();\n\n// send headers to tell the browser to close the connection\nheader(\"Content-Length: $size\");\nheader('Connection: close');\n\n// flush all output\nob_end_flush();\nob_flush();\nflush();\n\n// if you're using sessions, this prevents subsequent requests\n// from hanging while the background process executes\nif (session_id()) session_write_close();\n\n/******** background process starts here ********/\n</code></pre>\n" }, { "answer_id": 21037399, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/141026/315024\">Joeri Sebrechts' answer</a> is close, but it destroys any existing content that may be buffered before you wish to disconnect. It doesn't call <code>ignore_user_abort</code> properly, allowing the script to terminate prematurely. <a href=\"https://stackoverflow.com/a/7120170/315024\">diyism's answer</a> is good but is not generically applicable. E.g. a person may have greater or fewer output buffers that that answer does not handle, so it may simply not work in your situation and you won't know why.</p>\n\n<p>This function allows you to disconnect any time (as long as headers have not been sent yet) and retains the content you've generated so far. The extra processing time is unlimited by default.</p>\n\n<pre><code>function disconnect_continue_processing($time_limit = null) {\n ignore_user_abort(true);\n session_write_close();\n set_time_limit((int) $time_limit);//defaults to no limit\n while (ob_get_level() &gt; 1) {//only keep the last buffer if nested\n ob_end_flush();\n }\n $last_buffer = ob_get_level();\n $length = $last_buffer ? ob_get_length() : 0;\n header(\"Content-Length: $length\");\n header('Connection: close');\n if ($last_buffer) {\n ob_end_flush();\n }\n flush();\n}\n</code></pre>\n\n<p>If you need extra memory, too, allocate it before calling this function.</p>\n" }, { "answer_id": 26892012, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 2, "selected": false, "text": "<p>I'm on a shared host and <code>fastcgi_finish_request</code> is setup to exit scripts completely. I don't like the <code>connection: close</code> solution either. Using it forces a separate connection for subsequent requests, costing additional server resources. I read the <code>Transfer-Encoding: cunked</code> <a href=\"http://en.wikipedia.org/wiki/Chunked_transfer_encoding\" rel=\"nofollow\">Wikipedia Article</a> and learned that <code>0\\r\\n\\r\\n</code> terminates a response. I haven't thoroughly tested this across browsers versions and devices, but it works on all 4 of my current browsers.</p>\n\n<pre><code>// Disable automatic compression\n// @ini_set('zlib.output_compression', 'Off');\n// @ini_set('output_buffering', 'Off');\n// @ini_set('output_handler', '');\n// @apache_setenv('no-gzip', 1);\n\n// Chunked Transfer-Encoding &amp; Gzip Content-Encoding\nfunction ob_chunked_gzhandler($buffer, $phase) {\n if (!headers_sent()) header('Transfer-Encoding: chunked');\n $buffer = ob_gzhandler($buffer, $phase);\n return dechex(strlen($buffer)).\"\\r\\n$buffer\\r\\n\";\n}\n\nob_start('ob_chunked_gzhandler');\n\n// First Chunk\necho \"Hello World\";\nob_flush();\n\n// Second Chunk\necho \", Grand World\";\nob_flush();\n\nob_end_clean();\n\n// Terminating Chunk\necho \"\\x30\\r\\n\\r\\n\";\nob_flush();\nflush();\n\n// Post Processing should not be displayed\nfor($i=0; $i&lt;10; $i++) {\n print(\"Post-Processing\");\n sleep(1);\n}\n</code></pre>\n" }, { "answer_id": 26996177, "author": "Tasos", "author_id": 1127070, "author_profile": "https://Stackoverflow.com/users/1127070", "pm_score": 1, "selected": false, "text": "<p><em>Note for mod_fcgid users (please, use at your own risk).</em></p>\n\n<h2>Quick Solution</h2>\n\n<p>The accepted answer of <a href=\"https://stackoverflow.com/users/20980/joeri-sebrechts\">Joeri Sebrechts</a> is indeed functional. However, if you use <em>mod_fcgid</em> you may find that this solution does not work on its own. In other words, when the <em>flush</em> function is called the connection to the client does not get closed.</p>\n\n<p>The <code>FcgidOutputBufferSize</code> configuration parameter of <em>mod_fcgid</em> may be to blame. I have found this tip in:</p>\n\n<ol>\n<li><a href=\"http://sourceforge.net/p/mod-fcgid/mailman/message/20924039/#msg20909317\" rel=\"nofollow\">this reply of Travers Carter</a> and</li>\n<li><a href=\"http://fitzroytuesday.blogspot.gr/2012/08/php-fcgid-and-flush.html\" rel=\"nofollow\">this blog post of Seumas Mackinnon</a>.</li>\n</ol>\n\n<p>After reading the above, you may come to the conclusion that a quick solution would be to add the line (see \"Example Virtual Host\" at the end):</p>\n\n<pre><code>FcgidOutputBufferSize 0\n</code></pre>\n\n<p>in either your Apache configuration file (e.g, httpd.conf), your FCGI configuration file (e.g, fcgid.conf) or in your virtual hosts file (e.g., httpd-vhosts.conf).</p>\n\n<blockquote>\n <p>In (1) above, a variable named \"OutputBufferSize\" is mentioned. This is the old name of the <code>FcgidOutputBufferSize</code> mentioned in (2) (see the <a href=\"https://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html#upgrade\" rel=\"nofollow\">upgrade notes in the Apache web page for mod_fcgid</a>).</p>\n</blockquote>\n\n<h2>Details &amp; A Second Solution</h2>\n\n<p>The above solution disables the buffering performed by <em>mod_fcgid</em> either for the whole server or for a specific virtual host. This might lead to a performance penalty for your web site. On the other hand, this may well not be the case since PHP performs buffering on its own.</p>\n\n<p>In case you do not wish to disable <em>mod_fcgid</em>'s buffering there is another solution... <strong>you can force this buffer to flush</strong>.</p>\n\n<p>The code below does just that by building on the solution proposed by Joeri Sebrechts:</p>\n\n<pre><code>&lt;?php\n ob_end_clean();\n header(\"Connection: close\");\n ignore_user_abort(true); // just to be safe\n ob_start();\n echo('Text the user will see');\n\n echo(str_repeat(' ', 65537)); // [+] Line added: Fill up mod_fcgi's buffer.\n\n $size = ob_get_length();\n header(\"Content-Length: $size\");\n ob_end_flush(); // Strange behaviour, will not work\n flush(); // Unless both are called !\n // Do processing here \n sleep(30);\n echo('Text user will never see');\n?&gt;\n</code></pre>\n\n<p>What the added line of code essentially does is fill up <em>mod_fcgi</em>'s buffer, thus forcing it to flush. The number \"65537\" was chosen because the default value of the <code>FcgidOutputBufferSize</code> variable is \"65536\", as mentioned in the <a href=\"https://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html#fcgidoutputbuffersize\" rel=\"nofollow\">Apache web page for the corresponding directive</a>. Hence, you may need to adjust this value accordingly if another value is set in your environment.</p>\n\n<h2>My Environment</h2>\n\n<ul>\n<li>WampServer 2.5</li>\n<li>Apache 2.4.9</li>\n<li>PHP 5.5.19 VC11, x86, Non Thread Safe</li>\n<li>mod_fcgid/2.3.9</li>\n<li>Windows 7 Professional x64</li>\n</ul>\n\n<h2>Example Virtual Host</h2>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n DocumentRoot \"d:/wamp/www/example\"\n ServerName example.local\n\n FcgidOutputBufferSize 0\n\n &lt;Directory \"d:/wamp/www/example\"&gt;\n Require all granted\n &lt;/Directory&gt;\n&lt;/VirtualHost&gt;\n</code></pre>\n" }, { "answer_id": 28299471, "author": "Williem", "author_id": 3091630, "author_profile": "https://Stackoverflow.com/users/3091630", "pm_score": 1, "selected": false, "text": "<p>this worked for me</p>\n\n<pre><code>//avoid apache to kill the php running\nignore_user_abort(true);\n//start buffer output\nob_start();\n\necho \"show something to user1\";\n//close session file on server side to avoid blocking other requests\nsession_write_close();\n\n//send length header\nheader(\"Content-Length: \".ob_get_length());\nheader(\"Connection: close\");\n//really send content, can't change the order:\n//1.ob buffer to normal buffer,\n//2.normal buffer to output\nob_end_flush();\nflush();\n//continue do something on server side\nob_start();\n//replace it with the background task\nsleep(20);\n</code></pre>\n" }, { "answer_id": 40041923, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 3, "selected": false, "text": "<p>A better solution is to fork a background process. It is fairly straight forward on unix/linux:</p>\n\n<pre><code>&lt;?php\necho \"We'll email you as soon as this is done.\";\nsystem(\"php somestuff.php [email protected] &gt;/dev/null &amp;\");\n?&gt;\n</code></pre>\n\n<p>You should look at this question for better examples: </p>\n\n<p><a href=\"https://stackoverflow.com/q/45953/87015\">PHP execute a background process</a></p>\n" }, { "answer_id": 43113409, "author": "FluorescentGreen5", "author_id": 3881189, "author_profile": "https://Stackoverflow.com/users/3881189", "pm_score": 2, "selected": false, "text": "<p>TL;DR Answer:</p>\n\n<pre><code>ignore_user_abort(true); //Safety measure so that the user doesn't stop the script too early.\n\n$content = 'Hello World!'; //The content that will be sent to the browser.\n\nheader('Content-Length: ' . strlen($content)); //The browser will close the connection when the size of the content reaches \"Content-Length\", in this case, immediately.\n\nob_start(); //Content past this point...\n\necho $content;\n\n//...will be sent to the browser (the output buffer gets flushed) when this code executes.\nob_end_flush();\nob_flush();\nflush();\n\nif(session_id())\n{\n session_write_close(); //Closes writing to the output buffer.\n}\n\n//Anything past this point will be ran without involving the browser.\n</code></pre>\n\n<p>Function Answer:</p>\n\n<pre><code>ignore_user_abort(true);\n\nfunction sendAndAbort($content)\n{\n header('Content-Length: ' . strlen($content));\n\n ob_start();\n\n echo $content;\n\n ob_end_flush();\n ob_flush();\n flush();\n}\n\nsendAndAbort('Hello World!');\n\n//Anything past this point will be ran without involving the browser.\n</code></pre>\n" }, { "answer_id": 43327373, "author": "Sudharshana S L Srihari", "author_id": 5232157, "author_profile": "https://Stackoverflow.com/users/5232157", "pm_score": 0, "selected": false, "text": "<p><strong>Latest Working Solution</strong></p>\n\n<pre><code> // client can see outputs if any\n ignore_user_abort(true);\n ob_start();\n echo \"success\";\n $buffer_size = ob_get_length();\n session_write_close();\n header(\"Content-Encoding: none\");\n header(\"Content-Length: $buffer_size\");\n header(\"Connection: close\");\n ob_end_flush();\n ob_flush();\n flush();\n\n sleep(2);\n ob_start();\n // client cannot see the result of code below\n</code></pre>\n" }, { "answer_id": 49208805, "author": "WhiteAngel", "author_id": 1291512, "author_profile": "https://Stackoverflow.com/users/1291512", "pm_score": 0, "selected": false, "text": "<p>After trying many different solutions from this thread (after none of them worked for me), I've found solution on official PHP.net page:</p>\n\n<pre><code>function sendResponse($response) {\n ob_end_clean();\n header(\"Connection: close\\r\\n\");\n header(\"Content-Encoding: none\\r\\n\");\n ignore_user_abort(true);\n ob_start();\n\n echo $response; // Actual response that will be sent to the user\n\n $size = ob_get_length();\n header(\"Content-Length: $size\");\n ob_end_flush();\n flush();\n if (ob_get_contents()) {\n ob_end_clean();\n }\n}\n</code></pre>\n" }, { "answer_id": 72672603, "author": "Teson", "author_id": 247245, "author_profile": "https://Stackoverflow.com/users/247245", "pm_score": 0, "selected": false, "text": "<p>Couldn't get any of the above to work with IIS but:</p>\n<p>With all its limitations, the built in PHP -S webserver comes to the rescue.</p>\n<p>Caller script (IIS)</p>\n<pre><code>//limit of length required!\n&lt;?php\n$s = file_get_contents('http://127.0.0.1:8080/test.php',false,null,0,10);\necho $s;\n</code></pre>\n<p>Worker script (built in webserber @ 8080 - beware single thread):</p>\n<pre><code>ob_end_clean();\nheader(&quot;Connection: close&quot;);\nignore_user_abort(true);\nob_start();\necho 'Text the user will see';\n$size = ob_get_length();\nheader(&quot;Content-Length: $size&quot;);\nob_end_flush(); // All output buffers must be flushed here\nflush(); // Force output to client\n// Do processing here \nsleep(5);\nfile_put_contents('ts.txt',date('H:i:s',time()));\n//echo('Text user will never see');\n</code></pre>\n<p>Ugly enough? :)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82944/" ]
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running. I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery? ``` <?php echo( "We'll email you as soon as this is done." ); header( "Connection: Close" ); // do some stuff that will take a while mail( '[email protected]', "okay I'm done", 'Yup, all done.' ); ?> ```
The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script: * [Connection handling *Docs*](http://php.net/features.connection-handling) Supposedly it requires a bit more than sending a close header. --- OP then confirms: *yup, this did the trick:* [pointing to user-note #71172 (Nov 2006)](http://php.net/manual/en/features.connection-handling.php#71172) copied here: > > Closing the users browser connection whilst keeping your php script running has been an issue since [PHP] 4.1, when the behaviour of `register_shutdown_function()` was modified so that it would not automatically close the users connection. > > > sts at mail dot xubion dot hu Posted the original solution: > > > > ``` > <?php > header("Connection: close"); > ob_start(); > phpinfo(); > $size = ob_get_length(); > header("Content-Length: $size"); > ob_end_flush(); > flush(); > sleep(13); > error_log("do something in the background"); > ?> > > ``` > > Which works fine until you substitute `phpinfo()` for `echo('text I want user to see');` in which case the headers are never sent! > > > The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. Example: > > > > ``` > <?php > ob_end_clean(); > header("Connection: close"); > ignore_user_abort(true); // just to be safe > ob_start(); > echo('Text the user will see'); > $size = ob_get_length(); > header("Content-Length: $size"); > ob_end_flush(); // Strange behaviour, will not work > flush(); // Unless both are called ! > // Do processing here > sleep(30); > echo('Text user will never see'); > ?> > > ``` > > Just spent 3 hours trying to figure this one out, hope it helps someone :) > > > Tested in: > > > * IE 7.5730.11 > * Mozilla Firefox 1.81 > > > --- Later on in July 2010 in a [related answer](https://stackoverflow.com/a/3270882/367456) [*Arctic Fire*](https://stackoverflow.com/users/347655/arctic-fire) then linked two further user-notes that were-follow-ups to the one above: * [Connection Handling user-note #89177 (Feb 2009)](http://www.php.net/manual/en/features.connection-handling.php#89177) * [Connection Handling user-note #93441 (Sep 2009)](http://www.php.net/manual/en/features.connection-handling.php#93441)
138,379
<p>What happens if I use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx" rel="nofollow noreferrer">SHGetFolderPath</a> api call in a 32 bit system with CSIDL_PROGRAM_FILESx86 folder id instead of the CSIDL_PROGRAM_FILES id?</p> <p>Theoretically CSIDL_PROGRAM_FILESx86 should map to <code>C:\program files (x86)</code> in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?</p>
[ { "answer_id": 138473, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 4, "selected": true, "text": "<p>The different scenarios are described in <a href=\"http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx\" rel=\"nofollow noreferrer\">this article on MSDN</a>.</p>\n<p>Scroll down to remarks, &quot;FOLDERID_ProgramFiles&quot;</p>\n<pre><code>The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation.\n\nThe following tables summarize the KNOWNFOLDERID use in those cases.\n\nFOLDERID_ProgramFiles\nOS Application KNOWNFOLDERID Default Path CSIDL Equivalent\n32 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files CSIDL_PROGRAM_FILES\n32 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files CSIDL_PROGRAM_FILESX86\n32 bit 32 bit FOLDERID_ProgramFilesX64 (undefined) Not applicable Not applicable\n64 bit 64 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files CSIDL_PROGRAM_FILES\n64 bit 64 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILESX86\n64 bit 64 bit FOLDERID_ProgramFilesX64 %SystemDrive%\\Program Files None\n64 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILES\n64 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\\Program Files (x86) CSIDL_PROGRAM_FILESX86\n64 bit 32 bit FOLDERID_ProgramFilesX64 %SystemDrive%\\Program Files None\n</code></pre>\n<p>Summary: It will point to %SystemDrive%\\Program Files</p>\n" }, { "answer_id": 6204863, "author": "Stlopus", "author_id": 779843, "author_profile": "https://Stackoverflow.com/users/779843", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>GetEnvironmentVariable(\"ProgramW6432\", szBuffer, nBufferSize);\n</code></pre>\n\n<p>YMMV</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14587/" ]
What happens if I use [SHGetFolderPath](http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx) api call in a 32 bit system with CSIDL\_PROGRAM\_FILESx86 folder id instead of the CSIDL\_PROGRAM\_FILES id? Theoretically CSIDL\_PROGRAM\_FILESx86 should map to `C:\program files (x86)` in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?
The different scenarios are described in [this article on MSDN](http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx). Scroll down to remarks, "FOLDERID\_ProgramFiles" ``` The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation. The following tables summarize the KNOWNFOLDERID use in those cases. FOLDERID_ProgramFiles OS Application KNOWNFOLDERID Default Path CSIDL Equivalent 32 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES 32 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files CSIDL_PROGRAM_FILESX86 32 bit 32 bit FOLDERID_ProgramFilesX64 (undefined) Not applicable Not applicable 64 bit 64 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES 64 bit 64 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86 64 bit 64 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None 64 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILES 64 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86 64 bit 32 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None ``` Summary: It will point to %SystemDrive%\Program Files
138,383
<p>Sometimes coloring a logfile or other gives a good overview when looking for <em>stuff</em> and <em>behaviors</em></p> <p>I just saw that grep have a coloring feature</p> <pre><code>grep -C 99999 --color &lt;regexp&gt; &lt;filename&gt; </code></pre> <p>What other methods are there?</p>
[ { "answer_id": 138390, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>For searching source code, I use <a href=\"http://petdance.com/ack/\" rel=\"noreferrer\">ack</a>. It's got a lot of options that make sense for searching code (such as automatically ignoring SCM directories).</p>\n" }, { "answer_id": 138401, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 2, "selected": false, "text": "<p>There are many programs that support coloring like <a href=\"http://joakimandersson.se/projects/colortail/\" rel=\"nofollow noreferrer\">Colortail</a></p>\n\n<p>Maybe this can be helpful too: <a href=\"http://freshmeat.net/projects/genericcolouriser/\" rel=\"nofollow noreferrer\">GenericColouriser</a></p>\n" }, { "answer_id": 138484, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 1, "selected": false, "text": "<p>We use <a href=\"http://www.baremetalsoft.com/baretail/\" rel=\"nofollow noreferrer\">baretail</a>, now if they added color to their <a href=\"http://www.baremetalsoft.com/baregrep/index.php\" rel=\"nofollow noreferrer\">baregrep</a>, that would be nice.</p>\n" }, { "answer_id": 138528, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 4, "selected": false, "text": "<p>Here is a snippet for a log coloring tool I sometimes use. </p>\n\n<p>Note that is only works against stdin/stdout and in a terminal supporting ANSI colors.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;regex.h&gt;\n\n#define MAX_LINE 4096\n\n#define RESET \"\\033[0m\"\n#define BLACK \"\\033[30m\" /* Black */\n#define RED \"\\033[31m\" /* Red */\n#define GREEN \"\\033[32m\" /* Green */\n#define YELLOW \"\\033[33m\" /* Yellow */\n#define BLUE \"\\033[34m\" /* Blue */\n#define MAGENTA \"\\033[35m\" /* Magenta */\n#define CYAN \"\\033[36m\" /* Cyan */\n#define WHITE \"\\033[37m\" /* White */\n#define BOLDBLACK \"\\033[1m\\033[30m\" /* Bold Black */\n#define BOLDRED \"\\033[1m\\033[31m\" /* Bold Red */\n#define BOLDGREEN \"\\033[1m\\033[32m\" /* Bold Green */\n#define BOLDYELLOW \"\\033[1m\\033[33m\" /* Bold Yellow */\n#define BOLDBLUE \"\\033[1m\\033[34m\" /* Bold Blue */\n#define BOLDMAGENTA \"\\033[1m\\033[35m\" /* Bold Magenta */\n#define BOLDCYAN \"\\033[1m\\033[36m\" /* Bold Cyan */\n#define BOLDWHITE \"\\033[1m\\033[37m\" /* Bold White */\n\nstatic int selected_color = 0;\nstatic char *colors[] = {\n \"-green\", GREEN,\n \"-black\", BLACK,\n \"-red\", RED,\n \"-yellow\", YELLOW,\n \"-blue\", BLUE,\n \"-magenta\", MAGENTA,\n \"-cyan\", CYAN,\n \"-white\", WHITE,\n \"-boldgreen\", BOLDGREEN,\n \"-boldblack\", BOLDBLACK,\n \"-boldred\", BOLDRED,\n \"-boldyellow\", BOLDYELLOW,\n \"-boldblue\", BOLDBLUE,\n \"-boldmagenta\", BOLDMAGENTA,\n \"-boldcyan\", BOLDCYAN,\n \"-boldwhite\", BOLDWHITE,\n NULL\n};\n\n/*----------------------------------------------------------------------*/\n\nint main(int argc, char *argv[]) {\n char buf[MAX_LINE];\n int has_re = 0;\n regex_t re;\n\n if (argc &gt; 1) {\n if (argc &gt; 2) {\n int idx = 0;\n while (colors[idx*2]) {\n if (!strcmp(colors[idx*2], argv[1])) {\n selected_color = idx;\n break;\n }\n idx++;\n }\n if (regcomp(&amp;re, argv[2], REG_EXTENDED | REG_NEWLINE)) {\n printf(\"regcomp() failed!\\n\");\n return -1;\n }\n } else if (regcomp(&amp;re, argv[1], REG_EXTENDED | REG_NEWLINE)) {\n printf(\"regcomp() failed!\\n\");\n return -1;\n }\n has_re = 1;\n } else {\n printf(\"Usage: %s [ -red | -blue | -cyan | -white | -black | \"\n \"-yellow | -magenta ] &lt;regexp&gt;\\n\", argv[0]);\n return -1; \n }\n\n while (fgets(buf, MAX_LINE, stdin) == buf) {\n char *bbuf = buf;\n while (1) {\n if (has_re) {\n regmatch_t match[10];\n if (regexec(&amp;re, bbuf, re.re_nsub + 1, match, 0)) {\n printf(\"%s\", bbuf);\n break;\n } else {\n int i, idx;\n for (i=idx=0; i&lt;1; i++) {\n if (match[0].rm_so &lt; 0) {\n break;\n } else {\n printf(\"%.*s\", \n (int)(match[i].rm_so-idx), \n bbuf+idx);\n printf( \"%s%.*s\" RESET, \n colors[selected_color*2+1],\n (int)(match[i].rm_eo-match[i].rm_so), \n bbuf+(int)match[i].rm_so);\n idx = match[i].rm_eo;\n bbuf += idx;\n }\n }\n }\n }\n fflush(stdout);\n }\n }\n\n if (has_re) {\n regfree(&amp;re);\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 50229165, "author": "merlin2011", "author_id": 391161, "author_profile": "https://Stackoverflow.com/users/391161", "pm_score": 1, "selected": false, "text": "<p>This is an older question, but in case anyone is still looking, I recently created <a href=\"https://github.com/hq6/colorize\" rel=\"nofollow noreferrer\"><code>colorize</code></a>, a tool which allows one to specify either fixed patterns or regular expressions to match with specific colors. It works out of the box with an intuitive syntax for specifying highlighting, and <code>docopt</code> as its only dependency.</p>\n\n<pre><code>colorize.py -f 'This is an interesting line=Blue' -f 'Different topic=Red' Input.log\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ]
Sometimes coloring a logfile or other gives a good overview when looking for *stuff* and *behaviors* I just saw that grep have a coloring feature ``` grep -C 99999 --color <regexp> <filename> ``` What other methods are there?
For searching source code, I use [ack](http://petdance.com/ack/). It's got a lot of options that make sense for searching code (such as automatically ignoring SCM directories).
138,412
<p>I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.</p> <p>I have a GridView in which the code in the ASP reference to it in the HTML is minimal:</p> <pre><code>&lt;asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True"&gt; &lt;/asp:GridView&gt; </code></pre> <p>In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example:</p> <p>I set up the columns...</p> <pre><code>BoundField column = new BoundField(); column.DataField = columnName; column.HeaderText = "Heading"; column.SortExpression = columnName; grid.Columns.Add(column); </code></pre> <p>the data source...</p> <pre><code>SqlDataSource dataSource = new SqlDataSource( "System.Data.SqlClient", connectionString, generatedSelectCommand); </code></pre> <p>then the gridview...</p> <pre><code>grid.DataSource = dataSource; grid.DataKeyNames = mylistOfKeys; grid.DataBind(); </code></pre> <p>At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing?</p> <p>If there's a nicer way of doing this that would be helpful too as this looks messy to me!</p>
[ { "answer_id": 138467, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about this one, but if you use a standard SqlDataSource and you click on a field to sort according to that field, the SqlDataSource is populated again with the data and it is rebound to the grid. So the sorting does not happen on the client side and also can be done only when the selectmethod of the SQLDataSource is not DataReader.</p>\n\n<p>When handling the sorting event, do you recreate the SqlDataSource and rebound it to the GridView? Can you put the sort field and direction to the generatedSelectCommand, which you use? Or put it to the SortParameterName property of the SQLDataSource?</p>\n\n<p>I'm absolutely sure that you have to rebound the SqlDataSource to the grid, and since you create it on the fly, you have to populate it again.</p>\n" }, { "answer_id": 138492, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": true, "text": "<p>First you need to add an event: </p>\n\n<pre><code>&lt;asp:GridView AllowSorting=\"True\" OnSorting=\"gvName_Sorting\" ...\n</code></pre>\n\n<p>Then that event looks like:</p>\n\n<pre><code>protected void gvName_Sorting( object sender, GridViewSortEventArgs e )\n{\n ...\n //rebind gridview\n}\n</code></pre>\n\n<p>You basically have to get your data again.</p>\n\n<p>You're right that it looks messy and there is a better way: ASP.Net MVC</p>\n\n<p>Unfortunately that's a drastically different page model.</p>\n" }, { "answer_id": 2965130, "author": "Martin", "author_id": 355272, "author_profile": "https://Stackoverflow.com/users/355272", "pm_score": 0, "selected": false, "text": "<p>Better late than never?</p>\n\n<p>Some addition for Keith's suggestion which is basically the right one.</p>\n\n<p>Truth is, that you have to deal with sorting on gridView_Sorting event.\nThere is no need to DataBind() the GridView earlier, for example in Page_Load event. There you should only call the GridView.Sort() method instead of .DataBind(). Here is how it goes:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n If Not IsPostBack Then\n\n Me.gridView.Sort(Request.QueryString(\"sortExpression\"), Request.QueryString(\"sortDirection\"))\n\n End If\n\nEnd Sub\n</code></pre>\n\n<p>Next let's have a look on gridView_Sorting event.</p>\n\n<p>There you have to push the datasource to the right sorting. GridView itself does not handle that (in this case at least).</p>\n\n<pre><code>Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gridView.Sorting\n If IsPostBack Then\n e.Cancel = True\n Dim sortDir As SortDirection = SortDirection.Ascending\n If e.SortExpression = Me.Q_SortExpression And Me.Q_SortDirection = SortDirection.Ascending Then\n sortDir = SortDirection.Descending\n End If\n RedirectMe(e.SortExpression, sortDir)\n Else\n Dim sortExpr As String = e.SortExpression + \" \" + IIf(e.SortDirection = SortDirection.Ascending, \"ASC\", \"DESC\")\n Dim dv As System.Data.DataView = Me.dsrcView.Select(New DataSourceSelectArguments(sortExpr))\n Me.gridView.DataSource = dv\n Me.gridView.DataBind()\n End If\nEnd Sub\n</code></pre>\n\n<p>No need to code any sorting functionality in data source like passing sort parameters to stored procedure. All sorting takes place in the above pieces of code.</p>\n\n<p>Moreover, it's good to have the gridView.EnableViewState switched to False which causes the page to be much lighter for the network traffic and for the browser as well. Can do that as the grid is entirely recreated whenever the page is post back.</p>\n\n<p>Have a nice day!</p>\n\n<p>Martin</p>\n" }, { "answer_id": 4430230, "author": "Mike", "author_id": 540688, "author_profile": "https://Stackoverflow.com/users/540688", "pm_score": 3, "selected": false, "text": "<p>You could also just reassign the datasource.SelectCommand before the DataBind() call in the Sorting handler. Something like this:</p>\n\n<pre><code>protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)\n{\n GridView gv = (GridView)sender;\n SqlDataSource ds = (SqlDataSource)gv.DataSource;\n ds.SelectCommand = ds.SelectCommand + \" order by \" \n + e.SortExpression + \" \" + GetSortDirection(e.SortDirection);\n gvItems.DataSource = ds;\n gvItems.DataBind();\n}\n\nstring GetSortDirection(string sSortDirCmd)\n{\n string sSortDir;\n if ((SortDirection.Ascending == sSortDirCmd))\n {\n sSortDir = \"asc\";\n }\n else\n {\n sSortDir = \"desc\";\n }\n return sSortDir;\n}\n</code></pre>\n\n<p>I hope this help. Let me know if you need extra help to implement it.</p>\n\n<p>Enjoy!</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22185/" ]
I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource. I have a GridView in which the code in the ASP reference to it in the HTML is minimal: ``` <asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True"> </asp:GridView> ``` In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example: I set up the columns... ``` BoundField column = new BoundField(); column.DataField = columnName; column.HeaderText = "Heading"; column.SortExpression = columnName; grid.Columns.Add(column); ``` the data source... ``` SqlDataSource dataSource = new SqlDataSource( "System.Data.SqlClient", connectionString, generatedSelectCommand); ``` then the gridview... ``` grid.DataSource = dataSource; grid.DataKeyNames = mylistOfKeys; grid.DataBind(); ``` At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing? If there's a nicer way of doing this that would be helpful too as this looks messy to me!
First you need to add an event: ``` <asp:GridView AllowSorting="True" OnSorting="gvName_Sorting" ... ``` Then that event looks like: ``` protected void gvName_Sorting( object sender, GridViewSortEventArgs e ) { ... //rebind gridview } ``` You basically have to get your data again. You're right that it looks messy and there is a better way: ASP.Net MVC Unfortunately that's a drastically different page model.
138,419
<p>While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command:</p> <pre><code>SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL </code></pre> <p>But SQL Server Compact Edition doesn't support the <code>TOP</code> keyword. How can I port this command?</p>
[ { "answer_id": 138436, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 0, "selected": false, "text": "<p>Looks like it can't be done in compact. You have to read all the jobs, or make a SqlReader, and just read the first one.</p>\n" }, { "answer_id": 138439, "author": "Robinb", "author_id": 22064, "author_profile": "https://Stackoverflow.com/users/22064", "pm_score": 6, "selected": true, "text": "<pre><code>SELECT TOP(1) Id \nFROM tblJob \nWHERE Holder_Id IS NULL\n</code></pre>\n\n<p>Need the brackets as far as I know.</p>\n\n<p>reference: <a href=\"http://technet.microsoft.com/en-us/library/bb686896.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/bb686896.aspx</a></p>\n\n<p>addition: likewise, only for version 3.5 onwards</p>\n" }, { "answer_id": 140835, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>This is slightly orthogonal to your question.</p>\n\n<p>SQL Server Compact Edition actually doesn't perform very well with SQL queries. You get much better performance by opening tables directly. In .NET, you do this by setting the command object's <code>CommandText</code> property to the table name, and the <code>CommandType</code> property to <code>CommandType.TableDirect</code>.</p>\n\n<p>If you want to filter the results, you will need an index on the table on the column(s) you want to filter by. Specify the index to use by setting the <code>IndexName</code> property and use <code>SetRange</code> to set the filter.</p>\n\n<p>You can then read as many or as few records as you like.</p>\n" }, { "answer_id": 218981, "author": "Tomas Tintera", "author_id": 15136, "author_profile": "https://Stackoverflow.com/users/15136", "pm_score": 0, "selected": false, "text": "<p>Well found a reason. Management studio carries and uses it's own version od SQL Server Compact. See more in <a href=\"http://en.wikipedia.org/wiki/SQL_Server_Compact\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/SQL_Server_Compact</a>.</p>\n\n<blockquote>\n <p>SQL Server Management Studio 2005 can\n read and modify CE 3.0 and 3.1\n database files (with the latest\n service pack), but the SQL Server\n Management Studio 2008 from the\n \"Katmai\" 2008 CTP release (or later)\n is required to read version 3.5 files.</p>\n \n <p>The RTM of SQL Server Management\n Studio 2008 and Microsoft Visual\n Studio Express 2008 SP1 can create,\n modify and query CE 3.5 SP1 database\n files.</p>\n</blockquote>\n" }, { "answer_id": 3477373, "author": "Nau", "author_id": 419612, "author_profile": "https://Stackoverflow.com/users/419612", "pm_score": 1, "selected": false, "text": "<p>I've used Fill method of SqlCEDataAdapter. You can do:</p>\n\n<p>DbDataAdapter.Fill (DataSet, Int32, Int32, String) Adds or refreshes rows in a specified range in the DataSet to match those in the data source using the DataSet and DataTable names. \nSupported by the .NET Compact Framework. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-ie/library/system.data.common.dbdataadapter.fill(v=VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-ie/library/system.data.common.dbdataadapter.fill(v=VS.80).aspx</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15136/" ]
While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command: ``` SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL ``` But SQL Server Compact Edition doesn't support the `TOP` keyword. How can I port this command?
``` SELECT TOP(1) Id FROM tblJob WHERE Holder_Id IS NULL ``` Need the brackets as far as I know. reference: <http://technet.microsoft.com/en-us/library/bb686896.aspx> addition: likewise, only for version 3.5 onwards
138,422
<p>I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings?</p> <p>And what are the options amongst browsers.</p>
[ { "answer_id": 138456, "author": "yann.kmm", "author_id": 15780, "author_profile": "https://Stackoverflow.com/users/15780", "pm_score": 3, "selected": false, "text": "<p>You can also use the non-standard IE-only css attribute <a href=\"http://www.eskimo.com/~bloo/indexdot/css/properties/intl/writingmode.htm\" rel=\"noreferrer\">writing-mode</a></p>\n\n<pre><code>div.page { \n writing-mode: tb-rl;\n}\n</code></pre>\n" }, { "answer_id": 138474, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 3, "selected": false, "text": "<p>You might be able to use the <a href=\"http://www.w3.org/TR/CSS2/page.html\" rel=\"noreferrer\">CSS 2 @page rule</a> which allows you to set the <a href=\"http://www.w3.org/TR/CSS2/page.html#page-size-prop\" rel=\"noreferrer\">'size' property to landscape</a>.</p>\n" }, { "answer_id": 138483, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 4, "selected": false, "text": "<p>Try to add this your CSS:</p>\n\n<pre><code>@page {\n size: landscape;\n}\n</code></pre>\n" }, { "answer_id": 1392794, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 10, "selected": true, "text": "<p>In your CSS you can set the @page property as shown below. </p>\n\n<pre><code>@media print{@page {size: landscape}}\n</code></pre>\n\n<p>The @page is part of <a href=\"http://www.w3.org/TR/CSS21/page.html#page-box\" rel=\"noreferrer\">CSS 2.1 specification</a> however this <code>size</code> is not as highlighted by the answer to the question <a href=\"https://stackoverflow.com/questions/4249532/is-page-sizelandscape-obsolete\">Is @Page { size:landscape} obsolete?</a>:</p>\n\n<blockquote>\n <p>CSS 2.1 no longer specifies the size attribute. The current working\n draft for CSS3 Paged Media module does specify it (but this is not\n standard or accepted).</p>\n</blockquote>\n\n<p>As stated the size option comes from the <a href=\"http://www.w3.org/TR/css3-page/#page-size\" rel=\"noreferrer\">CSS 3 Draft Specification</a>. In theory it can be set to both a page size and orientation although in my sample the size is omitted.</p>\n\n<p>The support is very mixed with a <a href=\"https://developer.mozilla.org/en/Mozilla_CSS_support_chart#section_3\" rel=\"noreferrer\">bug report begin filed in firefox</a>, most browsers do not support it. </p>\n\n<p>It may seem to work in IE7 but this is because IE7 will remember the users last selection of landscape or portrait in print preview (only the browser is re-started).</p>\n\n<p><a href=\"https://web.archive.org/web/20090228163159/http://edacio.us:80/forum/comments.php?DiscussionID=39\" rel=\"noreferrer\">This article</a> does have some suggested work arounds using JavaScript or ActiveX that send keys to the users browser although it they are not ideal and rely on changing the browsers security settings. </p>\n\n<p>Alternately you could rotate the content rather than the page orientation. This can be done by creating a style and applying it to the body that includes these two lines but this also has draw backs creating many alignment and layout issues.</p>\n\n<pre><code>&lt;style type=\"text/css\" media=\"print\"&gt;\n .page\n {\n -webkit-transform: rotate(-90deg); \n -moz-transform:rotate(-90deg);\n filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n }\n&lt;/style&gt;\n</code></pre>\n\n<p>The final alternative I have found is to create a landscape version in a PDF. You can point to so when the user selects print it prints the PDF. However I could not get this to auto print work in IE7.</p>\n\n<pre><code>&lt;link media=\"print\" rel=\"Alternate\" href=\"print.pdf\"&gt;\n</code></pre>\n\n<p>In conclusion in some browsers it is relativity easy using the @page size option however in many browsers there is no sure way and it would depend on your content and environment. \nThis maybe why Google Documents creates a PDF when print is selected and then allows the user to open and print that.</p>\n" }, { "answer_id": 1709211, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 1, "selected": false, "text": "<p>I tried to solve this problem once, but all my research led me towards ActiveX controls/plug-ins. There is no trick that the browsers (3 years ago anyway) permitted to change any print settings (number of copies, paper size).</p>\n\n<p>I put my efforts into warning the user carefully that they needed to select \"landscape\" when the browsers print dialog appeared. I also created a \"print preview\" page, which worked much better than IE6's did! Our application had very wide tables of data in some reports, and the print preview made it clear to the users when the table would spill off the right-edge of the paper (since IE6 couldnt cope with printing on 2 sheets either).</p>\n\n<p>And yes, people are still using IE6 even now.</p>\n" }, { "answer_id": 3068496, "author": "Naveen Mettapally", "author_id": 370160, "author_profile": "https://Stackoverflow.com/users/370160", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\" media=\"print\"&gt;\n.landscape { \n width: 100%; \n height: 100%; \n margin: 0% 0% 0% 0%; filter: progid:DXImageTransform.Microsoft.BasicImage(Rotation=1); \n} \n&lt;/style&gt;\n</code></pre>\n\n<p>If you want this style to be applied to a table then create one div tag with this style class and add the table tag within this div tag and close the div tag at the end.</p>\n\n<p>This table will only print in landscape and all other pages will print in portrait mode only. But the problem is if the table size is more than the page width then we may loose some of the rows and sometimes headers also are missed. Be careful.</p>\n\n<p>Have a good day.</p>\n\n<p>Thank you,\nNaveen Mettapally.</p>\n" }, { "answer_id": 4540269, "author": "Ahmad Alfy", "author_id": 497828, "author_profile": "https://Stackoverflow.com/users/497828", "pm_score": 4, "selected": false, "text": "<p>Quoted from <a href=\"http://css-discuss.incutio.com/wiki/Print_Stylesheets#The_.40page_rule_and_forcing_Landscape_orientation\" rel=\"noreferrer\">CSS-Discuss Wiki</a></p>\n<blockquote>\n<p>The @page rule has been cut down in\nscope from CSS2 to CSS2.1. The full\nCSS2 @page rule was reportedly\nimplemented only in Opera (and buggily\neven then). My own testing shows that\nIE and Firefox don't support @page at\nall. According to the now-obsolescent\nCSS2 spec section 13.2.2 it is\npossible to override the user's\nsetting of orientation and (for\nexample) force printing in Landscape\nbut the relevant &quot;size&quot; property has\nbeen dropped from CSS2.1, consistent\nwith the fact that no current browser\nsupports it. It has been reinstated in\nthe CSS3 Paged Media module but note\nthat this is only a Working Draft (as\nat July 2009).</p>\n<p>Conclusion: forget\nabout @page for the present. If you\nfeel your document needs to be printed\nin Landscape orientation, ask yourself\nif you can instead make your design\nmore fluid. If you really can't\n(perhaps because the document contains\ndata tables with many columns, for\nexample), you will need to advise the\nuser to set the orientation to\nLandscape and perhaps outline how to\ndo it in the most common browsers. Of\ncourse, some browsers have a print\nfit-to-width (shrink-to-fit) feature\n(e.g. Opera, Firefox, IE7) but it's\ninadvisable to rely on users having\nthis facility or having it switched\non.</p>\n</blockquote>\n" }, { "answer_id": 13541556, "author": "Satheesh", "author_id": 1849501, "author_profile": "https://Stackoverflow.com/users/1849501", "pm_score": 1, "selected": false, "text": "<pre><code>-webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg);\n filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n</code></pre>\n\n<p>not working in Firefox 16.0.2 but it is working in Chrome</p>\n" }, { "answer_id": 24950044, "author": "Navin Rauniyar", "author_id": 2313718, "author_profile": "https://Stackoverflow.com/users/2313718", "pm_score": 1, "selected": false, "text": "<p>This also worked for me:</p>\n\n<pre><code>@media print and (orientation:landscape) { … }\n</code></pre>\n" }, { "answer_id": 26025787, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 5, "selected": false, "text": "<p>My solution:</p>\n<pre><code>&lt;style type=&quot;text/css&quot; media=&quot;print&quot;&gt;\n @page { \n size: landscape;\n }\n body { \n writing-mode: tb-rl;\n }\n&lt;/style&gt;\n</code></pre>\n<ul>\n<li>With <code>media=&quot;print&quot;</code> will apply only on Print.</li>\n<li>This works in <code>IE</code>, <code>Firefox</code> and <code>Chrome</code></li>\n</ul>\n" }, { "answer_id": 27787031, "author": "Shankar", "author_id": 1944282, "author_profile": "https://Stackoverflow.com/users/1944282", "pm_score": 2, "selected": false, "text": "<p>I created a blank MS Document with Landscape setting and then opened it in notepad. Copied and pasted the following to my html page</p>\n\n<pre><code>&lt;style type=\"text/css\" media=\"print\"&gt;\n @page Section1\n {size:11 8.5in;\n margin:.5in 13.6pt 0in 13.6pt;\n mso-header-margin:.5in;\n mso-footer-margin:.5in;\n mso-paper-source:4;}\ndiv.Section1\n {page:Section1;}\n&lt;/style&gt;\n\n\n\n&lt;div class=\"Section1\"&gt; put text / images / other stuff &lt;/div&gt;\n</code></pre>\n\n<p>The print preview shows the pages in a landscape size. This seems to be working fine on IE and Chrome, not tested on FF. </p>\n" }, { "answer_id": 42344471, "author": "robstarbuck", "author_id": 999248, "author_profile": "https://Stackoverflow.com/users/999248", "pm_score": 4, "selected": false, "text": "<p>The <code>size</code> property is what you're after as mentioned. To set both the the orientation and size of your page when printing, you could use the following:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* ISO Paper Size */\n@page {\n size: A4 landscape;\n}\n\n/* Size in mm */ \n@page {\n size: 100mm 200mm landscape;\n}\n\n/* Size in inches */ \n@page {\n size: 4in 6in landscape;\n}\n</code></pre>\n\n<p>Here's a link to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/@page/size\" rel=\"noreferrer\">@page documentation</a>.</p>\n" }, { "answer_id": 44069821, "author": "Denis", "author_id": 632199, "author_profile": "https://Stackoverflow.com/users/632199", "pm_score": 4, "selected": false, "text": "<p>It's not enough just to rotate the page content. Here is a right CSS which work in the most browsers (Chrome, Firefox, IE9+).</p>\n\n<p>First set body <code>margin</code> to 0, because otherwise page margins will be larger than those you set in the print dialog. Also set <code>background</code> color to visualize pages.</p>\n\n<pre><code>body {\n margin: 0;\n background: #CCCCCC;\n}\n</code></pre>\n\n<p><code>margin</code>, <code>border</code> and <code>background</code> are required to visualize pages.</p>\n\n<p><code>padding</code> must be set to the required print margin. In the print dialog you must set the same margins (10mm in this example).</p>\n\n<pre><code>div.portrait, div.landscape {\n margin: 10px auto;\n padding: 10mm;\n border: solid 1px black;\n overflow: hidden;\n page-break-after: always;\n background: white;\n}\n</code></pre>\n\n<p>The size of A4 page is 210mm x 297mm. You need to subtract print margins from the size. And set the size of page's content:</p>\n\n<pre><code>div.portrait {\n width: 190mm;\n height: 276mm;\n}\ndiv.landscape {\n width: 276mm;\n height: 190mm;\n}\n</code></pre>\n\n<p>I use 276mm instead of 277mm, because different browsers scale pages a little bit differently. So some of them will print 277mm-height content on two pages. The second page will be empty. It's more safe to use 276mm.</p>\n\n<p>We don't need any <code>margin</code>, <code>border</code>, <code>padding</code>, <code>background</code> on the printed page, so remove them:</p>\n\n<pre><code>@media print {\n body {\n background: none;\n -ms-zoom: 1.665;\n }\n div.portrait, div.landscape {\n margin: 0;\n padding: 0;\n border: none;\n background: none;\n }\n div.landscape {\n transform: rotate(270deg) translate(-276mm, 0);\n transform-origin: 0 0;\n }\n}\n</code></pre>\n\n<p>Note that the origin of transformation is <code>0 0</code>! Also the content of landscape pages must be moved 276mm down!</p>\n\n<p>Also if you have a mix of portrait and lanscape pages IE will zoom out the pages. We fix it by setting <code>-ms-zoom</code> to 1.665. If you'll set it to 1.6666 or something like this the right border of the page content may be cropped sometimes.</p>\n\n<p>If you need IE8- or other old browsers support you can use <code>-webkit-transform</code>, <code>-moz-transform</code>, <code>filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3)</code>. But for modern enough browsers it's not required.</p>\n\n<p>Here is a test page:</p>\n\n<pre><code>&lt;!DOCTYPE HTML&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /&gt;\n &lt;style&gt;\n ...Copy all styles here...\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div class=\"portrait\"&gt;A portrait page&lt;/div&gt;\n &lt;div class=\"landscape\"&gt;A landscape page&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 58727538, "author": "sherz", "author_id": 12331257, "author_profile": "https://Stackoverflow.com/users/12331257", "pm_score": -1, "selected": false, "text": "<p>You can try the following:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>@page {\n size: auto\n}\n</code></pre>\n" }, { "answer_id": 59071414, "author": "Arkadiy Bolotov", "author_id": 1708124, "author_profile": "https://Stackoverflow.com/users/1708124", "pm_score": 2, "selected": false, "text": "<p>I tried Denis's answer and hit some problems (portrait pages didn't print properly after going after landscape pages), so here is my solution:</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-css lang-css prettyprint-override\"><code>body {\r\n margin: 0;\r\n background: #CCCCCC;\r\n}\r\n\r\ndiv.page {\r\n margin: 10px auto;\r\n border: solid 1px black;\r\n display: block;\r\n page-break-after: always;\r\n width: 209mm;\r\n height: 296mm;\r\n overflow: hidden;\r\n background: white;\r\n}\r\n\r\ndiv.landscape-parent {\r\n width: 296mm;\r\n height: 209mm;\r\n}\r\n\r\ndiv.landscape {\r\n width: 296mm;\r\n height: 209mm;\r\n}\r\n\r\ndiv.content {\r\n padding: 10mm;\r\n}\r\n\r\nbody,\r\ndiv,\r\ntd {\r\n font-size: 13px;\r\n font-family: Verdana;\r\n}\r\n\r\n@media print {\r\n body {\r\n background: none;\r\n }\r\n div.page {\r\n width: 209mm;\r\n height: 296mm;\r\n }\r\n div.landscape {\r\n transform: rotate(270deg) translate(-296mm, 0);\r\n transform-origin: 0 0;\r\n }\r\n div.portrait,\r\n div.landscape,\r\n div.page {\r\n margin: 0;\r\n padding: 0;\r\n border: none;\r\n background: none;\r\n }\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"page\"&gt;\r\n &lt;div class=\"content\"&gt;\r\n First page in Portrait mode\r\n &lt;/div&gt;\r\n&lt;/div&gt;\r\n&lt;div class=\"page landscape-parent\"&gt;\r\n &lt;div class=\"landscape\"&gt;\r\n &lt;div class=\"content\"&gt;\r\n Second page in Landscape mode (correctly shows horizontally in browser and prints rotated in printer)\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;\r\n&lt;div class=\"page\"&gt;\r\n &lt;div class=\"content\"&gt;\r\n Third page in Portrait mode\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 67360337, "author": "Rich", "author_id": 6542267, "author_profile": "https://Stackoverflow.com/users/6542267", "pm_score": 2, "selected": false, "text": "<p>Here's what I came up with - add a negative rotation to the <code>&lt;html&gt;</code> element and a positive rotation of equal abs value to the <code>&lt;body&gt;</code>. That saved having to add a ton of CSS to style the body, and it worked like a charm:</p>\n<pre><code>html { \n transform: rotate(-90deg);\n}\n\nbody { \n transform: rotate(90deg);\n}\n</code></pre>\n" }, { "answer_id": 69067910, "author": "thphoenix", "author_id": 2112461, "author_profile": "https://Stackoverflow.com/users/2112461", "pm_score": 0, "selected": false, "text": "<p>The problem I faced is probably the same you have. Everyone here is using CSS to provide it statically, but I had to look for a dynamic solution so that it would change based on the active element without reloading the page..</p>\n<p>I created 2 files, portrait.css and landscape.css.</p>\n<p>portrait.css is blank, but landscape.css has one line.</p>\n<pre><code>@media print{@page {size: landscape}}\n</code></pre>\n<p>in my primary file, I added this line of html to specify portrait.css as default.</p>\n<pre><code> &lt;link rel=&quot;stylesheet&quot; id=&quot;PRINTLAYOUT&quot; href=&quot;portrait.css&quot; type=&quot;text/css&quot; /&gt;&lt;/link&gt;\n</code></pre>\n<p>Now, to switch you only have to change href in the element to switch printing modes.</p>\n<pre><code>$(&quot;#PRINTLAYOUT&quot;).attr(&quot;href&quot;,&quot;landscape.css&quot;)\n // OR \ndocument.getElementById(&quot;PRINTLAYOUT&quot;).href = &quot;landscape.css&quot; // I think...\n</code></pre>\n<p>This worked great for me, and I hope it helps someone else doing things the hard way like me.. As a note, $ represents JQuery.. If you are not using this yet, I highly recommend you start now.</p>\n" }, { "answer_id": 73721340, "author": "prajun7", "author_id": 12778051, "author_profile": "https://Stackoverflow.com/users/12778051", "pm_score": 0, "selected": false, "text": "<p>If you are using React and libraries like MUI, using plain CSS in your React app is not a good practice. The better approach will be to use a style component called <code>GlobalStyles</code>, which we can import from Material UI.\nThe code will look like this,</p>\n<pre><code>import { GlobalStyles } from '@mui/material';\nconst printStyle = {\n ['@media print']: {\n ['@page']: {\n size: 'landscape',\n margin: '2px',\n },\n },\n };\n</code></pre>\n<p>You might not need to use <code>@page</code> inside the <code>@media print</code> because <code>@page</code> is only for printing. <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/@page\" rel=\"nofollow noreferrer\">Documentation</a></p>\n<p>The margin will eliminate the URLs, the browser generates while printing.</p>\n<p>We can use the <code>GlobalStyles</code> in our App container. Like this</p>\n<pre><code>const App: React.FC = () =&gt; (\n &lt;&gt;\n &lt;GlobalStyles styles={printStyle} /&gt;\n &lt;AppView /&gt;\n &lt;/&gt;\n );\n</code></pre>\n<p>It will apply the above CSS whenever we call <code>windows.print()</code>.\nIf you are using other libraries besides MUI, there should be some components or plugins that you can use to apply the CSS globally.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings? And what are the options amongst browsers.
In your CSS you can set the @page property as shown below. ``` @media print{@page {size: landscape}} ``` The @page is part of [CSS 2.1 specification](http://www.w3.org/TR/CSS21/page.html#page-box) however this `size` is not as highlighted by the answer to the question [Is @Page { size:landscape} obsolete?](https://stackoverflow.com/questions/4249532/is-page-sizelandscape-obsolete): > > CSS 2.1 no longer specifies the size attribute. The current working > draft for CSS3 Paged Media module does specify it (but this is not > standard or accepted). > > > As stated the size option comes from the [CSS 3 Draft Specification](http://www.w3.org/TR/css3-page/#page-size). In theory it can be set to both a page size and orientation although in my sample the size is omitted. The support is very mixed with a [bug report begin filed in firefox](https://developer.mozilla.org/en/Mozilla_CSS_support_chart#section_3), most browsers do not support it. It may seem to work in IE7 but this is because IE7 will remember the users last selection of landscape or portrait in print preview (only the browser is re-started). [This article](https://web.archive.org/web/20090228163159/http://edacio.us:80/forum/comments.php?DiscussionID=39) does have some suggested work arounds using JavaScript or ActiveX that send keys to the users browser although it they are not ideal and rely on changing the browsers security settings. Alternately you could rotate the content rather than the page orientation. This can be done by creating a style and applying it to the body that includes these two lines but this also has draw backs creating many alignment and layout issues. ``` <style type="text/css" media="print"> .page { -webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg); filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3); } </style> ``` The final alternative I have found is to create a landscape version in a PDF. You can point to so when the user selects print it prints the PDF. However I could not get this to auto print work in IE7. ``` <link media="print" rel="Alternate" href="print.pdf"> ``` In conclusion in some browsers it is relativity easy using the @page size option however in many browsers there is no sure way and it would depend on your content and environment. This maybe why Google Documents creates a PDF when print is selected and then allows the user to open and print that.
138,449
<p>Here's the problem:</p> <p>In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me.</p> <p>How do I convert this Unicode string back to it's ASCII equivalent?</p> <p><hr> <strong>Edit</strong><br> Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise: </p> <pre> -> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database. -> Either Access or the reading component in .NET converted this to U+02C6 U+0065 (MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E) -> I need the (Extended) ASCII character 136 back. </pre> <p><hr> Here's what I've tried (I see now why this did not work...):</p> <pre><code>string myInput = Convert.ToString(Convert.ToChar(710)); byte[] asBytes = Encoding.ASCII.GetBytes(myInput); </code></pre> <p>But this does not result in 94 but a byte with value 63...<br> Here's a new try but it still does not work:</p> <pre><code>byte[] bytes = Encoding.ASCII.GetBytes("ê"); </code></pre> <p><hr> <strong>Soltution</strong><br> Thanks to both <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579">csgero</a> and <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583">bzlm</a> for pointing in the right direction I solved the problem <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent#141816">here</a>.</p>
[ { "answer_id": 138462, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Hmm … I'm not sure which character you mean. The caret (“^”, CIRCUMFLEX ACCENT) has the same code in ASCII and Unicode (U+005E).</p>\n\n<p>/EDIT: Damn, my fault. 710 (U+02C6) is actually the MODIFIER LETTER CIRCUMFLEX ACCENT. Unfortunately, this character isn't part of ASCII at all. It might look like the normal caret but it's a different character. Simple conversion won't help here. I'm not sure if .NET supports mapping of similar characters when converting from Unicode. Worth investigating, though.</p>\n" }, { "answer_id": 138485, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 0, "selected": false, "text": "<p>The value 63 is the question mark, AKA \"I am not able to display this character in ASCII\".</p>\n" }, { "answer_id": 138579, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 2, "selected": false, "text": "<p>You cannot use the default ASCII encoding (Encoding.ASCII) here, but must create the encoding with the appropriate code page using Encoding.GetEncoding(...). You might try to use code page 1252, which is a superset of ISO 8859-1.</p>\n" }, { "answer_id": 138583, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 2, "selected": false, "text": "<p>ASCII does not define ê; the number 136 comes from the number for the circumflex in 8-bit encodings such as Windows-1252. </p>\n\n<p>Can you verify that a small e with a circumflex (ê) is actually what is supposed to be stored in the Access database in this case? Perhaps U+02C6 U+0065 is the result of a conversion error, where the input is actually an e <em>followed by</em> a circumflex, or something else entirely. Perhaps your Access database has corrupt data in the sense that the designated encoding does not match the contents, in which case the .NET client might incorrectly parse the data (using the wrong decoder).</p>\n\n<p>If this error is indeed introduced during the reading from the database, perhaps pasting some code or configuration settings might help.</p>\n\n<p>In <a href=\"http://en.wikipedia.org/wiki/Code_page_437\" rel=\"nofollow noreferrer\">Code page 437</a>, character number 136 is an e with a circumflex.</p>\n" }, { "answer_id": 141816, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 5, "selected": true, "text": "<p>Okay, let's elaborate. Both <a href=\"https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579\">csgero</a> and <a href=\"https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583\">bzlm</a> pointed in the right direction.</p>\n\n<p>Because of blzm's reply I looked up the Windows-1252 page on wiki and found that it's called a codepage. The wikipedia article for <a href=\"http://en.wikipedia.org/wiki/Codepage\" rel=\"nofollow noreferrer\">Code page</a> which stated the following: </p>\n\n<blockquote>\n <p>No formal standard existed for these ‘<a href=\"http://en.wikipedia.org/wiki/Extended_ASCII\" rel=\"nofollow noreferrer\">extended character sets</a>’; IBM merely referred to the variants as code pages, as it had always done for variants of EBCDIC encodings.</p>\n</blockquote>\n\n<p>This led me to codepage 437:</p>\n\n<blockquote>\n <p>n ASCII-compatible code pages, the lower 128 characters maintained their standard US-ASCII values, and different pages (or sets of characters) could be made available in the upper 128 characters. DOS computers built for the North American market, for example, used <a href=\"http://en.wikipedia.org/wiki/Code_page_437\" rel=\"nofollow noreferrer\">code page 437</a>, which included accented characters needed for French, German, and a few other European languages, as well as some graphical line-drawing characters.</p>\n</blockquote>\n\n<p>So, codepage 437 was the codepage I was calling 'extended ASCII', it had the ê as character 136 so I looked up some other chars as well and they seem right.</p>\n\n<p>csgero came with the Encoding.GetEncoding() hint, I used it to create the following statement which solves my problem:</p>\n\n<pre><code>byte[] bytes = Encoding.GetEncoding(437).GetBytes(\"ê\");\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830/" ]
Here's the problem: In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me. How do I convert this Unicode string back to it's ASCII equivalent? --- **Edit** Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise: ``` -> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database. -> Either Access or the reading component in .NET converted this to U+02C6 U+0065 (MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E) -> I need the (Extended) ASCII character 136 back. ``` --- Here's what I've tried (I see now why this did not work...): ``` string myInput = Convert.ToString(Convert.ToChar(710)); byte[] asBytes = Encoding.ASCII.GetBytes(myInput); ``` But this does not result in 94 but a byte with value 63... Here's a new try but it still does not work: ``` byte[] bytes = Encoding.ASCII.GetBytes("ê"); ``` --- **Soltution** Thanks to both [csgero](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579) and [bzlm](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583) for pointing in the right direction I solved the problem [here](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent#141816).
Okay, let's elaborate. Both [csgero](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579) and [bzlm](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583) pointed in the right direction. Because of blzm's reply I looked up the Windows-1252 page on wiki and found that it's called a codepage. The wikipedia article for [Code page](http://en.wikipedia.org/wiki/Codepage) which stated the following: > > No formal standard existed for these ‘[extended character sets](http://en.wikipedia.org/wiki/Extended_ASCII)’; IBM merely referred to the variants as code pages, as it had always done for variants of EBCDIC encodings. > > > This led me to codepage 437: > > n ASCII-compatible code pages, the lower 128 characters maintained their standard US-ASCII values, and different pages (or sets of characters) could be made available in the upper 128 characters. DOS computers built for the North American market, for example, used [code page 437](http://en.wikipedia.org/wiki/Code_page_437), which included accented characters needed for French, German, and a few other European languages, as well as some graphical line-drawing characters. > > > So, codepage 437 was the codepage I was calling 'extended ASCII', it had the ê as character 136 so I looked up some other chars as well and they seem right. csgero came with the Encoding.GetEncoding() hint, I used it to create the following statement which solves my problem: ``` byte[] bytes = Encoding.GetEncoding(437).GetBytes("ê"); ```
138,477
<p>Is it possible to send my own developed exceptions over Soap to a client using http.sys??</p>
[ { "answer_id": 303158, "author": "Zach", "author_id": 8720, "author_profile": "https://Stackoverflow.com/users/8720", "pm_score": 0, "selected": false, "text": "<p>Yes, you can throw your own exceptions. Any uncaught exception that does not derive from SoapException will be bottled up by the .NET framework into a SoapException. You can derive from SoapException if you want to control how certain parts of the SoapException are formed (for instance, the fault and detail portions).</p>\n" }, { "answer_id": 9320072, "author": "dyslexicanaboko", "author_id": 603807, "author_profile": "https://Stackoverflow.com/users/603807", "pm_score": 1, "selected": false, "text": "<p>To the best of my knowledge unfortunately the answer is no. You cannot build your own custom exceptions on the server side and expect to use them on the client side through WSE. I can't give much technical background as to why (as in why this is not allowed by WSE), but I am sure about my answer because I tested this out.</p>\n\n<p>You can use the approach described in the provided link to return a custom exception that inherits from a System.Web.Services.Protocols.SoapException, however you must capture the exception on the client side as a SoapException since you will not be able to capture it as the custom exception type: <a href=\"http://msdn.microsoft.com/en-us/library/ms229064.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms229064.aspx</a></p>\n\n<p>To recreate the test for your own confirmation do the following:</p>\n\n<ol>\n<li>Create a test exception class, call it whatever you'd like and make sure it follows the pattern described in the link I provided above (there are code samples provided).</li>\n<li><p>Create a web method that explicitly returns the test exception like so:</p>\n\n<pre><code>'This is in VB.Net\n&lt;WebMethod()&gt; _\nPublic Function ThrowTestSoapException() As TestSoapException\n Return New TestSoapException()\nEnd Function\n</code></pre></li>\n<li><p>Try to regenerate your client's WSE Library (using WseWsdl3.exe) and you should receive an error message like this one: \"<em>Error: Server unavailable, please try later</em>\"</p></li>\n</ol>\n\n<p>That is as far as I could get when trying to create my own transferable Custom Exceptions. Again the only thing I was able to do was return a Custom Exception that inherited from the SoapException class, and caught it on the client side as a SoapException. That is the same method described in the link that \"CheGueVerra\" pointed out <a href=\"http://msdn.microsoft.com/en-us/library/aa480592.aspx\" rel=\"nofollow\">above</a>.</p>\n\n<p>In response to John Saunders's comment above: Yes, if <em>possible</em> move over to WCF, WSE is indeed obsolete. Since this is work related for me and for others asking these questions, making a shift from WSE to WCF would require managerial approval - so some of us cannot make those changes easily - even if we desperately want to. </p>\n" }, { "answer_id": 9321542, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 0, "selected": false, "text": "<p>Like the ASMX services it is based on, WSE has little support for SOAP Faults. You can return them (SoapException with Detail property set), but they won't appear in the WSDL. If received by a WSE client, they will appear as SoapException, not as a custom exception type.</p>\n\n<p>WCF does have full support for SOAP faults, both on the client and the server side.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to send my own developed exceptions over Soap to a client using http.sys??
To the best of my knowledge unfortunately the answer is no. You cannot build your own custom exceptions on the server side and expect to use them on the client side through WSE. I can't give much technical background as to why (as in why this is not allowed by WSE), but I am sure about my answer because I tested this out. You can use the approach described in the provided link to return a custom exception that inherits from a System.Web.Services.Protocols.SoapException, however you must capture the exception on the client side as a SoapException since you will not be able to capture it as the custom exception type: <http://msdn.microsoft.com/en-us/library/ms229064.aspx> To recreate the test for your own confirmation do the following: 1. Create a test exception class, call it whatever you'd like and make sure it follows the pattern described in the link I provided above (there are code samples provided). 2. Create a web method that explicitly returns the test exception like so: ``` 'This is in VB.Net <WebMethod()> _ Public Function ThrowTestSoapException() As TestSoapException Return New TestSoapException() End Function ``` 3. Try to regenerate your client's WSE Library (using WseWsdl3.exe) and you should receive an error message like this one: "*Error: Server unavailable, please try later*" That is as far as I could get when trying to create my own transferable Custom Exceptions. Again the only thing I was able to do was return a Custom Exception that inherited from the SoapException class, and caught it on the client side as a SoapException. That is the same method described in the link that "CheGueVerra" pointed out [above](http://msdn.microsoft.com/en-us/library/aa480592.aspx). In response to John Saunders's comment above: Yes, if *possible* move over to WCF, WSE is indeed obsolete. Since this is work related for me and for others asking these questions, making a shift from WSE to WCF would require managerial approval - so some of us cannot make those changes easily - even if we desperately want to.
138,493
<p>How does one handle a <code>DateTime</code> with a <code>NOT NULL</code>?</p> <p>I want to do something like this:</p> <pre><code>SELECT * FROM someTable WHERE thisDateTime IS NOT NULL </code></pre> <p>But how?</p>
[ { "answer_id": 138495, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 6, "selected": true, "text": "<p>erm it does work? I've just tested it?</p>\n\n<pre><code>/****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE TABLE [dbo].[DateTest](\n [Date1] [datetime] NULL,\n [Date2] [datetime] NOT NULL\n) ON [PRIMARY]\n\nGO\nInsert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')\nInsert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')\nGo\nSELECT * FROM DateTest WHERE Date1 is not NULL\nGO\nSELECT * FROM DateTest WHERE Date2 is not NULL\n</code></pre>\n" }, { "answer_id": 140658, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>Just to rule out a possibility - it doesn't appear to have anything to do with the <code>ANSI_NULLS</code> option, because that controls comparing to NULL with the <code>=</code> and <code>&lt;&gt;</code> operators. <code>IS [NOT] NULL</code> works whether <code>ANSI_NULLS</code> is <code>ON</code> or <code>OFF</code>.</p>\n\n<p>I've also tried this against SQL Server 2005 with <code>isql</code>, because <code>ANSI_NULLS</code> defaults to <code>OFF</code> when using DB-Library.</p>\n" }, { "answer_id": 11324686, "author": "H.M.", "author_id": 1218928, "author_profile": "https://Stackoverflow.com/users/1218928", "pm_score": 2, "selected": false, "text": "<p>I faced this problem where the following query doesn't work as expected:</p>\n\n<pre><code>select 1 where getdate()&lt;&gt;null\n</code></pre>\n\n<p>we expect it to show 1 because getdate() doesn't return null.\nI guess it has something to do with SQL failing to cast null as datetime and skipping the row!\nof course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation.\nas a solution you can create your own compare function like the following:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnCompareDates]\n(\n @DateTime1 datetime,\n @DateTime2 datetime\n)\nRETURNS bit\nAS\nBEGIN\n if (@DateTime1 is null and @DateTime2 is null) return 1;\n if (@DateTime1 = @DateTime2) return 1;\n return 0\nEND\n</code></pre>\n\n<p>and re writing the query like:</p>\n\n<pre><code>select 1 where dbo.fnCompareDates(getdate(),null)=0\n</code></pre>\n" }, { "answer_id": 62438076, "author": "Jose Manuel Jimenez Piqueras", "author_id": 13765241, "author_profile": "https://Stackoverflow.com/users/13765241", "pm_score": -1, "selected": false, "text": "<p>SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null) </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
How does one handle a `DateTime` with a `NOT NULL`? I want to do something like this: ``` SELECT * FROM someTable WHERE thisDateTime IS NOT NULL ``` But how?
erm it does work? I've just tested it? ``` /****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[DateTest]( [Date1] [datetime] NULL, [Date2] [datetime] NOT NULL ) ON [PRIMARY] GO Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008') Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008') Go SELECT * FROM DateTest WHERE Date1 is not NULL GO SELECT * FROM DateTest WHERE Date2 is not NULL ```
138,496
<p>How would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers? </p> <p>edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates. </p>
[ { "answer_id": 138810, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 6, "selected": true, "text": "<p>Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question?</p>\n\n<h1>Date Picking Widgets</h1>\n\n<p>1) <strong>Default Rails Solution</strong>: See <code>date_select</code> documentation <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html\" rel=\"noreferrer\">here</a>.</p>\n\n<p>2) <strong>Use a plugin</strong> : Why write code? I personally like the <a href=\"http://code.google.com/p/calendardateselect/\" rel=\"noreferrer\">CalendarDateSelect</a> plugin, using a pair of the suckers when I need a range.</p>\n\n<p>3) <strong>Adapt a Javascript widget to Rails</strong>: It is almost trivial to integrate something like the Yahoo UI library (YUI) <a href=\"http://developer.yahoo.com/yui/calendar/\" rel=\"noreferrer\">Calendar</a>, which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the <code>params[:start_date]</code> and <code>params[:end_date]</code>. YUI Calendar has native support for ranges.</p>\n\n<h1>Getting the data from the Widgets</h1>\n\n<p>1) <strong>Default Rails Solution</strong> See <code>date_select</code> documentation <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>#an application helper method you'll find helpful\n#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select\n\n# Reconstruct a date object from date_select helper form params\ndef build_date_from_params(field_name, params)\n Date.new(params[\"#{field_name.to_s}(1i)\"].to_i, \n params[\"#{field_name.to_s}(2i)\"].to_i, \n params[\"#{field_name.to_s}(3i)\"].to_i)\nend\n\n#goes into view\n&lt;%= date_select \"report\", \"start_date\", ... %&gt;\n&lt;%= date_select \"report\", \"end_date\", ... %&gt; \n\n#goes into controller -- add your own error handling/defaults, please!\nreport_start_date = build_date_from_params(\"start_date\", params[:report])\nreport_end_date = build_date_from_params(\"end_date\", params[:report]) \n</code></pre>\n\n<p>2) <strong>CalendarDateSelect</strong>: Rather similar to the above, just with sexier visible UI.</p>\n\n<p>3) <strong>Adapt a Javascript widget</strong>: Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some_form_element_name] will be initialized by Rails for you.</p>\n\n<pre><code>#goes in controller. Please handle errors yourself -- Javascript != trusted input.\nreport_start_date = Date.parse(params[:report_start_date])\n</code></pre>\n\n<h1>Writing the call to ActiveRecord</h1>\n\n<p>Easy as pie.</p>\n\n<pre><code> #initialize start_date and end_date up here, by pulling from params probably\n @models = SomeModel.find(:all, :conditions =&gt; ['date &gt;= ? and date &lt;= ?',\n start_date, end_date])\n #do something with models\n</code></pre>\n" }, { "answer_id": 140588, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 2, "selected": false, "text": "<p>It's not an unRESTful practice to have URL parameters control the range of selected records. In your index action, you can do what Patrick suggested and have this: </p>\n\n<pre><code> #initialize start_date and end_date up here, by pulling from params probably\n @models = SomeModel.find(:all, :conditions =&gt; ['date &gt;= ? and date &lt;= ?', params[:start_date], params[:end_date]])\n</code></pre>\n\n<p>Then in your index view, create a form that tacks on ?start_date=2008-01-01&amp;end_date=2008-12-31 to the URL. Remember that it's user-supplied input, so be careful with it. If you put it back on the screen in your index action, be sure to do it like this: </p>\n\n<pre><code>Showing records starting on \n&lt;%= h start_date %&gt; \nand ending on \n&lt;%= h end_date %&gt;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ]
How would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers? edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates.
Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question? Date Picking Widgets ==================== 1) **Default Rails Solution**: See `date_select` documentation [here](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html). 2) **Use a plugin** : Why write code? I personally like the [CalendarDateSelect](http://code.google.com/p/calendardateselect/) plugin, using a pair of the suckers when I need a range. 3) **Adapt a Javascript widget to Rails**: It is almost trivial to integrate something like the Yahoo UI library (YUI) [Calendar](http://developer.yahoo.com/yui/calendar/), which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the `params[:start_date]` and `params[:end_date]`. YUI Calendar has native support for ranges. Getting the data from the Widgets ================================= 1) **Default Rails Solution** See `date_select` documentation [here](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html). ``` #an application helper method you'll find helpful #credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select # Reconstruct a date object from date_select helper form params def build_date_from_params(field_name, params) Date.new(params["#{field_name.to_s}(1i)"].to_i, params["#{field_name.to_s}(2i)"].to_i, params["#{field_name.to_s}(3i)"].to_i) end #goes into view <%= date_select "report", "start_date", ... %> <%= date_select "report", "end_date", ... %> #goes into controller -- add your own error handling/defaults, please! report_start_date = build_date_from_params("start_date", params[:report]) report_end_date = build_date_from_params("end_date", params[:report]) ``` 2) **CalendarDateSelect**: Rather similar to the above, just with sexier visible UI. 3) **Adapt a Javascript widget**: Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some\_form\_element\_name] will be initialized by Rails for you. ``` #goes in controller. Please handle errors yourself -- Javascript != trusted input. report_start_date = Date.parse(params[:report_start_date]) ``` Writing the call to ActiveRecord ================================ Easy as pie. ``` #initialize start_date and end_date up here, by pulling from params probably @models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?', start_date, end_date]) #do something with models ```
138,497
<p>How can I iterate over each file in a directory using a <code>for</code> loop?</p> <p>And how could I tell if a certain entry is a directory or if it's just a file?</p>
[ { "answer_id": 138513, "author": "Axeman", "author_id": 22108, "author_profile": "https://Stackoverflow.com/users/22108", "pm_score": 3, "selected": false, "text": "<pre><code>for %1 in (*.*) do echo %1\n</code></pre>\n\n<p>Try \"HELP FOR\" in cmd for a full guide</p>\n\n<p>This is the guide for XP commands. <a href=\"http://www.ss64.com/nt/\" rel=\"nofollow noreferrer\">http://www.ss64.com/nt/</a></p>\n" }, { "answer_id": 138522, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 4, "selected": false, "text": "<p>%1 refers to the first argument passed in and can't be used in an iterator.</p>\n\n<p>Try this: </p>\n\n<pre><code>@echo off\nfor %%i in (*.*) do echo %%i\n</code></pre>\n" }, { "answer_id": 138538, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 10, "selected": true, "text": "<p>This lists all the files (and only the files) in the current directory and its subdirectories recursively:</p>\n<pre><code>for /r %i in (*) do echo %i\n</code></pre>\n<p>Also if you run that command in a batch file you need to double the % signs.</p>\n<pre><code>for /r %%i in (*) do echo %%i\n</code></pre>\n<p>(thanks @agnul)</p>\n" }, { "answer_id": 138540, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>I would use vbscript (Windows Scripting Host), because in batch I'm sure you cannot tell that a name is a file or a directory.</p>\n\n<p>In vbs, it can be something like this:</p>\n\n<pre><code>Dim fileSystemObject\nSet fileSystemObject = CreateObject(\"Scripting.FileSystemObject\")\n\nDim mainFolder\nSet mainFolder = fileSystemObject.GetFolder(myFolder)\n\nDim files\nSet files = mainFolder.Files\n\nFor Each file in files\n...\nNext\n\nDim subFolders\nSet subFolders = mainFolder.SubFolders\n\nFor Each folder in subFolders\n...\nNext\n</code></pre>\n\n<p>Check <a href=\"http://msdn.microsoft.com/en-us/library/d6dw7aeh(VS.85).aspx\" rel=\"nofollow noreferrer\">FileSystemObject on MSDN</a>.</p>\n" }, { "answer_id": 138581, "author": "Marco", "author_id": 22620, "author_profile": "https://Stackoverflow.com/users/22620", "pm_score": 8, "selected": false, "text": "<p>Iterate through...</p>\n\n<ul>\n<li>...files in current dir: <code>for %f in (.\\*) do @echo %f</code></li>\n<li>...subdirs in current dir: <code>for /D %s in (.\\*) do @echo %s</code></li>\n<li>...files in current and all subdirs: <code>for /R %f in (.\\*) do @echo %f</code></li>\n<li>...subdirs in current and all subdirs: <code>for /R /D %s in (.\\*) do @echo %s</code></li>\n</ul>\n\n<p>Unfortunately I did not find any way to iterate over files and subdirs at the same time.</p>\n\n<p>Just use <a href=\"http://www.cygwin.com\" rel=\"noreferrer\">cygwin</a> with its bash for much more functionality.</p>\n\n<p>Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?</p>\n\n<p>Also have a look here: <a href=\"http://technet.microsoft.com/en-us/library/bb490890.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/bb490890.aspx</a></p>\n" }, { "answer_id": 138964, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 6, "selected": false, "text": "<p>There is a subtle difference between running <code>FOR</code> from the command line and from a batch file. In a batch file, you need to put two <code>%</code> characters in front of each variable reference.</p>\n\n<p>From a command line:</p>\n\n<pre><code>FOR %i IN (*) DO ECHO %i\n</code></pre>\n\n<p>From a batch file:</p>\n\n<pre><code>FOR %%i IN (*) DO ECHO %%i\n</code></pre>\n" }, { "answer_id": 1092220, "author": "Jay", "author_id": 151152, "author_profile": "https://Stackoverflow.com/users/151152", "pm_score": 6, "selected": false, "text": "<p>This for-loop will list all files in a directory.</p>\n\n<pre><code>pushd somedir\nfor /f \"delims=\" %%f in ('dir /b /a-d-h-s') do echo %%f\npopd\n</code></pre>\n\n<p>\"delims=\" is useful to show long filenames with spaces in it....</p>\n\n<p>'/b\" show only names, not size dates etc..</p>\n\n<p>Some things to know about dir's /a argument.</p>\n\n<ul>\n<li>Any use of \"/a\" would list everything, including hidden and system attributes.</li>\n<li>\"/ad\" would only show subdirectories, including hidden and system ones.</li>\n<li>\"/a-d\" argument eliminates content with 'D'irectory attribute.</li>\n<li>\"/a-d-h-s\" will show everything, but entries with 'D'irectory, 'H'idden 'S'ystem attribute.</li>\n</ul>\n\n<p>If you use this on the commandline, remove a \"%\".</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 3811318, "author": "Ankur", "author_id": 447137, "author_profile": "https://Stackoverflow.com/users/447137", "pm_score": 2, "selected": false, "text": "<p>The following code creates a file Named <strong><em>\"AllFilesInCurrentDirectorylist.txt\"</em></strong> in the current Directory, which contains the list of all files (Only Files) in the current Directory. Check it out</p>\n\n<pre><code>dir /b /a-d &gt; AllFilesInCurrentDirectorylist.txt\n</code></pre>\n" }, { "answer_id": 4596730, "author": "sugerfunk", "author_id": 562923, "author_profile": "https://Stackoverflow.com/users/562923", "pm_score": 2, "selected": false, "text": "<p>Try this to test if a file is a directory:</p>\n\n<pre><code>FOR /F \"delims=\" %I IN ('DIR /B /AD \"filename\" 2^&gt;^&amp;1 ^&gt;NUL') DO IF \"%I\" == \"File Not Found\" ECHO Not a directory\n</code></pre>\n\n<p>This only will tell you whether a file is NOT a directory, which will also be true if the file doesn't exist, so be sure to check for that first if you need to. The carets (^) are used to escape the redirect symbols and the file listing output is redirected to NUL to prevent it from being displayed, while the DIR listing's error output is redirected to the output so you can test against DIR's message \"File Not Found\".</p>\n" }, { "answer_id": 14085171, "author": "Knoots", "author_id": 1936983, "author_profile": "https://Stackoverflow.com/users/1936983", "pm_score": 2, "selected": false, "text": "<p>I use the xcopy command with the /L option to get the file names. So if you want to get either a directory or all the files in the subdirectory you could do something like this:</p>\n\n<pre><code>for /f \"delims=\" %%a IN ('xcopy \"D:\\*.pdf\" c:\\ /l') do echo %%a\n</code></pre>\n\n<p>I just use the c:\\ as the destination because it always exists on windows systems and it is not copying so it does not matter. if you want the subdirectories too just use /s option on the end. You can also use the other switches of xcopy if you need them for other reasons. </p>\n" }, { "answer_id": 25790431, "author": "Max", "author_id": 798927, "author_profile": "https://Stackoverflow.com/users/798927", "pm_score": 2, "selected": false, "text": "<p>It could also use the <a href=\"http://technet.microsoft.com/en-us/library/cc753551.aspx\" rel=\"nofollow\">forfiles</a> command:</p>\n\n<pre><code>forfiles /s \n</code></pre>\n\n<p>and also check if it is a directory </p>\n\n<pre><code>forfiles /p c:\\ /s /m *.* /c \"cmd /c if @isdir==true echo @file is a directory\"\n</code></pre>\n" }, { "answer_id": 37140635, "author": "Aaron Votre", "author_id": 5334898, "author_profile": "https://Stackoverflow.com/users/5334898", "pm_score": 7, "selected": false, "text": "<p><strong>To iterate over each file a for loop will work:</strong></p>\n\n<p><code>for %%f in (directory\\path\\*) do ( something_here )</code></p>\n\n<p><strong>In my case I also wanted the file content, name, etc.</strong> </p>\n\n<p><em>This lead to a few issues and I thought my use case might help. Here is a loop that reads info from each '.txt' file in a directory and allows you do do something with it (setx for instance).</em></p>\n\n<pre><code>@ECHO OFF\nsetlocal enabledelayedexpansion\nfor %%f in (directory\\path\\*.txt) do (\n set /p val=&lt;%%f\n echo \"fullname: %%f\"\n echo \"name: %%~nf\"\n echo \"contents: !val!\"\n)\n</code></pre>\n\n<p>*Limitation: val&lt;=%%f will only get the first line of the file.</p>\n" }, { "answer_id": 40930205, "author": "Littlepony", "author_id": 7210128, "author_profile": "https://Stackoverflow.com/users/7210128", "pm_score": 2, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>::Example directory\nset SetupDir=C:\\Users\n\n::Loop in the folder with \"/r\" to search in recursive folders, %%f being a loop ::variable \nfor /r \"%SetupDir%\" %%f in (*.msi *.exe) do set /a counter+=1\n\necho there are %counter% files in your folder\n</code></pre>\n\n<p>it counts .msi and .exe files in your directory (and in the sub directory). So it also makes the difference between folders and files as executables.</p>\n\n<p>Just add an extension (.pptx .docx ..) if you need to filter other files in the loop</p>\n" }, { "answer_id": 52523587, "author": "Sam B", "author_id": 1058419, "author_profile": "https://Stackoverflow.com/users/1058419", "pm_score": 1, "selected": false, "text": "<p>In my case I had to delete all the files and folders underneath a temp folder. So this is how I ended up doing it. I had to run two loops one for file and one for folders. If files or folders have spaces in their names then you have to use \" \"</p>\n\n<pre><code>cd %USERPROFILE%\\AppData\\Local\\Temp\\\nrem files only\nfor /r %%a in (*) do (\necho deleting file \"%%a\" ...\nif exist \"%%a\" del /s /q \"%%a\"\n)\nrem folders only\nfor /D %%a in (*) do (\necho deleting folder \"%%a\" ...\nif exist \"%%a\" rmdir /s /q \"%%a\"\n)\n</code></pre>\n" }, { "answer_id": 54925414, "author": "jafarbtech", "author_id": 6082645, "author_profile": "https://Stackoverflow.com/users/6082645", "pm_score": 3, "selected": false, "text": "<p>To <strong>iterate through all files and folders</strong> you can use</p>\n\n<pre><code>for /F \"delims=\" %%a in ('dir /b /s') do echo %%a\n</code></pre>\n\n<p>To <strong>iterate through all folders only</strong> not with files, then you can use</p>\n\n<pre><code>for /F \"delims=\" %%a in ('dir /a:d /b /s') do echo %%a\n</code></pre>\n\n<p>Where <code>/s</code> will give all results throughout the directory tree in unlimited depth. You can skip <code>/s</code> if you want to iterate through the content of that folder not their sub folder</p>\n\n<h2>Implementing search in iteration</h2>\n\n<p>To <strong>iterate through a particular named files and folders</strong> you can search for the name and iterate using for loop</p>\n\n<pre><code>for /F \"delims=\" %%a in ('dir \"file or folder name\" /b /s') do echo %%a\n</code></pre>\n\n<p>To <strong>iterate through a particular named folders/directories and not files</strong>, then use <code>/AD</code> in the same command</p>\n\n<pre><code>for /F \"delims=\" %%a in ('dir \"folder name\" /b /AD /s') do echo %%a\n</code></pre>\n" }, { "answer_id": 56761665, "author": "datchung", "author_id": 4856020, "author_profile": "https://Stackoverflow.com/users/4856020", "pm_score": 3, "selected": false, "text": "<p>I had trouble getting jop's answer to work with an absolute path until I found this reference: <a href=\"https://ss64.com/nt/for_r.html\" rel=\"noreferrer\">https://ss64.com/nt/for_r.html</a></p>\n\n<p>The following example loops through all files in a directory given by the absolute path.</p>\n\n<pre><code>For /R C:\\absoulte\\path\\ %%G IN (*.*) do (\n Echo %%G\n)\n</code></pre>\n" }, { "answer_id": 59904503, "author": "Ste", "author_id": 8262102, "author_profile": "https://Stackoverflow.com/users/8262102", "pm_score": 3, "selected": false, "text": "<p>Here's my go with comments in the code.</p>\n\n<p>I'm just brushing up by biatch skills so forgive any blatant errors.</p>\n\n<p>I tried to write an all in one solution as best I can with a little modification where the user requires it.</p>\n\n<p><strong>Some important notes:</strong> Just change the variable <code>recursive</code> to <code>FALSE</code> if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.</p>\n\n<p><em>C&amp;C most welcome...</em></p>\n\n<pre><code>@echo off\ntitle %~nx0\nchcp 65001 &gt;NUL\nset \"dir=c:\\users\\%username%\\desktop\"\n::\n:: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1\n::\nsetlocal EnableDelayedExpansion\nrem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]\nrem By removing the /s switch from the first loop if you want to loop through\nrem the base folder only.\nset recursive=TRUE\nif %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )\nendlocal &amp; set recursive=%recursive%\ncd /d %dir%\necho Directory %cd%\nfor %%F in (\"*\") do (echo → %%F) %= Loop through the current directory. =%\nfor /f \"delims==\" %%D in ('dir \"%dir%\" /ad /b %recursive%') do ( %= Loop through the sub-directories only if the recursive variable is TRUE. =%\n echo Directory %%D\n echo %recursive% | find \"/s\" &gt;NUL 2&gt;NUL &amp;&amp; (\n pushd %%D\n cd /d %%D\n for /f \"delims==\" %%F in ('dir \"*\" /b') do ( %= Then loop through each pushd' folder and work on the files and folders =%\n echo %%~aF | find /v \"d\" &gt;NUL 2&gt;NUL &amp;&amp; ( %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%\n rem You can do stuff to your files here.\n rem Below are some examples of the info you can get by expanding the %%F variable.\n rem Uncomment one at a time to see the results.\n echo → %%~F &amp;rem expands %%F removing any surrounding quotes (\")\n rem echo → %%~dF &amp;rem expands %%F to a drive letter only\n rem echo → %%~fF &amp;rem expands %%F to a fully qualified path name\n rem echo → %%~pF &amp;rem expands %%A to a path only\n rem echo → %%~nF &amp;rem expands %%F to a file name only\n rem echo → %%~xF &amp;rem expands %%F to a file extension only\n rem echo → %%~sF &amp;rem expanded path contains short names only\n rem echo → %%~aF &amp;rem expands %%F to file attributes of file\n rem echo → %%~tF &amp;rem expands %%F to date/time of file\n rem echo → %%~zF &amp;rem expands %%F to size of file\n rem echo → %%~dpF &amp;rem expands %%F to a drive letter and path only\n rem echo → %%~nxF &amp;rem expands %%F to a file name and extension only\n rem echo → %%~fsF &amp;rem expands %%F to a full path name with short names only\n rem echo → %%~dp$dir:F &amp;rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string\n rem echo → %%~ftzaF &amp;rem expands %%F to a DIR like output line\n )\n )\n popd\n )\n )\necho/ &amp; pause &amp; cls\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
How can I iterate over each file in a directory using a `for` loop? And how could I tell if a certain entry is a directory or if it's just a file?
This lists all the files (and only the files) in the current directory and its subdirectories recursively: ``` for /r %i in (*) do echo %i ``` Also if you run that command in a batch file you need to double the % signs. ``` for /r %%i in (*) do echo %%i ``` (thanks @agnul)
138,501
<p>I have mixed data i nvarchar column (words and numbers). Which is fastest way to sort data in this column in Numeric Order.</p> <p>Result example:</p> <ul> <li>1</li> <li>2</li> <li>3</li> <li>...</li> <li>10</li> <li>11</li> <li>...</li> <li>aaaa</li> <li>aaab</li> <li>b</li> <li>ba</li> <li>ba</li> <li>...</li> </ul>
[ { "answer_id": 138507, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": -1, "selected": false, "text": "<p>Cast it. </p>\n\n<pre><code>SELECT * FROM foo ORDER BY CAST(somecolumn AS int);\n</code></pre>\n\n<p>Been a while since I've touched SQL Server, so my syntax might be entirely incorrect though :)</p>\n" }, { "answer_id": 138525, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 0, "selected": false, "text": "<p>You can either treat the data as alphanumeric, or numeric, not both at the same time. I don't think what you're trying to do is possible, the data model isn't set up appropriately.</p>\n" }, { "answer_id": 138549, "author": "SelvirK", "author_id": 17465, "author_profile": "https://Stackoverflow.com/users/17465", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>I don't think what you're trying to do\n is possible</p>\n</blockquote>\n\n<p>This example works fine</p>\n\n<pre><code>SELECT * FROM TableName\nORDER BY CASE WHEN 1 = IsNumeric(ColumnName) THEN Cast(ColumnName AS INT) END\n</code></pre>\n\n<p>Result is:</p>\n\n<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n<li>...</li>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>\n\n<p>But i need numbers first.</p>\n" }, { "answer_id": 138563, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 1, "selected": false, "text": "<p>--check for existance<br>\nif exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1)<br>\n drop table dbo.t<br>\ngo</p>\n\n<p>--create example table<br>\ncreate table dbo.t (c varchar(10) not null)<br>\nset nocount on </p>\n\n<p>--populate example table<br>\ninsert into dbo.t (c) values ('1')<br>\ninsert into dbo.t (c) values ('2')<br>\ninsert into dbo.t (c) values ('3 ')<br>\ninsert into dbo.t (c) values ('10 ')<br>\ninsert into dbo.t (c) values ('11')<br>\ninsert into dbo.t (c) values ('aaaa')<br>\ninsert into dbo.t (c) values ('aaab')<br>\ninsert into dbo.t (c) values ('b')<br>\ninsert into dbo.t (c) values ('ba')<br>\ninsert into dbo.t (c) values ('ba') </p>\n\n<p>--return the data<br>\nselect c from dbo.t<br>\norder by case when isnumeric(c) = 1 then 0 else 1 end,<br>\ncase when isnumeric(c) = 1 then cast(c as int) else 0 end,<br>\nc </p>\n" }, { "answer_id": 138567, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>ORDER BY\n CASE WHEN ISNUMERIC(column) = 1 THEN 0 ELSE 1 END,\n CASE WHEN ISNUMERIC(column) = 1 THEN CAST(column AS INT) ELSE 0 END,\n column\n</code></pre>\n\n<p>This works as expected.</p>\n\n<hr>\n\n<p><strong>Note</strong>: You say <em>fastest way</em>. This sql was fast for me to produce, but the execution plan shows a table-scan, followed by a scalar computation. This could possibly produce a temporary result containing all the values of that column with some extra temporary columns for the ISNUMERIC results. It might not be fast to execute.</p>\n" }, { "answer_id": 139562, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 2, "selected": false, "text": "<p>If you left pad your numbers with 0's and sort on that, you will get your desired results. You'll need to make sure that the number of 0's you pad with matches the size of the varchar column.</p>\n\n<p>Take a look at this example...</p>\n\n<pre><code>Declare @Temp Table(Data VarChar(20))\n\nInsert Into @Temp Values('1')\nInsert Into @Temp Values('2')\nInsert Into @Temp Values('3')\nInsert Into @Temp Values('10')\nInsert Into @Temp Values('11')\nInsert Into @Temp Values('aaaa')\nInsert Into @Temp Values('aaab')\nInsert Into @Temp Values('b')\nInsert Into @Temp Values('ba')\nInsert Into @Temp Values('ba')\n\nSelect * From @Temp\nOrder By Case When IsNumeric(Data) = 1 \n Then Right('0000000000000000000' + Data, 20) \n Else Data End\n</code></pre>\n\n<p>Also note that it is important when using a case statement that each branch of the case statement returns the same data type, or else you will get incorrect results or an error.</p>\n" }, { "answer_id": 139618, "author": "Learning", "author_id": 18275, "author_profile": "https://Stackoverflow.com/users/18275", "pm_score": -1, "selected": false, "text": "<p>This should work :</p>\n\n<pre><code>select * from Table order by ascii(Column)\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
I have mixed data i nvarchar column (words and numbers). Which is fastest way to sort data in this column in Numeric Order. Result example: * 1 * 2 * 3 * ... * 10 * 11 * ... * aaaa * aaab * b * ba * ba * ...
Use this: ``` ORDER BY CASE WHEN ISNUMERIC(column) = 1 THEN 0 ELSE 1 END, CASE WHEN ISNUMERIC(column) = 1 THEN CAST(column AS INT) ELSE 0 END, column ``` This works as expected. --- **Note**: You say *fastest way*. This sql was fast for me to produce, but the execution plan shows a table-scan, followed by a scalar computation. This could possibly produce a temporary result containing all the values of that column with some extra temporary columns for the ISNUMERIC results. It might not be fast to execute.
138,508
<p>My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)</p> <ol> <li>Models are the things that interface with the database</li> <li>Views are the design/layout of the page</li> <li>Controllers are where everything starts and are essentially the page logic</li> </ol> <p>I'm using <a href="http://codeigniter.com/" rel="noreferrer">CodeIgniter</a> but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.</p> <p>Where do I put global classes?</p> <p>I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)</p>
[ { "answer_id": 138527, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 1, "selected": false, "text": "<p>In <a href=\"http://cakephp.org\" rel=\"nofollow noreferrer\">CakePHP</a> there are 3 more \"parts\" : </p>\n\n<ol>\n<li>Behaviors </li>\n<li>Components</li>\n<li>Helpers</li>\n</ol>\n\n<p>Logic that are used by many models should be made as a behavior. I do not know if CodeIgniter have this logic or not, but if it doesnt, I would try to implement it as such. You can read about behaviors <a href=\"http://book.cakephp.org/view/88/Behaviors\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>(Components helps controller share logic and helpers help views in the same way).</p>\n" }, { "answer_id": 138595, "author": "kosoant", "author_id": 15114, "author_profile": "https://Stackoverflow.com/users/15114", "pm_score": 3, "selected": true, "text": "<p>Model is the wrong word to use when discussing what to do with products: each product is a <b>value object (VO)</b> (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table.</p>\n\n<p>Model is a <b>Data Access Object (DAO)</b> that has methods like</p>\n\n<pre><code>findByPk --&gt; returns a single value object\nfindAll --&gt; returns a collection of value objects (0-n)\netc.\n</code></pre>\n\n<p>In your case you would have a ProductDAO that has something like the above methods. This ProductDAO would then return ProductVO's and collections of them.</p>\n\n<p>Data Access Objects can also return <b>Business Objects (BO)</b> which may contain multiple VO's and additional methods that are business case specific. </p>\n\n<p>Addendum:\nIn your controller you call a ProductDAO to find the products you want.\nThe returned ProductVO(s) are then passed to the view (as request attributes in Java). The view then loops through/displays the data from the productVO's.</p>\n" }, { "answer_id": 138596, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "<p><strong>Model</strong> is part of your application where business logic happens. Model represents real life relations and dependencies between objects, like: Employee reports to a Manager, Manager supervises many Employees, Manager can assign Task to Employee, Task sends out notification when overdue. Model CAN and most often DO interface with database, but this is not a requirement.</p>\n\n<p><strong>View</strong> is basically everything that can be displayed or help in displaying. View contains templates, template objects, handles template composition and nesting, wraps with headers and footers, and produces output in one of well known formats (X/HTML, but also XML, RSS/Atom, CSV).</p>\n\n<p><strong>Controller</strong> is a translation layer that translates user actions to model operations. In other words, it tells model what to do and returns a response. Controller methods should be as small as possible and all business processing should be done in Model, and view logic processing should take place in View.</p>\n\n<p>Now, back to your question. It really depends if you need separate class for each product. In most cases, one class will suffice and 20 instances of it should be created. As products represent business logic it should belong to Model part of your application.</p>\n" }, { "answer_id": 138764, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 1, "selected": false, "text": "<p>The simplest way is to:</p>\n\n<ol>\n<li>Have a model class per database table. In this case it would be an object that held all the Product details.</li>\n<li>Put these classes into a package/namespace, e.g., com.company.model (Java / C#)</li>\n<li>Put the DAO classes into a package like com.company.model.dao</li>\n<li>Your view will consume data from the session/request/controller In this case I would have a List&lt;Product>.</li>\n<li>Oh, you're using PHP. Dunno how that changes things, but I imagine it has a Collections framework like any modern language.</li>\n</ol>\n" }, { "answer_id": 139120, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 1, "selected": false, "text": "<p>@Alexander mentions CakePHPs <em>Behaviors</em>, <em>Components</em> and <em>Helpers</em>. These are excellent for abstracting out common functionality. I find the Behaviors particularly useful as of course the bulk of the business logic is carried in the models. I am currently working on a project where we have behaviors like: </p>\n\n<ul>\n<li>Lockable</li>\n<li>Publishable</li>\n<li>Tagable</li>\n<li>Rateable</li>\n<li>Commentable</li>\n</ul>\n\n<p>etc.</p>\n\n<p>For code that transcends even the MVC framework i.e. code libraries that you use for various things that are not tied in to the particular framework you are using - in our case things like video encoding classes etc. CakePHP has the <em>vendors</em> folder. </p>\n\n<p>Anything that effectively has nothing to do with CakePHP goes in there. </p>\n\n<p>I suspect CodeIgniter doesn't have quite as flexible a structure, it's smaller and lighter than CakePHP, but a quick look at the <a href=\"http://manual.cakephp.org\" rel=\"nofollow noreferrer\">CakePHP Manual</a> to see how Behaviors, Components, Helpers, and the Vendors folder may be helpful. </p>\n\n<p>It should be an easy matter to just include some common helper classes from your models keep nice and <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it) 1. Models are the things that interface with the database 2. Views are the design/layout of the page 3. Controllers are where everything starts and are essentially the page logic I'm using [CodeIgniter](http://codeigniter.com/) but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks. Where do I put global classes? I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)
Model is the wrong word to use when discussing what to do with products: each product is a **value object (VO)** (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table. Model is a **Data Access Object (DAO)** that has methods like ``` findByPk --> returns a single value object findAll --> returns a collection of value objects (0-n) etc. ``` In your case you would have a ProductDAO that has something like the above methods. This ProductDAO would then return ProductVO's and collections of them. Data Access Objects can also return **Business Objects (BO)** which may contain multiple VO's and additional methods that are business case specific. Addendum: In your controller you call a ProductDAO to find the products you want. The returned ProductVO(s) are then passed to the view (as request attributes in Java). The view then loops through/displays the data from the productVO's.
138,511
<p>I know there's some <code>JAVA_OPTS</code> to set to remotely debug a Java program.</p> <p>What are they and what do they mean ?</p>
[ { "answer_id": 138518, "author": "Hans Sjunnesson", "author_id": 8683, "author_profile": "https://Stackoverflow.com/users/8683", "pm_score": 10, "selected": true, "text": "<p>I have <a href=\"http://www.eclipsezone.com/eclipse/forums/t53459.html\" rel=\"noreferrer\">this article</a> bookmarked on setting this up for Java 5 and below.</p>\n<p>Basically <a href=\"http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/tooldocs/windows/jdb.html\" rel=\"noreferrer\">run it with</a>:</p>\n<pre><code>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044\n</code></pre>\n<p>For <a href=\"http://javahowto.blogspot.ru/2010/09/java-agentlibjdwp-for-attaching.html\" rel=\"noreferrer\">Java 5 and above</a>, run it with:</p>\n<pre><code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044\n</code></pre>\n<p>If you want Java to <strong>wait for you to connect</strong> before executing the application, replace <code>suspend=n</code> with <code>suspend=y</code>.</p>\n" }, { "answer_id": 173447, "author": "paulgreg", "author_id": 3122, "author_profile": "https://Stackoverflow.com/users/3122", "pm_score": 9, "selected": false, "text": "<p>Before Java 5.0, use <code>-Xdebug</code> and <code>-Xrunjdwp</code> arguments. These options will still work in later versions, but it will run in interpreted mode instead of JIT, which will be slower.</p>\n\n<p>From Java 5.0, it is better to use the <code>-agentlib:jdwp</code> single option:</p>\n\n<pre><code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044\n</code></pre>\n\n<p>Options on <code>-Xrunjdwp</code> or <code>agentlib:jdwp</code> arguments are :</p>\n\n<ul>\n<li><code>transport=dt_socket</code> : means the way used to connect to JVM (socket is a good choice, it can be used to debug a distant computer)</li>\n<li><code>address=8000</code> : TCP/IP port exposed, to connect from the debugger, </li>\n<li><code>suspend=y</code> : if 'y', tell the JVM to wait until debugger is attached to begin execution, otherwise (if 'n'), starts execution right away.</li>\n</ul>\n" }, { "answer_id": 40306242, "author": "thebiggestlebowski", "author_id": 1483903, "author_profile": "https://Stackoverflow.com/users/1483903", "pm_score": 4, "selected": false, "text": "<p>For java 1.5 or greater: </p>\n\n<pre><code>java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 &lt;YourAppName&gt;\n</code></pre>\n\n<p>For java 1.4:</p>\n\n<pre><code>java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 &lt;YourAppName&gt;\n</code></pre>\n\n<p>For java 1.3: </p>\n\n<pre><code>java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 &lt;YourAppName&gt;\n</code></pre>\n\n<p>Here is output from a simple program:</p>\n\n<pre><code>java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled\nListening for transport dt_socket at address: 1044\nHello whirled\n</code></pre>\n" }, { "answer_id": 46329491, "author": "neves", "author_id": 10335, "author_profile": "https://Stackoverflow.com/users/10335", "pm_score": 2, "selected": false, "text": "<p>Here is the easiest solution.</p>\n\n<p>There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the <code>mvnDebug</code> command instead of <code>mvn</code>, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000. </p>\n\n<p>It'll take care of all the environment problems for you.</p>\n" }, { "answer_id": 48396996, "author": "Antony Shumskikh", "author_id": 6488013, "author_profile": "https://Stackoverflow.com/users/6488013", "pm_score": 7, "selected": false, "text": "<p>Since Java 9.0 JDWP supports only local connections by default.\n<a href=\"http://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435\" rel=\"noreferrer\">http://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435</a></p>\n\n<p>For remote debugging one should run program with <code>*:</code> in address:</p>\n\n<pre><code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000\n</code></pre>\n" }, { "answer_id": 49569527, "author": "Jovi Qiao", "author_id": 9573426, "author_profile": "https://Stackoverflow.com/users/9573426", "pm_score": 3, "selected": false, "text": "<h3>java</h3>\n\n<pre><code>java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=y -jar target/cxf-boot-simple-0.0.1-SNAPSHOT.jar\n</code></pre>\n\n<p><code>address</code> specifies the port at which it will allow to debug</p>\n\n<h3>Maven</h3>\n\n<p>**Debug Spring Boot app with Maven:</p>\n\n<pre><code>mvn spring-boot:run -Drun.jvmArguments=**\"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8001\"\n</code></pre>\n" }, { "answer_id": 54864975, "author": "Santosh b", "author_id": 5156999, "author_profile": "https://Stackoverflow.com/users/5156999", "pm_score": 2, "selected": false, "text": "<h2>Command Line</h2>\n\n<pre><code>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=PORT_NUMBER\n</code></pre>\n\n<h2>Gradle</h2>\n\n<pre><code>gradle bootrun --debug-jvm\n</code></pre>\n\n<h2>Maven</h2>\n\n<pre><code>mvn spring-boot:run -Drun.jvmArguments=\"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER\n</code></pre>\n" }, { "answer_id": 59893443, "author": "Boney", "author_id": 6102097, "author_profile": "https://Stackoverflow.com/users/6102097", "pm_score": 1, "selected": false, "text": "<pre><code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER\n</code></pre>\n\n<p>Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.</p>\n\n<p>For more details u can refer to : <a href=\"https://stackify.com/java-remote-debugging/\" rel=\"nofollow noreferrer\">https://stackify.com/java-remote-debugging/</a></p>\n" }, { "answer_id": 70015702, "author": "Prashant Jainer", "author_id": 7030465, "author_profile": "https://Stackoverflow.com/users/7030465", "pm_score": -1, "selected": false, "text": "<p>If you are using java 9 or higher, to remotely debug (which is also the case when you use docker at local) you have to provide <code>--debug *:($port)</code>. Because from java 9 <code>--debug ($port)</code> will only allow to debug <em><strong>at local, not remotely</strong></em>.</p>\n<p>So, you can provide command in docker-compose like\n<code>command: -- /opt/jboss/wildfly/bin/standalone.sh --debug *:8787</code></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
I know there's some `JAVA_OPTS` to set to remotely debug a Java program. What are they and what do they mean ?
I have [this article](http://www.eclipsezone.com/eclipse/forums/t53459.html) bookmarked on setting this up for Java 5 and below. Basically [run it with](http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/tooldocs/windows/jdb.html): ``` -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 ``` For [Java 5 and above](http://javahowto.blogspot.ru/2010/09/java-agentlibjdwp-for-attaching.html), run it with: ``` -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044 ``` If you want Java to **wait for you to connect** before executing the application, replace `suspend=n` with `suspend=y`.
138,514
<p>I have a ASP.NET 2.0 webpage with 2 UserControls (.ascx). Each UserControl contains a bunch of validators. Placing a ValidationSummary on the page will display all validation errors, of both UserControl's. Placing a ValidationSummary in each UserControl will display all the errors of both controls twice. </p> <p>What I want is a ValidationSummary for each UserControl, displaying only the errors on that UserControl. </p> <p>I've tried to solve this by setting the ValidationGroup property of the validators on each usercontrol dynamicaly. That way each validationsummary should display only the errors of its UserControl. I've used this code:</p> <pre><code>foreach (Control ctrl in this.Controls) { if (ctrl is BaseValidator) { (ctrl as BaseValidator).ValidationGroup = this.ClientID; } } ValidationSummary1.ValidationGroup = this.ClientID; </code></pre> <p>This however seems to disable both clientside and server side validation, because no validation occurs when submitting the form.</p> <p>Help?</p>
[ { "answer_id": 138557, "author": "Jonathan Carter", "author_id": 6412, "author_profile": "https://Stackoverflow.com/users/6412", "pm_score": 2, "selected": false, "text": "<p>The control that is causing your form submission (i.e. a Button control) has to be a part of the same validation group as any ValidationSummary and *Validator controls.</p>\n" }, { "answer_id": 139099, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 3, "selected": true, "text": "<p>If you use ValidationGroups, the validation only occurs if the control causing the postback is assign to the same ValidationGroup.</p>\n\n<p>If you want to use a single control to postback you can still do this but you would need to explicitly call the Page.Validate method.</p>\n\n<pre><code>Page.Validate(MyValidationGroup1);\nPage.Validate(MyValidationGroup2);\nif(Page.IsValid)\n{\n //do stuff\n}\n</code></pre>\n\n<p>Suggestion:\nWhy don't you expose a public property on your user controls called ValidationGroup?\nIn the setter you could explicitly set the validation group for each validator. You could also use your loop, but it would be more efficient to set each validator explicitly. This might improve the readability of the code using the user controls.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
I have a ASP.NET 2.0 webpage with 2 UserControls (.ascx). Each UserControl contains a bunch of validators. Placing a ValidationSummary on the page will display all validation errors, of both UserControl's. Placing a ValidationSummary in each UserControl will display all the errors of both controls twice. What I want is a ValidationSummary for each UserControl, displaying only the errors on that UserControl. I've tried to solve this by setting the ValidationGroup property of the validators on each usercontrol dynamicaly. That way each validationsummary should display only the errors of its UserControl. I've used this code: ``` foreach (Control ctrl in this.Controls) { if (ctrl is BaseValidator) { (ctrl as BaseValidator).ValidationGroup = this.ClientID; } } ValidationSummary1.ValidationGroup = this.ClientID; ``` This however seems to disable both clientside and server side validation, because no validation occurs when submitting the form. Help?
If you use ValidationGroups, the validation only occurs if the control causing the postback is assign to the same ValidationGroup. If you want to use a single control to postback you can still do this but you would need to explicitly call the Page.Validate method. ``` Page.Validate(MyValidationGroup1); Page.Validate(MyValidationGroup2); if(Page.IsValid) { //do stuff } ``` Suggestion: Why don't you expose a public property on your user controls called ValidationGroup? In the setter you could explicitly set the validation group for each validator. You could also use your loop, but it would be more efficient to set each validator explicitly. This might improve the readability of the code using the user controls.
138,533
<p>I have a swing gui with a tabbed pane in the north. Several key events are added to its input map:</p> <pre><code>InputMap paneInputMap = pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_E, KeyEvent.CTRL_MASK ), "finish"); paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_F1, KeyEvent.CTRL_MASK ), "toggletoolbar"); </code></pre> <p>If the tabbed pane or another button in a toolbar has the focus, <kbd>Ctrl</kbd>+<kbd>F1</kbd> has no function. If another component is focused (e.g. JTree), <kbd>Ctrl</kbd>+<kbd>F1</kbd> executes the action.</p> <p>The problem is, that it workes everywhere if I change the Keycode to e.g. <code>VK_F2</code>.</p> <p>The key <kbd>F1</kbd> is'nt used anywhere else in the program.</p> <p>Any idea?</p> <p>Thanks, André</p> <p><strong>Edit:</strong> A full text search in the java source code gave the answer: The <code>ToolTipManager</code> registeres the Key <kbd>Ctrl</kbd>+<kbd>F1</kbd> to display the tooltip text if the key combination is pressed. So if a button with a tooltip is focused, <kbd>Ctrl</kbd>+<kbd>F1</kbd> is handled by the <code>ToolTipManager</code>. Otherwise my action is called.</p>
[ { "answer_id": 138668, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 0, "selected": false, "text": "<p>May be the OS retargets the <kbd>F1</kbd> key? Install a key listener and see what events are handled.</p>\n\n<p>BTW: It would help if you could edit your question and insert some testable code.</p>\n" }, { "answer_id": 138767, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 3, "selected": true, "text": "<p>So that this gets an answer, here's the solution copied from your edit in the question. ;-)</p>\n\n<blockquote>\n <p>The ToolTipManager registeres the Key\n <kbd>Ctrl</kbd>+<kbd>F1</kbd> to display the tooltip text if\n the key combination is pressed. So if\n a button with a tooltip is focused,\n <kbd>Ctrl</kbd>+<kbd>F1</kbd> is handled by the\n ToolTipManager. Otherwise my action is\n called.</p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18633/" ]
I have a swing gui with a tabbed pane in the north. Several key events are added to its input map: ``` InputMap paneInputMap = pane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_E, KeyEvent.CTRL_MASK ), "finish"); paneInputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_F1, KeyEvent.CTRL_MASK ), "toggletoolbar"); ``` If the tabbed pane or another button in a toolbar has the focus, `Ctrl`+`F1` has no function. If another component is focused (e.g. JTree), `Ctrl`+`F1` executes the action. The problem is, that it workes everywhere if I change the Keycode to e.g. `VK_F2`. The key `F1` is'nt used anywhere else in the program. Any idea? Thanks, André **Edit:** A full text search in the java source code gave the answer: The `ToolTipManager` registeres the Key `Ctrl`+`F1` to display the tooltip text if the key combination is pressed. So if a button with a tooltip is focused, `Ctrl`+`F1` is handled by the `ToolTipManager`. Otherwise my action is called.
So that this gets an answer, here's the solution copied from your edit in the question. ;-) > > The ToolTipManager registeres the Key > `Ctrl`+`F1` to display the tooltip text if > the key combination is pressed. So if > a button with a tooltip is focused, > `Ctrl`+`F1` is handled by the > ToolTipManager. Otherwise my action is > called. > > >
138,550
<p>I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.</p> <p>For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.</p>
[ { "answer_id": 139151, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 3, "selected": false, "text": "<p>\"If your application handles its own file data type, you will need to register a file association for it. Put a ProgId inside your component. FileId should refer to the Id attribute of the File element describing the file meant to handle the files of this extension. Note the exclamation mark: it will return the short path of the file instead of the long one:\"</p>\n\n<pre><code>&lt;ProgId Id='AcmeFoobar.xyzfile' Description='Acme Foobar data file'&gt;\n &lt;Extension Id='xyz' ContentType='application/xyz'&gt;\n &lt;Verb Id='open' Sequence='10' Command='Open' Target='[!FileId]' Argument='\"%1\"' /&gt;\n &lt;/Extension&gt;\n&lt;/ProgId&gt;\n</code></pre>\n\n<p>Reference: <a href=\"https://www.firegiant.com/wix/tutorial/getting-started/beyond-files/\" rel=\"nofollow noreferrer\">https://www.firegiant.com/wix/tutorial/getting-started/beyond-files/</a></p>\n" }, { "answer_id": 139168, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 4, "selected": false, "text": "<p>After some additional research, I found a partial answer to this question in the <a href=\"http://www.tramontana.co.hu/wix/lesson1.php#1.7\" rel=\"noreferrer\">WiX Tutorial</a>. It shows an advertised solution and does not work with WiX 3.0, but given that information, I figured it out. Add a ProgId element to the component containing your executable, like the following:</p>\n<pre><code>&lt;ProgId Id=&quot;MyApplication.MyFile&quot; Description=&quot;My file type&quot;&gt;\n &lt;Extension Id=&quot;myext&quot; ContentType=&quot;application/whatever&quot;&gt;\n &lt;Verb Id=&quot;open&quot; Command=&quot;open&quot; TargetFile=&quot;MyApplication.exe&quot; Argument=&quot;&amp;quot;%1&amp;quot;&quot;/&gt;\n &lt;/Extension&gt;\n&lt;/ProgId&gt;\n</code></pre>\n<p>myext is the file extension without the dot, and MyApplication.exe is the file id (not name) of the executable file (i.e. the Id attribute of the File element).\nThis will register the file type with your executable and will supply a default icon (a white page with the application icon on it), which is sufficient for my needs. If you want to specify a dedicated icon, it seems you still have to do this yourself, like the following (code from the linked tutorial):</p>\n<pre><code>&lt;Registry Id='FooIcon1' Root='HKCR' Key='.xyz' Action='write' Type='string' Value='AcmeFoobar.xyzfile' /&gt;\n&lt;Registry Id='FooIcon2' Root='HKCR' Key='AcmeFoobar.xyzfile' Action='write' Type='string' Value='Acme Foobar data file' /&gt;\n&lt;Registry Id='FooIcon3' Root='HKCR' Key='AcmeFoobar.xyzfile\\DefaultIcon' Action='write' Type='string' Value='[INSTALLDIR]Foobar.exe,1' /&gt;\n</code></pre>\n<p>I didn't find a good solution for my bonus question though.</p>\n<p>Edit: I started writing this before the previous answer came. However, my solution actually works, in contrast to the previous answer.</p>\n" }, { "answer_id": 909334, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 4, "selected": false, "text": "<p>Unfortunately there's no way to do a \"safe\" association with Windows Installer. </p>\n\n<p>We just write everything out to the registry and then have a separate component that takes over the system-wide default and is only installed if no other application has already registered itself as the default.</p>\n\n<p>With Vista there's the new \"default programs\" interface, again you write everything out to the registry. Here's a complete example that we're using in our installer. (WiX 3.0)</p>\n\n<p><strong>Update:</strong> 12 months have passed since my original answer and I have a better understanding of file associations. Rather than writing everything manually I'm now using proper <code>ProgId</code> definitions which improves handling for advertised packages. See the updated code <a href=\"https://stackoverflow.com/questions/2772452/how-to-register-application-for-existing-file-types-using-wix-installer\">posted in response to this question</a>. </p>\n\n<pre><code>&lt;Component ....&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\" Name=\"ApplicationDescription\" Value=\"ACME Foobar XYZ Editor\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\" Name=\"ApplicationIcon\" Value=\"[APPLICATIONFOLDER]AcmeFoobar.exe,0\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\" Name=\"ApplicationName\" Value=\"ACME Foobar\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\\DefaultIcon\" Value=\"[APPLICATIONFOLDER]AcmeFoobar.exe,1\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\\FileAssociations\" Name=\".xyz\" Value=\"AcmeFoobar.Document\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\\MIMEAssociations\" Name=\"application/xyz\" Value=\"AcmeFoobar.Document\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\AcmeFoobar\\Capabilities\\shell\\Open\\command\" Value=\"&amp;quot;[APPLICATIONFOLDER]AcmeFoobar.exe&amp;quot; &amp;quot;%1&amp;quot;\" Type=\"string\" /&gt;\n\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\RegisteredApplications\" Name=\"Acme Foobar\" Value=\"SOFTWARE\\AcmeFoobar\\Capabilities\" Type=\"string\" /&gt;\n\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\.xyz\" Name=\"Content Type\" Value=\"application/xyz\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\.xyz\\AcmeFoobar.Document\\ShellNew\" Value=\"\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\.xyz\\OpenWithList\\AcmeFoobar.exe\" Value=\"\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\.xyz\\OpenWithProgids\" Name=\"AcmeFoobar.Document\" Value=\"\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\Applications\\AcmeFoobar.exe\\SupportedTypes\" Name=\".xyz\" Value=\"\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\Applications\\AcmeFoobar.exe\\shell\\open\" Name=\"FriendlyAppName\" Value=\"ACME Foobar\" Type=\"string\" /&gt;\n\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcmeFoobar.exe\" Value=\"[!AcmeFoobar.exe]\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcmeFoobar.exe\" Name=\"Path\" Value=\"[APPLICATIONFOLDER]\" Type=\"string\" /&gt;\n\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\SystemFileAssociations\\.xyz\\shell\\edit.AcmeFoobar.exe\" Value=\"Edit with ACME Foobar\" Type=\"string\" /&gt;\n &lt;RegistryValue Root=\"HKLM\" Key=\"SOFTWARE\\Classes\\SystemFileAssociations\\.xyz\\shell\\edit.AcmeFoobar.exe\\command\" Value=\"&amp;quot;[APPLICATIONFOLDER]AcmeFoobar.exe&amp;quot; &amp;quot;%1&amp;quot;\" Type=\"string\" /&gt;\n\n&lt;/Component&gt;\n\n\n\n&lt;Component ....&gt;\n &lt;ProgId Id=\"AcmeFoobar.Document\" Description=\"ACME XYZ Document\"&gt;\n &lt;Extension Id=\"pdf\" ContentType=\"application/xyz\"&gt;\n &lt;Verb Id=\"open\" Command=\"Open\" TargetFile=\"[APPLICATIONFOLDER]AcmeFoobar.exe\" Argument=\"%1\" /&gt;\n &lt;/Extension&gt;\n &lt;/ProgId&gt;\n\n &lt;Condition&gt;&lt;![CDATA[DEFAULTVIEWER=1]]&gt;&lt;/Condition&gt;\n&lt;/Component&gt;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20363/" ]
I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution. For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.
After some additional research, I found a partial answer to this question in the [WiX Tutorial](http://www.tramontana.co.hu/wix/lesson1.php#1.7). It shows an advertised solution and does not work with WiX 3.0, but given that information, I figured it out. Add a ProgId element to the component containing your executable, like the following: ``` <ProgId Id="MyApplication.MyFile" Description="My file type"> <Extension Id="myext" ContentType="application/whatever"> <Verb Id="open" Command="open" TargetFile="MyApplication.exe" Argument="&quot;%1&quot;"/> </Extension> </ProgId> ``` myext is the file extension without the dot, and MyApplication.exe is the file id (not name) of the executable file (i.e. the Id attribute of the File element). This will register the file type with your executable and will supply a default icon (a white page with the application icon on it), which is sufficient for my needs. If you want to specify a dedicated icon, it seems you still have to do this yourself, like the following (code from the linked tutorial): ``` <Registry Id='FooIcon1' Root='HKCR' Key='.xyz' Action='write' Type='string' Value='AcmeFoobar.xyzfile' /> <Registry Id='FooIcon2' Root='HKCR' Key='AcmeFoobar.xyzfile' Action='write' Type='string' Value='Acme Foobar data file' /> <Registry Id='FooIcon3' Root='HKCR' Key='AcmeFoobar.xyzfile\DefaultIcon' Action='write' Type='string' Value='[INSTALLDIR]Foobar.exe,1' /> ``` I didn't find a good solution for my bonus question though. Edit: I started writing this before the previous answer came. However, my solution actually works, in contrast to the previous answer.
138,552
<p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring. An example makes it clearer:</p> <pre><code>axbx'cxdxe'fxgh'ixj'k -&gt; axbx'cPdPe'fxgh'iPj'k </code></pre> <p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p> <p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br> however, I'm wondering if regular expressions can be used to do all the processing in one go.</p> <p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
[ { "answer_id": 138594, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 1, "selected": false, "text": "<p>Not with plain regexp. Regular expressions have no \"memory\" so they cannot distinguish between being \"inside\" or \"outside\" quotes. </p>\n\n<p>You need something more powerful, for example using <a href=\"http://gema.sourceforge.net\" rel=\"nofollow noreferrer\">gema</a> it would be straighforward:</p>\n\n<pre><code>'&lt;repl&gt;'=$0\nrepl:x=P\n</code></pre>\n" }, { "answer_id": 138598, "author": "Tobias Wärre", "author_id": 21097, "author_profile": "https://Stackoverflow.com/users/21097", "pm_score": 0, "selected": false, "text": "<p>Sorry to break your hopes, but you need a push-down automata to do that. There is more info here:\n<a href=\"http://en.wikipedia.org/wiki/Pushdown_automaton\" rel=\"nofollow noreferrer\">Pushdown Automaton</a></p>\n\n<p>In short, Regular expressions, which are finite state machines can only read and has no memory while pushdown automaton has a stack and manipulating capabilities.</p>\n\n<p>Edit: spelling...</p>\n" }, { "answer_id": 138615, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "<p>I was able to do this with Python:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.sub(r\"x(?=[^']*'([^']|'[^']*')*$)\", \"P\", \"axbx'cxdxe'fxgh'ixj'k\")\n\"axbx'cPdPe'fxgh'iPj'k\"\n</code></pre>\n\n<p>What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string.</p>\n\n<p>This relies on your assumption that the quotes are always balanced. This is also not very efficient.</p>\n" }, { "answer_id": 138620, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 1, "selected": false, "text": "<p>Similar discussion about balanced text replaces: <a href=\"https://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns#133771\">Can regular expressions be used to match nested patterns?</a></p>\n\n<p>Although you can try this in Vim, but it works well only if the string is on one line, and there's only one pair of 's.</p>\n\n<pre><code>:%s:\\('[^']*\\)x\\([^']*'\\):\\1P\\2:gci\n</code></pre>\n\n<p>If there's one more pair or even an unbalanced ', then it could fail. That's way I included the <code>c</code> a.k.a. confirm flag on the <code>ex</code> command.</p>\n\n<p>The same can be done with sed, without the interaction - or with <code>awk</code> so you can add some interaction.</p>\n\n<p>One possible solution is to break the lines on pairs of <code>'</code>s then you can do with vim solution. </p>\n" }, { "answer_id": 138755, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "<p>I converted Greg Hewgill's python code to C# and it worked!</p>\n\n<pre><code>[Test]\npublic void ReplaceTextInQuotes()\n{\n Assert.AreEqual(\"axbx'cPdPe'fxgh'iPj'k\", \n Regex.Replace(\"axbx'cxdxe'fxgh'ixj'k\",\n @\"x(?=[^']*'([^']|'[^']*')*$)\", \"P\"));\n}\n</code></pre>\n\n<p>That test passed.</p>\n" }, { "answer_id": 139467, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "<pre><code>Pattern: (?s)\\G((?:^[^']*'|(?&lt;=.))(?:'[^']*'|[^'x]+)*+)x\nReplacement: \\1P\n</code></pre>\n\n<ol>\n<li><code>\\G</code> &mdash; Anchor each match at the end of the previous one, or the start of the string.</li>\n<li><code>(?:^[^']*'|(?&lt;=.))</code> &mdash; If it is at the beginning of the string, match up to the first quote.</li>\n<li><code>(?:'[^']*'|[^'x]+)*+</code> &mdash; Match any block of unquoted characters, or any (non-quote) characters up to an 'x'.</li>\n</ol>\n\n<p>One sweep trough the source string, except for a single character look-behind.</p>\n" }, { "answer_id": 139802, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 2, "selected": false, "text": "<p>The trick is to use non-capturing group to match the part of the string <em>following</em> the match (character <strong>x</strong>) we are searching for.\nTrying to match the string up to <strong>x</strong> will only find either the first or the last occurence, depending whether non-greedy quantifiers are used.\nHere's Greg's idea transposed to Tcl, with comments.</p>\n\n<pre>\nset strIn {axbx'cxdxe'fxgh'ixj'k}\nset regex {(?x) # enable expanded syntax \n # - allows comments, ignores whitespace\n x # the actual match\n (?= # non-matching group\n [^']*' # match to end of current quoted substring\n ##\n ## assuming quotes are in pairs,\n ## make sure we actually were \n ## inside a quoted substring\n ## by making sure the rest of the string \n ## is what we expect it to be\n ##\n (\n [^']* # match any non-quoted substring\n | # ...or...\n '[^']*' # any quoted substring, including the quotes\n )* # any number of times\n $ # until we run out of string :)\n ) # end of non-matching group\n}\n\n#the same regular expression without the comments\nset regexCondensed {(?x)x(?=[^']*'([^']|'[^']*')*$)}\n\nset replRegex {P}\nset nMatches [regsub -all -- $regex $strIn $replRegex strOut]\nputs \"$nMatches replacements. \"\nif {$nMatches > 0} {\n puts \"Original: |$strIn|\"\n puts \"Result: |$strOut|\"\n}\nexit\n</pre>\n\n<p>This prints:</p>\n\n<pre><code>3 replacements. \nOriginal: |axbx'cxdxe'fxgh'ixj'k|\nResult: |axbx'cPdPe'fxgh'iPj'k|\n</code></pre>\n" }, { "answer_id": 140977, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>#!/usr/bin/perl -w\n\nuse strict;\n\n# Break up the string.\n# The spliting uses quotes\n# as the delimiter.\n# Put every broken substring\n# into the @fields array.\n\nmy @fields;\nwhile (&lt;&gt;) {\n @fields = split /'/, $_;\n}\n\n# For every substring indexed with an odd\n# number, search for x and replace it\n# with P.\n\nmy $count;\nmy $end = $#fields;\nfor ($count=0; $count &lt; $end; $count++) {\n if ($count % 2 == 1) {\n $fields[$count] =~ s/a/P/g;\n } \n}\n</code></pre>\n\n<p>Wouldn't this chunk do the job?</p>\n" }, { "answer_id": 150711, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>A more general (and simpler) solution which allows non-paired quotes.</p>\n\n<ol>\n<li>Find quoted string</li>\n<li><p>Replace 'x' by 'P' in the string</p>\n\n<pre><code>#!/usr/bin/env python\nimport re\n\ntext = \"axbx'cxdxe'fxgh'ixj'k\"\n\ns = re.sub(\"'.*?'\", lambda m: re.sub(\"x\", \"P\", m.group(0)), text)\n\nprint s == \"axbx'cPdPe'fxgh'iPj'k\", s\n# -&gt; True axbx'cPdPe'fxgh'iPj'k\n</code></pre></li>\n</ol>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
I need to replace character (say) **x** with character (say) **P** in a string, but only if it is contained in a quoted substring. An example makes it clearer: ``` axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k ``` Let's assume, for the sake of simplicity, that quotes always come in pairs. The obvious way is to just process the string one character at a time (a simple state machine approach); however, I'm wondering if regular expressions can be used to do all the processing in one go. My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.
I was able to do this with Python: ``` >>> import re >>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k") "axbx'cPdPe'fxgh'iPj'k" ``` What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string. This relies on your assumption that the quotes are always balanced. This is also not very efficient.
138,555
<p>I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?</p> <p>To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.</p>
[ { "answer_id": 138561, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://www.ibm.com/developerworks/library/tiptidy.html\" rel=\"nofollow noreferrer\"><strong>Convert from HTML to XML with HTML Tidy</strong></a></p>\n\n<p><a href=\"http://tidy.sourceforge.net/#binaries\" rel=\"nofollow noreferrer\"><strong>Downloadable Binaries</strong></a></p>\n\n<p>JRoppert, For your need, i guess you might want to look at the <a href=\"http://sourceforge.net/cvs/?group_id=27659\" rel=\"nofollow noreferrer\">Sources</a></p>\n\n<pre><code>c:\\temp&gt;tidy -help\ntidy [option...] [file...] [option...] [file...]\nUtility to clean up and pretty print HTML/XHTML/XML\nsee http://tidy.sourceforge.net/\n\nOptions for HTML Tidy for Windows released on 14 February 2006:\n\nFile manipulation\n-----------------\n -output &lt;file&gt;, -o write output to the specified &lt;file&gt;\n &lt;file&gt;\n -config &lt;file&gt; set configuration options from the specified &lt;file&gt;\n -file &lt;file&gt;, -f write errors to the specified &lt;file&gt;\n &lt;file&gt;\n -modify, -m modify the original input files\n\nProcessing directives\n---------------------\n -indent, -i indent element content\n -wrap &lt;column&gt;, -w wrap text at the specified &lt;column&gt;. 0 is assumed if\n &lt;column&gt; &lt;column&gt; is missing. When this option is omitted, the\n default of the configuration option \"wrap\" applies.\n -upper, -u force tags to upper case\n -clean, -c replace FONT, NOBR and CENTER tags by CSS\n -bare, -b strip out smart quotes and em dashes, etc.\n -numeric, -n output numeric rather than named entities\n -errors, -e only show errors\n -quiet, -q suppress nonessential output\n -omit omit optional end tags\n -xml specify the input is well formed XML\n -asxml, -asxhtml convert HTML to well formed XHTML\n -ashtml force XHTML to well formed HTML\n -access &lt;level&gt; do additional accessibility checks (&lt;level&gt; = 0, 1, 2, 3).\n 0 is assumed if &lt;level&gt; is missing.\n\nCharacter encodings\n-------------------\n -raw output values above 127 without conversion to entities\n -ascii use ISO-8859-1 for input, US-ASCII for output\n -latin0 use ISO-8859-15 for input, US-ASCII for output\n -latin1 use ISO-8859-1 for both input and output\n -iso2022 use ISO-2022 for both input and output\n -utf8 use UTF-8 for both input and output\n -mac use MacRoman for input, US-ASCII for output\n -win1252 use Windows-1252 for input, US-ASCII for output\n -ibm858 use IBM-858 (CP850+Euro) for input, US-ASCII for output\n -utf16le use UTF-16LE for both input and output\n -utf16be use UTF-16BE for both input and output\n -utf16 use UTF-16 for both input and output\n -big5 use Big5 for both input and output\n -shiftjis use Shift_JIS for both input and output\n -language &lt;lang&gt; set the two-letter language code &lt;lang&gt; (for future use)\n\nMiscellaneous\n-------------\n -version, -v show the version of Tidy\n -help, -h, -? list the command line options\n -xml-help list the command line options in XML format\n -help-config list all configuration options\n -xml-config list all configuration options in XML format\n -show-config list the current configuration settings\n\nUse --blah blarg for any configuration option \"blah\" with argument \"blarg\"\n\nInput/Output default to stdin/stdout respectively\nSingle letter options apart from -f may be combined\nas in: tidy -f errs.txt -imu foo.html\nFor further info on HTML see http://www.w3.org/MarkUp\n</code></pre>\n" }, { "answer_id": 138584, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": 0, "selected": false, "text": "<p>The easiest way is to set your Visual Studio IDE to identify the changes you need to make.\nYou can do this in Visual Studio 2008 by going to:\nTools, Options, Text Editor, HTML, Validation and choosing the appropriate target.\nPossibly XHTML 1.1 or XHTML 1.0 Transitional.</p>\n\n<p>For some information on the different types, read:\n<a href=\"http://msdn.microsoft.com/en-us/library/aa479043.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa479043.aspx</a></p>\n\n<p>Then you need to work through the points highlighted on your page.</p>\n" }, { "answer_id": 138609, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 3, "selected": false, "text": "<p>You can use a <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"noreferrer\">HTML Agility Pack</a>. Its open-source project from CodePlex.</p>\n" }, { "answer_id": 152669, "author": "hsivonen", "author_id": 18721, "author_profile": "https://Stackoverflow.com/users/18721", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://about.validator.nu/htmlparser/\" rel=\"nofollow noreferrer\">Validator.nu HTML Parser</a> comes with an HTML2XML sample program that does the conversion using the HTML5 parsing algorithm and infoset coercion rules.</p>\n" }, { "answer_id": 2485280, "author": "Cetin Sert", "author_id": 112882, "author_profile": "https://Stackoverflow.com/users/112882", "pm_score": 2, "selected": false, "text": "<p>Use Html2Xhtml for .NET 4.0:</p>\n\n<p>In-memory string-to-string conversion:</p>\n\n<pre><code>var xhtml = Html2Xhtml.RunAsFilter(stdin =&gt; stdin.Write(html)).ReadToEnd();\n</code></pre>\n\n<p>In-memory string-to-XDocument conversion:</p>\n\n<pre><code>var xdoc = Html2Xhtml.RunAsFilter(stdin =&gt; stdin.Write(html)).ReadToXDocument();\n</code></pre>\n\n<p>See <a href=\"http://corsis.sourceforge.net/index.php/Html2Xhtml\" rel=\"nofollow noreferrer\">http://corsis.sourceforge.net/index.php/Html2Xhtml</a> for more information.</p>\n" }, { "answer_id": 6236994, "author": "mite", "author_id": 772343, "author_profile": "https://Stackoverflow.com/users/772343", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://corsis.sourceforge.net/index.php/Html2Xhtml\" rel=\"nofollow\">http://corsis.sourceforge.net/index.php/Html2Xhtml</a>http://corsis.sourceforge.net/index.php/Html2Xhtml</p>\n\n<p>Html2Xhtml is a .NET 4.0 library for converting HTML to XHTML licensed under GPLv2 or above.</p>\n\n<p>I tested Html2Xhtml in the local reconstruction of a large online database of the European Union. Tidy/Tidy.NET would not even produce valid output most of the time, Chilkat's HTML-to-XML was a bit slow and produced strange results (misplaced, missing, unexplainable elements). In attempt to find a free, fast and reliable conversion tool I created this library. It converts 2 - 4x faster than all other libraries I tested.</p>\n\n<p>Html2Xhtml, combined with the power of LINQ to XML, is an excellent tool for all large-scale data extraction and web crawling scenarios.</p>\n" }, { "answer_id": 13516554, "author": "user1845579", "author_id": 1845579, "author_profile": "https://Stackoverflow.com/users/1845579", "pm_score": 2, "selected": false, "text": "<p>you can convert html to xhtml with tidy executable file:</p>\n\n<p>tidy -asxhtml -numeric &lt; index.html > index.xhml</p>\n\n<p>you can check the c# implementation <a href=\"http://www.dotnetobject.com/Thread-Html-to-Xhtml-conversion-in-c\" rel=\"nofollow\">here</a>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6777/" ]
I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done? To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.
[**Convert from HTML to XML with HTML Tidy**](http://www.ibm.com/developerworks/library/tiptidy.html) [**Downloadable Binaries**](http://tidy.sourceforge.net/#binaries) JRoppert, For your need, i guess you might want to look at the [Sources](http://sourceforge.net/cvs/?group_id=27659) ``` c:\temp>tidy -help tidy [option...] [file...] [option...] [file...] Utility to clean up and pretty print HTML/XHTML/XML see http://tidy.sourceforge.net/ Options for HTML Tidy for Windows released on 14 February 2006: File manipulation ----------------- -output <file>, -o write output to the specified <file> <file> -config <file> set configuration options from the specified <file> -file <file>, -f write errors to the specified <file> <file> -modify, -m modify the original input files Processing directives --------------------- -indent, -i indent element content -wrap <column>, -w wrap text at the specified <column>. 0 is assumed if <column> <column> is missing. When this option is omitted, the default of the configuration option "wrap" applies. -upper, -u force tags to upper case -clean, -c replace FONT, NOBR and CENTER tags by CSS -bare, -b strip out smart quotes and em dashes, etc. -numeric, -n output numeric rather than named entities -errors, -e only show errors -quiet, -q suppress nonessential output -omit omit optional end tags -xml specify the input is well formed XML -asxml, -asxhtml convert HTML to well formed XHTML -ashtml force XHTML to well formed HTML -access <level> do additional accessibility checks (<level> = 0, 1, 2, 3). 0 is assumed if <level> is missing. Character encodings ------------------- -raw output values above 127 without conversion to entities -ascii use ISO-8859-1 for input, US-ASCII for output -latin0 use ISO-8859-15 for input, US-ASCII for output -latin1 use ISO-8859-1 for both input and output -iso2022 use ISO-2022 for both input and output -utf8 use UTF-8 for both input and output -mac use MacRoman for input, US-ASCII for output -win1252 use Windows-1252 for input, US-ASCII for output -ibm858 use IBM-858 (CP850+Euro) for input, US-ASCII for output -utf16le use UTF-16LE for both input and output -utf16be use UTF-16BE for both input and output -utf16 use UTF-16 for both input and output -big5 use Big5 for both input and output -shiftjis use Shift_JIS for both input and output -language <lang> set the two-letter language code <lang> (for future use) Miscellaneous ------------- -version, -v show the version of Tidy -help, -h, -? list the command line options -xml-help list the command line options in XML format -help-config list all configuration options -xml-config list all configuration options in XML format -show-config list the current configuration settings Use --blah blarg for any configuration option "blah" with argument "blarg" Input/Output default to stdin/stdout respectively Single letter options apart from -f may be combined as in: tidy -f errs.txt -imu foo.html For further info on HTML see http://www.w3.org/MarkUp ```
138,565
<p>For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor.</p> <p>The constructor:</p> <pre><code> public function SQLMethods() { $SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword); if (!$SQLConnection) { die('Could not connect: ' . mysql_error()); } mysql_select_db($SQLDB, $SQLConnection); } </code></pre> <p>The function in question:</p> <pre><code> public function ExecuteQuery($Query) { mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error()); } </code></pre> <p>Does anyone see what the issue might be? Does the connection close after the constructor completes?</p>
[ { "answer_id": 138590, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 4, "selected": true, "text": "<p>you should declare $SQLConnection in your class, and you should refer to it as </p>\n\n<pre><code> $this-&gt;SQLConnection\n</code></pre>\n\n<p>and not simply $SQLConnection.</p>\n" }, { "answer_id": 138591, "author": "Greg", "author_id": 1916, "author_profile": "https://Stackoverflow.com/users/1916", "pm_score": 2, "selected": false, "text": "<p><code>$SQLConnection</code> doesn't exist within the <code>ExecuteQuery</code> method.</p>\n\n<p>You can either pass it directly as a parameter to <code>ExecuteQuery</code>, or add an <code>sqlConnection</code> class property that is set in the constructor and accessed as <code>$this-&gt;sqlConnection</code> inside your class methods.</p>\n" }, { "answer_id": 138599, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 1, "selected": false, "text": "<p>The variable <code>$SQLConnection</code> <code>ExecuteQuery()</code> is trying to use is created within another scope. (The <code>SQLMethods</code> function).</p>\n\n<p>The connection closes when the PHP script has done its work or if you close it yourself (if the connection is made within that script)</p>\n\n<p>You should skip the <code>$SQLConnection</code> variable within <code>ExecuteQuery</code> as stated by the php.net documentation </p>\n\n<blockquote>\n <p>If the link identifier is not specified, the last link opened by <code>mysql_connect()</code> is assumed.</p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14877/" ]
For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor. The constructor: ``` public function SQLMethods() { $SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword); if (!$SQLConnection) { die('Could not connect: ' . mysql_error()); } mysql_select_db($SQLDB, $SQLConnection); } ``` The function in question: ``` public function ExecuteQuery($Query) { mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error()); } ``` Does anyone see what the issue might be? Does the connection close after the constructor completes?
you should declare $SQLConnection in your class, and you should refer to it as ``` $this->SQLConnection ``` and not simply $SQLConnection.
138,576
<p>I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up.</p> <p>Here is the command I am using:</p> <pre><code>tree /f /a &gt; output.txt </code></pre> <p>The results in the console window are fine:</p> <pre> \---Erika szobája cover.jpg Erika szobája.m3u Kátai Tamás - 01 Télvíz.ogg Kátai Tamás - 02 Zölderdõ.ogg Kátai Tamás - 03 Renoir kertje.ogg Kátai Tamás - 04 Esõben szaladtál.ogg Kátai Tamás - 05 Ázik az út.ogg Kátai Tamás - 06 Sûrû völgyek takaród.ogg Kátai Tamás - 07 Õszhozó.ogg Kátai Tamás - 08 Mécsvilág.ogg Kátai Tamás - 09 Zúzmara.ogg </pre> <p>But the text file is no good:</p> <pre> \---Erika szob ja cover.jpg Erika szob ja.m3u K tai Tam s - 01 T‚lv¡z.ogg K tai Tam s - 02 Z”lderdä.ogg K tai Tam s - 03 Renoir kertje.ogg K tai Tam s - 04 Esäben szaladt l.ogg K tai Tam s - 05 µzik az £t.ogg K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg K tai Tam s - 07 åszhoz¢.ogg K tai Tam s - 08 M‚csvil g.ogg K tai Tam s - 09 Z£zmara.ogg </pre> <p>How can I fix this? Ideally the text file would be exactly the same as the output in the console window.</p> <p>I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters.</p>
[ { "answer_id": 138736, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 4, "selected": false, "text": "<p>If you output as non-Unicode (which you apparently do), you have to view the text file you create using the same encoding the Console window uses. That's why it looks correct in the console. In some text editors, you can choose an encoding (or \"code page\") when you open a file. (How to output as Unicode I don't know. cmd /U doesn't do what the documentation says.)</p>\n\n<p>The Console encoding depends on your Windows installation. For me, it's \"Western European (DOS)\" (or just \"MS-DOS\") in Microsoft Word.</p>\n" }, { "answer_id": 139302, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>I decided I had to have a look at <code>tree.com</code> and figure out why it's not respecting the Unicode setting of the console. It turns out that (like many of the command-line file utilities), it uses a library called <code>ulib.dll</code> to do all the printing (specifically, <code>TREE::DisplayName</code> calls <code>WriteString</code> in <code>ulib</code>).</p>\n\n<p>Now, in <code>ulib</code>, the <code>WriteString</code> method is implemented in two classes, <code>SCREEN</code> and <code>STREAM</code>. The <code>SCREEN</code> version uses <code>WriteConsoleW</code> directly, so all the Unicode characters get correctly displayed. The <code>STREAM</code> version converts the Unicode text to one of three different encodings (<code>_UseConsoleConversions</code> ⇒ console codepage (<code>GetConsoleCP</code>), <code>_UseAnsiConversions</code> ⇒ default ANSI codepage, otherwise ⇒ default OEM codepage), and then writes this out. I don't know how to change the conversion mode, and I don't believe the conversion can be disabled.</p>\n\n<p>I've only looked at this briefly, so perhaps more adventurous souls can speak more about it! :-)</p>\n" }, { "answer_id": 2767458, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 2, "selected": false, "text": "<p>The short answer is <strong>you cannot</strong> and this is because <code>tree.com</code> is an ANSI application, even on Windows 7.</p>\n\n<p>The only solution is to write your own <code>tree</code> implementation. Also you could file a bug to Microsoft, but I doubt they are not already aware about it.</p>\n" }, { "answer_id": 8556928, "author": "Chris", "author_id": 1105206, "author_profile": "https://Stackoverflow.com/users/1105206", "pm_score": 2, "selected": false, "text": "<p>This worked for me: </p>\n\n<pre><code>tree /f /a &gt; %temp%\\Listing &gt;&gt; files.txt\n</code></pre>\n" }, { "answer_id": 11199864, "author": "Ricardo Bohner", "author_id": 1481477, "author_profile": "https://Stackoverflow.com/users/1481477", "pm_score": 7, "selected": true, "text": "<p>Have someone already tried this:</p>\n\n<pre><code>tree /f /a |clip\n</code></pre>\n\n<p>Open notepad, ctrl + V, save in notepad as output.txt with unicode support?</p>\n" }, { "answer_id": 14517967, "author": "Kenn", "author_id": 629644, "author_profile": "https://Stackoverflow.com/users/629644", "pm_score": 2, "selected": false, "text": "<p>You can try </p>\n\n<pre><code>tree /A &gt; output.txt\n</code></pre>\n\n<p>Though it looks different from the CMD line, it still could be acceptable. :P</p>\n" }, { "answer_id": 15961769, "author": "XP1", "author_id": 412486, "author_profile": "https://Stackoverflow.com/users/412486", "pm_score": 4, "selected": false, "text": "<p>Use PowerShell:</p>\n\n<pre><code>powershell -command \"tree /f &gt; tree.txt\"\n</code></pre>\n\n<h2>Test case:</h2>\n\n<p><code>create.ps1</code>:</p>\n\n<pre><code>mkdir \"Erika szobája\"\n$null | Set-Content \"Erika szobája/cover.jpg\"\n$null | Set-Content \"Erika szobája/Erika szobája.m3u\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 01 Télvíz.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 02 Zölderdõ.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 03 Renoir kertje.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 04 Esõben szaladtál.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 05 Ázik az út.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 06 Sûrû völgyek takaród.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 07 Õszhozó.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 08 Mécsvilág.ogg\"\n$null | Set-Content \"Erika szobája/Kátai Tamás - 09 Zúzmara.ogg\"\n</code></pre>\n\n<p>Output:</p>\n\n<p><code>tree.txt</code>:</p>\n\n<pre><code>Folder PATH listing\nVolume serial number is 00000000 0000:0000\nC:.\n│ create.ps1\n│ tree.txt\n│ \n└───Erika szobája\n cover.jpg\n Erika szobája.m3u\n Kátai Tamás - 01 Télvíz.ogg\n Kátai Tamás - 02 Zölderdo.ogg\n Kátai Tamás - 03 Renoir kertje.ogg\n Kátai Tamás - 04 Esoben szaladtál.ogg\n Kátai Tamás - 05 Azik az út.ogg\n Kátai Tamás - 06 Sûrû völgyek takaród.ogg\n Kátai Tamás - 07 Oszhozó.ogg\n Kátai Tamás - 08 Mécsvilág.ogg\n Kátai Tamás - 09 Zúzmara.ogg\n</code></pre>\n\n<h1>EDIT:</h1>\n\n<h1>Enhanced and improved version for power users</h1>\n\n<p><a href=\"https://i.stack.imgur.com/xTbFr.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xTbFr.png\" alt=\"List tree menu working with Unicode\"></a></p>\n\n<h2>Test case:</h2>\n\n<pre><code>$null | Set-Content \"欲速则不达.txt\"\n$null | Set-Content \"爱不是占有,是欣赏.txt\"\n$null | Set-Content \"您先请是礼貌.txt\"\n$null | Set-Content \"萝卜青菜,各有所爱.txt\"\n$null | Set-Content \"广交友,无深交.txt\"\n$null | Set-Content \"一见钟情.txt\"\n$null | Set-Content \"山雨欲来风满楼.txt\"\n\n$null | Set-Content \"悪妻は百年の不作。.txt\"\n$null | Set-Content \"残り物には福がある。.txt\"\n$null | Set-Content \"虎穴に入らずんば虎子を得ず。.txt\"\n$null | Set-Content \"夏炉冬扇.txt\"\n$null | Set-Content \"花鳥風月.txt\"\n$null | Set-Content \"起死回生.txt\"\n$null | Set-Content \"自業自得.txt\"\n\n$null | Set-Content \"아는 길도 물어가라.txt\"\n$null | Set-Content \"빈 수레가 요란하다.txt\"\n$null | Set-Content \"방귀뀐 놈이 성낸다.txt\"\n$null | Set-Content \"뜻이 있는 곳에 길이 있다.txt\"\n$null | Set-Content \"콩 심은데 콩나고, 팥 심은데 팥난다.txt\"\n</code></pre>\n\n<p>From his <a href=\"https://stackoverflow.com/questions/138576/saving-tree-f-a-results-to-a-textfile-with-unicode-support/139302#139302\">answer</a>, @Chris Jester-Young wrote:</p>\n\n<blockquote>\n <p>Now, in <code>ulib</code>, the <code>WriteString</code> method is implemented in two\n classes, <code>SCREEN</code> and <code>STREAM</code>. The <code>SCREEN</code> version uses\n <code>WriteConsoleW</code> directly, so all the Unicode characters get correctly\n displayed. The <code>STREAM</code> version converts the Unicode text to one of\n three different encodings (<code>_UseConsoleConversions</code> ⇒ console codepage\n (<code>GetConsoleCP</code>), <code>_UseAnsiConversions</code> ⇒ default ANSI codepage,\n otherwise ⇒ default OEM codepage), and then writes this out.</p>\n</blockquote>\n\n<p>This means that we cannot rely on getting the characters from a stream. File redirections won't work. We have to rely on writing to the console to get the Unicode characters.</p>\n\n<p>The workaround, or hack, is to write the tree to the console and then dump the buffer to a file.</p>\n\n<p>I have written the scripts to add the tree context menu when you right click on directories in Explorer. Save the files in the same directory and then run <code>Install list menu.bat</code> as administrator to install.</p>\n\n<p><code>Install list menu.bat</code></p>\n\n<pre><code>@echo on\n\nregedit /s \"List files.reg\"\n\ncopy \"List.ps1\" \"%SystemRoot%\"\n\npause\n</code></pre>\n\n<p><code>List files.reg</code></p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n; Directory.\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Shell\\List]\n\"MUIVerb\"=\"List\"\n\"ExtendedSubCommandsKey\"=\"Directory\\\\ContextMenus\\\\List\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\Files]\n\"MUIVerb\"=\"Files\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\Files\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'files' -directory '%1'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,66,00,69,00,6c,00,65,00,73,00,27,00,20,00,2d,00,\\\n 64,00,69,00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,31,\\\n 00,27,00,00,00\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\FilesRecursively]\n\"MUIVerb\"=\"Files recursively\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\FilesRecursively\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'filesRecursively' -directory '%1'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,66,00,69,00,6c,00,65,00,73,00,52,00,65,00,63,00,\\\n 75,00,72,00,73,00,69,00,76,00,65,00,6c,00,79,00,27,00,20,00,2d,00,64,00,69,\\\n 00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,31,00,27,00,\\\n 00,00\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\Tree]\n\"MUIVerb\"=\"Tree\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\ContextMenus\\List\\Shell\\Tree\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'tree' -directory '%1'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,74,00,72,00,65,00,65,00,27,00,20,00,2d,00,64,00,\\\n 69,00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,31,00,27,\\\n 00,00,00\n\n; Directory background.\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\Shell\\List]\n\"MUIVerb\"=\"List\"\n\"ExtendedSubCommandsKey\"=\"Directory\\\\Background\\\\ContextMenus\\\\List\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\Files]\n\"MUIVerb\"=\"Files\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\Files\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'files' -directory '%V'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,66,00,69,00,6c,00,65,00,73,00,27,00,20,00,2d,00,\\\n 64,00,69,00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,56,\\\n 00,27,00,00,00\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\FilesRecursively]\n\"MUIVerb\"=\"Files recursively\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\FilesRecursively\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'filesRecursively' -directory '%V'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,66,00,69,00,6c,00,65,00,73,00,52,00,65,00,63,00,\\\n 75,00,72,00,73,00,69,00,76,00,65,00,6c,00,79,00,27,00,20,00,2d,00,64,00,69,\\\n 00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,56,00,27,00,\\\n 00,00\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\Tree]\n\"MUIVerb\"=\"Tree\"\n\n[HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\Background\\ContextMenus\\List\\Shell\\Tree\\Command]\n; powershell -executionPolicy bypass \"%SystemRoot%\\List.ps1\" -type 'tree' -directory '%V'\n@=hex(2):70,00,6f,00,77,00,65,00,72,00,73,00,68,00,65,00,6c,00,6c,00,20,00,2d,\\\n 00,65,00,78,00,65,00,63,00,75,00,74,00,69,00,6f,00,6e,00,50,00,6f,00,6c,00,\\\n 69,00,63,00,79,00,20,00,62,00,79,00,70,00,61,00,73,00,73,00,20,00,22,00,25,\\\n 00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,00,5c,00,\\\n 4c,00,69,00,73,00,74,00,2e,00,70,00,73,00,31,00,22,00,20,00,2d,00,74,00,79,\\\n 00,70,00,65,00,20,00,27,00,74,00,72,00,65,00,65,00,27,00,20,00,2d,00,64,00,\\\n 69,00,72,00,65,00,63,00,74,00,6f,00,72,00,79,00,20,00,27,00,25,00,56,00,27,\\\n 00,00,00\n</code></pre>\n\n<p><code>List.ps1</code></p>\n\n<pre><code>function sortNaturally {\n [Regex]::replace($_, '\\d+', {\n $args[0].value.padLeft(20)\n })\n}\n\nfunction writeList {\n param(\n [parameter(mandatory = $true)]\n [string] $text = $null\n )\n\n $filePath = \"$env:temp\\List.txt\"\n $text &gt; \"$filePath\"\n notepad \"$filePath\" | out-null\n del \"$filePath\"\n}\n\nfunction listFiles {\n param(\n [switch] $recurse = $false\n )\n\n get-childItem -name -recurse:$recurse -force | sort-object $function:sortNaturally | out-string\n}\n\nfunction listTree {\n tree /f\n}\n\nfunction getBufferText {\n $rawUi = $host.ui.rawUi\n $width = [Math]::max([Math]::max($rawUi.bufferSize.width, $rawUi.windowSize.width) - 1, 0)\n $height = [Math]::max($rawUi.cursorPosition.y - 1, 0)\n\n $lines = new-object System.Text.StringBuilder\n $characters = new-object System.Text.StringBuilder\n\n for ($h = 0; $h -lt $height; $h += 1) {\n $rectangle = new-object System.Management.Automation.Host.Rectangle 0, $h, $width, $h\n $buffer = $rawUi.getBufferContents($rectangle)\n\n for ($w = 0; $w -lt $width; $w += 1) {\n $cell = $buffer[0, $w]\n $character = $cell.character\n $characters.append($character) | out-null\n }\n\n $lines.appendLine($characters.toString()) | out-null\n $characters.length = 0\n }\n\n $lines.toString() -replace '[ \\0]*\\r?\\n', \"`r`n\"\n}\n\nfunction main {\n param(\n [parameter(mandatory = $true)]\n [string] $type = $null,\n\n [parameter(mandatory = $true)]\n [string] $directory = $null\n )\n\n $outputEncoding = [Text.UTF8Encoding]::UTF8\n [Console]::outputEncoding = [Text.UTF8Encoding]::UTF8\n $PSDefaultParameterValues['out-file:encoding'] = 'utf8'\n\n set-location -literalPath \"$directory\"\n\n $typeFunction = @{\n 'files' = { writeList -text $(listFiles) };\n 'filesRecursively' = { writeList -text $(listFiles -recurse) };\n 'tree' = {\n listTree\n writeList -text $(getBufferText)\n }\n }\n\n &amp;($typeFunction.get_item($type))\n}\n\nmain @args\n</code></pre>\n" }, { "answer_id": 16087554, "author": "Ricardo Bohner", "author_id": 2295852, "author_profile": "https://Stackoverflow.com/users/2295852", "pm_score": 3, "selected": false, "text": "<p>This will save the results as ASCII (American Standard Code for Information Interchange) on your desktop, ASCII\\ANSI doesn't recognize every international or extended character:</p>\n\n<pre><code>tree /f &gt; ascii.txt\n</code></pre>\n\n<p>This will convert your ASCII text to Unicode (/c must precede actual command):</p>\n\n<pre><code>cmd /u /c type ascii.txt &gt; unicode.txt\n</code></pre>\n\n<p>So why not just think of the ascii file as a temporary file and delete it?</p>\n\n<pre><code>del ascii.txt\n</code></pre>\n\n<p>If you must put all in one line you could use:</p>\n\n<pre><code>tree /f &gt; ascii.txt &amp; cmd.exe /u /c type ascii.txt &gt; unicode.txt &amp; del ascii.txt\n</code></pre>\n" }, { "answer_id": 38905948, "author": "Miguel", "author_id": 6678484, "author_profile": "https://Stackoverflow.com/users/6678484", "pm_score": 0, "selected": false, "text": "<p>I've succeeded getting the output as it is in console, with all non-ascii characters not converted, by outputting to the console (just <code>tree</code>) and then copying from it (system menu -> Edit -> Mark, selecting all, Enter). Console buffer size should be increased in advance, depending on number files/folders, in the console's properties (system menu -> Properties). Other ways didn't work. <code>tree|clip</code>, mentioned in an earlier post, converts non-ascii characters to ascii ones the same as <code>tree&gt;file.txt</code>.</p>\n" }, { "answer_id": 44244216, "author": "user1959451", "author_id": 1959451, "author_profile": "https://Stackoverflow.com/users/1959451", "pm_score": 1, "selected": false, "text": "<p>I've managed to properly output non-ascii characters from tree command into a file via <a href=\"https://jpsoft.com/downloads/v21/tcc.exe\" rel=\"nofollow noreferrer\">Take Command Console</a>.</p>\n\n<p>In TCC type \"option\" and on first tab select \"Unicode output\". Then simply run </p>\n\n<pre><code>tree /f /a &gt; output.txt\n</code></pre>\n" }, { "answer_id": 51255816, "author": "Gras Double", "author_id": 289317, "author_profile": "https://Stackoverflow.com/users/289317", "pm_score": 2, "selected": false, "text": "<p>XP1's answer is great, but had a minor caveat: the output encoding is UCS2-LE, while I'd prefer UTF8 (smaller filesize, and more widespread).</p>\n\n<p>After <em>a lot</em> of searching and head scratching, I can finally present you the following command, that produces an UTF8-BOM file:</p>\n\n<pre><code>PowerShell -Command \"TREE /F | Out-File output.txt -Encoding utf8\"\n</code></pre>\n\n<p>If the output filename has spaces:</p>\n\n<pre><code>PowerShell -Command \"TREE /F | Out-File \"\"output file.txt\"\" -Encoding utf8\"\n</code></pre>\n\n<p>Many thanks to this article: <a href=\"https://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/\" rel=\"nofollow noreferrer\">https://www.kongsli.net/2012/04/20/powershell-gotchas-redirect-to-file-encodes-in-unicode/</a></p>\n\n<hr>\n\n<p>Also, personally I have created the following files in my PATH:</p>\n\n<p><code>xtree.cmd</code>:</p>\n\n<pre><code>@IF [%1]==[] @(\n ECHO You have to specify an output file.\n GOTO :EOF\n)\n\n@PowerShell -Command \"TREE | Out-File %1 -Encoding utf8\"\n</code></pre>\n\n<p><code>xtreef.cmd</code>:</p>\n\n<pre><code>@IF [%1]==[] @(\n ECHO You have to specify an output file.\n GOTO :EOF\n)\n\n@PowerShell -Command \"TREE /F | Out-File %1 -Encoding utf8\"\n</code></pre>\n\n<p>Finally, instead of <code>tree &gt; output.txt</code> I just do <code>xtree output.txt</code></p>\n" }, { "answer_id": 55885092, "author": "guest", "author_id": 11421070, "author_profile": "https://Stackoverflow.com/users/11421070", "pm_score": 0, "selected": false, "text": "<p>I used this method to catalog nearly 100 SDRAM and USB flashdrives and it worked fine. </p>\n\n<p>From within DOS.... </p>\n\n<p>C:\\doskey [enter] {to enable handy keyboard shortcuts}</p>\n\n<p>C:\\tree j:\\ >> d:\\MyCatalog.txt /a [enter] {j:= is my USB drive ; d:= is where I want catalog ; /a = see other postings on this page} </p>\n" }, { "answer_id": 68489416, "author": "Minty", "author_id": 6804439, "author_profile": "https://Stackoverflow.com/users/6804439", "pm_score": 0, "selected": false, "text": "<p>XP1's answer is great, or at least the best here—tree command just can't handle some symbols even with this treatment.</p>\n<p>However, at least on my setup, this script will generate trees missing the final line. While I'm unsure why exactly this happens, it can be fixed by modifying function listTree to look like this:</p>\n<pre><code>function listTree {\n tree /f\n echo .\n}\n</code></pre>\n<p>Where <code>echo .</code> prints a line for PowerShell to cannibalize freely. This sacrifice sates it and the tree is output in entirety.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48281/" ]
I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up. Here is the command I am using: ``` tree /f /a > output.txt ``` The results in the console window are fine: ``` \---Erika szobája cover.jpg Erika szobája.m3u Kátai Tamás - 01 Télvíz.ogg Kátai Tamás - 02 Zölderdõ.ogg Kátai Tamás - 03 Renoir kertje.ogg Kátai Tamás - 04 Esõben szaladtál.ogg Kátai Tamás - 05 Ázik az út.ogg Kátai Tamás - 06 Sûrû völgyek takaród.ogg Kátai Tamás - 07 Õszhozó.ogg Kátai Tamás - 08 Mécsvilág.ogg Kátai Tamás - 09 Zúzmara.ogg ``` But the text file is no good: ``` \---Erika szob ja cover.jpg Erika szob ja.m3u K tai Tam s - 01 T‚lv¡z.ogg K tai Tam s - 02 Z”lderdä.ogg K tai Tam s - 03 Renoir kertje.ogg K tai Tam s - 04 Esäben szaladt l.ogg K tai Tam s - 05 µzik az £t.ogg K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg K tai Tam s - 07 åszhoz¢.ogg K tai Tam s - 08 M‚csvil g.ogg K tai Tam s - 09 Z£zmara.ogg ``` How can I fix this? Ideally the text file would be exactly the same as the output in the console window. I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters.
Have someone already tried this: ``` tree /f /a |clip ``` Open notepad, ctrl + V, save in notepad as output.txt with unicode support?
138,600
<p>What is the right way of initializing a static map? Do we need a static function that will initialize it? </p>
[ { "answer_id": 138612, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 9, "selected": false, "text": "<p>Using C++11:</p>\n\n<pre><code>#include &lt;map&gt;\nusing namespace std;\n\nmap&lt;int, char&gt; m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};\n</code></pre>\n\n<p>Using <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html\" rel=\"noreferrer\">Boost.Assign</a>:</p>\n\n<pre><code>#include &lt;map&gt;\n#include \"boost/assign.hpp\"\nusing namespace std;\nusing namespace boost::assign;\n\nmap&lt;int, char&gt; m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');\n</code></pre>\n" }, { "answer_id": 138618, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 5, "selected": false, "text": "<p>I would wrap the map inside a static object, and put the map initialisation code in the constructor of this object, this way you are sure the map is created before the initialisation code is executed.</p>\n" }, { "answer_id": 138633, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 7, "selected": false, "text": "<p>Best way is to use a function:</p>\n\n<pre><code>#include &lt;map&gt;\n\nusing namespace std;\n\nmap&lt;int,int&gt; create_map()\n{\n map&lt;int,int&gt; m;\n m[1] = 2;\n m[3] = 4;\n m[5] = 6;\n return m;\n}\n\nmap&lt;int,int&gt; m = create_map();\n</code></pre>\n" }, { "answer_id": 1730798, "author": "Vite Falcon", "author_id": 210634, "author_profile": "https://Stackoverflow.com/users/210634", "pm_score": 7, "selected": false, "text": "<p>It's not a complicated issue to make something similar to boost. Here's a class with just three functions, including the constructor, to replicate what boost did (almost).</p>\n\n<pre><code>template &lt;typename T, typename U>\nclass create_map\n{\nprivate:\n std::map&lt;T, U> m_map;\npublic:\n create_map(const T& key, const U& val)\n {\n m_map[key] = val;\n }\n\n create_map&lt;T, U>& operator()(const T& key, const U& val)\n {\n m_map[key] = val;\n return *this;\n }\n\n operator std::map&lt;T, U>()\n {\n return m_map;\n }\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre>\nstd::map mymap = create_map&lt;int, int >(1,2)(3,4)(5,6);\n</pre>\n\n<p>The above code works best for initialization of global variables or static members of a class which needs to be initialized and you have no idea when it gets used first but you want to assure that the values are available in it.</p>\n\n<p>If say, you've got to insert elements into an existing std::map... here's another class for you.</p>\n\n<pre><code>template &lt;typename MapType&gt;\nclass map_add_values {\nprivate:\n MapType mMap;\npublic:\n typedef typename MapType::key_type KeyType;\n typedef typename MapType::mapped_type MappedType;\n\n map_add_values(const KeyType&amp; key, const MappedType&amp; val)\n {\n mMap[key] = val;\n }\n\n map_add_values&amp; operator()(const KeyType&amp; key, const MappedType&amp; val) {\n mMap[key] = val;\n return *this;\n }\n\n void to (MapType&amp; map) {\n map.insert(mMap.begin(), mMap.end());\n }\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>typedef std::map&lt;int, int&gt; Int2IntMap;\nInt2IntMap testMap;\nmap_add_values&lt;Int2IntMap&gt;(1,2)(3,4)(5,6).to(testMap);\n</code></pre>\n\n<p>See it in action with GCC 4.7.2 here: <a href=\"http://ideone.com/3uYJiH\" rel=\"noreferrer\">http://ideone.com/3uYJiH</a></p>\n\n<p><strong>############### EVERYTHING BELOW THIS IS OBSOLETE #################</strong></p>\n\n<p><strong>EDIT</strong>: The <code>map_add_values</code> class below, which was the original solution I had suggested, would fail when it comes to GCC 4.5+. Please look at the code above for how to <strong>add</strong> values to existing map.</p>\n\n<pre><code>\ntemplate&lt;typename T, typename U>\nclass map_add_values\n{\nprivate:\n std::map&lt;T,U>& m_map;\npublic:\n map_add_values(std::map&lt;T, U>& _map):m_map(_map){}\n map_add_values& operator()(const T& _key, const U& _val)\n {\n m_map[key] = val;\n return *this;\n }\n};</code></pre>\n\n<p>Usage:</p>\n\n<pre>std::map&lt;int, int> my_map;\n// Later somewhere along the code\nmap_add_values&lt;int,int>(my_map)(1,2)(3,4)(5,6);</pre>\n\n<p>NOTE: Previously I used a <code>operator []</code> for adding the actual values. This is not possible as commented by dalle.</p>\n\n<p><strong>##################### END OF OBSOLETE SECTION #####################</strong></p>\n" }, { "answer_id": 1731203, "author": "eduffy", "author_id": 7536, "author_profile": "https://Stackoverflow.com/users/7536", "pm_score": 3, "selected": false, "text": "<p>This is similar to <code>PierreBdR</code>, without copying the map.</p>\n\n<pre><code>#include &lt;map&gt;\n\nusing namespace std;\n\nbool create_map(map&lt;int,int&gt; &amp;m)\n{\n m[1] = 2;\n m[3] = 4;\n m[5] = 6;\n return true;\n}\n\nstatic map&lt;int,int&gt; m;\nstatic bool _dummy = create_map (m);\n</code></pre>\n" }, { "answer_id": 2096681, "author": "Brian Neal", "author_id": 63485, "author_profile": "https://Stackoverflow.com/users/63485", "pm_score": 6, "selected": false, "text": "<p>Here is another way that uses the 2-element data constructor. No functions are needed to initialize it. There is no 3rd party code (Boost), no static functions or objects, no tricks, just simple C++:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n\ntypedef std::map&lt;std::string, int&gt; MyMap;\n\nconst MyMap::value_type rawData[] = {\n MyMap::value_type(\"hello\", 42),\n MyMap::value_type(\"world\", 88),\n};\nconst int numElems = sizeof rawData / sizeof rawData[0];\nMyMap myMap(rawData, rawData + numElems);\n</code></pre>\n\n<p>Since I wrote this answer C++11 is out. You can now directly initialize STL containers using the new initializer list feature:</p>\n\n<pre><code>const MyMap myMap = { {\"hello\", 42}, {\"world\", 88} };\n</code></pre>\n" }, { "answer_id": 24584993, "author": "user2185945", "author_id": 2185945, "author_profile": "https://Stackoverflow.com/users/2185945", "pm_score": -1, "selected": false, "text": "<p>You have some very good answers here, but I'm to me, it looks like a case of \"when all you know is a hammer\"...</p>\n\n<p>The simplest answer of to why there is no standard way to initialise a static map, is there is no good reason to ever use a static map... </p>\n\n<p>A map is a structure designed for fast lookup, of an unknown set of elements. If you know the elements before hand, simply use a C-array. Enter the values in a sorted manner, or run sort on them, if you can't do this. You can then get log(n) performance by using the stl::functions to loop-up entries, lower_bound/upper_bound. When I have tested this previously they normally perform at least 4 times faster than a map.</p>\n\n<p>The advantages are many fold...\n- faster performance (*4, I've measured on many CPU's types, it's always around 4)\n- simpler debugging. It's just easier to see what's going on with a linear layout.\n- Trivial implementations of copy operations, should that become necessary.\n- It allocates no memory at run time, so will never throw an exception.\n- It's a standard interface, and so is very easy to share across, DLL's, or languages, etc.</p>\n\n<p>I could go on, but if you want more, why not look at Stroustrup's many blogs on the subject.</p>\n" }, { "answer_id": 24683285, "author": "user3826594", "author_id": 3826594, "author_profile": "https://Stackoverflow.com/users/3826594", "pm_score": 4, "selected": false, "text": "<p>Just wanted to share a pure C++ 98 work around:</p>\n\n<pre><code>#include &lt;map&gt;\n\nstd::map&lt;std::string, std::string&gt; aka;\n\nstruct akaInit\n{\n akaInit()\n {\n aka[ \"George\" ] = \"John\";\n aka[ \"Joe\" ] = \"Al\";\n aka[ \"Phil\" ] = \"Sue\";\n aka[ \"Smitty\" ] = \"Yando\";\n }\n} AkaInit;\n</code></pre>\n" }, { "answer_id": 39423771, "author": "Dmitry Oberemchenko", "author_id": 6816103, "author_profile": "https://Stackoverflow.com/users/6816103", "pm_score": 4, "selected": false, "text": "<p>You can try:</p>\n\n<pre><code>std::map &lt;int, int&gt; mymap = \n{\n std::pair &lt;int, int&gt; (1, 1),\n std::pair &lt;int, int&gt; (2, 2),\n std::pair &lt;int, int&gt; (2, 2)\n};\n</code></pre>\n" }, { "answer_id": 41368801, "author": "isnullxbh", "author_id": 6266408, "author_profile": "https://Stackoverflow.com/users/6266408", "pm_score": 5, "selected": false, "text": "<p>For example:</p>\n\n<pre><code>const std::map&lt;LogLevel, const char*&gt; g_log_levels_dsc =\n{\n { LogLevel::Disabled, \"[---]\" },\n { LogLevel::Info, \"[inf]\" },\n { LogLevel::Warning, \"[wrn]\" },\n { LogLevel::Error, \"[err]\" },\n { LogLevel::Debug, \"[dbg]\" }\n};\n</code></pre>\n\n<p>If map is a data member of a class, you can initialize it directly in header by the following way (since C++17):</p>\n\n<pre><code>// Example\n\ntemplate&lt;&gt;\nclass StringConverter&lt;CacheMode&gt; final\n{\npublic:\n static auto convert(CacheMode mode) -&gt; const std::string&amp;\n {\n // validate...\n return s_modes.at(mode);\n }\n\nprivate:\n static inline const std::map&lt;CacheMode, std::string&gt; s_modes =\n {\n { CacheMode::All, \"All\" },\n { CacheMode::Selective, \"Selective\" },\n { CacheMode::None, \"None\" }\n // etc\n };\n}; \n</code></pre>\n" }, { "answer_id": 42650007, "author": "Emanuele Benedetti", "author_id": 5720542, "author_profile": "https://Stackoverflow.com/users/5720542", "pm_score": 3, "selected": false, "text": "<p>If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:</p>\n\n<pre><code>typedef std::pair&lt; int, char &gt; elemPair_t;\nelemPair_t elemPairs[] = \n{\n elemPair_t( 1, 'a'), \n elemPair_t( 3, 'b' ), \n elemPair_t( 5, 'c' ), \n elemPair_t( 7, 'd' )\n};\n\nconst std::map&lt; int, char &gt; myMap( &amp;elemPairs[ 0 ], &amp;elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );\n</code></pre>\n" }, { "answer_id": 66635078, "author": "Hans Olsson", "author_id": 5603247, "author_profile": "https://Stackoverflow.com/users/5603247", "pm_score": 2, "selected": false, "text": "<p>In addition to the good top answer of using</p>\n<pre><code>const std::map&lt;int, int&gt; m = {{1,1},{4,2},{9,3},{16,4},{32,9}}\n</code></pre>\n<p>there's an additional possibility by directly calling a lambda that can be useful in a few cases:</p>\n<pre><code>const std::map&lt;int, int&gt; m = []()-&gt;auto {\n std::map&lt;int, int&gt; m;\n m[1]=1;\n m[4]=2;\n m[9]=3;\n m[16]=4;\n m[32]=9;\n return m;\n}();\n</code></pre>\n<p>Clearly a simple initializer list is better when writing this from scratch with literal values, but it does open up additional possibilities:</p>\n<pre><code>const std::map&lt;int, int&gt; m = []()-&gt;auto {\n std::map&lt;int, int&gt; m;\n for(int i=1;i&lt;5;++i) m[i*i]=i;\n m[32]=9;\n return m;\n}();\n</code></pre>\n<p>(Obviously it should be a normal function if you want to re-use it; and this does require recent C++.)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15163/" ]
What is the right way of initializing a static map? Do we need a static function that will initialize it?
Using C++11: ``` #include <map> using namespace std; map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; ``` Using [Boost.Assign](http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html): ``` #include <map> #include "boost/assign.hpp" using namespace std; using namespace boost::assign; map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd'); ```
138,607
<p>I have a very simple bit of script that changes the status of an item in a MySql database - it works fine in IE7, but if I try it in Firefox, it looks like it's worked, but hasn't... Which is extremely odd.</p> <p>The code is very simple - first I get the details of the record I'm looking for:</p> <pre><code>&lt;cfscript&gt; // Get the Product Attribute details Arguments.qGetProductAttribute = Application.cfcProducts.getProductAttributes(Arguments.iProductAttributeID); &lt;/cfscript&gt; </code></pre> <p>This is working fine, if I dump the results, it's just the content of the record as expected. So then I use an if statement to change the 'active' field from one to zero or vice versa.</p> <pre><code>&lt;!--- If Product Attribute is active, mark as inactive ---&gt; &lt;cfif Arguments.qGetProductAttribute.bActive EQ 0&gt; &lt;cfquery name="qChangeStatus" datasource="#Request.sDSN#"&gt; UPDATE tblProductAttributes SET bActive = &lt;cfqueryparam value="1" cfsqltype="CF_SQL_INTEGER" maxlength="1" /&gt; WHERE iProductAttributeID = &lt;cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" /&gt;; &lt;/cfquery&gt; &lt;!--- Else if Product Attribute is inactive, mark as active ---&gt; &lt;cfelseif Arguments.qGetProductAttribute.bActive EQ 1&gt; &lt;cfquery name="qChangeStatus" datasource="#Request.sDSN#"&gt; UPDATE tblProductAttributes SET bActive = &lt;cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER" maxlength="1" /&gt; WHERE iProductAttributeID = &lt;cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" /&gt;; &lt;/cfquery&gt; &lt;/cfif&gt; </code></pre> <p>I can't see any reason whatsoever for this not to work... and indeed, in IE7 it works perfectly...</p> <p>What happens is after this script is run, the browser goes back to the page that displays all of these records. For each record if the 'bActive' field is set to '1', it will display the word 'Active' and if it's set to 'zero', it will display 'Disabled'. Simple enough.</p> <p>If I run the script to disable a record, Firefox actually displays the word 'disabled' as expected, but the database record doesn't change!</p> <p>I'm at a loss... how can server-side code work fine in one browser and not in another?!</p>
[ { "answer_id": 138659, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 2, "selected": false, "text": "<p>Are you 100% certain that the database record does not change? You could get this affect if firefox calls you script twice, once before the page is rendered and once after.</p>\n\n<p>So the product gets set to disabled, then after the page is sent to the browser it is updated again (and as it is already disabled, it is re-enabled).</p>\n\n<p>If you have add a last update field to the database and update that every time your product is amended then you would be able to tell if this is the case. </p>\n\n<p>EDIT: responding to the comments below, a quick + dirty fix would be to check the last update time stamp first and if its with in n seconds of the current time dismiss the update.</p>\n\n<p>Do you have any plug-ins in firefox that maybe re-calling the page? perhaps for dev purposes? an easy test to see if its your script or a quirk in firefox would be to change your get url to a form with a post method, as the browser/ plug-in shouldn't re-call a post request.</p>\n" }, { "answer_id": 139807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try removing the semi-colon at the end of your WHERE clauses in your SQL code.</p>\n\n<pre><code>WHERE iProductAttributeID = &lt;cfqueryparam value=\"#Arguments.iProductAttributeID#\" cfsqltype=\"CF_SQL_INTEGER\" /&gt;;\n</code></pre>\n" }, { "answer_id": 140577, "author": "ale", "author_id": 21960, "author_profile": "https://Stackoverflow.com/users/21960", "pm_score": 2, "selected": false, "text": "<p>This may be a browser caching issue. There's no way that straight CF code could be affected by the browser being used. What happens if you refresh the page where you're displaying the products? You also need to look at the database directly to see if the value is changing or not.</p>\n\n<p>On a bit of a tangent, you can eliminate the need for an if statement at all with a little simple math.</p>\n\n<pre><code>&lt;cfquery name=\"qChangeStatus\" datasource=\"#Request.sDSN#\"&gt;\n UPDATE tblProductAttributes\n SET\n bActive = &lt;cfqueryparam value=\"#val(1 - Arguments.qGetProductAttribute.bActive)#\" cfsqltype=\"CF_SQL_INTEGER\" maxlength=\"1\" /&gt;\n WHERE \n iProductAttributeID = &lt;cfqueryparam value=\"#Arguments.iProductAttributeID#\" cfsqltype=\"CF_SQL_INTEGER\" /&gt;;\n&lt;/cfquery&gt;\n</code></pre>\n" }, { "answer_id": 140722, "author": "Brian Sadler", "author_id": 6912, "author_profile": "https://Stackoverflow.com/users/6912", "pm_score": 2, "selected": false, "text": "<p>The code you've posted isn't the cause of the error because it's all server side code - there's nothing happening on the client in there.</p>\n\n<p>I'd turn on CF debugging (including database activity) and stick a tag right after the closing tag, and before any redirection back to the product view page. Run the code and look at the SQL debug output. </p>\n\n<p>My guess is that when using Firefox the block of code containing the queries just doesn't get called.</p>\n" }, { "answer_id": 149803, "author": "Gary Stanton", "author_id": 22113, "author_profile": "https://Stackoverflow.com/users/22113", "pm_score": 3, "selected": true, "text": "<p>I found the cause of the problem... Firebug.</p>\n\n<p>I haven't the slightest idea what Firebug thinks it's doing, if I remove the 'cflocation' tag from the script (the one that takes the user back to the summary page), then it works fine. But if I keep it in, Firebug seems to run the function again before forwarding the browser to the summary page.</p>\n\n<p>There's no reason for it to be doing this.\nUn-bloody-belivable.</p>\n\n<p>At least it won't be happening on the clients' machines.</p>\n" }, { "answer_id": 238565, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>all those different answers, and none of them worked for me. I had to go to another forum where someone said it was the Skype Extension Addon in Firefox which causes ColdFusion databases to go crazy or not function. I uninstalled the Skype extension (thank you, Skype) and everything was back to normal. Hope this works for someone else too.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22113/" ]
I have a very simple bit of script that changes the status of an item in a MySql database - it works fine in IE7, but if I try it in Firefox, it looks like it's worked, but hasn't... Which is extremely odd. The code is very simple - first I get the details of the record I'm looking for: ``` <cfscript> // Get the Product Attribute details Arguments.qGetProductAttribute = Application.cfcProducts.getProductAttributes(Arguments.iProductAttributeID); </cfscript> ``` This is working fine, if I dump the results, it's just the content of the record as expected. So then I use an if statement to change the 'active' field from one to zero or vice versa. ``` <!--- If Product Attribute is active, mark as inactive ---> <cfif Arguments.qGetProductAttribute.bActive EQ 0> <cfquery name="qChangeStatus" datasource="#Request.sDSN#"> UPDATE tblProductAttributes SET bActive = <cfqueryparam value="1" cfsqltype="CF_SQL_INTEGER" maxlength="1" /> WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />; </cfquery> <!--- Else if Product Attribute is inactive, mark as active ---> <cfelseif Arguments.qGetProductAttribute.bActive EQ 1> <cfquery name="qChangeStatus" datasource="#Request.sDSN#"> UPDATE tblProductAttributes SET bActive = <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER" maxlength="1" /> WHERE iProductAttributeID = <cfqueryparam value="#Arguments.iProductAttributeID#" cfsqltype="CF_SQL_INTEGER" />; </cfquery> </cfif> ``` I can't see any reason whatsoever for this not to work... and indeed, in IE7 it works perfectly... What happens is after this script is run, the browser goes back to the page that displays all of these records. For each record if the 'bActive' field is set to '1', it will display the word 'Active' and if it's set to 'zero', it will display 'Disabled'. Simple enough. If I run the script to disable a record, Firefox actually displays the word 'disabled' as expected, but the database record doesn't change! I'm at a loss... how can server-side code work fine in one browser and not in another?!
I found the cause of the problem... Firebug. I haven't the slightest idea what Firebug thinks it's doing, if I remove the 'cflocation' tag from the script (the one that takes the user back to the summary page), then it works fine. But if I keep it in, Firebug seems to run the function again before forwarding the browser to the summary page. There's no reason for it to be doing this. Un-bloody-belivable. At least it won't be happening on the clients' machines.
138,616
<p>I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window.</p> <p>How can I accomplish that in C++?</p> <p><strong>Update.</strong></p> <p>I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu').</p>
[ { "answer_id": 138657, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 1, "selected": false, "text": "<p>Once you have another window's top level handle, you may be able to call <a href=\"http://msdn.microsoft.com/en-us/library/ms647640(VS.85).aspx\" rel=\"nofollow noreferrer\">GetMenu()</a> to retrieve the Window's system menu and then modify it, eg:</p>\n\n<pre><code>HMENU hMenu = GetMenu(hwndNext);\n</code></pre>\n" }, { "answer_id": 138661, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx\" rel=\"nofollow noreferrer\">EnumWindows()</a> to enumerate top level Windows.</p>\n\n<p>I don't have a specific answer for the second part of your question, but if you subclass the window, I imagine you can modify the system menu.</p>\n\n<p>EDIT: or do what Chris said: call GetMenu()</p>\n" }, { "answer_id": 138788, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>Re: the update - please note that not even Microsoft Windows requires windows to have a sytem menu. GetMenu( ) may return 0. You'll need to intercept window creation as well, because each new top window presumably needs it too.</p>\n\n<p>Also, what you propose is rather intrusive to other applications. How are you going to ensure they don't break when you modify their menus? And how are you going to ensure you suppress the messages? In particular, how will you ensure you intercept them before anyone else sees them? To quote Raymond Chen, imagine what happens if two programs would try that.</p>\n" }, { "answer_id": 138896, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 3, "selected": false, "text": "<p>For Windows, another way to get the top-level windows (besides EnumWindows, which uses a callback) is to get the first child of the desktop and then retrieve all its siblings:</p>\n\n<pre><code>HWND wnd = GetWindow(GetDesktopWindow(), GW_CHILD);\nwhile (wnd) {\n // handle 'wnd' here\n // ...\n wnd = GetNextWindow(wnd, GW_HWNDNEXT);\n}\n</code></pre>\n\n<p>As for getting the <em>system</em> menu, use the <a href=\"http://msdn.microsoft.com/en-us/library/ms647985(VS.85).aspx\" rel=\"noreferrer\"><code>GetSystemMenu</code></a> function, with FALSE as the second argument. The <a href=\"http://msdn.microsoft.com/en-us/library/ms647640(VS.85).aspx\" rel=\"noreferrer\"><code>GetMenu</code></a> mentioned in the other answers returns the <em>normal</em> window menu.</p>\n\n<p>Note, however, that while adding a custom menu item to a foreign process's window is easy, responding to the selection of that item is a bit tricky. You'll either have to inject some code to the process in order to be able to subclass the window, or install a global hook (probably a <code>WH_GETMESSAGE</code> or <code>WH_CBT</code> type) to monitor <code>WM_SYSCOMMAND</code> messages. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22623/" ]
I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window. How can I accomplish that in C++? **Update.** I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu').
For Windows, another way to get the top-level windows (besides EnumWindows, which uses a callback) is to get the first child of the desktop and then retrieve all its siblings: ``` HWND wnd = GetWindow(GetDesktopWindow(), GW_CHILD); while (wnd) { // handle 'wnd' here // ... wnd = GetNextWindow(wnd, GW_HWNDNEXT); } ``` As for getting the *system* menu, use the [`GetSystemMenu`](http://msdn.microsoft.com/en-us/library/ms647985(VS.85).aspx) function, with FALSE as the second argument. The [`GetMenu`](http://msdn.microsoft.com/en-us/library/ms647640(VS.85).aspx) mentioned in the other answers returns the *normal* window menu. Note, however, that while adding a custom menu item to a foreign process's window is easy, responding to the selection of that item is a bit tricky. You'll either have to inject some code to the process in order to be able to subclass the window, or install a global hook (probably a `WH_GETMESSAGE` or `WH_CBT` type) to monitor `WM_SYSCOMMAND` messages.
138,617
<p>Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters?</p> <p>For example I have the following navigation-rule</p> <pre><code>&lt;navigation-rule&gt; &lt;navigation-case&gt; &lt;from-outcome&gt;showMessage&lt;/from-outcome&gt; &lt;to-view-id&gt;/showMessage.jsf&lt;/to-view-id&gt; &lt;redirect/&gt; &lt;/navigation-case&gt; &lt;/navigation-rule&gt; </code></pre> <p>In my page I would like to output the following html code:</p> <pre><code>&lt;a href="/showMessage.jsf?msg=23"&gt;click to see the message&lt;/a&gt; </code></pre> <p>I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.</p>
[ { "answer_id": 139620, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": 0, "selected": false, "text": "<p>Have you considered a form?</p>\n\n<pre><code>&lt;h:form&gt;\n &lt;h:commandLink value=\"Click to see the message\" action=\"#{handler.outcome}\" /&gt;\n &lt;h:inputHidden id=\"msgId\" value=\"#{bean.msgId}\"/&gt;\n&lt;/h:form&gt;\n</code></pre>\n" }, { "answer_id": 140050, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": true, "text": "<p>This is an interesting idea. I'd be curious to know how it pans out in practice.</p>\n\n<p><strong>Getting the navigation rules</strong></p>\n\n<p>Navigation is handled by the <a href=\"http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html\" rel=\"noreferrer\">NavigationHandler</a>. Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses.</p>\n\n<p>As I see it, you can:</p>\n\n<ol>\n<li>parse faces-config.xml on initialization and store the rules in the application context (<em>easy</em>)</li>\n<li>implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow (<em>workable, but takes a bit of work</em>)</li>\n<li>mock your own <a href=\"http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html\" rel=\"noreferrer\">FacesContext</a> and pass it to the existing navigation handler (<em>really difficult to make two FacesContext object coexist in same thread and extremely inefficient</em>)</li>\n</ol>\n\n<p>Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans?</p>\n\n<p><strong>Using the navigation rules</strong></p>\n\n<p>Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind.</p>\n\n<pre><code>&lt;managed-bean&gt;\n &lt;managed-bean-name&gt;navBean&lt;/managed-bean-name&gt;\n &lt;managed-bean-class&gt;foo.NavBean&lt;/managed-bean-class&gt;\n &lt;managed-bean-scope&gt;application&lt;/managed-bean-scope&gt;\n&lt;/managed-bean&gt;\n</code></pre>\n\n<p>Source:</p>\n\n<pre><code>package foo;\n\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.net.URLEncoder;\n\nimport javax.faces.context.ExternalContext;\nimport javax.faces.context.FacesContext;\n\npublic class NavBean implements Serializable {\n\n private String getView() {\n String viewId = \"/showMessage.faces\"; // or look this up somewhere\n return viewId;\n }\n\n /**\n * Regular link to page\n */\n public String getUrlLink() {\n FacesContext context = FacesContext.getCurrentInstance();\n ExternalContext extContext = context.getExternalContext();\n String viewId = getView();\n String navUrl = context.getExternalContext().encodeActionURL(\n extContext.getRequestContextPath() + viewId);\n return navUrl;\n }\n\n /**\n * Just some value\n */\n public String getValue() {\n return \"\" + System.currentTimeMillis();\n }\n\n /**\n * Invoked by action\n */\n public String invokeRedirect() {\n FacesContext context = FacesContext.getCurrentInstance();\n ExternalContext extContext = context.getExternalContext();\n String viewId = getView();\n try {\n String charEncoding = extContext.getRequestCharacterEncoding();\n String name = URLEncoder.encode(\"foo\", charEncoding);\n String value = URLEncoder.encode(getValue(), charEncoding);\n viewId = extContext.getRequestContextPath() + viewId + '?' + name\n + \"=\" + value;\n String urlLink = context.getExternalContext().encodeActionURL(\n viewId);\n extContext.redirect(urlLink);\n } catch (IOException e) {\n extContext.log(getClass().getName() + \".invokeRedirect\", e);\n }\n return null;\n }\n\n}\n</code></pre>\n\n<p><strong>GET</strong></p>\n\n<p>For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list.</p>\n\n<pre><code>&lt;h:outputLink value=\"#{navBean.urlLink}\"&gt;\n &lt;f:param name=\"foo\" value=\"#{navBean.value}\" /&gt;\n &lt;h:outputText value=\"get\" /&gt;\n&lt;/h:outputLink&gt;\n</code></pre>\n\n<p><strong>POST</strong></p>\n\n<p>If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink).</p>\n\n<pre><code>&lt;h:commandLink id=\"myCommandLink\" action=\"#{navBean.invokeRedirect}\"&gt;\n &lt;h:outputText value=\"post\" /&gt;\n&lt;/h:commandLink&gt;\n</code></pre>\n\n<p><strong>Notes</strong></p>\n\n<p>Note that <a href=\"http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/ExternalContext.html#encodeActionURL(java.lang.String)\" rel=\"noreferrer\">ExternalContext.encodeActionURL</a> is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use <em>encodeResourceURL</em> if you were encoding a link to an image or download file.</p>\n" }, { "answer_id": 163930, "author": "Ian McLaird", "author_id": 18796, "author_profile": "https://Stackoverflow.com/users/18796", "pm_score": 0, "selected": false, "text": "<p>You could use a commandLink with nested param tags. This is basically the same as hubbardr said above:</p>\n\n<pre><code>&lt;h:form&gt;\n &lt;h:commandLink value=\"click here\" action=\"${handler.outcome}\"&gt;\n &lt;f:param name=\"msgId\" value=\"${bean.id}\" /&gt;\n &lt;/h:commandLink&gt;\n&lt;/h:form&gt;\n</code></pre>\n\n<p>Then in your backing bean you need to do:</p>\n\n<pre><code>Map requestMap = FacesContext.getCurrentInstance()\n .getExternalContext().getRequestParameterMap();\nString msgId = (String) requestMap.get(\"msgId\");\n</code></pre>\n\n<p>And then do whatever you need to do.</p>\n" }, { "answer_id": 1669555, "author": "Lincoln", "author_id": 202007, "author_profile": "https://Stackoverflow.com/users/202007", "pm_score": 2, "selected": false, "text": "<p>Tried using PrettyFaces? It's an open-source JSF extension designed specifically to make bookmarkable JSF pages / JSF with GET requests possible.</p>\n\n<p><a href=\"http://ocpsoft.com/prettyfaces\" rel=\"nofollow noreferrer\" title=\"PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigation for JSF / JSF2\">PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigation for JSF / JSF2</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331/" ]
Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters? For example I have the following navigation-rule ``` <navigation-rule> <navigation-case> <from-outcome>showMessage</from-outcome> <to-view-id>/showMessage.jsf</to-view-id> <redirect/> </navigation-case> </navigation-rule> ``` In my page I would like to output the following html code: ``` <a href="/showMessage.jsf?msg=23">click to see the message</a> ``` I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.
This is an interesting idea. I'd be curious to know how it pans out in practice. **Getting the navigation rules** Navigation is handled by the [NavigationHandler](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html). Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses. As I see it, you can: 1. parse faces-config.xml on initialization and store the rules in the application context (*easy*) 2. implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow (*workable, but takes a bit of work*) 3. mock your own [FacesContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html) and pass it to the existing navigation handler (*really difficult to make two FacesContext object coexist in same thread and extremely inefficient*) Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans? **Using the navigation rules** Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind. ``` <managed-bean> <managed-bean-name>navBean</managed-bean-name> <managed-bean-class>foo.NavBean</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> </managed-bean> ``` Source: ``` package foo; import java.io.IOException; import java.io.Serializable; import java.net.URLEncoder; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; public class NavBean implements Serializable { private String getView() { String viewId = "/showMessage.faces"; // or look this up somewhere return viewId; } /** * Regular link to page */ public String getUrlLink() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); String navUrl = context.getExternalContext().encodeActionURL( extContext.getRequestContextPath() + viewId); return navUrl; } /** * Just some value */ public String getValue() { return "" + System.currentTimeMillis(); } /** * Invoked by action */ public String invokeRedirect() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); try { String charEncoding = extContext.getRequestCharacterEncoding(); String name = URLEncoder.encode("foo", charEncoding); String value = URLEncoder.encode(getValue(), charEncoding); viewId = extContext.getRequestContextPath() + viewId + '?' + name + "=" + value; String urlLink = context.getExternalContext().encodeActionURL( viewId); extContext.redirect(urlLink); } catch (IOException e) { extContext.log(getClass().getName() + ".invokeRedirect", e); } return null; } } ``` **GET** For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list. ``` <h:outputLink value="#{navBean.urlLink}"> <f:param name="foo" value="#{navBean.value}" /> <h:outputText value="get" /> </h:outputLink> ``` **POST** If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink). ``` <h:commandLink id="myCommandLink" action="#{navBean.invokeRedirect}"> <h:outputText value="post" /> </h:commandLink> ``` **Notes** Note that [ExternalContext.encodeActionURL](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/ExternalContext.html#encodeActionURL(java.lang.String)) is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use *encodeResourceURL* if you were encoding a link to an image or download file.
138,638
<p>Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have</p> <pre><code>using antlr.collections; using myNamespace; </code></pre> <p>at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have</p> <pre><code>using myNamespace; </code></pre> <p>at the top of their files?</p>
[ { "answer_id": 138642, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 2, "selected": false, "text": "<p>How about deriving a class using the same name in the new namespace? I meant:</p>\n\n<pre><code>namespace MyForms {\n class Class1 : Some.Other.Namespace.Class1 {\n // ...\n }\n}\n</code></pre>\n" }, { "answer_id": 138654, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>No, you can't.</p>\n\n<p>The full path to and name of a class is part of its identity.</p>\n" }, { "answer_id": 138663, "author": "Omar Kooheji", "author_id": 20400, "author_profile": "https://Stackoverflow.com/users/20400", "pm_score": 2, "selected": false, "text": "<p>create a new class that inherits the class in your new namespace. It's not ideal, but it's useful for unit testing and the like.</p>\n\n<p>You should think about why you are doing this though, classes are broken up into namespaces for a reason.</p>\n" }, { "answer_id": 138779, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": true, "text": "<p>Bear in mind that the consumers of your code won't actually <em>need</em> to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source.</p>\n\n<p>The bigger \"impact\" (if indeed there really is a severe one) is that the consumer of your code will need a hard reference to the assembly where antlr.collections is defined. </p>\n\n<p>However, if that's documented up front, I honestly don't see it being that big of a problem. It's no different than the consumer of a SubSonic-generated DAL needing references both to the generated DAL assembly and the original SubSonic assembly. (And, quite possibly, using statements as well.)</p>\n\n<p>Dependencies are what they are. There's a reason classes are broken into namespaces -- primarily for organization and to reduce naming conflicts. Not knowing what classes are in the namespace you mention, I don't know how likely such a conflict actually is in your scenario ... But attempting to move the class from one namespace to another, or to hide the fact that such is needed by deriving a blank class from it, is probably not the best idea. It won't kill the consumers of your class to have another reference and using statement.</p>\n" }, { "answer_id": 138977, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 1, "selected": false, "text": "<p>If you derive from the class and return your derived class, you'll make yourself responsible for providing all of the documentation for the return type.</p>\n\n<p>I think you'll be doing the developers who use your library a disservice because they won't necessarily know that what they're really working with is a type from antir.collections (not that I even know what that is, but that's not the point). If the developer comes to StackOverflow.com searching for information on that return type, are they more likely to find information if the type is from a \"common\" library, or from yours?</p>\n" }, { "answer_id": 139654, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 1, "selected": false, "text": "<p>The only solution is to hide the whole dependency to the type antlr.collections.AST.</p>\n\n<p>You can use an <a href=\"http://en.wikipedia.org/wiki/Adapter_pattern\" rel=\"nofollow noreferrer\">Adapter</a> fot that purpose.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have ``` using antlr.collections; using myNamespace; ``` at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have ``` using myNamespace; ``` at the top of their files?
Bear in mind that the consumers of your code won't actually *need* to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source. The bigger "impact" (if indeed there really is a severe one) is that the consumer of your code will need a hard reference to the assembly where antlr.collections is defined. However, if that's documented up front, I honestly don't see it being that big of a problem. It's no different than the consumer of a SubSonic-generated DAL needing references both to the generated DAL assembly and the original SubSonic assembly. (And, quite possibly, using statements as well.) Dependencies are what they are. There's a reason classes are broken into namespaces -- primarily for organization and to reduce naming conflicts. Not knowing what classes are in the namespace you mention, I don't know how likely such a conflict actually is in your scenario ... But attempting to move the class from one namespace to another, or to hide the fact that such is needed by deriving a blank class from it, is probably not the best idea. It won't kill the consumers of your class to have another reference and using statement.
138,680
<p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p> <p>What I need ideally is custom command when in command mode. E.g.</p> <p>ESC</p> <p>:do_this</p> <p>:do_that</p>
[ { "answer_id": 138709, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": 5, "selected": true, "text": "<p>vim supports scripting in python (and in perl as well, I think).</p>\n\n<p>You just have to make sure that the vim distribution you are using has been compiled with python support.</p>\n\n<p>If you are using a Linux system, you can download the source and then compile it with</p>\n\n<pre><code>./configure --enable-pythoninterp \nmake\nsudo make install\n</code></pre>\n\n<p>Inside vim, you can type</p>\n\n<pre><code>:version\n</code></pre>\n\n<p>to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise).</p>\n\n<p>Then, to check the usage of the python module, you can type</p>\n\n<pre><code>:help python\n</code></pre>\n\n<p>P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well.</p>\n\n<p>P.P.S: to create a \"custom command in command mode\" (if I understand correctly what you mean), you can create a function \"MyFunction\" in a vim script (using python or the vim scripting language) and then invoke it with </p>\n\n<pre><code>:Call MyFunction()\n</code></pre>\n\n<p>Check </p>\n\n<pre><code>:help user-functions\n</code></pre>\n\n<p>for details</p>\n" }, { "answer_id": 138720, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 3, "selected": false, "text": "<p>Yes it is. There are several extensions on <a href=\"http://www.vim.org/scripts/index.php\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/index.php</a> </p>\n\n<p>It can be done with python as well if the support for python is compiled in. </p>\n\n<p>Article about it: <a href=\"http://www.techrepublic.com/article/extending-vim-with-python/\" rel=\"nofollow noreferrer\">http://www.techrepublic.com/article/extending-vim-with-python/</a> </p>\n\n<p>Google is our friend.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 5293536, "author": "vrybas", "author_id": 523157, "author_profile": "https://Stackoverflow.com/users/523157", "pm_score": 2, "selected": false, "text": "<p>Had a problems to compile Vim with Python. </p>\n\n<blockquote>\n <p>...checking if compile and link flags for Python are sane... no: PYTHON DISABLED\" in the ./configure output.</p>\n</blockquote>\n\n<p>On Ubuntu 10.04 you have to install <code>python2.6-dev</code>. The flags for <code>./configure</code> are:</p>\n\n<pre><code>--enable-pythoninterp\n--with-python-config-dir=/usr/lib/python2.6/config\n</code></pre>\n\n<p>Make sure you got a path to directory, which contains <code>config.c</code> file. Also no <code>/</code> at the end of the path! That caused me problems.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22623/" ]
is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do\_this :do\_that
vim supports scripting in python (and in perl as well, I think). You just have to make sure that the vim distribution you are using has been compiled with python support. If you are using a Linux system, you can download the source and then compile it with ``` ./configure --enable-pythoninterp make sudo make install ``` Inside vim, you can type ``` :version ``` to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise). Then, to check the usage of the python module, you can type ``` :help python ``` P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well. P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with ``` :Call MyFunction() ``` Check ``` :help user-functions ``` for details
138,747
<p>A client of mine uses Oracle 9i's utl_smtp to send mails out notifications to managers when their employees have made travel requests and they woul like quite a few changes made to the mailouts done. </p> <p>We're having a lot of problems getting utl_smtp to talk to any smtp server on our network. We've even tried installing free smtp server on the oracle box but it will not spot the mail server running on port 25. The error code is ORA-29278.</p> <p>So two questions really.</p> <ol> <li><p>Does anyone have any experience setting up email using Oracle's utl_smtp utility and have any suggestions as to where we might be going wrong.</p></li> <li><p>Does anyone know if it is possible to get utl_smtp to dump text emails to a directory much as you can do if you're using system.net.mail's specifiedpickupdirectory config setting. This would be by far the preferable option.</p></li> </ol> <p>Thanks, Dan</p>
[ { "answer_id": 139021, "author": "Dan Maharry", "author_id": 2756, "author_profile": "https://Stackoverflow.com/users/2756", "pm_score": 1, "selected": false, "text": "<p>Yes, we can telnet to the server.</p>\n\n<pre><code>-- ****** Object: Stored Procedure TRAVELADMIN_DEV.HTML_EMAIL Script Date: 22/08/2008 12:41:02 ******\nCREATE PROCEDURE \"HTML_EMAIL\" (\n p_to in varchar2,\n p_cc in varchar2,\n p_from in varchar2,\n p_subject in varchar2,\n p_text in varchar2 default null,\n p_html in varchar2 default null\n )\nis\n l_boundary varchar2(255) default 'a1b2c3d4e3f2g1';\n l_connection utl_smtp.connection;\n l_body_html clob := empty_clob; --This LOB will be the email message\n l_offset number;\n l_ammount number;\n l_temp varchar2(32767) default null;\n p_smtp_hostname varchar2(30):= 'rockies';\n p_smtp_portnum varchar2(2) := '25';\nbegin\n l_connection := utl_smtp.open_connection( p_smtp_hostname, p_smtp_portnum );\n utl_smtp.helo( l_connection, p_smtp_hostname );\n utl_smtp.mail( l_connection, p_from );\n utl_smtp.rcpt( l_connection, p_to );\n l_temp := l_temp || 'MIME-Version: 1.0' || chr(13) || chr(10);\n l_temp := l_temp || 'To: ' || p_to || chr(13) || chr(10);\n IF ((p_cc &lt;&gt; NULL) OR (LENGTH(p_cc) &gt; 0)) THEN\n l_temp := l_temp || 'Cc: ' || p_cc || chr(13) || chr(10);\n utl_smtp.rcpt( l_connection, p_cc );\n END IF;\n l_temp := l_temp || 'From: ' || p_from || chr(13) || chr(10);\n l_temp := l_temp || 'Subject: ' || p_subject || chr(13) || chr(10);\n l_temp := l_temp || 'Reply-To: ' || p_from || chr(13) || chr(10);\n l_temp := l_temp || 'Content-Type: multipart/alternative; boundary=' ||\n chr(34) || l_boundary || chr(34) || chr(13) ||\n chr(10);\n ----------------------------------------------------\n -- Write the headers\n dbms_lob.createtemporary( l_body_html, false, 10 );\n dbms_lob.write(l_body_html,length(l_temp),1,l_temp);\n ----------------------------------------------------\n -- Write the text boundary\n l_offset := dbms_lob.getlength(l_body_html) + 1;\n l_temp := '--' || l_boundary || chr(13)||chr(10);\n l_temp := l_temp || 'content-type: text/plain; charset=us-ascii' ||\n chr(13) || chr(10) || chr(13) || chr(10);\n dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);\n ----------------------------------------------------\n -- Write the plain text portion of the email\n l_offset := dbms_lob.getlength(l_body_html) + 1;\n dbms_lob.write(l_body_html,length(p_text),l_offset,p_text);\n ----------------------------------------------------\n -- Write the HTML boundary\n l_temp := chr(13)||chr(10)||chr(13)||chr(10)||'--' || l_boundary ||\n chr(13) || chr(10);\n l_temp := l_temp || 'content-type: text/html;' ||\n chr(13) || chr(10) || chr(13) || chr(10);\n l_offset := dbms_lob.getlength(l_body_html) + 1;\n dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);\n ----------------------------------------------------\n -- Write the HTML portion of the message\n l_offset := dbms_lob.getlength(l_body_html) + 1;\n dbms_lob.write(l_body_html,length(p_html),l_offset,p_html);\n ----------------------------------------------------\n -- Write the final html boundary\n l_temp := chr(13) || chr(10) || '--' || l_boundary || '--' || chr(13);\n l_offset := dbms_lob.getlength(l_body_html) + 1;\n dbms_lob.write(l_body_html,length(l_temp),l_offset,l_temp);\n ----------------------------------------------------\n -- Send the email in 1900 byte chunks to UTL_SMTP\n l_offset := 1;\n l_ammount := 1900;\n utl_smtp.open_data(l_connection);\n while l_offset &lt; dbms_lob.getlength(l_body_html) loop\n utl_smtp.write_data(l_connection,\n dbms_lob.substr(l_body_html,l_ammount,l_offset));\n l_offset := l_offset + l_ammount ;\n l_ammount := least(1900,dbms_lob.getlength(l_body_html) - l_ammount);\n end loop;\n utl_smtp.close_data(l_connection);\n utl_smtp.quit( l_connection );\n dbms_lob.freetemporary(l_body_html);\nend;\n</code></pre>\n" }, { "answer_id": 139223, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<ul>\n<li>The OPEN_CONNECTION parameter should be the FQDN or IP address of the server you're connecting to.</li>\n<li>The HELO parameter should be the FQDN of the machine you're connecting from.</li>\n</ul>\n\n<p>If this doesn't work, do you know which line it errors on?</p>\n" }, { "answer_id": 139860, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 3, "selected": true, "text": "<p>Looks like the HELO is the problem. Please can we check with a simple testcase...</p>\n\n<pre><code>set serveroutput on\n\ndeclare\n lConnection UTL_SMTP.CONNECTION;\nbegin\n lConnection := UTL_SMTP.OPEN_CONNECTION(your_smtp_server);\n DBMS_OUTPUT.PUT_LINE('Opened ok');\n\n UTL_SMTP.HELO(lConnection, your_client_machine_name);\n DBMS_OUTPUT.PUT_LINE('HELO ok');\n\n UTL_SMTP.MAIL(lConnection, your_email_address);\n UTL_SMTP.RCPT(lConnection, your_email_address);\n DBMS_OUTPUT.PUT_LINE('Addressing ok');\nend;\n/\n</code></pre>\n" }, { "answer_id": 179045, "author": "Dan Maharry", "author_id": 2756, "author_profile": "https://Stackoverflow.com/users/2756", "pm_score": 2, "selected": false, "text": "<p>Looks like we've resolved this.\nTo answer the two questions.</p>\n\n<ol>\n<li><p>Double check that the schema calling <code>utl_smtp</code> has execute permissions on <code>sys.utl_smtp</code>, <code>sys.utl_tcp</code> and <code>sys.dbms_lob</code>. Also check that at no time the message being sent is > 32Kb.</p></li>\n<li><p>No there is no way to get utl_smtp to dump emails to a directory a la system.net.mail.</p></li>\n</ol>\n\n<p>Thanks to cagcowboy for the help.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2756/" ]
A client of mine uses Oracle 9i's utl\_smtp to send mails out notifications to managers when their employees have made travel requests and they woul like quite a few changes made to the mailouts done. We're having a lot of problems getting utl\_smtp to talk to any smtp server on our network. We've even tried installing free smtp server on the oracle box but it will not spot the mail server running on port 25. The error code is ORA-29278. So two questions really. 1. Does anyone have any experience setting up email using Oracle's utl\_smtp utility and have any suggestions as to where we might be going wrong. 2. Does anyone know if it is possible to get utl\_smtp to dump text emails to a directory much as you can do if you're using system.net.mail's specifiedpickupdirectory config setting. This would be by far the preferable option. Thanks, Dan
Looks like the HELO is the problem. Please can we check with a simple testcase... ``` set serveroutput on declare lConnection UTL_SMTP.CONNECTION; begin lConnection := UTL_SMTP.OPEN_CONNECTION(your_smtp_server); DBMS_OUTPUT.PUT_LINE('Opened ok'); UTL_SMTP.HELO(lConnection, your_client_machine_name); DBMS_OUTPUT.PUT_LINE('HELO ok'); UTL_SMTP.MAIL(lConnection, your_email_address); UTL_SMTP.RCPT(lConnection, your_email_address); DBMS_OUTPUT.PUT_LINE('Addressing ok'); end; / ```
138,785
<p>I'm trying to learn RegEx in Ruby, based on what I'm reading in "<em>The Rails Way</em>". But, even this simple example has me stumped. I can't tell if it is a typo or not:</p> <pre><code>text.gsub(/\s/, "-").gsub([^\W-], '').downcase </code></pre> <p>It seems to me that this would replace all spaces with <code>-</code>, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on <code>^</code>:</p> <blockquote> <p>syntax error, unexpected '^', expecting ']'</p> </blockquote> <p>If I take out the <code>^</code>, it fails again on the W.</p>
[ { "answer_id": 138800, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 2, "selected": false, "text": "<p>You forgot the slashes. It should be <code>/[^\\W-]/</code></p>\n" }, { "answer_id": 138809, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<pre><code>&gt;&gt; text = \"I love spaces\"\n=&gt; \"I love spaces\"\n&gt;&gt; text.gsub(/\\s/, \"-\").gsub(/[^\\W-]/, '').downcase\n=&gt; \"--\"\n</code></pre>\n\n<p>Missing //</p>\n\n<p>Although this makes a little more sense :-)</p>\n\n<pre><code>&gt;&gt; text.gsub(/\\s/, \"-\").gsub(/([^\\W-])/, '\\1').downcase\n=&gt; \"i-love-spaces\"\n</code></pre>\n\n<p>And this is probably what is meant</p>\n\n<pre><code>&gt;&gt; text.gsub(/\\s/, \"-\").gsub(/[^\\w-]/, '').downcase\n=&gt; \"i-love-spaces\"\n</code></pre>\n\n<p>\\W means \"not a word\"\n\\w means \"a word\"</p>\n\n<p>The // generate a regexp object</p>\n\n<blockquote>\n <blockquote>\n <p>/[^\\W-]/.class\n => Regexp</p>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 138834, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 1, "selected": false, "text": "<p>The slashes are to say that the thing between them is a regular expression, much like quotes say the thing between them is a string.</p>\n" }, { "answer_id": 138855, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Well, .gsub(/[^\\W-]/,'') says replace anything that's a not word nor a - for nothing.</p>\n\n<p>You probably want</p>\n\n<pre><code>&gt;&gt; text.gsub(/\\s/, \"-\").gsub(/[^\\w-]/, '').downcase\n=&gt; \"i-love-spaces\"\n</code></pre>\n\n<p>Lower case \\w (\\W is just the opposite)</p>\n" }, { "answer_id": 142565, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>Step 1: <a href=\"http://www.zenspider.com/Languages/Ruby/QuickRef.html\" rel=\"nofollow noreferrer\">Add this to your bookmarks</a>. Whenever I need to look up regexes, it's my first stop</p>\n\n<p>Step 2: Let's walk through your code</p>\n\n<pre><code>text.gsub(/\\s/, \"-\")\n</code></pre>\n\n<p>You're calling the <code>gsub</code> function, and giving it 2 parameters.<br>\nThe first parameter is <code>/\\s/</code>, which is ruby for \"create a new regexp containing <code>\\s</code> (the // are like special \"\" for regexes).<br>\nThe second parameter is the string <code>\"-\"</code>.</p>\n\n<p>This will therefore replace all whitespace characters with hyphens. So far, so good.</p>\n\n<pre><code>.gsub([^\\W-], '').downcase\n</code></pre>\n\n<p>Next you call gsub again, passing it 2 parameters. \nThe first parameter is <code>[^\\W-]</code>. Because we didn't quote it in forward-slashes, ruby will literally try run that code. <code>[]</code> creates an array, then it tries to put <code>^\\W-</code> into the array, which is not valid code, so it breaks.<br>\nChanging it to <code>/[^\\W-]/</code> gives us a valid regex.</p>\n\n<p>Looking at the regex, the <code>[]</code> says 'match any character in this group. The group contains <code>\\W</code> (which means non-word character) and <code>-</code>, so the regex should match any non-word character, or any hyphen.</p>\n\n<p>As the second thing you pass to gsub is an empty string, it should end up replacing all the non-word characters and hyphens with empty string (thereby stripping them out )</p>\n\n<pre><code>.downcase\n</code></pre>\n\n<p>Which just converts the string to lower case.</p>\n\n<p>Hope this helps :-) </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
I'm trying to learn RegEx in Ruby, based on what I'm reading in "*The Rails Way*". But, even this simple example has me stumped. I can't tell if it is a typo or not: ``` text.gsub(/\s/, "-").gsub([^\W-], '').downcase ``` It seems to me that this would replace all spaces with `-`, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on `^`: > > syntax error, unexpected '^', expecting ']' > > > If I take out the `^`, it fails again on the W.
``` >> text = "I love spaces" => "I love spaces" >> text.gsub(/\s/, "-").gsub(/[^\W-]/, '').downcase => "--" ``` Missing // Although this makes a little more sense :-) ``` >> text.gsub(/\s/, "-").gsub(/([^\W-])/, '\1').downcase => "i-love-spaces" ``` And this is probably what is meant ``` >> text.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase => "i-love-spaces" ``` \W means "not a word" \w means "a word" The // generate a regexp object > > > > > > /[^\W-]/.class > > => Regexp > > > > > > > > >
138,819
<p>If I am iterating over each file using :</p> <pre><code>@echo off FOR %%f IN (*\*.\**) DO ( echo %%f ) </code></pre> <p>how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : <code>echo "%t:~-3%"</code> to print but with no success.</p>
[ { "answer_id": 138847, "author": "Sam Holloway", "author_id": 1377325, "author_profile": "https://Stackoverflow.com/users/1377325", "pm_score": 6, "selected": true, "text": "<p>The FOR command has several built-in switches that allow you to modify file names. Try the following:</p>\n\n<pre><code>@echo off\nfor %%i in (*.*) do echo \"%%~xi\"\n</code></pre>\n\n<p>For further details, use <code>help for</code> to get a complete list of the modifiers - there are quite a few!</p>\n" }, { "answer_id": 138913, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>This works, although it's not blindingly fast:</p>\n\n<pre><code>@echo off\nfor %%f in (*.*) do call :procfile %%f\ngoto :eof\n\n:procfile\n set fname=%1\n set ename=\n:loop1\n if \"%fname%\"==\"\" (\n set ename=\n goto :exit1\n )\n if not \"%fname:~-1%\"==\".\" (\n set ename=%fname:~-1%%ename%\n set fname=%fname:~0,-1%\n goto :loop1\n )\n:exit1\n echo.%ename%\n goto :eof\n</code></pre>\n" }, { "answer_id": 712610, "author": "system PAUSE", "author_id": 52963, "author_profile": "https://Stackoverflow.com/users/52963", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/138819#138847\">Sam</a>'s answer is definitely the easiest for what you want. But I wanted to add:</p>\n\n<p>Don't <code>set</code> a variable inside the <code>()</code>'s of a <code>for</code> and expect to use it right away, unless you have previously issued</p>\n\n<pre><code>setlocal ENABLEDELAYEDEXPANSION\n</code></pre>\n\n<p>and you are using <code>!</code> instead of % to wrap the variable name. For instance,</p>\n\n<pre><code>@echo off\nsetlocal ENABLEDELAYEDEXPANSION\n\nFOR %%f IN (*.*) DO (\n\n set t=%%f\n echo !t:~-3!\n\n)\n</code></pre>\n\n<p>Check out</p>\n\n<pre><code>set /?\n</code></pre>\n\n<p>for more info.</p>\n\n<p>The other alternative is to call a subroutine to do the <code>set</code>, like <a href=\"https://stackoverflow.com/questions/138819#138913\">Pax</a> shows.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
If I am iterating over each file using : ``` @echo off FOR %%f IN (*\*.\**) DO ( echo %%f ) ``` how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : `echo "%t:~-3%"` to print but with no success.
The FOR command has several built-in switches that allow you to modify file names. Try the following: ``` @echo off for %%i in (*.*) do echo "%%~xi" ``` For further details, use `help for` to get a complete list of the modifiers - there are quite a few!
138,839
<p>Currently I use .Net <code>WebBrowser.Document.Images()</code> to do this. It requires the <code>Webrowser</code> to load the document. It's messy and takes up resources. </p> <p>According to <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php">this question</a> XPath is better than a regex at this. </p> <p>Anyone know how to do this in C#?</p>
[ { "answer_id": 138863, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": -1, "selected": false, "text": "<p>If it's valid xhtml, you could do this:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.LoadXml(html);\nXmlNodeList results = doc.SelectNodes(\"//img/@src\");\n</code></pre>\n" }, { "answer_id": 138867, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>If all you need is images I would just use a regular expression. Something like this should do the trick:</p>\n\n<pre><code>Regex rg = new Regex(@\"&lt;img.*?src=\"\"(.*?)\"\"\", RegexOptions.IgnoreCase);\n</code></pre>\n" }, { "answer_id": 138892, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 7, "selected": true, "text": "<p>If your input string is valid XHTML you can treat is as xml, load it into an xmldocument, and do XPath magic :) But it's not always the case.</p>\n\n<p>Otherwise you can try this function, that will return all image links from HtmlSource :</p>\n\n<pre><code>public List&lt;Uri&gt; FetchLinksFromSource(string htmlSource)\n{\n List&lt;Uri&gt; links = new List&lt;Uri&gt;();\n string regexImgSrc = @\"&lt;img[^&gt;]*?src\\s*=\\s*[\"\"']?([^'\"\" &gt;]+?)[ '\"\"][^&gt;]*?&gt;\";\n MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);\n foreach (Match m in matchesImgSrc)\n {\n string href = m.Groups[1].Value;\n links.Add(new Uri(href));\n }\n return links;\n}\n</code></pre>\n\n<p>And you can use it like this :</p>\n\n<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://www.example.com\");\nrequest.Credentials = System.Net.CredentialCache.DefaultCredentials;\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\nif (response.StatusCode == HttpStatusCode.OK)\n{\n using(StreamReader sr = new StreamReader(response.GetResponseStream()))\n {\n List&lt;Uri&gt; links = FetchLinksFromSource(sr.ReadToEnd());\n }\n}\n</code></pre>\n" }, { "answer_id": 141711, "author": "Paul Mrozowski", "author_id": 3656, "author_profile": "https://Stackoverflow.com/users/3656", "pm_score": 4, "selected": false, "text": "<p>The big issue with any HTML parsing is the \"well formed\" part. You've seen the crap HTML out there - how much of it is really well formed? I needed to do something similar - parse out all links in a document (and in my case) update them with a rewritten link. I found the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"noreferrer\">Html Agility Pack</a> over on CodePlex. It rocks (and handles malformed HTML).</p>\n\n<p>Here's a snippet for iterating over links in a document:</p>\n\n<pre><code>HtmlDocument doc = new HtmlDocument();\ndoc.Load(@\"C:\\Sample.HTM\");\nHtmlNodeCollection linkNodes = doc.DocumentNode.SelectNodes(\"//a/@href\");\n\nContent match = null;\n\n// Run only if there are links in the document.\nif (linkNodes != null)\n{\n foreach (HtmlNode linkNode in linkNodes)\n {\n HtmlAttribute attrib = linkNode.Attributes[\"href\"];\n // Do whatever else you need here\n }\n}\n</code></pre>\n\n<p><a href=\"http://www.rcs-solutions.com/blog/2008/08/13/ProcessingHTMLDocuments.aspx\" rel=\"noreferrer\">Original Blog Post</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5648/" ]
Currently I use .Net `WebBrowser.Document.Images()` to do this. It requires the `Webrowser` to load the document. It's messy and takes up resources. According to [this question](https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) XPath is better than a regex at this. Anyone know how to do this in C#?
If your input string is valid XHTML you can treat is as xml, load it into an xmldocument, and do XPath magic :) But it's not always the case. Otherwise you can try this function, that will return all image links from HtmlSource : ``` public List<Uri> FetchLinksFromSource(string htmlSource) { List<Uri> links = new List<Uri>(); string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>"; MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline); foreach (Match m in matchesImgSrc) { string href = m.Groups[1].Value; links.Add(new Uri(href)); } return links; } ``` And you can use it like this : ``` HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com"); request.Credentials = System.Net.CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { using(StreamReader sr = new StreamReader(response.GetResponseStream())) { List<Uri> links = FetchLinksFromSource(sr.ReadToEnd()); } } ```
138,880
<p>Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down?</p>
[ { "answer_id": 138891, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 0, "selected": false, "text": "<p>Use Firefox with Firebug to compare the HTTP Headers in the Request and Response from both servers.</p>\n" }, { "answer_id": 138897, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>Might be a communication problem. Try wireshark against the server that freezes and the server that doesn't freeze. Compare the results to see if there is a difference.</p></li>\n<li><p>Narrow down the problem. Start cutting out code until IE6 doesn't freeze. Then you might be able to figure out exactly what is causing the problem.</p></li>\n</ol>\n" }, { "answer_id": 138906, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 1, "selected": false, "text": "<p>Try both in IE6 on different machines, preferably with as few addons as possible such as spyware blockers or Google Toolbars...</p>\n" }, { "answer_id": 138931, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>You can also try : <a href=\"http://projects.nikhilk.net/WebDevHelper/Default.aspx\" rel=\"nofollow noreferrer\">http://projects.nikhilk.net/WebDevHelper/Default.aspx</a></p>\n\n<p>That installs in IE and may help you in troubleshooting network issues and such. You may be able to see exactly when and where it freezes in the request/response by using its tracing features.</p>\n" }, { "answer_id": 138974, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>Is the freezing happening on your development server or your production server? Weather your developer server locks up IE6 or not isn't that big of a deal, but if your production server fails to kill IE6 you might have a problem!</p>\n\n<p>:-P</p>\n" }, { "answer_id": 139101, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": false, "text": "<p>You need to determine the difference between them, so I'd start out with the following:</p>\n\n<pre><code>curl -D first.headers -o first.body http://first.example.com\ncurl -D second.headers -o second.body http://second.example.com\ndiff -u first.headers second.headers\ndiff -u first.body second.body\n</code></pre>\n" }, { "answer_id": 422730, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've been having this problem today on an AJAX-heavy site. I think I've narrowed the problem down to the server having GZIP compression turned on. When the GZIP was turned off on our server, IE6 loaded the page without freezing at all. When GZIP is turned on, IE6 freezes/crashes completely. </p>\n\n<p>I also noticed that images were being served with GZIP from our server, so I disabled that for images and this solved the problem with IE6 freezing/crashing. Now the server uses GZIP only for .js, .html, and JSON.</p>\n" }, { "answer_id": 649969, "author": "Martijn", "author_id": 61222, "author_profile": "https://Stackoverflow.com/users/61222", "pm_score": -1, "selected": false, "text": "<p>Perhaps some more info that will help you.</p>\n\n<p>We had the same problem and narrowed it also down to the GZIP compression. The key was that we had gzip compression on for our ScriptResources, which also deliver the javascripts used by the controls in our .NET page.</p>\n\n<p>Apperently there is a bug in IE6 that causes is to freeze, we believe that the browser receives the files and parses them <strong>before unpacking them</strong>, which causes the freeze.</p>\n\n<p>For now we have turned off the gzip compression, but as we have a large number of files provided through the ScriptsResource manager we need a different solution.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/138880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
Our web site (running Rails) freezes IE6 nearly every time. The same code, deployed on a different server, does not freeze IE6. Where and how should we start tracking this down?
You need to determine the difference between them, so I'd start out with the following: ``` curl -D first.headers -o first.body http://first.example.com curl -D second.headers -o second.body http://second.example.com diff -u first.headers second.headers diff -u first.body second.body ```