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
106,963
<p>I'm building the world's simplest library application. All I want to be able to do is scan in a book's UPC (barcode) using a typical scanner (which just types the numbers of the barcode into a field) and then use it to look up data about the book... at a minimum, title, author, year published, and either the Dewey Decimal or Library of Congress catalog number.</p> <p>The goal is to print out a tiny sticker ("spine label") with the card catalog number that I can stick on the spine of the book, and then I can sort the books by card catalog number on the shelves in our company library. That way books on similar subjects will tend to be near each other, for example, if you know you're looking for a book about accounting, all you have to do is find SOME book about accounting and you'll see the other half dozen that we have right next to it which makes it convenient to browse the library.</p> <p>There seem to be lots of web APIs to do this, including Amazon and the Library of Congress. But those are all extremely confusing to me. What I really just want is a single higher level function that takes a UPC barcode number and returns some basic data about the book.</p>
[ { "answer_id": 106987, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 3, "selected": false, "text": "<p><strong>Edit</strong> It would be pretty easy if you had ISBN. but converting from UPC to ISBN is not as easy as you'd like.</p>\n\n<p>Here's some javascript code for it from <a href=\"http://isbn.nu\" rel=\"noreferrer\">http://isbn.nu</a> where it's done in script</p>\n\n<pre><code>if (indexisbn.indexOf(\"978\") == 0) {\n isbn = isbn.substr(3,9);\n var xsum = 0;\n var add = 0;\n var i = 0;\n for (i = 0; i &lt; 9; i++) {\n add = isbn.substr(i,1);\n xsum += (10 - i) * add;\n }\n xsum %= 11;\n xsum = 11 - xsum;\n if (xsum == 10) { xsum = \"X\"; }\n if (xsum == 11) { xsum = \"0\"; }\n isbn += xsum;\n}\n</code></pre>\n\n<p>However, that only converts from UPC to ISBN <em>some</em> of the time.</p>\n\n<p>You may want to look at the <a href=\"http://www.eblong.com/zarf/bookscan/\" rel=\"noreferrer\">barcode scanning project page</a>, too - one person's journey to scan books.</p>\n\n<p>So you know about <a href=\"http://www.amazon.com/AWS-home-page-Money/b?ie=UTF8&amp;node=3435361\" rel=\"noreferrer\">Amazon Web Services</a>. But that assumes amazon has the book and has scanned in the UPC.</p>\n\n<p>You can also try the <a href=\"http://www.upcdatabase.com/\" rel=\"noreferrer\">UPCdatabase</a> at <a href=\"http://www.upcdatabase.com/item/\" rel=\"noreferrer\">http://www.upcdatabase.com/item/</a>{UPC}, but this is also incomplete - at least it's growing..</p>\n\n<p>The library of congress database is also incomplete with UPCs so far (although it's pretty comprehensive), and is harder to get automated.</p>\n\n<p>Currently, it seems like you'd have to write this yourself in order to have a high-level lookup that returns simple information (and tries each service)</p>\n" }, { "answer_id": 107024, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>My librarian wife uses <a href=\"http://www.worldcat.org/\" rel=\"nofollow noreferrer\">http://www.worldcat.org/</a>, but they key off ISBN. If you can scan that, you're golden. Looking at a few books, it looks like the UPC is the same or related to the ISBN.</p>\n\n<p>Oh, <a href=\"http://www.eblong.com/zarf/bookscan/#convert\" rel=\"nofollow noreferrer\">these guys</a> have a function for doing the conversion from UPC to ISBN.</p>\n" }, { "answer_id": 107032, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 7, "selected": true, "text": "<p>There's a very straightforward web based solution over at ISBNDB.com that you may want to look at.</p>\n<p><strong>Edit:</strong> Updated API documentation link, now there's version 2 available as well</p>\n<p><a href=\"https://isbndb.com/isbn-database\" rel=\"noreferrer\">Link to prices and tiers here</a></p>\n<p>You can be up and running in just a few minutes (these examples are from API v1):</p>\n<ul>\n<li><p>register on the site and get a key to use the API</p>\n</li>\n<li><p>try a URL like:</p>\n<p><code>http://isbndb.com/api/books.xml?access_key=</code><em>{yourkey}</em><code>&amp;index1=isbn&amp;results=details&amp;value1=9780143038092</code></p>\n</li>\n</ul>\n<p>The results=details gets additional details including the card catalog number.</p>\n<p>As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers.</p>\n<p>Here's a sample response:</p>\n<pre><code>&lt;ISBNdb server_time=&quot;2008-09-21T00:08:57Z&quot;&gt;\n &lt;BookList total_results=&quot;1&quot; page_size=&quot;10&quot; page_number=&quot;1&quot; shown_results=&quot;1&quot;&gt;\n &lt;BookData book_id=&quot;the_joy_luck_club_a12&quot; isbn=&quot;0143038095&quot;&gt;\n &lt;Title&gt;The Joy Luck Club&lt;/Title&gt;\n &lt;TitleLong/&gt;\n &lt;AuthorsText&gt;Amy Tan, &lt;/AuthorsText&gt;\n &lt;PublisherText publisher_id=&quot;penguin_non_classics&quot;&gt;Penguin (Non-Classics)&lt;/PublisherText&gt;\n &lt;Details dewey_decimal=&quot;813.54&quot; physical_description_text=&quot;288 pages&quot; language=&quot;&quot; edition_info=&quot;Paperback; 2006-09-21&quot; dewey_decimal_normalized=&quot;813.54&quot; lcc_number=&quot;&quot; change_time=&quot;2006-12-11T06:26:55Z&quot; price_time=&quot;2008-09-20T23:51:33Z&quot;/&gt;\n &lt;/BookData&gt;\n &lt;/BookList&gt;\n&lt;/ISBNdb&gt;\n</code></pre>\n" }, { "answer_id": 107034, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 2, "selected": false, "text": "<p>Sounds like the sort of job one might get a small software company to do for you...</p>\n\n<p>More seriously, there are services that provide an interface to the ISBN catalog, www.literarymarketplace.com.</p>\n\n<p>On worldcat.com, you can <a href=\"http://www.worldcat.org/links/default.jsp#isbn\" rel=\"nofollow noreferrer\">create a URL using the ISBN</a> that will take you straight to a book detail page. That page isn't as very useful because it's still HTML scraping to get the data, but they have a link to download the book data in a couple \"standard\" formats.</p>\n\n<p>For example, their demo book: <a href=\"http://www.worldcat.org/isbn/9780060817084\" rel=\"nofollow noreferrer\">http://www.worldcat.org/isbn/9780060817084</a>\nHas a \"EndNote\" format download link <a href=\"http://www.worldcat.org/oclc/123348009?page=endnote&amp;client=worldcat.org-detailed_record\" rel=\"nofollow noreferrer\">http://www.worldcat.org/oclc/123348009?page=endnote&amp;client=worldcat.org-detailed_record</a>, and you can harvest the data from that file very easily. That's linked from their own OCLC number, not the ISBN, but the scrape to convert that isn't hard, and they may yet have a good interface to do it.</p>\n" }, { "answer_id": 107037, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 1, "selected": false, "text": "<p>Using the web site <a href=\"http://www.librarything.com\" rel=\"nofollow noreferrer\">Library Thing</a>, you can scan in your barcodes (the entire barcode, not just the ISBN - if you have a scanning \"wedge\" you're in luck) and build your library. (It is an excellent social network - think StackOverflow for book enthusiasts.)</p>\n\n<p>Then, using the TOOLS section, you can export your library. Now you have a text file to import/parse and can create your labels, a card catalog, etc.</p>\n" }, { "answer_id": 107105, "author": "JohnMeyers", "author_id": 18923, "author_profile": "https://Stackoverflow.com/users/18923", "pm_score": 1, "selected": false, "text": "<p>I'm afraid the problem is database access. Companies pay to have a UPC assigned and so the database isn't freely accessible. The <a href=\"http://www.upcdatabase.com/\" rel=\"nofollow noreferrer\">UPCdatabase</a> site mentioned by Philip is a start, as is <a href=\"http://upcdata.info/\" rel=\"nofollow noreferrer\">UPCData.info</a>, but they're user entered--which means incomplete and possibly inaccurate.</p>\n\n<p>You can always enter in the UPC to Google and get a hit, but that's not very automated. But it does get it right most of the time.</p>\n\n<p>I thought I remembered Jon Udell doing something like this (e.g., <a href=\"http://weblog.infoworld.com/udell/LibraryLookup\" rel=\"nofollow noreferrer\">see this</a>), but it was purely ISBN based.</p>\n\n<p>Looks like you've found a new project for someone to work on!</p>\n" }, { "answer_id": 169778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Note: I'm the LibraryThing guy, so this is partial self-promotion.</p>\n\n<p>Take a look at <a href=\"https://stackoverflow.com/questions/41469/how-to-fetch-a-book-title-from-an-isbn-number\">this StackOverflow answer</a>, which covers some good ways to get data for a given ISBN.</p>\n\n<p>To your issues, Amazon includes a simple DDC (Dewey); Google does not. The WorldCat API does, but you need to be an OCLC library to use it. </p>\n\n<p>The ISBN/UPC issue is complex. Prefer the ISBN, if you can find them. Mass market paperbacks sometimes sport UPCs on the outside and an ISBN on inside. </p>\n\n<p>LibraryThing members have developed a few pages on the issue and on efforts to map the two:</p>\n\n<ul>\n<li><a href=\"http://www.librarything.com/wiki/index.php/UPC\" rel=\"nofollow noreferrer\">http://www.librarything.com/wiki/index.php/UPC</a></li>\n<li><a href=\"http://www.librarything.com/wiki/index.php/CueCat:_ISBNs_and_Barcodes\" rel=\"nofollow noreferrer\">http://www.librarything.com/wiki/index.php/CueCat:_ISBNs_and_Barcodes</a></li>\n</ul>\n\n<p>If you buy from Borders your book's barcodes will all be stickered over with their own internal barcodes (called a \"BINC\"). Most annoyingly whatever glue they use gets harder and harder to remove cleanly over time. I know of no API that converts them. LibraryThing does it by screenscraping.</p>\n\n<p>For an API, I'd go with Amazon. LibraryThing is a good non-API option, resolving BINCs and adding DDC and LCC for books that don't have them by looking at other editions of the \"work.\" </p>\n\n<p>What's missing is the label part. Someone needs to create a good PDF template for that.</p>\n" }, { "answer_id": 486182, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "<p>If you're wanting to use Amazon you can implement it easily with <a href=\"http://weblogs.asp.net/fmarguerie/archive/2006/06/26/introducing-linq-to-amazon.aspx\" rel=\"nofollow noreferrer\">LINQ to Amazon</a>.</p>\n" }, { "answer_id": 2546701, "author": "Matt B", "author_id": 274236, "author_profile": "https://Stackoverflow.com/users/274236", "pm_score": 0, "selected": false, "text": "<p>Working in the library world we simply connect to the LMS pass in the barcode and hey presto back comes the data. I believe there are a number of free LMS providers - Google for \"open source lms\".</p>\n\n<p>Note: This probably works off ISBN...</p>\n" }, { "answer_id": 3020188, "author": "cheekygeek", "author_id": 364202, "author_profile": "https://Stackoverflow.com/users/364202", "pm_score": 0, "selected": false, "text": "<p>You can find a PHP implemented ISBN lookup tool at <a href=\"http://www.dawsoninteractive.com/articles/article/php-isbn-lookup-tool\" rel=\"nofollow noreferrer\">Dawson Interactive</a>.</p>\n" }, { "answer_id": 43575900, "author": "mosca1337", "author_id": 413600, "author_profile": "https://Stackoverflow.com/users/413600", "pm_score": 0, "selected": false, "text": "<p>I frequently recommend using <strong>Amazon's Product Affiliate API</strong> (check it out here <a href=\"https://affiliate-program.amazon.com\" rel=\"nofollow noreferrer\">https://affiliate-program.amazon.com</a>), however there are a few other options available as well.</p>\n\n<p>If you want to guarantee the accuracy of the data, you can go with the a paid solution. GS1 is the organization that issues UPC codes, so their information should always be accurate (<a href=\"https://www.gs1us.org/tools/gs1-company-database-gepir\" rel=\"nofollow noreferrer\">https://www.gs1us.org/tools/gs1-company-database-gepir</a>).</p>\n\n<p>There are also a number of third party databases with relevant information such as <a href=\"https://www.upccodesearch.com/\" rel=\"nofollow noreferrer\">https://www.upccodesearch.com/</a> or <a href=\"https://www.upcdatabase.com/\" rel=\"nofollow noreferrer\">https://www.upcdatabase.com/</a> .</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/106963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4/" ]
I'm building the world's simplest library application. All I want to be able to do is scan in a book's UPC (barcode) using a typical scanner (which just types the numbers of the barcode into a field) and then use it to look up data about the book... at a minimum, title, author, year published, and either the Dewey Decimal or Library of Congress catalog number. The goal is to print out a tiny sticker ("spine label") with the card catalog number that I can stick on the spine of the book, and then I can sort the books by card catalog number on the shelves in our company library. That way books on similar subjects will tend to be near each other, for example, if you know you're looking for a book about accounting, all you have to do is find SOME book about accounting and you'll see the other half dozen that we have right next to it which makes it convenient to browse the library. There seem to be lots of web APIs to do this, including Amazon and the Library of Congress. But those are all extremely confusing to me. What I really just want is a single higher level function that takes a UPC barcode number and returns some basic data about the book.
There's a very straightforward web based solution over at ISBNDB.com that you may want to look at. **Edit:** Updated API documentation link, now there's version 2 available as well [Link to prices and tiers here](https://isbndb.com/isbn-database) You can be up and running in just a few minutes (these examples are from API v1): * register on the site and get a key to use the API * try a URL like: `http://isbndb.com/api/books.xml?access_key=`*{yourkey}*`&index1=isbn&results=details&value1=9780143038092` The results=details gets additional details including the card catalog number. As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers. Here's a sample response: ``` <ISBNdb server_time="2008-09-21T00:08:57Z"> <BookList total_results="1" page_size="10" page_number="1" shown_results="1"> <BookData book_id="the_joy_luck_club_a12" isbn="0143038095"> <Title>The Joy Luck Club</Title> <TitleLong/> <AuthorsText>Amy Tan, </AuthorsText> <PublisherText publisher_id="penguin_non_classics">Penguin (Non-Classics)</PublisherText> <Details dewey_decimal="813.54" physical_description_text="288 pages" language="" edition_info="Paperback; 2006-09-21" dewey_decimal_normalized="813.54" lcc_number="" change_time="2006-12-11T06:26:55Z" price_time="2008-09-20T23:51:33Z"/> </BookData> </BookList> </ISBNdb> ```
106,965
<p>Is there a way to read a locked file across a network given that you are the machine admin on the remote machine? I haven't been able to read the locked file locally, and attempting it over the network adds another layer of difficulty.</p>
[ { "answer_id": 106987, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 3, "selected": false, "text": "<p><strong>Edit</strong> It would be pretty easy if you had ISBN. but converting from UPC to ISBN is not as easy as you'd like.</p>\n\n<p>Here's some javascript code for it from <a href=\"http://isbn.nu\" rel=\"noreferrer\">http://isbn.nu</a> where it's done in script</p>\n\n<pre><code>if (indexisbn.indexOf(\"978\") == 0) {\n isbn = isbn.substr(3,9);\n var xsum = 0;\n var add = 0;\n var i = 0;\n for (i = 0; i &lt; 9; i++) {\n add = isbn.substr(i,1);\n xsum += (10 - i) * add;\n }\n xsum %= 11;\n xsum = 11 - xsum;\n if (xsum == 10) { xsum = \"X\"; }\n if (xsum == 11) { xsum = \"0\"; }\n isbn += xsum;\n}\n</code></pre>\n\n<p>However, that only converts from UPC to ISBN <em>some</em> of the time.</p>\n\n<p>You may want to look at the <a href=\"http://www.eblong.com/zarf/bookscan/\" rel=\"noreferrer\">barcode scanning project page</a>, too - one person's journey to scan books.</p>\n\n<p>So you know about <a href=\"http://www.amazon.com/AWS-home-page-Money/b?ie=UTF8&amp;node=3435361\" rel=\"noreferrer\">Amazon Web Services</a>. But that assumes amazon has the book and has scanned in the UPC.</p>\n\n<p>You can also try the <a href=\"http://www.upcdatabase.com/\" rel=\"noreferrer\">UPCdatabase</a> at <a href=\"http://www.upcdatabase.com/item/\" rel=\"noreferrer\">http://www.upcdatabase.com/item/</a>{UPC}, but this is also incomplete - at least it's growing..</p>\n\n<p>The library of congress database is also incomplete with UPCs so far (although it's pretty comprehensive), and is harder to get automated.</p>\n\n<p>Currently, it seems like you'd have to write this yourself in order to have a high-level lookup that returns simple information (and tries each service)</p>\n" }, { "answer_id": 107024, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>My librarian wife uses <a href=\"http://www.worldcat.org/\" rel=\"nofollow noreferrer\">http://www.worldcat.org/</a>, but they key off ISBN. If you can scan that, you're golden. Looking at a few books, it looks like the UPC is the same or related to the ISBN.</p>\n\n<p>Oh, <a href=\"http://www.eblong.com/zarf/bookscan/#convert\" rel=\"nofollow noreferrer\">these guys</a> have a function for doing the conversion from UPC to ISBN.</p>\n" }, { "answer_id": 107032, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 7, "selected": true, "text": "<p>There's a very straightforward web based solution over at ISBNDB.com that you may want to look at.</p>\n<p><strong>Edit:</strong> Updated API documentation link, now there's version 2 available as well</p>\n<p><a href=\"https://isbndb.com/isbn-database\" rel=\"noreferrer\">Link to prices and tiers here</a></p>\n<p>You can be up and running in just a few minutes (these examples are from API v1):</p>\n<ul>\n<li><p>register on the site and get a key to use the API</p>\n</li>\n<li><p>try a URL like:</p>\n<p><code>http://isbndb.com/api/books.xml?access_key=</code><em>{yourkey}</em><code>&amp;index1=isbn&amp;results=details&amp;value1=9780143038092</code></p>\n</li>\n</ul>\n<p>The results=details gets additional details including the card catalog number.</p>\n<p>As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers.</p>\n<p>Here's a sample response:</p>\n<pre><code>&lt;ISBNdb server_time=&quot;2008-09-21T00:08:57Z&quot;&gt;\n &lt;BookList total_results=&quot;1&quot; page_size=&quot;10&quot; page_number=&quot;1&quot; shown_results=&quot;1&quot;&gt;\n &lt;BookData book_id=&quot;the_joy_luck_club_a12&quot; isbn=&quot;0143038095&quot;&gt;\n &lt;Title&gt;The Joy Luck Club&lt;/Title&gt;\n &lt;TitleLong/&gt;\n &lt;AuthorsText&gt;Amy Tan, &lt;/AuthorsText&gt;\n &lt;PublisherText publisher_id=&quot;penguin_non_classics&quot;&gt;Penguin (Non-Classics)&lt;/PublisherText&gt;\n &lt;Details dewey_decimal=&quot;813.54&quot; physical_description_text=&quot;288 pages&quot; language=&quot;&quot; edition_info=&quot;Paperback; 2006-09-21&quot; dewey_decimal_normalized=&quot;813.54&quot; lcc_number=&quot;&quot; change_time=&quot;2006-12-11T06:26:55Z&quot; price_time=&quot;2008-09-20T23:51:33Z&quot;/&gt;\n &lt;/BookData&gt;\n &lt;/BookList&gt;\n&lt;/ISBNdb&gt;\n</code></pre>\n" }, { "answer_id": 107034, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 2, "selected": false, "text": "<p>Sounds like the sort of job one might get a small software company to do for you...</p>\n\n<p>More seriously, there are services that provide an interface to the ISBN catalog, www.literarymarketplace.com.</p>\n\n<p>On worldcat.com, you can <a href=\"http://www.worldcat.org/links/default.jsp#isbn\" rel=\"nofollow noreferrer\">create a URL using the ISBN</a> that will take you straight to a book detail page. That page isn't as very useful because it's still HTML scraping to get the data, but they have a link to download the book data in a couple \"standard\" formats.</p>\n\n<p>For example, their demo book: <a href=\"http://www.worldcat.org/isbn/9780060817084\" rel=\"nofollow noreferrer\">http://www.worldcat.org/isbn/9780060817084</a>\nHas a \"EndNote\" format download link <a href=\"http://www.worldcat.org/oclc/123348009?page=endnote&amp;client=worldcat.org-detailed_record\" rel=\"nofollow noreferrer\">http://www.worldcat.org/oclc/123348009?page=endnote&amp;client=worldcat.org-detailed_record</a>, and you can harvest the data from that file very easily. That's linked from their own OCLC number, not the ISBN, but the scrape to convert that isn't hard, and they may yet have a good interface to do it.</p>\n" }, { "answer_id": 107037, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 1, "selected": false, "text": "<p>Using the web site <a href=\"http://www.librarything.com\" rel=\"nofollow noreferrer\">Library Thing</a>, you can scan in your barcodes (the entire barcode, not just the ISBN - if you have a scanning \"wedge\" you're in luck) and build your library. (It is an excellent social network - think StackOverflow for book enthusiasts.)</p>\n\n<p>Then, using the TOOLS section, you can export your library. Now you have a text file to import/parse and can create your labels, a card catalog, etc.</p>\n" }, { "answer_id": 107105, "author": "JohnMeyers", "author_id": 18923, "author_profile": "https://Stackoverflow.com/users/18923", "pm_score": 1, "selected": false, "text": "<p>I'm afraid the problem is database access. Companies pay to have a UPC assigned and so the database isn't freely accessible. The <a href=\"http://www.upcdatabase.com/\" rel=\"nofollow noreferrer\">UPCdatabase</a> site mentioned by Philip is a start, as is <a href=\"http://upcdata.info/\" rel=\"nofollow noreferrer\">UPCData.info</a>, but they're user entered--which means incomplete and possibly inaccurate.</p>\n\n<p>You can always enter in the UPC to Google and get a hit, but that's not very automated. But it does get it right most of the time.</p>\n\n<p>I thought I remembered Jon Udell doing something like this (e.g., <a href=\"http://weblog.infoworld.com/udell/LibraryLookup\" rel=\"nofollow noreferrer\">see this</a>), but it was purely ISBN based.</p>\n\n<p>Looks like you've found a new project for someone to work on!</p>\n" }, { "answer_id": 169778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Note: I'm the LibraryThing guy, so this is partial self-promotion.</p>\n\n<p>Take a look at <a href=\"https://stackoverflow.com/questions/41469/how-to-fetch-a-book-title-from-an-isbn-number\">this StackOverflow answer</a>, which covers some good ways to get data for a given ISBN.</p>\n\n<p>To your issues, Amazon includes a simple DDC (Dewey); Google does not. The WorldCat API does, but you need to be an OCLC library to use it. </p>\n\n<p>The ISBN/UPC issue is complex. Prefer the ISBN, if you can find them. Mass market paperbacks sometimes sport UPCs on the outside and an ISBN on inside. </p>\n\n<p>LibraryThing members have developed a few pages on the issue and on efforts to map the two:</p>\n\n<ul>\n<li><a href=\"http://www.librarything.com/wiki/index.php/UPC\" rel=\"nofollow noreferrer\">http://www.librarything.com/wiki/index.php/UPC</a></li>\n<li><a href=\"http://www.librarything.com/wiki/index.php/CueCat:_ISBNs_and_Barcodes\" rel=\"nofollow noreferrer\">http://www.librarything.com/wiki/index.php/CueCat:_ISBNs_and_Barcodes</a></li>\n</ul>\n\n<p>If you buy from Borders your book's barcodes will all be stickered over with their own internal barcodes (called a \"BINC\"). Most annoyingly whatever glue they use gets harder and harder to remove cleanly over time. I know of no API that converts them. LibraryThing does it by screenscraping.</p>\n\n<p>For an API, I'd go with Amazon. LibraryThing is a good non-API option, resolving BINCs and adding DDC and LCC for books that don't have them by looking at other editions of the \"work.\" </p>\n\n<p>What's missing is the label part. Someone needs to create a good PDF template for that.</p>\n" }, { "answer_id": 486182, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "<p>If you're wanting to use Amazon you can implement it easily with <a href=\"http://weblogs.asp.net/fmarguerie/archive/2006/06/26/introducing-linq-to-amazon.aspx\" rel=\"nofollow noreferrer\">LINQ to Amazon</a>.</p>\n" }, { "answer_id": 2546701, "author": "Matt B", "author_id": 274236, "author_profile": "https://Stackoverflow.com/users/274236", "pm_score": 0, "selected": false, "text": "<p>Working in the library world we simply connect to the LMS pass in the barcode and hey presto back comes the data. I believe there are a number of free LMS providers - Google for \"open source lms\".</p>\n\n<p>Note: This probably works off ISBN...</p>\n" }, { "answer_id": 3020188, "author": "cheekygeek", "author_id": 364202, "author_profile": "https://Stackoverflow.com/users/364202", "pm_score": 0, "selected": false, "text": "<p>You can find a PHP implemented ISBN lookup tool at <a href=\"http://www.dawsoninteractive.com/articles/article/php-isbn-lookup-tool\" rel=\"nofollow noreferrer\">Dawson Interactive</a>.</p>\n" }, { "answer_id": 43575900, "author": "mosca1337", "author_id": 413600, "author_profile": "https://Stackoverflow.com/users/413600", "pm_score": 0, "selected": false, "text": "<p>I frequently recommend using <strong>Amazon's Product Affiliate API</strong> (check it out here <a href=\"https://affiliate-program.amazon.com\" rel=\"nofollow noreferrer\">https://affiliate-program.amazon.com</a>), however there are a few other options available as well.</p>\n\n<p>If you want to guarantee the accuracy of the data, you can go with the a paid solution. GS1 is the organization that issues UPC codes, so their information should always be accurate (<a href=\"https://www.gs1us.org/tools/gs1-company-database-gepir\" rel=\"nofollow noreferrer\">https://www.gs1us.org/tools/gs1-company-database-gepir</a>).</p>\n\n<p>There are also a number of third party databases with relevant information such as <a href=\"https://www.upccodesearch.com/\" rel=\"nofollow noreferrer\">https://www.upccodesearch.com/</a> or <a href=\"https://www.upcdatabase.com/\" rel=\"nofollow noreferrer\">https://www.upcdatabase.com/</a> .</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/106965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2712/" ]
Is there a way to read a locked file across a network given that you are the machine admin on the remote machine? I haven't been able to read the locked file locally, and attempting it over the network adds another layer of difficulty.
There's a very straightforward web based solution over at ISBNDB.com that you may want to look at. **Edit:** Updated API documentation link, now there's version 2 available as well [Link to prices and tiers here](https://isbndb.com/isbn-database) You can be up and running in just a few minutes (these examples are from API v1): * register on the site and get a key to use the API * try a URL like: `http://isbndb.com/api/books.xml?access_key=`*{yourkey}*`&index1=isbn&results=details&value1=9780143038092` The results=details gets additional details including the card catalog number. As an aside, generally the barcode is the isbn in either isbn10 or isbn13. You just have to delete the last 5 numbers if you are using a scanner and you pick up 18 numbers. Here's a sample response: ``` <ISBNdb server_time="2008-09-21T00:08:57Z"> <BookList total_results="1" page_size="10" page_number="1" shown_results="1"> <BookData book_id="the_joy_luck_club_a12" isbn="0143038095"> <Title>The Joy Luck Club</Title> <TitleLong/> <AuthorsText>Amy Tan, </AuthorsText> <PublisherText publisher_id="penguin_non_classics">Penguin (Non-Classics)</PublisherText> <Details dewey_decimal="813.54" physical_description_text="288 pages" language="" edition_info="Paperback; 2006-09-21" dewey_decimal_normalized="813.54" lcc_number="" change_time="2006-12-11T06:26:55Z" price_time="2008-09-20T23:51:33Z"/> </BookData> </BookList> </ISBNdb> ```
106,979
<p>I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process?</p>
[ { "answer_id": 106982, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "<p>I use Monitor.Wait / Pulse on a Queue of work items.</p>\n" }, { "answer_id": 106994, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "<p>If the pieces of data are independant then treat the pieces of data as work items to be processed by a pool of threads. Use the thread pool and <code>QueueUserWorkItem</code> to post the data to the thread(s). You should get better scalability using a pool of symmetric threads and limiting the amount of synchronisation that has to occur between the producer and consumer(s).</p>\n\n<p>For example (from <a href=\"http://msdn.microsoft.com/en-us/library/4yd16hza.aspx\" rel=\"noreferrer\">MSDN</a>):</p>\n\n<pre><code> TaskInfo ti = new TaskInfo(\"This report displays the number {0}.\", 42);\n\n // Queue the task and data.\n if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) { \n Console.WriteLine(\"Main thread does some work, then sleeps.\");\n\n // If you comment out the Sleep, the main thread exits before\n // the ThreadPool task has a chance to run. ThreadPool uses \n // background threads, which do not keep the application \n // running. (This is a simple example of a race condition.)\n Thread.Sleep(1000);\n\n Console.WriteLine(\"Main thread exits.\");\n }\n else {\n Console.WriteLine(\"Unable to queue ThreadPool request.\"); \n }\n\n\n// The thread procedure performs the independent task, in this case\n// formatting and printing a very simple report.\n//\nstatic void ThreadProc(Object stateInfo) {\n TaskInfo ti = (TaskInfo) stateInfo;\n Console.WriteLine(ti.Boilerplate, ti.Value); \n}\n</code></pre>\n" }, { "answer_id": 107011, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 0, "selected": false, "text": "<p>Does the \"store in the DB\" thread always need to be running? It seems like perhaps the best option (if possible) would be to have the polling thread spin up another thread to do the save. Depending on the number of threads being created though, it could be that having the first polling thread use ThreadPool.QueueUserWorkItem() might be the more efficient route. </p>\n\n<p>For more efficiency, when saving to the database, I would use async I/O on the DB rather than the sync methods. </p>\n\n<p>Anytime you can get away from having to communicate directly between two threads, you should. Having to throw together some sync primitives, your code won't be as easy to debug and could introduce some very subtle race conditions that cause \"once in a million execution\" type bugs (which are far from fun to find/fix). </p>\n\n<p>If the second thread always needs to be executing, let us know why with some more information and we can come back with a more in-depth answer.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 107336, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 0, "selected": false, "text": "<p>I personally would have thread 1 raise events which thread 2 can respond to. The threads can be wired up to the appropriate events by the controlling process which initiates both the threads.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/106979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I have two threads, one needs to poll a bunch of separate static resources looking for updates. The other one needs to get the data and store it in the database. How can thread 1 tell thread 2 that there is something to process?
If the pieces of data are independant then treat the pieces of data as work items to be processed by a pool of threads. Use the thread pool and `QueueUserWorkItem` to post the data to the thread(s). You should get better scalability using a pool of symmetric threads and limiting the amount of synchronisation that has to occur between the producer and consumer(s). For example (from [MSDN](http://msdn.microsoft.com/en-us/library/4yd16hza.aspx)): ``` TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42); // Queue the task and data. if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) { Console.WriteLine("Main thread does some work, then sleeps."); // If you comment out the Sleep, the main thread exits before // the ThreadPool task has a chance to run. ThreadPool uses // background threads, which do not keep the application // running. (This is a simple example of a race condition.) Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } else { Console.WriteLine("Unable to queue ThreadPool request."); } // The thread procedure performs the independent task, in this case // formatting and printing a very simple report. // static void ThreadProc(Object stateInfo) { TaskInfo ti = (TaskInfo) stateInfo; Console.WriteLine(ti.Boilerplate, ti.Value); } ```
107,018
<p>There are a couple of different .NET XSLT functions that I see used in the out of the box SharePoint web parts (RSS Viewer and Data View web part).</p> <pre><code>&lt;xsl:stylesheet xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime" ...&gt; ... &lt;xsl:value-of select="rssaggwrt:MakeSafe($Html)"/&gt; &lt;a href="{ddwrt:EnsureAllowedProtocol(string(link))}"&gt;More...&lt;/a&gt; ... &lt;/xsl:stylesheet&gt; </code></pre> <p>Where can I find a reference that describes all of the extension functions that SharePoint provides?</p>
[ { "answer_id": 107021, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>Here is some documentation I found that describes the ddwrt (<a href=\"http://schemas.microsoft.com/WebParts/v2/DataView/runtime\" rel=\"nofollow noreferrer\">http://schemas.microsoft.com/WebParts/v2/DataView/runtime</a>) namespace.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa505323.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa505323.aspx</a></p>\n" }, { "answer_id": 108877, "author": "cascadianista", "author_id": 19717, "author_profile": "https://Stackoverflow.com/users/19717", "pm_score": 3, "selected": true, "text": "<p>I have been wanting more info on ddwrt as well. The most information I have been able to find is from Serge van den Oever that was later turned into the MSDN article referenced in the previous answer. </p>\n\n<p><a href=\"http://weblogs.asp.net/soever/archive/2005/01/03/345535.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/soever/archive/2005/01/03/345535.aspx</a></p>\n\n<p>As he noted in his blog post, this article contains some info that was censored in the MSDN article.</p>\n\n<p>Other than this article, there is very little written on the topic. It unfortunately appears that scouring existing generated code (such as the xsl in DataForm web parts) is the best technique to learn more at present.</p>\n" }, { "answer_id": 2419472, "author": "Alex Nolasco", "author_id": 65694, "author_profile": "https://Stackoverflow.com/users/65694", "pm_score": 1, "selected": false, "text": "<p>Good question +1</p>\n\n<p>See also</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd583143%28office.11%29.aspx\" rel=\"nofollow noreferrer\">SharePoint Data View Web Part Extension Functions in the ddwrt Namespace</a> \nby Serge van den Oever</p>\n" }, { "answer_id": 5568952, "author": "Rob Creamer", "author_id": 695148, "author_profile": "https://Stackoverflow.com/users/695148", "pm_score": 1, "selected": false, "text": "<p>Serge's article points to Microsoft.SharePoint, where you can find the Microsoft.SharePoint.WebPartPages namespace. In there, you can find the DdwRuntime and the BaseDdwRuntime. There, you can find all of the ddwrt functions. I used a decompiler to look this up.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
There are a couple of different .NET XSLT functions that I see used in the out of the box SharePoint web parts (RSS Viewer and Data View web part). ``` <xsl:stylesheet xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime" ...> ... <xsl:value-of select="rssaggwrt:MakeSafe($Html)"/> <a href="{ddwrt:EnsureAllowedProtocol(string(link))}">More...</a> ... </xsl:stylesheet> ``` Where can I find a reference that describes all of the extension functions that SharePoint provides?
I have been wanting more info on ddwrt as well. The most information I have been able to find is from Serge van den Oever that was later turned into the MSDN article referenced in the previous answer. <http://weblogs.asp.net/soever/archive/2005/01/03/345535.aspx> As he noted in his blog post, this article contains some info that was censored in the MSDN article. Other than this article, there is very little written on the topic. It unfortunately appears that scouring existing generated code (such as the xsl in DataForm web parts) is the best technique to learn more at present.
107,049
<p>We have a rather simple site (minimal JS) with plain html and CSS. It is a simple mobile interface for our main application.</p> <p>We are running into trouble because we have more than one column and several browsers seem to force single columns.</p> <p>Through some searching I ran into 2 meta tags.</p> <pre><code>&lt;meta name="MobileOptimized" content="220" /&gt; &lt;meta name="viewport" content="width=320" /&gt; </code></pre> <p>With these we have a good 'scaled' view for IE Mobile and the iPhone. We have not run into any problems with palm's Blazer. But Blackberry is another matter.</p> <p>Does the Blackberry have a simple way to control the view of the browser as well? By simple I mean without making a special page for that device.</p>
[ { "answer_id": 107366, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>My recommendation would be to create two or three versions of the site:</p>\n\n<ul>\n<li>Full blown site for modern desktop browsers (if it's a very heavy application)</li>\n<li>Site with minimal JS and CSS for good mobile browsers and Desktop browsers (IPhone and SkyFire come to mind)</li>\n<li>Site with no JS, single column and mostly just plain text.</li>\n</ul>\n\n<p>The reason is that coding for 3-4 desktop browsers is hard enough. Don't kill yourself over another hundred devices to code for and create a simple page that just puts out information.</p>\n\n<p>Remember the basic design principle of web development: Users don't care. They want information, or functionality. It will look a whole lot better for you if you had a simple, clear layout for bad mobile browsers (IE or Blackberry) then try to hack up something that eventually becomes a maintainability nightmare and potentially make you look bad if somebody uses yet another mobile browser and you have not written the phone-specific site for yet.</p>\n" }, { "answer_id": 107663, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 3, "selected": true, "text": "<p>I wouldn't bother making a \"medium\" version for the iPhone etc, iPhone users can just look at your real web page easily enough. Have your full version and a single column version, and you'll reach the largest audience with minimal work.</p>\n\n<p>To answer your question though, there's no good way to make the Blackberry do anything other than 1 column views. You can get it to look fairly professional, as CSS and simple javascript still apply, but you'll have to lose a lot of your horizontal real estate.</p>\n" }, { "answer_id": 276231, "author": "staktrace", "author_id": 12050, "author_profile": "https://Stackoverflow.com/users/12050", "pm_score": 1, "selected": false, "text": "<p>BlackBerry (from OS 4.6 and higher) supports both the meta-viewport tag as well as the meta-HandheldFriendly tag. See the \"Content Design Guidelines\" document at <a href=\"http://na.blackberry.com/eng/support/docs/subcategories/?userType=21&amp;category=BlackBerry+Browser\" rel=\"nofollow noreferrer\">http://na.blackberry.com/eng/support/docs/subcategories/?userType=21&amp;category=BlackBerry+Browser</a> for details.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4923/" ]
We have a rather simple site (minimal JS) with plain html and CSS. It is a simple mobile interface for our main application. We are running into trouble because we have more than one column and several browsers seem to force single columns. Through some searching I ran into 2 meta tags. ``` <meta name="MobileOptimized" content="220" /> <meta name="viewport" content="width=320" /> ``` With these we have a good 'scaled' view for IE Mobile and the iPhone. We have not run into any problems with palm's Blazer. But Blackberry is another matter. Does the Blackberry have a simple way to control the view of the browser as well? By simple I mean without making a special page for that device.
I wouldn't bother making a "medium" version for the iPhone etc, iPhone users can just look at your real web page easily enough. Have your full version and a single column version, and you'll reach the largest audience with minimal work. To answer your question though, there's no good way to make the Blackberry do anything other than 1 column views. You can get it to look fairly professional, as CSS and simple javascript still apply, but you'll have to lose a lot of your horizontal real estate.
107,054
<p>I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph. </p> <p>For example, there is a huge difference in spacing between a "W" and an "I"</p> <p><img src="https://i.stack.imgur.com/2TsvYm.png" alt="&#39;I&#39; Outdent"><br> <img src="https://i.stack.imgur.com/DnZVSm.png" alt="&#39;W&#39; Outdent"></p> <p>Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.</p> <p><strong>PS</strong>: I don't necessarily need compatibility in IE or Opera</p>
[ { "answer_id": 107111, "author": "Matthew Rapati", "author_id": 15000, "author_profile": "https://Stackoverflow.com/users/15000", "pm_score": 0, "selected": false, "text": "<p>I tried using a fix-width font like 'courier new' and since the characters are more or less the same width it made it a lot less noticeable.</p>\n\n<p>Edit - this font is decent but might only work for windows</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p.outdent:first-letter {\n font-family: ms mincho;\n font-size: 8em;\n line-height: 1;\n font-weight: normal;\n float: left;\n margin: -0.1em 0 0 -.55em;\n letter-spacing: 0.05em;\n}\n</code></pre>\n" }, { "answer_id": 107149, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 4, "selected": true, "text": "<p>Apply this to <code>p.outdent:first-letter</code>:</p>\n\n<pre><code>margin-left: -800px;\npadding-right: 460px;\nfloat: right;\n</code></pre>\n\n<p>This will position the first letter on the right edge of the paragraph, then shove it left it by more or less the width of the paragraph, then move both the letter and all the padding into the float's large negative margin so the paragraph fits in the margin and doesn't try to wrap around.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph. For example, there is a huge difference in spacing between a "W" and an "I" !['I' Outdent](https://i.stack.imgur.com/2TsvYm.png) !['W' Outdent](https://i.stack.imgur.com/DnZVSm.png) Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be. **PS**: I don't necessarily need compatibility in IE or Opera
Apply this to `p.outdent:first-letter`: ``` margin-left: -800px; padding-right: 460px; float: right; ``` This will position the first letter on the right edge of the paragraph, then shove it left it by more or less the width of the paragraph, then move both the letter and all the padding into the float's large negative margin so the paragraph fits in the margin and doesn't try to wrap around.
107,117
<p>I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue&lt;T&gt;. Does anyone know why? Seems kind of weird.</p>
[ { "answer_id": 107133, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 0, "selected": false, "text": "<p>(I assume you mean Queue&lt;T&gt; for the second one.)</p>\n\n<p>I can't specifically answer the question, except that the IsSynchronized and SyncRoot properties (but not Synchronise() explicitly) are inherited from the ICollection interface. None of the generic collections use this and the ICollection&lt;T&gt; interface does not include SyncRoot.</p>\n\n<p>As to why it is not included, I can only speculate that they weren't being used either in the way intended by the library designers or they simply weren't being used enough to justify retaining them in the newer collections.</p>\n" }, { "answer_id": 107182, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 3, "selected": false, "text": "<p>You might find the Parallel CTP worth checking out; here's a blog entry from the guys who are putting it together that's pretty topical:</p>\n\n<p><a href=\"http://blogs.msdn.com/pfxteam/archive/2008/08/12/8852005.aspx\" rel=\"nofollow noreferrer\">Enumerating Concurrent Collections</a></p>\n\n<p>It's not quite the same thing, but it might solve your bigger problem. (They even use <code>Queue&lt;T&gt;</code> versus <code>ConcurrentQueue&lt;T&gt;</code> as their example.)</p>\n" }, { "answer_id": 107789, "author": "Matt Ryan", "author_id": 19548, "author_profile": "https://Stackoverflow.com/users/19548", "pm_score": 7, "selected": true, "text": "<p><strong>Update</strong> - in .NET 4, there now is <code>ConcurrentQueue&lt;T&gt;</code> in System.Collections.Concurrent, as documented here <a href=\"http://msdn.microsoft.com/en-us/library/dd267265.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd267265.aspx</a>. It's interesting to note that its IsSynchronized method (rightly) returns false.</p>\n\n<p><code>ConcurrentQueue&lt;T&gt;</code> is a complete ground up rewrite, creating copies of the queue to enumerate, and using advanced no-lock techniques like <code>Interlocked.CompareExchange()</code> and <code>Thread.SpinWait()</code>.</p>\n\n<p>The rest of this answer is still relevant insofar as it relates to the demise of the old Synchronize() and SyncRoot members, and why they didn't work very well from an API perspective.</p>\n\n<hr>\n\n<p>As per Zooba's comment, the BCL team decided that too many developers were misunderstanding the purpose of Synchronise (and to a lesser extent, SyncRoot)</p>\n\n<p>Brian Grunkemeyer described this on the BCL team blog a couple of years back:\n<a href=\"http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx</a></p>\n\n<p>The key issue is getting the correct granularity around locks, where some developers would naively use multiple properties or methods on a \"synchronized\" collection and believe their code to be thread safe. Brian uses Queue as his example, </p>\n\n<pre><code>if (queue.Count &gt; 0) {\n object obj = null;\n try {\n obj = queue.Dequeue();\n</code></pre>\n\n<p>Developers wouldn't realize that Count could be changed by another thread before Dequeue was invoked.</p>\n\n<p>Forcing developers to use an explicit lock statement around the whole operation means preventing this false sense of security.</p>\n\n<p>As Brian mentions, the removal of SyncRoot was partly because it had mainly been introduced to support Synchronized, but also because in many cases there is a better choice of lock object - most of the time, either the Queue instance itself, or a </p>\n\n<pre><code>private static object lockObjForQueueOperations = new object();\n</code></pre>\n\n<p>on the class owning the instance of the Queue... </p>\n\n<p>This latter approach is usually safest as it avoids some other common traps:</p>\n\n<ul>\n<li><a href=\"https://haacked.com/archive/2006/08/08/threadingneverlockthisredux.aspx/\" rel=\"nofollow noreferrer\">Never lock(this)</a></li>\n<li><a href=\"http://blogs.msdn.com/ricom/archive/2003/12/06/41779.aspx\" rel=\"nofollow noreferrer\">Don't lock(string) or lock(typeof(A))</a></li>\n</ul>\n\n<p>As they say, <a href=\"http://blogs.msdn.com/jmstall/archive/2008/01/30/why-threading-is-hard.aspx\" rel=\"nofollow noreferrer\">threading is hard</a>, and making it seem easy can be dangerous.</p>\n" }, { "answer_id": 5463018, "author": "Shane Castle", "author_id": 90340, "author_profile": "https://Stackoverflow.com/users/90340", "pm_score": 3, "selected": false, "text": "<p>There is one now, in .Net 4.0: </p>\n\n<pre><code>ConcurrentQueue&lt;T&gt; \n</code></pre>\n\n<p>in System.Collections.Concurrent</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd267265.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/dd267265.aspx</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue<T>. Does anyone know why? Seems kind of weird.
**Update** - in .NET 4, there now is `ConcurrentQueue<T>` in System.Collections.Concurrent, as documented here <http://msdn.microsoft.com/en-us/library/dd267265.aspx>. It's interesting to note that its IsSynchronized method (rightly) returns false. `ConcurrentQueue<T>` is a complete ground up rewrite, creating copies of the queue to enumerate, and using advanced no-lock techniques like `Interlocked.CompareExchange()` and `Thread.SpinWait()`. The rest of this answer is still relevant insofar as it relates to the demise of the old Synchronize() and SyncRoot members, and why they didn't work very well from an API perspective. --- As per Zooba's comment, the BCL team decided that too many developers were misunderstanding the purpose of Synchronise (and to a lesser extent, SyncRoot) Brian Grunkemeyer described this on the BCL team blog a couple of years back: <http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx> The key issue is getting the correct granularity around locks, where some developers would naively use multiple properties or methods on a "synchronized" collection and believe their code to be thread safe. Brian uses Queue as his example, ``` if (queue.Count > 0) { object obj = null; try { obj = queue.Dequeue(); ``` Developers wouldn't realize that Count could be changed by another thread before Dequeue was invoked. Forcing developers to use an explicit lock statement around the whole operation means preventing this false sense of security. As Brian mentions, the removal of SyncRoot was partly because it had mainly been introduced to support Synchronized, but also because in many cases there is a better choice of lock object - most of the time, either the Queue instance itself, or a ``` private static object lockObjForQueueOperations = new object(); ``` on the class owning the instance of the Queue... This latter approach is usually safest as it avoids some other common traps: * [Never lock(this)](https://haacked.com/archive/2006/08/08/threadingneverlockthisredux.aspx/) * [Don't lock(string) or lock(typeof(A))](http://blogs.msdn.com/ricom/archive/2003/12/06/41779.aspx) As they say, [threading is hard](http://blogs.msdn.com/jmstall/archive/2008/01/30/why-threading-is-hard.aspx), and making it seem easy can be dangerous.
107,132
<p>As a follow up to "<a href="https://stackoverflow.com/questions/105400/what-are-indexes-and-how-can-i-use-them-to-optimize-queries-in-my-database">What are indexes and how can I use them to optimise queries in my database?</a>" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database?</p> <p>After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns...</p>
[ { "answer_id": 107142, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 3, "selected": false, "text": "<p>In general (I don't use mssql so can't comment specifically), primary keys make good indexes. They are unique and must have a value specified. (Also, primary keys make such good indexes that they normally have an index created automatically.)</p>\n\n<p>An index is effectively a copy of the column which has been sorted to allow binary search (which is much faster than linear search). Database systems may use various tricks to speed up search even more, particularly if the data is more complex than a simple number.</p>\n\n<p>My suggestion would be to not use any indexes initially and profile your queries. If a particular query (such as searching for people by surname, for example) is run very often, try creating an index over the relevate attributes and profile again. If there is a noticeable speed-up on queries and a negligible slow-down on insertions and updates, keep the index.</p>\n\n<p>(Apologies if I'm repeating stuff mentioned in your other question, I hadn't come across it previously.)</p>\n" }, { "answer_id": 107145, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 2, "selected": false, "text": "<p>A GUID column is not the best candidate for indexing. Indexes are best suited to columns with a data type that can be given some meaningful order, ie sorted (integer, date etc).</p>\n\n<p>It does not matter if the data in a column is generally increasing. If you create an index on the column, the index will create it's own data structure that will simply reference the actual items in your table without concern for stored order (a non-clustered index). Then for example a binary search can be performed over your index data structure to provide fast retrieval. </p>\n\n<p>It is also possible to create a \"clustered index\" that will physically reorder your data. However you can only have one of these per table, whereas you can have multiple non-clustered indexes.</p>\n" }, { "answer_id": 107146, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 0, "selected": false, "text": "<p>It should be even faster if you are using a GUID. \nSuppose you have the records</p>\n\n<ol>\n<li>100</li>\n<li>200</li>\n<li>3000</li>\n<li>....</li>\n</ol>\n\n<p>If you have an index(binary search, you can find the physical location of the record you are looking for in O( lg n) time, instead of searching sequentially O(n) time. This is because you dont know what records you have in you table.</p>\n" }, { "answer_id": 107147, "author": "jwanagel", "author_id": 15118, "author_profile": "https://Stackoverflow.com/users/15118", "pm_score": 2, "selected": false, "text": "<p>It really depends on your queries. For example, if you almost only write to a table then it is best not to have any indexes, they just slow down the writes and never get used. Any column you are using to join with another table is a good candidate for an index.</p>\n\n<p>Also, read about the Missing Indexes feature. It monitors the actual queries being used against your database and can tell you what indexes would have improved the performace.</p>\n" }, { "answer_id": 107153, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 5, "selected": false, "text": "<p>Some folks answered a similar question here: <a href=\"https://stackoverflow.com/questions/79241/how-do-you-know-what-a-good-index-is\">How do you know what a good index is?</a></p>\n\n<p>Basically, it really depends on how you will be querying your data. You want an index that quickly identifies a small subset of your dataset that is relevant to a query. If you never query by datestamp, you don't need an index on it, even if it's mostly unique. If all you do is get events that happened in a certain date range, you definitely want one. In most cases, an index on gender is pointless -- but if all you do is get stats about all males, and separately, about all females, it might be worth your while to create one. Figure out what your query patterns will be, and access to which parameter narrows the search space the most, and that's your best index.</p>\n\n<p>Also consider the kind of index you make -- B-trees are good for most things and allow range queries, but hash indexes get you straight to the point (but don't allow ranges). Other types of indexes have other pros and cons.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 107159, "author": "curtisk", "author_id": 17651, "author_profile": "https://Stackoverflow.com/users/17651", "pm_score": 1, "selected": false, "text": "<p>The ol' rule of thumb was columns that are used a lot in WHERE, ORDER BY, and GROUP BY clauses, or any that seemed to be used in joins frequently. Keep in mind I'm referring to indexes, NOT Primary Key</p>\n\n<p>Not to give a 'vanilla-ish' answer, but it truly depends on how you are accessing the data</p>\n" }, { "answer_id": 107163, "author": "Joseph", "author_id": 19493, "author_profile": "https://Stackoverflow.com/users/19493", "pm_score": 0, "selected": false, "text": "<p>Best index depends on the contents of the table and what you are trying to accomplish. </p>\n\n<p>Taken an example A member database with a Primary Key of the Members Social Security Numnber. We choose the S.S. because the application priamry referes to the individual in this way but you also want to create a search function that will utilize the members first and last name. I would then suggest creating a index over those two fields. </p>\n\n<p>You should first find out what data you will be querying and then make the determination of which data you need indexed.</p>\n" }, { "answer_id": 107166, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 2, "selected": false, "text": "<p>Your primary key should always be an index. (I'd be surprised if it weren't automatically indexed by MS SQL, in fact.) You should also index columns you <code>SELECT</code> or <code>ORDER</code> by frequently; their purpose is both quick lookup of a single value and faster sorting.</p>\n\n<p>The only real danger in indexing <code>too</code> many columns is slowing down changes to rows in large tables, as the indexes all need updating too. If you're really not sure what to index, just time your slowest queries, look at what columns are being used most often, and index them. Then see how much faster they are.</p>\n" }, { "answer_id": 107167, "author": "Plasmer", "author_id": 397314, "author_profile": "https://Stackoverflow.com/users/397314", "pm_score": 4, "selected": false, "text": "<p>It all depends on what queries you expect to ask about the tables. If you ask for all rows with a certain value for column X, you will have to do a full table scan if an index can't be used.</p>\n\n<p>Indexes will be useful if:</p>\n\n<ul>\n<li>The column or columns have a high degree of uniqueness</li>\n<li>You frequently need to look for a certain value or range of values for\nthe column.</li>\n</ul>\n\n<p>They will not be useful if:</p>\n\n<ul>\n<li>You are selecting a large % (>10-20%) of the rows in the table</li>\n<li>The additional space usage is an issue</li>\n<li>You want to maximize insert performance. Every index on a table reduces insert and update performance because they must be updated each time the data changes.</li>\n</ul>\n\n<p>Primary key columns are typically great for indexing because they are unique and are often used to lookup rows.</p>\n" }, { "answer_id": 107172, "author": "pappes", "author_id": 19494, "author_profile": "https://Stackoverflow.com/users/19494", "pm_score": 3, "selected": false, "text": "<p>Any column that is going to be regularly used to extract data from the table should be indexed.</p>\n\n<p>This includes:\nforeign keys - </p>\n\n<pre><code>select * from tblOrder where status_id=:v_outstanding\n</code></pre>\n\n<p>descriptive fields - </p>\n\n<pre><code>select * from tblCust where Surname like \"O'Brian%\"\n</code></pre>\n\n<p>The columns do not need to be unique. In fact you can get really good performance from a binary index when searching for exceptions.</p>\n\n<pre><code>select * from tblOrder where paidYN='N'\n</code></pre>\n" }, { "answer_id": 107214, "author": "Ian Suttle", "author_id": 19421, "author_profile": "https://Stackoverflow.com/users/19421", "pm_score": 2, "selected": false, "text": "<p>Numeric data types which are ordered in ascending or descending order are good indexes for multiple reasons. First, numbers are generally faster to evaluate than strings (varchar, char, nvarchar, etc). Second, if your values aren't ordered, rows and/or pages may need to be shuffled about to update your index. That's additional overhead.</p>\n\n<p>If you're using SQL Server 2005 and set on using uniqueidentifiers (guids), and do NOT need them to be of a random nature, check out the sequential uniqueidentifier type.</p>\n\n<p>Lastly, if you're talking about clustered indexes, you're talking about the sort of the physical data. If you have a string as your clustered index, that could get ugly.</p>\n" }, { "answer_id": 8937872, "author": "Somnath Muluk", "author_id": 1045444, "author_profile": "https://Stackoverflow.com/users/1045444", "pm_score": 7, "selected": false, "text": "<p>Indexes can play an important role in query optimization and searching the results speedily from tables. The most important step is to select which columns are to be indexed. There are two major places where we can consider indexing: columns referenced in the WHERE clause and columns used in JOIN clauses. In short, such columns should be indexed against which you are required to search particular records. Suppose, we have a table named buyers where the SELECT query uses indexes like below:</p>\n<pre><code>SELECT\n buyer_id /* no need to index */\nFROM buyers\nWHERE first_name='Tariq' /* consider indexing */\nAND last_name='Iqbal' /* consider indexing */\n</code></pre>\n<p>Since &quot;buyer_id&quot; is referenced in the SELECT portion, MySQL will not use it to limit the chosen rows. Hence, there is no great need to index it. The below is another example little different from the above one:</p>\n<pre><code>SELECT\n buyers.buyer_id, /* no need to index */\n country.name /* no need to index */\nFROM buyers LEFT JOIN country\nON buyers.country_id=country.country_id /* consider indexing */\nWHERE\n first_name='Tariq' /* consider indexing */\nAND\n last_name='Iqbal' /* consider indexing */\n</code></pre>\n<p>According to the above queries first_name, last_name columns can be indexed as they are located in the WHERE clause. Also an additional field, country_id from country table, can be considered for indexing because it is in a JOIN clause. So indexing can be considered on every field in the WHERE clause or a JOIN clause.</p>\n<p>The following list also offers a few tips that you should always keep in mind when intend to create indexes into your tables:</p>\n<ul>\n<li>Only index those columns that are required in WHERE and ORDER BY clauses. Indexing columns in abundance will result in some disadvantages.</li>\n<li>Try to take benefit of &quot;index prefix&quot; or &quot;multi-columns index&quot; feature of MySQL. If you create an index such as INDEX(first_name, last_name), don’t create INDEX(first_name). However, &quot;index prefix&quot; or &quot;multi-columns index&quot; is not recommended in all search cases.</li>\n<li>Use the NOT NULL attribute for those columns in which you consider the indexing, so that NULL values will never be stored.</li>\n<li>Use the --log-long-format option to log queries that aren’t using indexes. In this way, you can examine this log file and adjust your queries accordingly.</li>\n<li>The EXPLAIN statement helps you to reveal that how MySQL will execute a query. It shows how and in what order tables are joined. This can be much useful for determining how to write optimized queries, and whether the columns are needed to be indexed.</li>\n</ul>\n<p><strong>Update (23 Feb'15):</strong></p>\n<p>Any index (good/bad) increases insert and update time.</p>\n<p>Depending on your indexes (number of indexes and type), result is searched. If your search time is gonna increase because of index then that's bad index.</p>\n<p>Likely in any book, &quot;Index Page&quot; could have chapter start page, topic page number starts, also sub topic page starts. Some clarification in Index page helps but more detailed index might confuse you or scare you. Indexes are also having memory.</p>\n<p>Index selection should be wise. Keep in mind not all columns would require index.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
As a follow up to "[What are indexes and how can I use them to optimise queries in my database?](https://stackoverflow.com/questions/105400/what-are-indexes-and-how-can-i-use-them-to-optimize-queries-in-my-database)" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database? After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto\_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns...
Indexes can play an important role in query optimization and searching the results speedily from tables. The most important step is to select which columns are to be indexed. There are two major places where we can consider indexing: columns referenced in the WHERE clause and columns used in JOIN clauses. In short, such columns should be indexed against which you are required to search particular records. Suppose, we have a table named buyers where the SELECT query uses indexes like below: ``` SELECT buyer_id /* no need to index */ FROM buyers WHERE first_name='Tariq' /* consider indexing */ AND last_name='Iqbal' /* consider indexing */ ``` Since "buyer\_id" is referenced in the SELECT portion, MySQL will not use it to limit the chosen rows. Hence, there is no great need to index it. The below is another example little different from the above one: ``` SELECT buyers.buyer_id, /* no need to index */ country.name /* no need to index */ FROM buyers LEFT JOIN country ON buyers.country_id=country.country_id /* consider indexing */ WHERE first_name='Tariq' /* consider indexing */ AND last_name='Iqbal' /* consider indexing */ ``` According to the above queries first\_name, last\_name columns can be indexed as they are located in the WHERE clause. Also an additional field, country\_id from country table, can be considered for indexing because it is in a JOIN clause. So indexing can be considered on every field in the WHERE clause or a JOIN clause. The following list also offers a few tips that you should always keep in mind when intend to create indexes into your tables: * Only index those columns that are required in WHERE and ORDER BY clauses. Indexing columns in abundance will result in some disadvantages. * Try to take benefit of "index prefix" or "multi-columns index" feature of MySQL. If you create an index such as INDEX(first\_name, last\_name), don’t create INDEX(first\_name). However, "index prefix" or "multi-columns index" is not recommended in all search cases. * Use the NOT NULL attribute for those columns in which you consider the indexing, so that NULL values will never be stored. * Use the --log-long-format option to log queries that aren’t using indexes. In this way, you can examine this log file and adjust your queries accordingly. * The EXPLAIN statement helps you to reveal that how MySQL will execute a query. It shows how and in what order tables are joined. This can be much useful for determining how to write optimized queries, and whether the columns are needed to be indexed. **Update (23 Feb'15):** Any index (good/bad) increases insert and update time. Depending on your indexes (number of indexes and type), result is searched. If your search time is gonna increase because of index then that's bad index. Likely in any book, "Index Page" could have chapter start page, topic page number starts, also sub topic page starts. Some clarification in Index page helps but more detailed index might confuse you or scare you. Indexes are also having memory. Index selection should be wise. Keep in mind not all columns would require index.
107,150
<p>How do I capture the event of the clicking the Selected Node of a TreeView? It doesn't fire the <strong>SelectedNodeChanged</strong> since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?</p> <p><strong>UPDATE</strong>: When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.</p> <p>I'll probably do this over the Christmas holidays and I'll report back with the results.</p> <p><strong>UPDATE</strong>: I have come up with a solution below that sub-classes the TreeView control.</p>
[ { "answer_id": 107298, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": false, "text": "<p>Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method.</p>\n\n<pre><code>protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){\n // Do whatever you're doing\n TreeView1.SelectedNode.Selected = false;\n}\n</code></pre>\n" }, { "answer_id": 107466, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can always use the MouseDown or MouseUp event and check to see if it the selected node.</p>\n" }, { "answer_id": 107509, "author": "Larry Smithmier", "author_id": 4911, "author_profile": "https://Stackoverflow.com/users/4911", "pm_score": 2, "selected": false, "text": "<p>Store what is selected and use code in the Page_Load event handler to compare what is selected to what you have stored. Page_Load is called for every post back even if the selected value doesn't change, unlike SelectedNodeChanged.</p>\n\n<p>Example</p>\n\n<p><a href=\"http://smithmier.com/TreeViewExample.png\" rel=\"nofollow noreferrer\" title=\"Screen snippit of example\">alt text http://smithmier.com/TreeViewExample.png</a></p>\n\n<p>html</p>\n\n<pre><code>&lt;form id=\"form1\" runat=\"server\"&gt;\n&lt;div&gt;\n &lt;asp:TreeView ID=\"TreeView1\" runat=\"server\" OnSelectedNodeChanged=\"TreeView1_SelectedNodeChanged\"\n ShowLines=\"True\"&gt;\n &lt;Nodes&gt;\n &lt;asp:TreeNode Text=\"Root\" Value=\"Root\"&gt;\n &lt;asp:TreeNode Text=\"RootSub1\" Value=\"RootSub1\"&gt;&lt;/asp:TreeNode&gt;\n &lt;asp:TreeNode Text=\"RootSub2\" Value=\"RootSub2\"&gt;&lt;/asp:TreeNode&gt;\n &lt;/asp:TreeNode&gt;\n &lt;asp:TreeNode Text=\"Root2\" Value=\"Root2\"&gt;\n &lt;asp:TreeNode Text=\"Root2Sub1\" Value=\"Root2Sub1\"&gt;\n &lt;asp:TreeNode Text=\"Root2Sub1Sub1\" Value=\"Root2Sub1Sub1\"&gt;&lt;/asp:TreeNode&gt;\n &lt;/asp:TreeNode&gt;\n &lt;asp:TreeNode Text=\"Root2Sub2\" Value=\"Root2Sub2\"&gt;&lt;/asp:TreeNode&gt;\n &lt;/asp:TreeNode&gt;\n &lt;/Nodes&gt;\n &lt;/asp:TreeView&gt;\n &lt;asp:Label ID=\"Label1\" runat=\"server\" Text=\"Selected\"&gt;&lt;/asp:Label&gt;\n &lt;asp:TextBox ID=\"TextBox1\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;asp:Label ID=\"Label2\" runat=\"server\" Text=\"Label\"&gt;&lt;/asp:Label&gt;&lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if(TreeView1.SelectedNode!=null &amp;&amp; this.TextBox1.Text == TreeView1.SelectedNode.Value.ToString())\n {\n Label2.Text = (int.Parse(Label2.Text) + 1).ToString();\n }\n else\n {\n Label2.Text = \"0\";\n }\n}\nprotected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)\n{\n this.TextBox1.Text = TreeView1.SelectedNode.Value.ToString();\n}\n</code></pre>\n" }, { "answer_id": 357247, "author": "Drell", "author_id": 41801, "author_profile": "https://Stackoverflow.com/users/41801", "pm_score": 1, "selected": false, "text": "<p>When you're adding nodes to the tree in the _TreeNodePopulate() event, set the .SelectionAction property on the node.</p>\n\n<pre><code>TreeNode newCNode;\nnewCNode = new TreeNode(\"New Node\");\n\nnewCNode.SelectAction = TreeNodeSelectAction.Select;\n\n//now you can set the .NavigateUrl property to call the same page with some query string parameter to catch in the page_load()\n\nnewCNode.NavigateUrl = \"~/ThisPage.aspx?args=\" + someNodeAction\n\nRootNode.ChildNodes.Add(newCNode);\n</code></pre>\n" }, { "answer_id": 384163, "author": "BlackMael", "author_id": 19377, "author_profile": "https://Stackoverflow.com/users/19377", "pm_score": 3, "selected": false, "text": "<p>After a somewhat lengthy period, I have finally had some time to look into how to subclass the TreeView to handle a Selected Node being clicked.</p>\n\n<p>Here is my solution which exposes a new event <strong>SelectedNodeClicked</strong> which you can handle from the Page or wherever.\n(<em>If needed it is a simple task to refactor into C#</em>)</p>\n\n<pre><code>Imports System.Web.UI\nImports System.Web\n\n\nPublic Class MyTreeView\n Inherits System.Web.UI.WebControls.TreeView\n\n Public Event SelectedNodeClicked As EventHandler\n\n Private Shared ReadOnly SelectedNodeClickEvent As Object\n\n Private Const CurrentValuePathState As String = \"CurrentValuePath\"\n\n Protected Property CurrentValuePath() As String\n Get\n Return Me.ViewState(CurrentValuePathState)\n End Get\n Set(ByVal value As String)\n Me.ViewState(CurrentValuePathState) = value\n End Set\n End Property\n\n Friend Sub RaiseSelectedNodeClicked()\n\n Me.OnSelectedNodeClicked(EventArgs.Empty)\n\n End Sub\n\n Protected Overridable Sub OnSelectedNodeClicked(ByVal e As EventArgs)\n\n RaiseEvent SelectedNodeClicked(Me, e)\n\n End Sub\n\n Protected Overrides Sub OnSelectedNodeChanged(ByVal e As System.EventArgs)\n\n MyBase.OnSelectedNodeChanged(e)\n\n ' Whenever the Selected Node changed, remember its ValuePath for future reference\n Me.CurrentValuePath = Me.SelectedNode.ValuePath\n\n End Sub\n\n Protected Overrides Sub RaisePostBackEvent(ByVal eventArgument As String)\n\n ' Check if the node that caused the event is the same as the previously selected node\n If Me.SelectedNode IsNot Nothing AndAlso Me.SelectedNode.ValuePath.Equals(Me.CurrentValuePath) Then\n Me.RaiseSelectedNodeClicked()\n End If\n\n MyBase.RaisePostBackEvent(eventArgument)\n\n End Sub\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 4324859, "author": "Evren", "author_id": 526612, "author_profile": "https://Stackoverflow.com/users/526612", "pm_score": 1, "selected": false, "text": "<pre><code>protected void Page_Load(object sender, EventArgs e) \n {\n if (!IsPostBack)\n {\n TreeView1.SelectedNode.Selected = false;\n }\n }\n</code></pre>\n\n<p>works for me </p>\n" }, { "answer_id": 12234199, "author": "Randa Hesham", "author_id": 1428242, "author_profile": "https://Stackoverflow.com/users/1428242", "pm_score": 1, "selected": false, "text": "<p>c#:</p>\n\n<pre><code>TreeNode node = TreeTypes.FindNode(obj.CustomerTypeId.ToString());\n\n\nTreeTypes.Nodes[TreeTypes.Nodes.IndexOf(node)].Select();\n</code></pre>\n" }, { "answer_id": 27902024, "author": "MOJTABA GIVI", "author_id": 2906181, "author_profile": "https://Stackoverflow.com/users/2906181", "pm_score": -1, "selected": false, "text": "<p>i have a problem look like but i solved it !</p>\n\n<p>in server side code :</p>\n\n<pre><code> protected void MainTreeView_SelectedNodeChanged(object sender, EventArgs e)\n {\n ClearTreeView();\n MainTreeView.SelectedNode.Text = \"&lt;span class='SelectedTreeNodeStyle'&gt;\" + MainTreeView.SelectedNode.Text + \"&lt;/span&gt;\";\n MainTreeView.SelectedNode.Selected = false;\n\n }\n\n public void ClearTreeView()\n {\n for (int i = 0; i &lt; MainTreeView.Nodes.Count; i++)\n {\n for(int j=0;j&lt; MainTreeView.Nodes[i].ChildNodes.Count;j++)\n {\n ClearNodeText(MainTreeView.Nodes[i].ChildNodes[j]);\n }\n ClearNodeText(MainTreeView.Nodes[i]);\n }\n }\n\n public void ClearNodeText(TreeNode tn)\n {\n tn.Text = tn.Text.Replace(\"&lt;span class='SelectedTreeNodeStyle'&gt;\", \"\").Replace(\"&lt;/span&gt;\", \"\");\n }\n</code></pre>\n\n<p>in client side code :</p>\n\n<pre><code> &lt;style type=\"text/css\"&gt;\n .SelectedTreeNodeStyle { font-weight: bold;}\n &lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 60446718, "author": "French Refilou", "author_id": 12977684, "author_profile": "https://Stackoverflow.com/users/12977684", "pm_score": 0, "selected": false, "text": "<p>I use the <code>ShowCheckBox</code> property and the Checked property to \"highlight\" the selected item. \nWhen the <code>SelectedNodeChanged</code> event raises:</p>\n\n<ol>\n<li>I set to false the <code>ShowCheckBox</code> property and the <code>Checked</code> property for the old selected one and I set to true the <code>ShowCheckBox</code> property and the <code>Checked</code> property for the new selected one.</li>\n<li>I use the selected node for any action</li>\n<li>Finally, I unselect the selected item: \n<code>myTreeView.SelecteNode.Selected = false</code></li>\n</ol>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19377/" ]
How do I capture the event of the clicking the Selected Node of a TreeView? It doesn't fire the **SelectedNodeChanged** since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked? **UPDATE**: When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked. I'll probably do this over the Christmas holidays and I'll report back with the results. **UPDATE**: I have come up with a solution below that sub-classes the TreeView control.
Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method. ``` protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){ // Do whatever you're doing TreeView1.SelectedNode.Selected = false; } ```
107,160
<p>I recently started work on a personal coding project using C++ and KDevelop. Although I started out by just hacking around, I figure it'll be better in the long run if I set up a proper unit test suite before going too much further. I've created a seperate test-runner executable as a sub project, and the tests I've added to it appear to function properly. So far, success.</p> <p>However, I'd really like to get my unit tests running every time I build, not only when I explicitly run them. This will be especially true as I split up the mess I've made into convenience libraries, each of which will probably have its own test executable. Rather than run them all by hand, I'd like to get them to run as the final step in my build process. I've looked all through the options in the project menu and the automake manager, but I can't figure out how to set this up.</p> <p>I imagine this could probably be done by editing the makefile by hand. Unfortunately, my makefile-fu is a bit weak, and I'm also afraid that KDevelop might overwrite any changes I make by hand the next time I change something through the IDE. Therefore, if there's an option on how to do this through KDevelop itself, I'd much prefer to go that way.</p> <p>Does anybody know how I could get KDevelop to run my test executables as part of the build process? Thank you!</p> <p>(I'm not 100% tied to KDevelop. If KDevelop can't do this, or else if there's an IDE that makes this much easier, I could be convinced to switch.)</p>
[ { "answer_id": 108086, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 3, "selected": true, "text": "<p>\nAlthough you <i>could</i> manipulate the default `make` target to run your tests,\nit is generally not recommended, because every invocation of\n</p>\n\n<pre>make</pre>\n\n<p>\nwould run all the tests.\nYou should use the \"check\" target instead,\nwhich is an accepted quasi-standard among software packages.\nBy doing that,\nthe tests are only started when you run\n</p>\n\n<pre>make check</pre>\n\n<p>\nYou can then easily configure KDevelop\nto run \"make check\" instead of just \"make\".\n</p>\n\n<p>\nSince you are using automake (through KDevelop),\nyou don't need to write the \"check\" target yourself.\nInstead, just edit your `Makefile.am` and set some variables:\n</p>\n\n<pre>\nTESTS = ...\n</pre>\n\n<p>Please have a look at the\n<a href=\"http://www.gnu.org/software/automake/manual/html_node/Tests.html#Tests\" rel=\"nofollow noreferrer\">automake documentation, \"Support for test suites\"</a>\nfor further information.</p>\n" }, { "answer_id": 8608452, "author": "Caruccio", "author_id": 561948, "author_profile": "https://Stackoverflow.com/users/561948", "pm_score": 0, "selected": false, "text": "<p>I got it working this way:</p>\n\n<pre><code>$ cat src/base64.c\n//code to be tested\nint encode64(...) { ... }\n\n#ifdef UNITTEST\n#include &lt;assert.h&gt;\nint main(int argc, char* argv[])\n{\n assert( encode64(...) == 0 );\n return 0;\n}\n#endif //UNITTEST\n/* end file.c */\n\n$ cat src/Makefile.am\n...\ncheck_PROGRAMS = base64-test\nbase64_test_SOURCES = base64.c\nbase64_test_CPPFLAGS = -I../include -DUNITTEST\nTESTS = base64-test\n</code></pre>\n\n<p>A <em>make check</em> would build src/base64-test and run it:</p>\n\n<pre><code>$ make check\n...\nPASS: base64-test\n==================\nAll 1 tests passed\n==================\n...\n</code></pre>\n\n<p>Now I'm trying to encapsulate it all as a m4 macro to be used like this:</p>\n\n<pre><code>MAKE_UNITTEST(base64.c)\n</code></pre>\n\n<p>which should produce something like the solution above.</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19491/" ]
I recently started work on a personal coding project using C++ and KDevelop. Although I started out by just hacking around, I figure it'll be better in the long run if I set up a proper unit test suite before going too much further. I've created a seperate test-runner executable as a sub project, and the tests I've added to it appear to function properly. So far, success. However, I'd really like to get my unit tests running every time I build, not only when I explicitly run them. This will be especially true as I split up the mess I've made into convenience libraries, each of which will probably have its own test executable. Rather than run them all by hand, I'd like to get them to run as the final step in my build process. I've looked all through the options in the project menu and the automake manager, but I can't figure out how to set this up. I imagine this could probably be done by editing the makefile by hand. Unfortunately, my makefile-fu is a bit weak, and I'm also afraid that KDevelop might overwrite any changes I make by hand the next time I change something through the IDE. Therefore, if there's an option on how to do this through KDevelop itself, I'd much prefer to go that way. Does anybody know how I could get KDevelop to run my test executables as part of the build process? Thank you! (I'm not 100% tied to KDevelop. If KDevelop can't do this, or else if there's an IDE that makes this much easier, I could be convinced to switch.)
Although you *could* manipulate the default `make` target to run your tests, it is generally not recommended, because every invocation of ``` make ``` would run all the tests. You should use the "check" target instead, which is an accepted quasi-standard among software packages. By doing that, the tests are only started when you run ``` make check ``` You can then easily configure KDevelop to run "make check" instead of just "make". Since you are using automake (through KDevelop), you don't need to write the "check" target yourself. Instead, just edit your `Makefile.am` and set some variables: ``` TESTS = ... ``` Please have a look at the [automake documentation, "Support for test suites"](http://www.gnu.org/software/automake/manual/html_node/Tests.html#Tests) for further information.
107,196
<p>When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. </p> <p>Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it? </p> <p>This is using Visual Studio 2005 / WinForms.</p> <p><strong>Update:</strong> Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it? </p> <p><strong>Update:</strong> After looking in Ildasm/diff, it seems like the following items are different:</p> <ul> <li>Two bytes in PE header at the start of the file.</li> <li>&lt;PrivateImplementationDetails&gt;{<em>guid</em>} section </li> <li>Cryptic part of the string table near the end (wonder why, I did not change the strings)</li> <li>Parts of assembly info at the end of file.</li> </ul> <p>No idea how to eliminate any of these, if at all possible...</p>
[ { "answer_id": 107202, "author": "Slapout", "author_id": 19072, "author_profile": "https://Stackoverflow.com/users/19072", "pm_score": -1, "selected": false, "text": "<p>Could be that the build or revision numbers have changed. </p>\n" }, { "answer_id": 107435, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 4, "selected": false, "text": "<p>I think that would be the TimeDateStamp field in the IMAGE_FILE_HEADER header of the <a href=\"http://msdn.microsoft.com/en-us/library/ms809762.aspx\" rel=\"noreferrer\">PE32 specifications</a>.</p>\n" }, { "answer_id": 107448, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 5, "selected": true, "text": "<p>My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time.</p>\n\n<p>Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all:</p>\n\n<ul>\n<li>Module.Mvid: A build-time-generated GUID. Always changes, every build.</li>\n<li>AssemblyRef.HashValue: Could change if you're referencing another assembly that has also been rebuilt since the old build.</li>\n</ul>\n\n<p>If this really, really bothers you, my best tip on finding out exactly what is changing would be to diff the actual metadata tables. The way to get these is to use the ildasm MetaInfo window:</p>\n\n<pre><code>View &gt; MetaInfo &gt; Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next step\n\nView &gt; MetaInfo &gt; Show!\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ]
When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it? This is using Visual Studio 2005 / WinForms. **Update:** Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it? **Update:** After looking in Ildasm/diff, it seems like the following items are different: * Two bytes in PE header at the start of the file. * <PrivateImplementationDetails>{*guid*} section * Cryptic part of the string table near the end (wonder why, I did not change the strings) * Parts of assembly info at the end of file. No idea how to eliminate any of these, if at all possible...
My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time. Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all: * Module.Mvid: A build-time-generated GUID. Always changes, every build. * AssemblyRef.HashValue: Could change if you're referencing another assembly that has also been rebuilt since the old build. If this really, really bothers you, my best tip on finding out exactly what is changing would be to diff the actual metadata tables. The way to get these is to use the ildasm MetaInfo window: ``` View > MetaInfo > Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next step View > MetaInfo > Show! ```
107,292
<p>We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN.</p> <p>In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. </p> <p>When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level.</p> <p>Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE?</p> <p>Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs?</p>
[ { "answer_id": 107308, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 0, "selected": false, "text": "<p>What we did with shared assemblies during development phase (in a project which had loads of these), is that we put them on a network share (N Drive) type of a place, and every developer referenced them from there.</p>\n\n<p>Our build process would always update this share with the latest versions. This way the actual assemblies never had to be kept in source control. Only the code.</p>\n" }, { "answer_id": 107525, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 4, "selected": true, "text": "<p>What we did at our company was to set up a <strong>tools</strong> repository, and then a <strong>project</strong> repository. The <strong>tools</strong> repository is a Subversion repository, organized as follows:</p>\n\n<pre><code>/svn/tools/\n vendor1/\n too11/\n 1.0/\n 1.1/\n latest = a copy of vendor1/tool1/1.1\n tool2/\n 1.0/\n 1.5/\n latest = a copy of vendor1/tool2/1.5\n vendor2/\n foo/\n 1.0.0/\n 1.1.0/\n 1.2.0/\n latest = a copy of vendor2/foo/1.2.0\n</code></pre>\n\n<p>Every time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated. </p>\n\n<p><strong>[Clarification:</strong> this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.<strong>]</strong></p>\n\n<p>One of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally.</p>\n\n<hr>\n\n<p>The <strong>projects</strong> repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like:</p>\n\n<pre><code>/svn/\n branches/\n tags/\n trunk/\n foo/\n source/\n tools/\n publish/\n foo-build.xml (for NAnt)\n foo.build (for MSBuild)\n</code></pre>\n\n<p>The tools directory has a Subversion <strong>svn:externals</strong> property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands:</p>\n\n<pre><code>svn import publish /svn/tools/vendor2/foo/1.2.3\nsvn delete /svn/tools/vendor2/foo/latest\nsvn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest\n</code></pre>\n\n<p>Developers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates.</p>\n\n<p>If you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet.</p>\n\n<blockquote>\n <p>Note: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit.</p>\n</blockquote>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6354/" ]
We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN. In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level. Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE? Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs?
What we did at our company was to set up a **tools** repository, and then a **project** repository. The **tools** repository is a Subversion repository, organized as follows: ``` /svn/tools/ vendor1/ too11/ 1.0/ 1.1/ latest = a copy of vendor1/tool1/1.1 tool2/ 1.0/ 1.5/ latest = a copy of vendor1/tool2/1.5 vendor2/ foo/ 1.0.0/ 1.1.0/ 1.2.0/ latest = a copy of vendor2/foo/1.2.0 ``` Every time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated. **[Clarification:** this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.**]** One of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally. --- The **projects** repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like: ``` /svn/ branches/ tags/ trunk/ foo/ source/ tools/ publish/ foo-build.xml (for NAnt) foo.build (for MSBuild) ``` The tools directory has a Subversion **svn:externals** property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands: ``` svn import publish /svn/tools/vendor2/foo/1.2.3 svn delete /svn/tools/vendor2/foo/latest svn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest ``` Developers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates. If you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet. > > Note: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit. > > >
107,294
<p>I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use <b>new</b> I am dynamically allocating memory.</p> <p>My question is the following:</p> <p>If i were to use <code>cout &lt;&lt; &amp;p</code>, it would display the "virtual memory location" of <code>p</code>. Is there a way in which I could manipulate this "virtual memory location?"</p> <p>For example, the following code shows an array of <code>int</code>s.</p> <p>If I wanted to show the value of <code>p[1]</code> and I knew the "virtual memory location" of <code>p</code>, could I somehow do "<code>&amp;p + 1</code>" and obtain the value of <code>p[1]</code> with <code>cout &lt;&lt; *p</code>, which will now point to the second element in the array?</p> <pre><code>int *p; p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; </code></pre>
[ { "answer_id": 107301, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 4, "selected": true, "text": "<p>Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.</p>\n\n<pre><code>int *p = new int[3];\np[0] = 13;\np[1] = 54;\np[2] = 42;\n\ncout &lt;&lt; *p &lt;&lt; ' ' &lt;&lt; *(p+1) &lt;&lt; ' ' &lt;&lt; *(p+2);\n</code></pre>\n\n<p>Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. <em>int</em> on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.</p>\n" }, { "answer_id": 107313, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 2, "selected": false, "text": "<p>Not quite. <code>&amp;p</code> is the address <em>of the pointer <code>p</code></em>. <code>&amp;p+1</code> will refer to an address which is one <code>int*</code> further along. What you want to do is </p>\n\n<pre><code>p=p+1; /* or ++p or p++ */\n</code></pre>\n\n<p>Now when you do </p>\n\n<pre><code>cout &lt;&lt; *p;\n</code></pre>\n\n<p>You will get 54. The difference is, <code>p</code> contains the <em>address of the start of the array of ints</em>, while <code>&amp;p</code> is the <em>address of p</em>. To move one item along, you need to point further into the <em>int array</em>, not further along your stack, which is where <code>p</code> lives.</p>\n\n<p>If you only had <code>&amp;p</code> then you would need to do the following:</p>\n\n<pre><code>int **q = &amp;p; /* q now points to p */\n*q = *q+1;\ncout &lt;&lt; *p;\n</code></pre>\n\n<p>That will also output 54 if I am not mistaken.</p>\n" }, { "answer_id": 107316, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 2, "selected": false, "text": "<p>It's been a while (many years) since I worked with pointers but I know that if p is pointing at the beginning of the array (i.e. p[0]) and you incremented it (i.e. p++) then p will now be pointing at p[1].</p>\n\n<p>I think that you have to de-reference p to get to the value. You dereference a pointer by putting a * in front of it.</p>\n\n<p>So *p = 33 with change p[0] to 33.</p>\n\n<p>I'm guessing that to get the second element you would use *(p+1) so the syntax you'd need would be:</p>\n\n<pre><code>cout &lt;&lt; *(p+1)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cout &lt;&lt; *(++p)\n</code></pre>\n" }, { "answer_id": 107351, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I like to do this:</p>\n\n<pre><code>&amp;p[1]\n</code></pre>\n\n<p>To me it looks neater.</p>\n" }, { "answer_id": 107461, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 1, "selected": false, "text": "<p>Think of \"pointer types\" in C and C++ as laying down a very long, logical <strong>row of cells</strong> superimposed on the bytes in the memory space of the CPU, starting at byte 0. The width of each cell, in bytes, depends on the \"type\" of the pointer. Each pointer type lays downs a row with differing cell widths. A <code>\"int *\"</code> pointer lays down a row of 4-byte cells, since the storage width of an int is 4 bytes. A <code>\"double *\"</code> lays down a 8-byte per-cell row; a <code>\"struct foo *\"</code> pointer lays down a row with each cell the width of a single <code>\"struct foo\"</code>, whatever that is. The \"address\" of any \"thing\" is the byte offset, starting at 0, of the cell in the row holding the \"thing\".<br><br><strong>Pointer arithmetic is based on cells in the row, not bytes.</strong> \"<code>*(p+10)</code>\" is a reference to the 10th cell past \"p\", where the cell size is determined by the type of p. If the type of \"p\" is \"int\", the address of \"p+10\" is 40 bytes past p; if p is a pointer to a struct 1000 bytes long, \"p+10\" is 10,000 bytes past p. (Note that the compiler gets to choose an optimal size for a struct that may be larger than what you'd think; this is due to \"padding\" and \"alignment\". The 1000 byte struct discussed might actually take 1024 bytes per cell, for example, so \"p+10\" would actually be 10,240 bytes past p.)</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17162/" ]
I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use **new** I am dynamically allocating memory. My question is the following: If i were to use `cout << &p`, it would display the "virtual memory location" of `p`. Is there a way in which I could manipulate this "virtual memory location?" For example, the following code shows an array of `int`s. If I wanted to show the value of `p[1]` and I knew the "virtual memory location" of `p`, could I somehow do "`&p + 1`" and obtain the value of `p[1]` with `cout << *p`, which will now point to the second element in the array? ``` int *p; p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; ```
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself. ``` int *p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; cout << *p << ' ' << *(p+1) << ' ' << *(p+2); ``` Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. *int* on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.
107,314
<p>We've been using selenium with great success to handle high-level website testing (in addition to extensive python doctests at a module level). However now we're using extjs for a lot of pages and its proving difficult to incorporate Selenium tests for the complex components like grids. </p> <p>Has anyone had success writing automated tests for extjs-based web pages? Lots of googling finds people with similar problems, but few answers. Thanks!</p>
[ { "answer_id": 107369, "author": "Ryan Guest", "author_id": 1811, "author_profile": "https://Stackoverflow.com/users/1811", "pm_score": 2, "selected": false, "text": "<p>Can you provide more insight into the types of problems you're having with extjs testing?</p>\n\n<p>One Selenium extension I find useful is <a href=\"http://wiki.openqa.org/display/SEL/waitForCondition\" rel=\"nofollow noreferrer\">waitForCondition</a>. If your problem seems to be trouble with the Ajax events, you can use waitForCondition to wait for events to happen.</p>\n" }, { "answer_id": 185372, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 2, "selected": false, "text": "<p>I have been testing my ExtJs web application with selenium. One of the biggest problem was selecting an item in the grid in order to do something with it.</p>\n\n<p>For this, I wrote helper method (in SeleniumExtJsUtils class which is a collection of useful methods for easier interaction with ExtJs):</p>\n\n<pre><code>/**\n * Javascript needed to execute in order to select row in the grid\n * \n * @param gridId Grid id\n * @param rowIndex Index of the row to select\n * @return Javascript to select row\n */\npublic static String selectGridRow(String gridId, int rowIndex) {\n return \"Ext.getCmp('\" + gridId + \"').getSelectionModel().selectRow(\" + rowIndex + \", true)\";\n}\n</code></pre>\n\n<p>and when I needed to select a row, I'd just call:</p>\n\n<pre><code>selenium.runScript( SeleniumExtJsUtils.selectGridRow(\"&lt;myGridId&gt;\", 5) );\n</code></pre>\n\n<p>For this to work I need to set my id on the grid and not let ExtJs generate it's own.</p>\n" }, { "answer_id": 219506, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 8, "selected": true, "text": "<p>The biggest hurdle in testing ExtJS with Selenium is that ExtJS doesn't render standard HTML elements and the Selenium IDE will naively (and rightfully) generate commands targeted at elements that just act as decor -- superfluous elements that help ExtJS with the whole desktop-look-and-feel. Here are a few tips and tricks that I've gathered while writing automated Selenium test against an ExtJS app.</p>\n\n<h1>General Tips</h1>\n\n<h2>Locating Elements</h2>\n\n<p>When generating Selenium test cases by recording user actions with Selenium IDE on Firefox, Selenium will base the recorded actions on the ids of the HTML elements. However, for most clickable elements, ExtJS uses generated ids like \"ext-gen-345\" which are likely to change on a subsequent visit to the same page, even if no code changes have been made. After recording user actions for a test, there needs to be a manual effort to go through all such actions that depend on generated ids and to replace them. There are two types of replacements that can be made:</p>\n\n<h2>Replacing an Id Locator with a CSS or XPath Locator</h2>\n\n<p>CSS locators begin with \"css=\" and XPath locators begin with \"//\" (the \"xpath=\" prefix is optional). CSS locators are less verbose and are easier to read and should be preferred over XPath locators. However, there can be cases where XPath locators need to be used because a CSS locator simply can't cut it.</p>\n\n<h2>Executing JavaScript</h2>\n\n<p>Some elements require more than simple mouse/keyboard interactions due to the complex rendering carried out by ExtJS. For example, a Ext.form.CombBox is not really a <code>&lt;select&gt;</code> element but a text input with a detached drop-down list that's somewhere at the bottom of the document tree. In order to properly simulate a ComboBox selection, it's possible to first simulate a click on the drop-down arrow and then to click on the list that appears. However, locating these elements through CSS or XPath locators can be cumbersome. An alternative is to locate the ComoBox component itself and call methods on it to simulate the selection:</p>\n\n<pre><code>var combo = Ext.getCmp('genderComboBox'); // returns the ComboBox components\ncombo.setValue('female'); // set the value\ncombo.fireEvent('select'); // because setValue() doesn't trigger the event\n</code></pre>\n\n<p>In Selenium the <code>runScript</code> command can be used to perform the above operation in a more concise form:</p>\n\n<pre><code>with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); }\n</code></pre>\n\n<h2>Coping with AJAX and Slow Rendering</h2>\n\n<p>Selenium has \"*AndWait\" flavors for all commands for waiting for page loads when a user action results in page transitions or reloads. However, since AJAX fetches don't involve actual page loads, these commands can't be used for synchronization. The solution is to make use of visual clues like the presence/absence of an AJAX progress indicator or the appearance of rows in a grid, additional components, links etc. For example:</p>\n\n<pre><code>Command: waitForElementNotPresent\nTarget: css=div:contains('Loading...')\n</code></pre>\n\n<p>Sometimes an element will appear only after a certain amount of time, depending on how fast ExtJS renders components after a user action results in a view change. Instead of using arbitary delays with the <code>pause</code> command, the ideal method is to wait until the element of interest comes within our grasp. For example, to click on an item after waiting for it to appear:</p>\n\n<pre><code>Command: waitForElementPresent\nTarget: css=span:contains('Do the funky thing')\nCommand: click\nTarget: css=span:contains('Do the funky thing')\n</code></pre>\n\n<p>Relying on arbitrary pauses is not a good idea since timing differences that result from running the tests in different browsers or on different machines will make the test cases flaky.</p>\n\n<h2>Non-clickable Items</h2>\n\n<p>Some elements can't be triggered by the <code>click</code> command. It's because the event listener is actually on the container, watching for mouse events on its child elements, that eventually bubble up to the parent. The tab control is one example. To click on the a tab, you have to simulate a <code>mouseDown</code> event at the tab label:</p>\n\n<pre><code>Command: mouseDownAt\nTarget: css=.x-tab-strip-text:contains('Options')\nValue: 0,0\n</code></pre>\n\n<h2>Field Validation</h2>\n\n<p>Form fields (Ext.form.* components) that have associated regular expressions or vtypes for validation will trigger validation with a certain delay (see the <code>validationDelay</code> property which is set to 250ms by default), after the user enters text or immediately when the field loses focus -- or blurs (see the <code>validateOnDelay</code> property). In order to trigger field validation after issuing the type Selenium command to enter some text inside a field, you have to do either of the following:</p>\n\n<ul>\n<li><p><strong>Triggering Delayed Validation</strong></p>\n\n<p>ExtJS fires off the validation delay timer when the field receives keyup events. To trigger this timer, simply issue a dummy keyup event (it doesn't matter which key you use as ExtJS ignores it), followed by a short pause that is longer than the validationDelay:</p>\n\n<pre><code>Command: keyUp\nTarget: someTextArea\nValue: x\nCommand: pause\nTarget: 500\n</code></pre></li>\n<li><p><strong>Triggering Immediate Validation</strong></p>\n\n<p>You can inject a blur event into the field to trigger immediate validation:</p>\n\n<pre><code>Command: runScript\nTarget: someComponent.nameTextField.fireEvent(\"blur\")\n</code></pre></li>\n</ul>\n\n<h2>Checking for Validation Results</h2>\n\n<p>Following validation, you can check for the presence or absence of an error field:</p>\n\n<pre><code>Command: verifyElementNotPresent \nTarget: //*[@id=\"nameTextField\"]/../*[@class=\"x-form-invalid-msg\" and not(contains(@style, \"display: none\"))]\n\nCommand: verifyElementPresent \nTarget: //*[@id=\"nameTextField\"]/../*[@class=\"x-form-invalid-msg\" and not(contains(@style, \"display: none\"))]\n</code></pre>\n\n<p>Note that the \"display: none\" check is necessary because once an error field is shown and then it needs to be hidden, ExtJS will simply hide error field instead of entirely removing it from the DOM tree.</p>\n\n<h1>Element-specific Tips</h1>\n\n<h2>Clicking an Ext.form.Button</h2>\n\n<ul>\n<li><p><strong>Option 1</strong></p>\n\n<p>Command: click\n Target: css=button:contains('Save')</p>\n\n<p>Selects the button by its caption</p></li>\n<li><p><strong>Option 2</strong></p>\n\n<p>Command: click\n Target: css=#save-options button</p>\n\n<p>Selects the button by its id</p></li>\n</ul>\n\n<h2>Selecting a Value from an Ext.form.ComboBox</h2>\n\n<pre><code>Command: runScript\nTarget: with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); }\n</code></pre>\n\n<p>First sets the value and then explicitly fires the select event in case there are observers.</p>\n" }, { "answer_id": 441741, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Useful tips for fetch grid via Id of grid on the page:\nI think you can extend more useful function from this API.</p>\n\n<pre><code> sub get_grid_row {\n my ($browser, $grid, $row) = @_;\n\n\n my $script = \"var doc = this.browserbot.getCurrentWindow().document;\\n\" .\n \"var grid = doc.getElementById('$grid');\\n\" .\n \"var table = grid.getElementsByTagName('table');\\n\" .\n \"var result = '';\\n\" .\n \"var row = 0;\\n\" . \n \"for (var i = 0; i &lt; table.length; i++) {\\n\" .\n \" if (table[i].className == 'x-grid3-row-table') {\\n\".\n \" row++;\\n\" . \n \" if (row == $row) {\\n\" .\n \" var cols_len = table[i].rows[0].cells.length;\\n\" .\n \" for (var j = 0; j &lt; cols_len; j++) {\\n\" .\n \" var cell = table[i].rows[0].cells[j];\\n\" .\n \" if (result.length == 0) {\\n\" .\n \" result = getText(cell);\\n\" .\n \" } else { \\n\" .\n \" result += '|' + getText(cell);\\n\" .\n \" }\\n\" .\n \" }\\n\" .\n \" }\\n\" .\n \" }\\n\" .\n \"}\\n\" .\n \"result;\\n\";\n\n my $result = $browser-&gt;get_eval($script);\n my @res = split('\\|', $result);\n return @res;\n }\n</code></pre>\n" }, { "answer_id": 1471119, "author": "Master-Test", "author_id": 178398, "author_profile": "https://Stackoverflow.com/users/178398", "pm_score": 2, "selected": false, "text": "<p>To detect that element is visible you use the clause:\n<code>not(contains(@style, \"display: none\")</code></p>\n\n<p>It's better to use this:</p>\n\n<pre><code>visible_clause = \"not(ancestor::*[contains(@style,'display: none')\" +\n \" or contains(@style, 'visibility: hidden') \" + \n \" or contains(@class,'x-hide-display')])\"\n\nhidden_clause = \"parent::*[contains(@style,'display: none')\" + \n \" or contains(@style, 'visibility: hidden')\" + \n \" or contains(@class,'x-hide-display')]\"\n</code></pre>\n" }, { "answer_id": 2542989, "author": "Chun", "author_id": 292829, "author_profile": "https://Stackoverflow.com/users/292829", "pm_score": 1, "selected": false, "text": "<p>For complex UI that is not formal HTML, xPath is always something you can count on, but a little complex when it comes to different UI implementation using ExtJs.</p>\n\n<p>You can use Firebug and Firexpath as firefox extensions to test an certain element's xpath, and simple pass full xpath as parameter to selenium.</p>\n\n<p>For example in java code:</p>\n\n<pre><code>String fullXpath = \"xpath=//div[@id='mainDiv']//div[contains(@class,'x-grid-row')]//table/tbody/tr[1]/td[1]//button\"\n\nselenium.click(fullXpath);\n</code></pre>\n" }, { "answer_id": 19590566, "author": "Brian Wendt", "author_id": 2308628, "author_profile": "https://Stackoverflow.com/users/2308628", "pm_score": 2, "selected": false, "text": "<h2>Easier testing through custom HTML data- attributes</h2>\n\n<p>From the <a href=\"http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.AbstractComponent-cfg-itemId\" rel=\"nofollow\">Sencha documentation</a>:</p>\n\n<blockquote>\n <p>An itemId can be used as an alternative way to get a reference to a component when no object reference is available. Instead of using an id with Ext.getCmp, use itemId with Ext.container.Container.getComponent which will retrieve itemId's or id's. Since itemId's are an index to the container's internal MixedCollection, the itemId is scoped locally to the container -- avoiding potential conflicts with Ext.ComponentManager which requires a unique id.</p>\n</blockquote>\n\n<p>Overriding the <code>Ext.AbstractComponent</code>'s <code>onBoxReady</code> method, I set a custom data attribute (whose name comes from my custom <code>testIdAttr</code> property of each component) to the component's <code>itemId</code> value, if it exists. Add the <code>Testing.overrides.AbstractComponent</code> class to your <code>application.js</code> file's <code>requires</code> array. </p>\n\n<pre><code>/**\n * Overrides the Ext.AbstracComponent's onBoxReady\n * method to add custom data attributes to the\n * component's dom structure.\n *\n * @author Brian Wendt\n */\nExt.define('Testing.overrides.AbstractComponent', {\n override: 'Ext.AbstractComponent',\n\n\n onBoxReady: function () {\n var me = this,\n el = me.getEl();\n\n\n if (el &amp;&amp; el.dom &amp;&amp; me.itemId) {\n el.dom.setAttribute(me.testIdAttr || 'data-selenium-id', me.itemId);\n }\n\n\n me.callOverridden(arguments);\n }\n});\n</code></pre>\n\n<p>This method provides developers with a way to reuse a descriptive identifier within their code and to have those identifiers available each time the page is rendered. No more searching through non-descriptive, dynamically-generated ids.</p>\n" }, { "answer_id": 19802364, "author": "John V", "author_id": 2958562, "author_profile": "https://Stackoverflow.com/users/2958562", "pm_score": 2, "selected": false, "text": "<p>Ext JS web pages can be tricky to test, because of the complicated HTML they end up generating like with Ext JS grids. </p>\n\n<p><a href=\"http://html5robot.com\" rel=\"nofollow\">HTML5 Robot</a> deals with this by using a series of best practices for how to reliably lookup and interact with components based on attributes and conditions which are not dynamic. It then provides shortcuts for doing this with all of the HTML, Ext JS, and Sencha Touch components that you would need to interact with. It comes in 2 flavors:</p>\n\n<ol>\n<li><strong>Java</strong> - Familiar Selenium and JUnit based API that has built in web driver support for all modern browsers.</li>\n<li><strong>Gwen</strong> - A human style language for quickly and easily creating and maintaining browser tests, which comes with its own integrated development environment. All of which is based on the Java API.</li>\n</ol>\n\n<p>For example if you were wanting to find the Ext JS grid row containing the text \"Foo\", you could do the following in Java:</p>\n\n<pre><code>findExtJsGridRow(\"Foo\");\n</code></pre>\n\n<p>...and you could do the following in Gwen:</p>\n\n<pre><code>extjsgridrow by text \"Foo\"\n</code></pre>\n\n<p>There is a lot of documentation for both <a href=\"http://html5robot.com/java-api/locating-components/\" rel=\"nofollow\">Java</a> and Gwen for how to work with Ext JS specific components. The documentation also details the resulting HTML for all of these Ext JS components, which you also may find useful.</p>\n" }, { "answer_id": 21476518, "author": "JonnyRaa", "author_id": 962696, "author_profile": "https://Stackoverflow.com/users/962696", "pm_score": 3, "selected": false, "text": "<p>This <a href=\"http://developertips.blogspot.co.uk/search/label/WebDriver\">blog</a> helped me a lot. He's written quite a lot on the topic and it seems like its still active. The guy also seems to appreciate good design.</p>\n\n<p>He basically talks about using sending javascript to do queries and using the Ext.ComponentQuery.query method to retrieve stuff in the same way you do in your ext app internally. That way you can use xtypes and itemIds and dont have to worry about trying to parse any of the mad auto-generated stuff.</p>\n\n<p>I found <a href=\"http://developertips.blogspot.co.uk/2013/09/locate-extjs-component-selenium-web.html\">this article</a> in particular very helpful.</p>\n\n<p>Might post something a bit more detailed on here soon - still trying to get my head around how to do this properly</p>\n" }, { "answer_id": 24670268, "author": "olyv", "author_id": 2504101, "author_profile": "https://Stackoverflow.com/users/2504101", "pm_score": 1, "selected": false, "text": "<p>When I was testing ExtJS application using WebDriver I used next approach: I looked for field by label's text and got <code>@for</code> attribute from label. For example, we have a label </p>\n\n<pre><code>&lt;label id=\"dynamic_id_label\" class=\"TextboxLabel\" for=\"textField_which_I_am_lloking_for\"&gt;\nName Of Needed Label\n&lt;label/&gt;\n</code></pre>\n\n<p>And we need to point WebDriver some input: <code>//input[@id=(//label[contains(text(),'Name Of Needed Label')]/@for)]</code>.</p>\n\n<p>So, it will pick the id from <code>@for</code> attribute and use it further. This is probably the simplest case but it gives you the way to locate element. It is much harder when you have no label but then you need to find some element and write your xpath looking for siblings, descend/ascend elements.</p>\n" }, { "answer_id": 38885163, "author": "bertanasco", "author_id": 890222, "author_profile": "https://Stackoverflow.com/users/890222", "pm_score": 2, "selected": false, "text": "<p>We are developing a testing framework that uses selenium and encountered problems with extjs (since it's client side rendering). I find it useful to look for an element once the DOM is ready.</p>\n\n<pre><code>public static boolean waitUntilDOMIsReady(WebDriver driver) {\n def maxSeconds = DEFAULT_WAIT_SECONDS * 10\n for (count in 1..maxSeconds) {\n Thread.sleep(100)\n def ready = isDOMReady(driver);\n if (ready) {\n break;\n }\n }\n}\n\npublic static boolean isDOMReady(WebDriver driver){\n return driver.executeScript(\"return document.readyState\");\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19506/" ]
We've been using selenium with great success to handle high-level website testing (in addition to extensive python doctests at a module level). However now we're using extjs for a lot of pages and its proving difficult to incorporate Selenium tests for the complex components like grids. Has anyone had success writing automated tests for extjs-based web pages? Lots of googling finds people with similar problems, but few answers. Thanks!
The biggest hurdle in testing ExtJS with Selenium is that ExtJS doesn't render standard HTML elements and the Selenium IDE will naively (and rightfully) generate commands targeted at elements that just act as decor -- superfluous elements that help ExtJS with the whole desktop-look-and-feel. Here are a few tips and tricks that I've gathered while writing automated Selenium test against an ExtJS app. General Tips ============ Locating Elements ----------------- When generating Selenium test cases by recording user actions with Selenium IDE on Firefox, Selenium will base the recorded actions on the ids of the HTML elements. However, for most clickable elements, ExtJS uses generated ids like "ext-gen-345" which are likely to change on a subsequent visit to the same page, even if no code changes have been made. After recording user actions for a test, there needs to be a manual effort to go through all such actions that depend on generated ids and to replace them. There are two types of replacements that can be made: Replacing an Id Locator with a CSS or XPath Locator --------------------------------------------------- CSS locators begin with "css=" and XPath locators begin with "//" (the "xpath=" prefix is optional). CSS locators are less verbose and are easier to read and should be preferred over XPath locators. However, there can be cases where XPath locators need to be used because a CSS locator simply can't cut it. Executing JavaScript -------------------- Some elements require more than simple mouse/keyboard interactions due to the complex rendering carried out by ExtJS. For example, a Ext.form.CombBox is not really a `<select>` element but a text input with a detached drop-down list that's somewhere at the bottom of the document tree. In order to properly simulate a ComboBox selection, it's possible to first simulate a click on the drop-down arrow and then to click on the list that appears. However, locating these elements through CSS or XPath locators can be cumbersome. An alternative is to locate the ComoBox component itself and call methods on it to simulate the selection: ``` var combo = Ext.getCmp('genderComboBox'); // returns the ComboBox components combo.setValue('female'); // set the value combo.fireEvent('select'); // because setValue() doesn't trigger the event ``` In Selenium the `runScript` command can be used to perform the above operation in a more concise form: ``` with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); } ``` Coping with AJAX and Slow Rendering ----------------------------------- Selenium has "\*AndWait" flavors for all commands for waiting for page loads when a user action results in page transitions or reloads. However, since AJAX fetches don't involve actual page loads, these commands can't be used for synchronization. The solution is to make use of visual clues like the presence/absence of an AJAX progress indicator or the appearance of rows in a grid, additional components, links etc. For example: ``` Command: waitForElementNotPresent Target: css=div:contains('Loading...') ``` Sometimes an element will appear only after a certain amount of time, depending on how fast ExtJS renders components after a user action results in a view change. Instead of using arbitary delays with the `pause` command, the ideal method is to wait until the element of interest comes within our grasp. For example, to click on an item after waiting for it to appear: ``` Command: waitForElementPresent Target: css=span:contains('Do the funky thing') Command: click Target: css=span:contains('Do the funky thing') ``` Relying on arbitrary pauses is not a good idea since timing differences that result from running the tests in different browsers or on different machines will make the test cases flaky. Non-clickable Items ------------------- Some elements can't be triggered by the `click` command. It's because the event listener is actually on the container, watching for mouse events on its child elements, that eventually bubble up to the parent. The tab control is one example. To click on the a tab, you have to simulate a `mouseDown` event at the tab label: ``` Command: mouseDownAt Target: css=.x-tab-strip-text:contains('Options') Value: 0,0 ``` Field Validation ---------------- Form fields (Ext.form.\* components) that have associated regular expressions or vtypes for validation will trigger validation with a certain delay (see the `validationDelay` property which is set to 250ms by default), after the user enters text or immediately when the field loses focus -- or blurs (see the `validateOnDelay` property). In order to trigger field validation after issuing the type Selenium command to enter some text inside a field, you have to do either of the following: * **Triggering Delayed Validation** ExtJS fires off the validation delay timer when the field receives keyup events. To trigger this timer, simply issue a dummy keyup event (it doesn't matter which key you use as ExtJS ignores it), followed by a short pause that is longer than the validationDelay: ``` Command: keyUp Target: someTextArea Value: x Command: pause Target: 500 ``` * **Triggering Immediate Validation** You can inject a blur event into the field to trigger immediate validation: ``` Command: runScript Target: someComponent.nameTextField.fireEvent("blur") ``` Checking for Validation Results ------------------------------- Following validation, you can check for the presence or absence of an error field: ``` Command: verifyElementNotPresent Target: //*[@id="nameTextField"]/../*[@class="x-form-invalid-msg" and not(contains(@style, "display: none"))] Command: verifyElementPresent Target: //*[@id="nameTextField"]/../*[@class="x-form-invalid-msg" and not(contains(@style, "display: none"))] ``` Note that the "display: none" check is necessary because once an error field is shown and then it needs to be hidden, ExtJS will simply hide error field instead of entirely removing it from the DOM tree. Element-specific Tips ===================== Clicking an Ext.form.Button --------------------------- * **Option 1** Command: click Target: css=button:contains('Save') Selects the button by its caption * **Option 2** Command: click Target: css=#save-options button Selects the button by its id Selecting a Value from an Ext.form.ComboBox ------------------------------------------- ``` Command: runScript Target: with (Ext.getCmp('genderComboBox')) { setValue('female'); fireEvent('select'); } ``` First sets the value and then explicitly fires the select event in case there are observers.
107,382
<p>I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it? </p> <p>For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2.</p> <p>Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs. </p> <p>Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example:</p> <p>The tokenizer would produce the following tokens given the following input = "INP :x:"<br>:</p> <pre><code>Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL </code></pre> <p>These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E</p> <pre><code>if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");} </code></pre> <p>I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.</p>
[ { "answer_id": 107410, "author": "Max Galkin", "author_id": 2351099, "author_profile": "https://Stackoverflow.com/users/2351099", "pm_score": 1, "selected": false, "text": "<p>I guess such an index would only have meaning in some simple case, like in your example.</p>\n\n<p>If you'll take a regex like \"ab*c*z\" (where by * I mean any character) and a string \"abbbcbbcdd\", what should be the index, you are talking about?\nIt will depend on the algorithm used for mathcing...\nCould fail on \"abbbc...\" or on \"abbbcbbc...\"</p>\n" }, { "answer_id": 107528, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 0, "selected": false, "text": "<p>I don't believe it's possible, but I am intrigued why you would want it.</p>\n" }, { "answer_id": 107540, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": true, "text": "<p>I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little:</p>\n\n<ol>\n<li>Get the Regex class source code\n(e.g.\n<a href=\"http://www.codeplex.com/NetMassDownloader\" rel=\"nofollow noreferrer\">http://www.codeplex.com/NetMassDownloader</a>\nto download the .Net source). </li>\n<li>Change the code to have a readonly\nproperty with the failure index. </li>\n<li>Make sure your code uses that Regex\nrather than Microsoft's.</li>\n</ol>\n" }, { "answer_id": 108715, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 0, "selected": false, "text": "<p>In order to do that you would need either callbacks embedded in the regex (which AFAIK C# doesn't support) or preferably hooks into the regex engine. Even then, it's not clear what result you would want if backtracking was involved.</p>\n" }, { "answer_id": 11730129, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 0, "selected": false, "text": "<p>It is not possible to be able to tell where a regex fails. as a result you need to take a different approach. You need to compare strings. Use a regex to remove all the things that could vary and compare it with the string that you know it does not change.</p>\n\n<p>I run into the same problem came up to your answer and had to work out my own solution. Here it is:</p>\n\n<p><a href=\"https://stackoverflow.com/a/11730035/637142\">https://stackoverflow.com/a/11730035/637142</a></p>\n\n<p>hope it helps</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15075/" ]
I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it? For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2. Edit for clarification. The reason I need this is to allow me to simplify the parsing component of my application. The application is an Assmebly language teaching tool which allows students to write, compile, and execute assembly like programs. Currently I have a tokenizer class which converts input strings into Tokens using regex's. This works very well. For example: The tokenizer would produce the following tokens given the following input = "INP :x:" : ``` Token.OPCODE, Token.WHITESPACE, Token.LABEL, Token.EOL ``` These tokens are then analysed to ensure they conform to a syntax for a given statement. Currently this is done using IF statements and is proving cumbersome. The upside of this approach is that I can provide detailed error messages. I.E ``` if(token[2] != Token.LABEL) { throw new SyntaxError("Expected label");} ``` I want to use a regular expression to define a syntax instead of the annoying IF statements. But in doing so I lose the ability to return detailed error reports. I therefore would at least like to inform the user of WHERE the error occurred.
I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little: 1. Get the Regex class source code (e.g. <http://www.codeplex.com/NetMassDownloader> to download the .Net source). 2. Change the code to have a readonly property with the failure index. 3. Make sure your code uses that Regex rather than Microsoft's.
107,405
<p>What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if <code>http://somedomain/foo/</code> will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?</p>
[ { "answer_id": 107427, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 8, "selected": true, "text": "<p><strong>edit</strong>: This answer works, but nowadays you should just use the <a href=\"http://docs.python-requests.org/en/latest/index.html\" rel=\"noreferrer\">requests</a> library as mentioned by other answers below.</p>\n\n<hr>\n\n<p>Use <a href=\"https://docs.python.org/2/library/httplib.html\" rel=\"noreferrer\">httplib</a>.</p>\n\n<pre><code>&gt;&gt;&gt; import httplib\n&gt;&gt;&gt; conn = httplib.HTTPConnection(\"www.google.com\")\n&gt;&gt;&gt; conn.request(\"HEAD\", \"/index.html\")\n&gt;&gt;&gt; res = conn.getresponse()\n&gt;&gt;&gt; print res.status, res.reason\n200 OK\n&gt;&gt;&gt; print res.getheaders()\n[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]\n</code></pre>\n\n<p>There's also a <code>getheader(name)</code> to get a specific header.</p>\n" }, { "answer_id": 358075, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Probably easier: use urllib or urllib2.</p>\n\n<pre><code>&gt;&gt;&gt; import urllib\n&gt;&gt;&gt; f = urllib.urlopen('http://google.com')\n&gt;&gt;&gt; f.info().gettype()\n'text/html'\n</code></pre>\n\n<p>f.info() is a dictionary-like object, so you can do f.info()['content-type'], etc.</p>\n\n<p><a href=\"http://docs.python.org/library/urllib.html\" rel=\"nofollow noreferrer\">http://docs.python.org/library/urllib.html</a><br>\n<a href=\"http://docs.python.org/library/urllib2.html\" rel=\"nofollow noreferrer\">http://docs.python.org/library/urllib2.html</a><br>\n<a href=\"http://docs.python.org/library/httplib.html\" rel=\"nofollow noreferrer\">http://docs.python.org/library/httplib.html</a></p>\n\n<p>The docs note that httplib is not normally used directly.</p>\n" }, { "answer_id": 779985, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As an aside, when using the httplib (at least on 2.5.2), trying to read the response of a HEAD request will block (on readline) and subsequently fail. If you do not issue read on the response, you are unable to send another request on the connection, you will need to open a new one. Or accept a long delay between requests.</p>\n" }, { "answer_id": 2070916, "author": "doshea", "author_id": 251448, "author_profile": "https://Stackoverflow.com/users/251448", "pm_score": 7, "selected": false, "text": "<p><a href=\"https://docs.python.org/2/library/urllib2.html\" rel=\"noreferrer\">urllib2</a> can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path.</p>\n\n<pre><code>&gt;&gt;&gt; import urllib2\n&gt;&gt;&gt; class HeadRequest(urllib2.Request):\n... def get_method(self):\n... return \"HEAD\"\n... \n&gt;&gt;&gt; response = urllib2.urlopen(HeadRequest(\"http://google.com/index.html\"))\n</code></pre>\n\n<p>Headers are available via response.info() as before. Interestingly, you can find the URL that you were redirected to:</p>\n\n<pre><code>&gt;&gt;&gt; print response.geturl()\nhttp://www.google.com.au/index.html\n</code></pre>\n" }, { "answer_id": 2630687, "author": "IgorGanapolsky", "author_id": 6998684, "author_profile": "https://Stackoverflow.com/users/6998684", "pm_score": 1, "selected": false, "text": "<p>I have found that httplib is slightly faster than urllib2. I timed two programs - one using httplib and the other using urllib2 - sending HEAD requests to 10,000 URL's. The httplib one was faster by several minutes. <strong>httplib</strong>'s total stats were: real 6m21.334s\n user 0m2.124s\n sys 0m16.372s</p>\n\n<p>And <strong>urllib2</strong>'s total stats were: real 9m1.380s\n user 0m16.666s\n sys 0m28.565s</p>\n\n<p>Does anybody else have input on this?</p>\n" }, { "answer_id": 4421712, "author": "Paweł Prażak", "author_id": 539481, "author_profile": "https://Stackoverflow.com/users/539481", "pm_score": 4, "selected": false, "text": "<p>Just:</p>\n\n<pre><code>import urllib2\nrequest = urllib2.Request('http://localhost:8080')\nrequest.get_method = lambda : 'HEAD'\n\nresponse = urllib2.urlopen(request)\nresponse.info().gettype()\n</code></pre>\n\n<p>Edit: I've just came to realize there is httplib2 :D</p>\n\n<pre><code>import httplib2\nh = httplib2.Http()\nresp = h.request(\"http://www.google.com\", 'HEAD')\nassert resp[0]['status'] == 200\nassert resp[0]['content-type'] == 'text/html'\n...\n</code></pre>\n\n<p><a href=\"http://httplib2.googlecode.com/hg/doc/html/libhttplib2.html\" rel=\"noreferrer\">link text</a></p>\n" }, { "answer_id": 7387509, "author": "daliusd", "author_id": 457066, "author_profile": "https://Stackoverflow.com/users/457066", "pm_score": 5, "selected": false, "text": "<p>I believe the <a href=\"http://docs.python-requests.org/en/latest/index.html\">Requests</a> library should be mentioned as well.</p>\n" }, { "answer_id": 9227931, "author": "Pranay Agarwal", "author_id": 1175514, "author_profile": "https://Stackoverflow.com/users/1175514", "pm_score": 2, "selected": false, "text": "<pre><code>import httplib\nimport urlparse\n\ndef unshorten_url(url):\n parsed = urlparse.urlparse(url)\n h = httplib.HTTPConnection(parsed.netloc)\n h.request('HEAD', parsed.path)\n response = h.getresponse()\n if response.status/100 == 3 and response.getheader('Location'):\n return response.getheader('Location')\n else:\n return url\n</code></pre>\n" }, { "answer_id": 12997216, "author": "K Z", "author_id": 853611, "author_profile": "https://Stackoverflow.com/users/853611", "pm_score": 6, "selected": false, "text": "<p>Obligatory <a href=\"http://docs.python-requests.org/en/latest/\"><code>Requests</code></a> way:</p>\n\n<pre><code>import requests\n\nresp = requests.head(\"http://www.google.com\")\nprint resp.status_code, resp.text, resp.headers\n</code></pre>\n" }, { "answer_id": 15420705, "author": "Octavian Damiean", "author_id": 418183, "author_profile": "https://Stackoverflow.com/users/418183", "pm_score": 4, "selected": false, "text": "<p>For completeness to have a Python3 answer equivalent to the accepted answer using <em>httplib</em>.</p>\n\n<p>It is basically the same code just that the library isn't called <em>httplib</em> anymore but <em>http.client</em></p>\n\n<pre><code>from http.client import HTTPConnection\n\nconn = HTTPConnection('www.google.com')\nconn.request('HEAD', '/index.html')\nres = conn.getresponse()\n\nprint(res.status, res.reason)\n</code></pre>\n" }, { "answer_id": 16960321, "author": "estani", "author_id": 1182464, "author_profile": "https://Stackoverflow.com/users/1182464", "pm_score": 0, "selected": false, "text": "<p>And yet another approach (similar to Pawel answer):</p>\n\n<pre><code>import urllib2\nimport types\n\nrequest = urllib2.Request('http://localhost:8080')\nrequest.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)\n</code></pre>\n\n<p>Just to avoid having unbounded methods at instance level.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if `http://somedomain/foo/` will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?
**edit**: This answer works, but nowadays you should just use the [requests](http://docs.python-requests.org/en/latest/index.html) library as mentioned by other answers below. --- Use [httplib](https://docs.python.org/2/library/httplib.html). ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.google.com") >>> conn.request("HEAD", "/index.html") >>> res = conn.getresponse() >>> print res.status, res.reason 200 OK >>> print res.getheaders() [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')] ``` There's also a `getheader(name)` to get a specific header.
107,414
<p>As a base SAS programmer, you know the drill:</p> <p>You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement.</p> <p>What's your best trick for not having those unbalanced quotes bother you?</p>
[ { "answer_id": 107443, "author": "Martin Bøgelund", "author_id": 18968, "author_profile": "https://Stackoverflow.com/users/18968", "pm_score": 3, "selected": false, "text": "<p>As for myself, I usually <a href=\"http://www.google.dk/search?q=sas+unbalanced+quote&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a\" rel=\"noreferrer\">Google for \"SAS unbalanced quote\"</a>, and end up with submitting something like <a href=\"http://support.sas.com/publishing/pubcat/chaps/55513.pdf\" rel=\"noreferrer\">this</a>:</p>\n\n<pre><code>*); */; /*’*/ /*”*/; %mend;\n</code></pre>\n\n<p>... to break out of unclosed comments, quotes and macro functions.</p>\n" }, { "answer_id": 110267, "author": "Anindya", "author_id": 4741, "author_profile": "https://Stackoverflow.com/users/4741", "pm_score": -1, "selected": false, "text": "<p>Yes, I believe the official SAS documentation recommends the solution you have proposed for yourself.</p>\n" }, { "answer_id": 417979, "author": "CuppM", "author_id": 34440, "author_profile": "https://Stackoverflow.com/users/34440", "pm_score": 0, "selected": false, "text": "<p>You could always just issue a terminate submitted statements command and resubmit what you're trying to run.</p>\n" }, { "answer_id": 536803, "author": "AFHood", "author_id": 65050, "author_profile": "https://Stackoverflow.com/users/65050", "pm_score": 3, "selected": false, "text": "<p>Here is the one I use. </p>\n\n<pre><code> ;*';*\";*/;quit;run;\n ODS _ALL_ CLOSE;\n QUIT; RUN;\n</code></pre>\n" }, { "answer_id": 557654, "author": "robmandu", "author_id": 67082, "author_profile": "https://Stackoverflow.com/users/67082", "pm_score": 0, "selected": false, "text": "<p>just wanted to reiterate AFHood's suggestion to use the <code>ODS _ALL_ CLOSE;</code> statement. That's a key one to include. And make sure you use it every time you're finished with ODS anyway.</p>\n" }, { "answer_id": 573419, "author": "Chang Chung", "author_id": 69117, "author_profile": "https://Stackoverflow.com/users/69117", "pm_score": 4, "selected": true, "text": "<p>enterprise guide 3 used to put the following line at the top of its automatically generated code:</p>\n\n<pre><code>*';*\";*/;run;\n</code></pre>\n\n<p>however, the only way to really \"reset\" from all kinds of something unbalanced problems is to quit the sas session, and balance whatever is unbalanced before re-submitting the code. Using this kind of quick (cheap?) hacks does not address the root cause.</p>\n\n<p>by the way, <code>ods _all_ close;</code> closes <em>all</em> the ods destinations, including the default, results destination. in an interactive session, you should open it again with <code>ods results;</code> or <code>ods results on;</code> at least according to the documention. but when i tested it on my 9.2, it did not work, as shown below:</p>\n\n<pre><code>%put sysvlong=&amp;sysvlong sysscpl=&amp;sysscpl;\n/* sysvlong=9.02.01M0P020508 sysscpl=X64_VSPRO */\n\nods _all_ close;\nproc print data=sashelp.class;\nrun;\n/* on log\nWARNING: No output destinations active.\n*/\n\nods results on;\nproc print data=sashelp.class;\nrun;\n/* on log\nWARNING: No output destinations active.\n*/\n</code></pre>\n" }, { "answer_id": 9597722, "author": "Sabby", "author_id": 1254125, "author_profile": "https://Stackoverflow.com/users/1254125", "pm_score": 1, "selected": false, "text": "<p>I had a situation with unbalanced quotes in a macro and the only solution was to close the instance of SAS and start over.</p>\n\n<p>I feel that's an unacceptable flaw in SAS.</p>\n\n<p>However, I used the methods by BOTH #2 and #5 and it worked. #2 first and then #1. I put them above ALL code, including my code header, explaining what this program was doing.</p>\n\n<p>Worked like a charm.</p>\n" }, { "answer_id": 45320764, "author": "Mohit Kalra", "author_id": 6052681, "author_profile": "https://Stackoverflow.com/users/6052681", "pm_score": 0, "selected": false, "text": "<p>Closing the SAS Session worked in my case. I think you can try this once before you try other methods mentioned here.</p>\n" }, { "answer_id": 52230291, "author": "fireblood", "author_id": 6544371, "author_profile": "https://Stackoverflow.com/users/6544371", "pm_score": 1, "selected": false, "text": "<p>I wrote a perl program that reads through any given SAS program and keeps track of things that should come in pairs. With things like parentheses, which can be embedded, it prints the level of nesting at the beginning of every line. It needs to be able to distinguish parentheses that are part of macro functions from those that are part of data step functions, including %sysfunc calls that reside in the macro environment but make calls to data step functions (must also do similar for %syscall macro function invocations), but that is doable through regular expressions. If the level of nesting goes negative, it is a clue that the problem may be nearby.</p>\n\n<p>It also starts counting single and double quotes from the start of the program and identifies whether the count of each such symbol it encounters is odd or even. As with parentheses, it needs to be able to distinguish quotes that are part of macro code from those that are part of data step code and also those that are part of literal strings such as O'Riley and %nrstr(%'%\") and not count them, but pattern matching can handle that too.</p>\n\n<p>If the problem of the mismatched item stems from code that is generated at runtime by macro code and is therefore not present in the source program, then I turn on option mfile to write the generated data step code to a file and then run the perl script against that code.</p>\n\n<p>I chose perl because of its strong pattern-matching capabilities but any other pattern-matching language should work fine. Hope this helps.</p>\n" }, { "answer_id": 59709280, "author": "StatsStudent", "author_id": 4615298, "author_profile": "https://Stackoverflow.com/users/4615298", "pm_score": 1, "selected": false, "text": "<p>This works nearly every time for me:</p>\n\n<pre><code>; *'; *\"; */;\nODS _ALL_ CLOSE;\nquit; run; %MEND;\ndata _NULL_; putlog \"DONE\"; run;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18968/" ]
As a base SAS programmer, you know the drill: You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement. What's your best trick for not having those unbalanced quotes bother you?
enterprise guide 3 used to put the following line at the top of its automatically generated code: ``` *';*";*/;run; ``` however, the only way to really "reset" from all kinds of something unbalanced problems is to quit the sas session, and balance whatever is unbalanced before re-submitting the code. Using this kind of quick (cheap?) hacks does not address the root cause. by the way, `ods _all_ close;` closes *all* the ods destinations, including the default, results destination. in an interactive session, you should open it again with `ods results;` or `ods results on;` at least according to the documention. but when i tested it on my 9.2, it did not work, as shown below: ``` %put sysvlong=&sysvlong sysscpl=&sysscpl; /* sysvlong=9.02.01M0P020508 sysscpl=X64_VSPRO */ ods _all_ close; proc print data=sashelp.class; run; /* on log WARNING: No output destinations active. */ ods results on; proc print data=sashelp.class; run; /* on log WARNING: No output destinations active. */ ```
107,464
<p>There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."</p> <p>Is JavaScript an object-oriented language?</p>
[ { "answer_id": 107470, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 5, "selected": false, "text": "<p>The short answer is Yes. For more information:</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Javascript\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>JavaScript is heavily object-based.\n Objects are associative arrays,\n augmented with prototypes (see below).\n Object property names are associative\n array keys: obj.x = 10 and obj[\"x\"] =\n 10 are equivalent, the dot notation\n being merely syntactic sugar.\n Properties and their values can be\n added, changed, or deleted at\n run-time. The properties of an object\n can also be enumerated via a for...in\n loop.</p>\n</blockquote>\n\n<p>Also, see <a href=\"http://www.sitepoint.com/article/oriented-programming-1/\" rel=\"nofollow noreferrer\">this series of articles</a> about OOP with Javascript.</p>\n" }, { "answer_id": 107471, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 5, "selected": false, "text": "<p>Javascript is a multi-paradigm language that supports procedural, object-oriented (prototype-based) and functional programming styles.</p>\n\n<p>Here is an <a href=\"http://mckoss.com/jscript/object.htm\" rel=\"nofollow noreferrer\">article</a> discussing how to do OO in Javascript.</p>\n" }, { "answer_id": 107480, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>JavaScript is a very good language to write object oriented web apps. It can support OOP because supports inheritance through prototyping also properties and methods. You can have polymorphism, encapsulation and many sub-classing paradigms.</p>\n" }, { "answer_id": 107489, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 4, "selected": false, "text": "<p>Languages do not need to behave exactly like Java to be object-oriented. Everything in Javascript is an object; compare to C++ or earlier Java, which are widely considered object-oriented to some degree but still based on primitives. Polymorphism is a non-issue in Javascript, as it doesn't much care about types at all. The only core OO feature not directly supported by the syntax is inheritance, but that can easily be implemented however the programmer wants using prototypes: <a href=\"http://www.crockford.com/javascript/inheritance.html\" rel=\"nofollow noreferrer\">here</a> is one such example.</p>\n" }, { "answer_id": 107492, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://www.asp.net/ajax/downloads/\" rel=\"nofollow noreferrer\">Microsoft Ajax Client Library</a> makes it simple to implement OO in javascript. It supports inharitence, and interface implementation.</p>\n" }, { "answer_id": 107521, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>I think a lot of people answer this question \"no\" because JavaScript does not implement classes, in the traditional OO sense. Unfortunately (IMHO), that is coming in ECMAScript 4. Until then, viva la prototype! :-)</p>\n" }, { "answer_id": 107536, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": -1, "selected": false, "text": "<p>I would say it has capabilities to seem OO. Especially if you take advantage of it's ability to create methods on an existing object (anonymous methods in some languages). Client script libraries like jquery (jquery.com) or prototype (prototypejs.org) are good examples of libraries taking advantage of this, making javascript behave pretty OO-like.</p>\n" }, { "answer_id": 107555, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 2, "selected": false, "text": "<p>This is of course subjective and an academic question. Some people argue whether an OO language has to implement classes and inheritance, others write programs that change your life. ;-)</p>\n\n<p>(But really, why should an OO language have to implement classes? I'd think <em>objects</em> were the key components. How you create and then use them is another matter.)</p>\n" }, { "answer_id": 107570, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "<p>Unlike most object-oriented languages, JavaScript (before ECMA 262 Edition 4, anyway) has no concept of classes, but prototypes. As such, it is indeed somewhat subjective whether to call it object-oriented or not.</p>\n\n<p>@eliben: Wikipedia says object-<em>based</em>. That's not the same as object-oriented. In fact, <a href=\"http://en.wikipedia.org/wiki/Object-based\" rel=\"nofollow noreferrer\">their article on object-based</a> distinguishes between object-oriented languages and prototype-based ones, explicitly calling JavaScript <em>not</em> object-oriented.</p>\n" }, { "answer_id": 107578, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>I think when you can follow the same or similar design patterns as a true OO language like Java/C#, you can pretty much call it an OO language. Some aspects are obviously different but you can still use very well established OO design pattersn.</p>\n" }, { "answer_id": 107651, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p>JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do.</p>\n\n<p>There is a way to achieve 'normal' inheritance in JavaScript (<a href=\"http://www.crockford.com/javascript/inheritance.html\" rel=\"nofollow noreferrer\">Reference here</a>), but the basic model is based on prototyping.</p>\n" }, { "answer_id": 107773, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 0, "selected": false, "text": "<p>Everything in javascript is an object - classes are objects, functions are objects, numbers are objects, objects objects objects. It's not as strict about typing as other languages, but it's definitely possible to write OOP JS.</p>\n" }, { "answer_id": 107781, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 1, "selected": false, "text": "<p>Hanselminutes <a href=\"http://www.hanselminutes.com/default.aspx?showID=146\" rel=\"nofollow noreferrer\">episode 146</a> looks at OO Ajax. It was a good show and definitely a good show to help form an opinion.</p>\n" }, { "answer_id": 108255, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 0, "selected": false, "text": "<p>Yes, it is. However, it doesn't support all of the features one would expect in an object oriented programming language lacking inheritance and polymorphism. This doesn't mean, however, that you cannot simulate these capabilities through the prototyping system that is avaialble to the language.</p>\n" }, { "answer_id": 108773, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 7, "selected": true, "text": "<p>IMO (and it is only an opinion) <strong>the</strong> key characteristic of an object orientated language would be that it would support <a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"nofollow noreferrer\"><em>polymorphism</em></a>. Pretty much all dynamic languages do that.</p>\n\n<p>The next characteristic would be <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29\" rel=\"nofollow noreferrer\"><em>encapsulation</em></a> and that is pretty easy to do in Javascript also.</p>\n\n<p>However in the minds of many it is <a href=\"http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29\" rel=\"nofollow noreferrer\"><em>inheritance</em></a> (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.</p>\n\n<p>Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.</p>\n\n<p>So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass.</p>\n\n<p><strong>Edit</strong>: The supplementary question is raised \"how does prototypal inheritance sacrifice encapsulation?\" Consider this example of a non-prototypal approach:-</p>\n\n<pre><code>function MyClass() {\n var _value = 1;\n this.getValue = function() { return _value; }\n}\n</code></pre>\n\n<p>The _value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-</p>\n\n<pre><code>function MyClass() {\n var _value = 1;\n}\nMyClass.prototype.getValue = function() { return _value; }\n</code></pre>\n\n<p>Well this is broken. Since the function assigned to getValue is no longer in scope with _value it can't access it. We would need to promote _value to an attribute of <code>this</code> but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.</p>\n\n<p>Despite this my vote still remains that Javascript is object oriented. Why? Because given an <a href=\"http://en.wikipedia.org/wiki/Object-oriented_design\" rel=\"nofollow noreferrer\">OOD</a> I can implement it in Javascript.</p>\n" }, { "answer_id": 112548, "author": "bmeck", "author_id": 12781, "author_profile": "https://Stackoverflow.com/users/12781", "pm_score": 0, "selected": false, "text": "<p>Javascript is not an object oriented language as typically considered, mainly due to lack of true inheritance, DUCK typing allows for a semi-true form of inheritance/polymorphism along with the Object.prototype allowing for complex function sharing. At its heart however the lack of inheritance leads to a weak polymorphism to take place since the DUCK typing will insist some object with the same attribute names are an instance of an Object which they were not intended to be used as. Thus adding attributes to random object transforms their type's base in a manner of speaking.</p>\n" }, { "answer_id": 116317, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 3, "selected": false, "text": "<p>JavaScript is object-oriented, but is not a <em>class-based</em> object-oriented language like Java, C++, C#, etc. Class-based OOP languages are a subset of the larger family of OOP languages which also include prototype-based languages like JavaScript and Self.</p>\n" }, { "answer_id": 116355, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 0, "selected": false, "text": "<p>Technically it is a prototype language, but it's easy to to OO in it.</p>\n" }, { "answer_id": 116363, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 0, "selected": false, "text": "<p>It is object oriented, but not based on classes, it's based on prototypes.</p>\n" }, { "answer_id": 116401, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 3, "selected": false, "text": "<p>Yes and no.</p>\n\n<p>JavaScript is, as Douglas Crockford puts it, \"<a href=\"http://javascript.crockford.com/javascript.html\" rel=\"nofollow noreferrer\">the world's most misunderstood programming language</a>.\" He has some <a href=\"http://www.crockford.com/javascript/\" rel=\"nofollow noreferrer\">great articles on JavaScript</a> that I'd strongly recommend reading on what exactly JavaScript is. It has more in common with LISP that C++.</p>\n" }, { "answer_id": 152464, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>JavaScript is a prototype-based programming language (probably prototype-based scripting language is more correct definition). It employs cloning and not inheritance. A prototype-based programming language is a style of object-oriented programming without classes. While object-oriented programming languages encourages development focus on taxonomy and relationships, prototype-based programming languages encourages to focus on behavior first and then later classify.</p>\n\n<p>The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean </p>\n\n<blockquote>\n <p><em>only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.</em>\n <sup><a href=\"http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en\" rel=\"nofollow noreferrer\">(source)</a></sup></p>\n</blockquote>\n\n<p>In object-oriented programming, each object is capable of receiving messages, processing data, and sending messages to other objects.</p>\n\n<p>For a language to be object-oriented in may include features as encapsulation, modularity, polymorphism, and inheritance, but it is not a requirement. Object-oriented programming languages that make use of classes are often referred to as classed-based programming languages, but it is by no means a must to make use of classes to be object-oriented.</p>\n\n<p>JavaScript uses prototypes to define object properties, including methods and inheritance.</p>\n\n<p>Conclusion: JavaScript IS object-oriented.</p>\n" }, { "answer_id": 154409, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 2, "selected": false, "text": "<p>it <em>is</em> a good thread. Here's some resources i like. Most people start out with prototype, jquery, or one of the top 6 libs(mootools, ExtJS, YUI), which have different object models. Prototype tries to replicate classical O-O as most people think of it </p>\n\n<p><a href=\"http://jquery.com/blog/2006/08/20/why-jquerys-philosophy-is-better/\" rel=\"nofollow noreferrer\">http://jquery.com/blog/2006/08/20/why-jquerys-philosophy-is-better/</a></p>\n\n<p>Here's a picture of prototypes and functions that i refer to a lot</p>\n\n<p><a href=\"http://www.mollypages.org/misc/js.mp\" rel=\"nofollow noreferrer\">http://www.mollypages.org/misc/js.mp</a>?</p>\n" }, { "answer_id": 322084, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 0, "selected": false, "text": "<p>Objects in JavaScript inherit directly from objects. What can be more object oriented?</p>\n" }, { "answer_id": 4060144, "author": "angelcervera", "author_id": 248304, "author_profile": "https://Stackoverflow.com/users/248304", "pm_score": 2, "selected": false, "text": "<p>I am responding this question bounced from another angle.</p>\n\n<p>This is an eternal topic, and we could open a flame war in a lot of forums.</p>\n\n<p>When people assert that JavaScript is an OO programming language because they can use OOD with this, then I ask: Why is not C an OO programming language? Repeat, you can use OOD with C and if you said that C is an OO programming language everybody will said you that you are crazy.</p>\n\n<p>We could put here a lot of references about this topic in very old books and forums, because this topic is older than the Internet :)</p>\n\n<p>JavaScript has not changed for many years, but new programmers want to show JavaScript is an OO programming language. Why? JavaScript is a powerful language, but is not an OO programming language.</p>\n\n<p>An OO programming language must have objects, method, property, classes, encapsulation, aggregation, inheritance and polymorphism. You could implement all this points, but JavaScript has not them.</p>\n\n<p>An very illustrate example: In chapter 6 of \"Object-Oriented JavaScript\" describe <strong>10 manners to implement \"inheritance\".</strong> How many manners there are in Java? One, and in C++? One, and in Delphi (Object Pascal)? One, and in Objective-C? One.</p>\n\n<p>Why is this different? Because Java, C++, Delphi and Objective-C are designed with OOP in mind, but not JavaScript.</p>\n\n<p>When I was a student (in 1993), in university, there was a typical home work: Implement a program designed using a OOD (Object-oriented design) with a non-OO language. In those times, the language selected was C (not C++). The objective of this practices was to make clear the difference between OOD and OOP, and could differentiate between OOP and non-OOP languages.</p>\n\n<p>Anyway, it is evidence that not all people have some opinion about this topic :)</p>\n\n<p><strong>Anyway, in my opinion, JavaScript is a powerful language and the future in the client side layer!</strong></p>\n" }, { "answer_id": 9055254, "author": "rodrigo-silveira", "author_id": 774907, "author_profile": "https://Stackoverflow.com/users/774907", "pm_score": 1, "selected": false, "text": "<p>Misko Hevery did an excellent introductory Google Tech Talk where he talks about objects in Javascript. I've found this to be a good starting point for people either questioning the use of objects in Javascript, or wanting to get started with them:</p>\n\n<ul>\n<li><a href=\"http://goo.gl/FJiqM\" rel=\"nofollow\">Introduction to JavaScript and Browser DOM</a></li>\n</ul>\n" }, { "answer_id": 10553573, "author": "Kokodoko", "author_id": 1083572, "author_profile": "https://Stackoverflow.com/users/1083572", "pm_score": 0, "selected": false, "text": "<p>For me personally the main attraction of OOP programming is the ability to have self-contained classes with unexposed (private) inner workings. </p>\n\n<p>What confuses me to no end in Javascript is that you can't even use function names, because \nyou run the risk of having that same function name somewhere else in any of the external libraries that you're using.</p>\n\n<p>Even though some very smart people have found workarounds for this, isn't it weird that Javascript in its purest form requires you to create code that is highly unreadable?</p>\n\n<p>The beauty of OOP is that you can spend your time thinking about your app's logic, without having to worry about syntax.</p>\n" }, { "answer_id": 10582788, "author": "Vinayak Bevinakatti", "author_id": 28557, "author_profile": "https://Stackoverflow.com/users/28557", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>Is JavaScript object-oriented?</p>\n<p>Answer : Yes</p>\n</blockquote>\n<p>It has objects which can contain data and methods that act upon that data. Objects can contain other objects.</p>\n<ul>\n<li>It does not have classes, but it does have constructors which do what classes do, including acting as containers for class variables and methods.</li>\n<li>It does not have class-oriented inheritance, but it does have prototype-oriented inheritance.</li>\n</ul>\n<p>The two main ways of building up object systems are by inheritance (is-a) and by aggregation (has-a). JavaScript does both, but its dynamic nature allows it to excel at aggregation.</p>\n<p>Some argue that JavaScript is not truly object oriented because it does not provide information hiding. That is, objects cannot have private variables and private methods: All members are public.</p>\n<p>But it turns out that <strong><a href=\"http://www.crockford.com/javascript/private.html\" rel=\"nofollow noreferrer\">JavaScript objects can have private variables</a></strong> and private methods. (Click here now to find out how.) Of course, few understand this because JavaScript is the world's most misunderstood programming language.</p>\n<p>Some argue that JavaScript is not truly object oriented because it does not provide inheritance. But it turns out that <strong><a href=\"http://javascript.crockford.com/inheritance.html\" rel=\"nofollow noreferrer\">JavaScript supports not only classical inheritance, but other code reuse patterns as well.</a></strong></p>\n<p>Sources : <a href=\"http://javascript.crockford.com/javascript.html\" rel=\"nofollow noreferrer\">http://javascript.crockford.com/javascript.html</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO." Is JavaScript an object-oriented language?
IMO (and it is only an opinion) **the** key characteristic of an object orientated language would be that it would support [*polymorphism*](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming). Pretty much all dynamic languages do that. The next characteristic would be [*encapsulation*](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) and that is pretty easy to do in Javascript also. However in the minds of many it is [*inheritance*](http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29) (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented. Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation. So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass. **Edit**: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:- ``` function MyClass() { var _value = 1; this.getValue = function() { return _value; } } ``` The \_value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:- ``` function MyClass() { var _value = 1; } MyClass.prototype.getValue = function() { return _value; } ``` Well this is broken. Since the function assigned to getValue is no longer in scope with \_value it can't access it. We would need to promote \_value to an attribute of `this` but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken. Despite this my vote still remains that Javascript is object oriented. Why? Because given an [OOD](http://en.wikipedia.org/wiki/Object-oriented_design) I can implement it in Javascript.
107,546
<p>I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types.</p> <p>This can be an IE specific solution (IE6+).</p> <p>I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow".</p> <p>That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context.</p> <p>However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved.</p> <p>Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?</p>
[ { "answer_id": 107632, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 3, "selected": false, "text": "<p>Have you tried to apply the <a href=\"http://www.w3.org/TR/CSS2/text.html#caps-prop\" rel=\"noreferrer\">text-transform</a> CSS style to your controls?</p>\n" }, { "answer_id": 107662, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": true, "text": "<p>I'm not sure if this is what you're trying to do, but here is a function (<a href=\"http://individed.com/code/to-title-case/js/to-title-case.js\" rel=\"nofollow noreferrer\">reference</a>) to convert a given string to title case:</p>\n\n<pre><code>function toTitleCase(str) {\n return str.replace(/([\\w&amp;`'‘’\"“.@:\\/\\{\\(\\[&lt;&gt;_]+-? *)/g, function(match, p1, index, title){ // ' fix syntax highlighting\n if (index &gt; 0 &amp;&amp; title.charAt(index - 2) != \":\" &amp;&amp; \n match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\\.?|via)[ -]/i) &gt; -1)\n return match.toLowerCase();\n if (title.substring(index - 1, index + 1).search(/['\"_{([]/) &gt; -1)\n return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);\n if (match.substr(1).search(/[A-Z]+|&amp;|[\\w]+[._][\\w]+/) &gt; -1 ||\n title.substring(index - 1, index + 1).search(/[\\])}]/) &gt; -1)\n return match;\n return match.charAt(0).toUpperCase() + match.substr(1);\n });\n}\n</code></pre>\n" }, { "answer_id": 107686, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 0, "selected": false, "text": "<p>You pose an interesting question. Acting upon each key press may be more limiting because you will not know what comes immediately after a given keycode (the complexity of undoing a reaction that turns out to be incorrect could mean having to go to a TextRange-based routine anyway). Granted, I haven't wrestled with code on this problem to date, so this is a hypothesis in my head.</p>\n\n<p>At any length, here's a Title Casing function (java implementation inspired by a John Gruber blogging automation) which may spur ideas when it comes to handling the actual casing code:</p>\n\n<blockquote>\n <p><a href=\"http://individed.com/code/to-title-case/\" rel=\"nofollow noreferrer\">http://individed.com/code/to-title-case/</a></p>\n</blockquote>\n" }, { "answer_id": 9258337, "author": "Dewi Morgan", "author_id": 1178786, "author_profile": "https://Stackoverflow.com/users/1178786", "pm_score": 2, "selected": false, "text": "<p>Sometimes, not to do it is the right answer to a coding problem.</p>\n\n<p>I really would NOT do this, unless you feel you can write a script to correctly set the case in the following sentence, if you were to first convert it to lowercase and pass it into the script.</p>\n\n<p>Jean-Luc \"The King\" O'Brien MacHenry van d'Graaf IIV (PhD, OBE), left his Macintosh with in Macdonald's with his friends MacIntosh and MacDonald. Jesus gave His Atari ST at AT&amp;T's \"Aids for AIDS\" gig in St George's st, with Van Halen in van Henry's van, performing The Tempest.</p>\n\n<p>You have set yourself up for a fall by trying to create a Natural Language Parser. You can never do this as well as the user will. At best, you can do an approximation, and give the user the ability to edit and force a correction when you get it wrong. But often in such cases, the editing is more work than just doing it manually and right in the first place.</p>\n\n<p>That said, if you have the space and power to store and search a large n-gram corpus of suitably capitalized words, you would at least be able to have a wild stab at the most likely desired case.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2742/" ]
I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types. This can be an IE specific solution (IE6+). I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into formatted text. i.e. the macro "so" could auto expand upon hitting spacebar to "stackoverflow". That said, I have access to the keyCode information, as well I am using the TextRange methods to select a word ("so") and expanding it to "stackoverflow". Thus, I have some semblence of context. However, I need to check this context to know whether I should auto-capitalize. This also needs to work regardless of whether a macro is involved. Since I'm monitoring keystrokes for the macros, should I just monitor for punctuation (it's more than just periods that signal a capital letter) and auto-cap the next letter typed, or should I use TextRange and analyze context?
I'm not sure if this is what you're trying to do, but here is a function ([reference](http://individed.com/code/to-title-case/js/to-title-case.js)) to convert a given string to title case: ``` function toTitleCase(str) { return str.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title){ // ' fix syntax highlighting if (index > 0 && title.charAt(index - 2) != ":" && match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ -]/i) > -1) return match.toLowerCase(); if (title.substring(index - 1, index + 1).search(/['"_{([]/) > -1) return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2); if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || title.substring(index - 1, index + 1).search(/[\])}]/) > -1) return match; return match.charAt(0).toUpperCase() + match.substr(1); }); } ```
107,549
<p>When we compile a dll using __stdcall inside visual studio 2008 the compiled function names inside the dll are.</p> <p>FunctionName</p> <p>Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.</p> <p>FunctionName@numberOfParameters or == FunctionName@8</p> <p>How do you tell GCC compiler to remove @nn from exported symbols in the dll?</p>
[ { "answer_id": 107564, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 4, "selected": true, "text": "<p>__stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @).</p>\n\n<p>So, a function:</p>\n\n<pre><code>void __stdcall Foo(int a, int b);\n</code></pre>\n\n<p>...would become _Foo@8.</p>\n\n<p>If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated.</p>\n\n<p>Perhaps this is the difference?</p>\n" }, { "answer_id": 254789, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": false, "text": "<p>Just use <code>-Wl,--kill-at</code> on the gcc command line, which will pass <code>--kill-at</code> to the linker.</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://sourceware.org/binutils/docs/ld/Options.html#Options\" rel=\"noreferrer\">http://sourceware.org/binutils/docs/ld/Options.html#Options</a></li>\n<li><a href=\"http://www.geocities.com/yongweiwu/stdcall.htm\" rel=\"noreferrer\">http://www.geocities.com/yongweiwu/stdcall.htm</a></li>\n</ul>\n" }, { "answer_id": 24137148, "author": "Matthias", "author_id": 519852, "author_profile": "https://Stackoverflow.com/users/519852", "pm_score": 2, "selected": false, "text": "<p>You can also use <code>-Wl,--add-stdcall-alias</code> to your linker options in GCC. This will ensure that both function names (decorated and undecorated) are present and can be used as alias.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17382/" ]
When we compile a dll using \_\_stdcall inside visual studio 2008 the compiled function names inside the dll are. FunctionName Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like. FunctionName@numberOfParameters or == FunctionName@8 How do you tell GCC compiler to remove @nn from exported symbols in the dll?
\_\_stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @). So, a function: ``` void __stdcall Foo(int a, int b); ``` ...would become \_Foo@8. If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated. Perhaps this is the difference?
107,562
<p>I'm trying to install faac and am running into errors. Here are the errors I get when trying to build it:</p> <hr> <pre><code>[root@test faac]# ./bootstrap configure.in:11: warning: underquoted definition of MY_DEFINE run info '(automake)Extending aclocal' or see http://sources.redhat.com/automake/automake.html#Extending-aclocal aclocal:configure.in:17: warning: macro `AM_PROG_LIBTOOL' not found in library common/mp4v2/Makefile.am:5: Libtool library used but `LIBTOOL' is undefined common/mp4v2/Makefile.am:5: common/mp4v2/Makefile.am:5: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL' common/mp4v2/Makefile.am:5: to `configure.in' and run `aclocal' and `autoconf' again. libfaac/Makefile.am:1: Libtool library used but `LIBTOOL' is undefined libfaac/Makefile.am:1: libfaac/Makefile.am:1: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL' libfaac/Makefile.am:1: to `configure.in' and run `aclocal' and `autoconf' again. configure.in:17: error: possibly undefined macro: AM_PROG_LIBTOOL If this token and others are legitimate, please use m4_pattern_allow. See the Autoconf documentation. </code></pre> <hr> <p>Does anyone know what this means? I was unable to find anything about this so I figured I'd ask you guys. Thank you for your help.</p> <p>EDIT: Here's my versions of linux, libtool, automake and autoconf:</p> <pre><code>[root@test faac]# libtool --version ltmain.sh (GNU libtool) 2.2 Written by Gordon Matzigkeit &lt;[email protected]&gt;, 1996 Copyright (C) 2008 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# autoconf --version autoconf (GNU Autoconf) 2.59 Written by David J. MacKenzie and Akim Demaille. Copyright (C) 2003 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# automake --version automake (GNU automake) 1.9.2 Written by Tom Tromey &lt;[email protected]&gt;. Copyright 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# cat /etc/redhat-release Red Hat Enterprise Linux WS release 4 (Nahant) </code></pre>
[ { "answer_id": 107592, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 2, "selected": false, "text": "<p>I think the first thing to check is that you have libtool installed.</p>\n\n<p>Edit:</p>\n\n<p>This is what I get on Ubuntu 8.04:</p>\n\n<pre><code>$ ./bootstrap \nconfigure.in:11: warning: underquoted definition of MY_DEFINE\nconfigure.in:11: run info '(automake)Extending aclocal'\nconfigure.in:11: or see http://sources.redhat.com/automake/automake.html#Extending-aclocal\nconfigure.in:4: installing `./install-sh'\nconfigure.in:4: installing `./missing'\ncommon/mp4v2/Makefile.am: installing `./depcomp'\n\n$ libtool --version\nltmain.sh (GNU libtool) 1.5.26 Debian 1.5.26-1ubuntu1 (1.1220.2.493 2008/02/01 16:58:18)\n\nCopyright (C) 2008 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n$ autoconf --version\nautoconf (GNU Autoconf) 2.61\nCopyright (C) 2006 Free Software Foundation, Inc.\nThis is free software. You may redistribute copies of it under the terms of\nthe GNU General Public License &lt;http://www.gnu.org/licenses/gpl.html&gt;.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by David J. MacKenzie and Akim Demaille.\n\n$ automake --version\nautomake (GNU automake) 1.10.1\nCopyright (C) 2008 Free Software Foundation, Inc.\nLicense GPLv2+: GNU GPL version 2 or later &lt;http://gnu.org/licenses/gpl.html&gt;\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by Tom Tromey &lt;[email protected]&gt;\n and Alexandre Duret-Lutz &lt;[email protected]&gt;.\n</code></pre>\n" }, { "answer_id": 107607, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 0, "selected": false, "text": "<p>Maybe your automake doesn't know about your libtool for some reason. It looks like you've got two copies of libtool installed, which might be confusing it.</p>\n\n<p>Maybe you should remove both copies, plus all automake, autoconf installs, and reinstall them (possibly from source?).</p>\n\n<p>I guess the first step is to find out the locations of the active copies of the tools:</p>\n\n<pre><code>which libtool\nwhich automake\nwhich autoconf\n</code></pre>\n" }, { "answer_id": 138655, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 1, "selected": false, "text": "<p>So your problem is that automake/conf don't know about libtool.</p>\n\n<p>You need to reinstall all of them. Either from all from source, or all from binary packages.\nIf installing from source, ensure they are all installed to the same location.</p>\n" }, { "answer_id": 188741, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 0, "selected": false, "text": "<p>It sounds like autoconf/automake cannot find <code>libtool.m4</code>, and therefore cannot resolve the macro <code>AM_PROG_LIBTOOL</code>. Look for this file under your libtool installation and copy/link it under <code>/usr/share/aclocal/</code>.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to install faac and am running into errors. Here are the errors I get when trying to build it: --- ``` [root@test faac]# ./bootstrap configure.in:11: warning: underquoted definition of MY_DEFINE run info '(automake)Extending aclocal' or see http://sources.redhat.com/automake/automake.html#Extending-aclocal aclocal:configure.in:17: warning: macro `AM_PROG_LIBTOOL' not found in library common/mp4v2/Makefile.am:5: Libtool library used but `LIBTOOL' is undefined common/mp4v2/Makefile.am:5: common/mp4v2/Makefile.am:5: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL' common/mp4v2/Makefile.am:5: to `configure.in' and run `aclocal' and `autoconf' again. libfaac/Makefile.am:1: Libtool library used but `LIBTOOL' is undefined libfaac/Makefile.am:1: libfaac/Makefile.am:1: The usual way to define `LIBTOOL' is to add `AC_PROG_LIBTOOL' libfaac/Makefile.am:1: to `configure.in' and run `aclocal' and `autoconf' again. configure.in:17: error: possibly undefined macro: AM_PROG_LIBTOOL If this token and others are legitimate, please use m4_pattern_allow. See the Autoconf documentation. ``` --- Does anyone know what this means? I was unable to find anything about this so I figured I'd ask you guys. Thank you for your help. EDIT: Here's my versions of linux, libtool, automake and autoconf: ``` [root@test faac]# libtool --version ltmain.sh (GNU libtool) 2.2 Written by Gordon Matzigkeit <[email protected]>, 1996 Copyright (C) 2008 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# autoconf --version autoconf (GNU Autoconf) 2.59 Written by David J. MacKenzie and Akim Demaille. Copyright (C) 2003 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# automake --version automake (GNU automake) 1.9.2 Written by Tom Tromey <[email protected]>. Copyright 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [root@test faac]# cat /etc/redhat-release Red Hat Enterprise Linux WS release 4 (Nahant) ```
I think the first thing to check is that you have libtool installed. Edit: This is what I get on Ubuntu 8.04: ``` $ ./bootstrap configure.in:11: warning: underquoted definition of MY_DEFINE configure.in:11: run info '(automake)Extending aclocal' configure.in:11: or see http://sources.redhat.com/automake/automake.html#Extending-aclocal configure.in:4: installing `./install-sh' configure.in:4: installing `./missing' common/mp4v2/Makefile.am: installing `./depcomp' $ libtool --version ltmain.sh (GNU libtool) 1.5.26 Debian 1.5.26-1ubuntu1 (1.1220.2.493 2008/02/01 16:58:18) Copyright (C) 2008 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ autoconf --version autoconf (GNU Autoconf) 2.61 Copyright (C) 2006 Free Software Foundation, Inc. This is free software. You may redistribute copies of it under the terms of the GNU General Public License <http://www.gnu.org/licenses/gpl.html>. There is NO WARRANTY, to the extent permitted by law. Written by David J. MacKenzie and Akim Demaille. $ automake --version automake (GNU automake) 1.10.1 Copyright (C) 2008 Free Software Foundation, Inc. License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Tom Tromey <[email protected]> and Alexandre Duret-Lutz <[email protected]>. ```
107,611
<p>I need to load some fonts temporarily in my program. Preferably from a dll resource file.</p>
[ { "answer_id": 107702, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>I found <a href=\"http://www.eggheadcafe.com/software/aspnet/30018713/load-font-from-resource.aspx\" rel=\"nofollow noreferrer\">this</a> with Google. I have cut &amp; pasted the relevant code below.</p>\n\n<p>You need to add the font to your resource file:</p>\n\n<pre><code>\n34 FONT \"myfont.ttf\"\n</code></pre>\n\n<p>The following C code will load the font from the DLL resource and release it from memory when you are finished using it.</p>\n\n<pre>\nDWORD Count;\nHMODULE Module = LoadLibrary(\"mylib.dll\");\nHRSRC Resource = FindResource(Module,MAKEINTRESOURCE(34),RT_FONT);\nDWORD Length = SizeofResource(Module,Resource);\nHGLOBAL Address = LoadResource(Module,Resource);\nHANDLE Handle = AddFontMemResourceEx(Address,Length,0,&Count);\n\n/* Use the font here... */\n\nRemoveFontMemResourceEx(Handle);\nFreeLibrary(Module);\n</pre>\n" }, { "answer_id": 107922, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 1, "selected": false, "text": "<p>Here's some code that will load/make available the font from inside your executable (ie, the font was embedded as a resource, rather than something you had to install into Windows generally). </p>\n\n<p>Note that the font is available to <em>any</em> application until your program gets rid of it.\nI don't know how useful you'll find this, but I have used it a few times. I've never put the font into a dll (I prefer this 'embed into the exe' approach) but don't imagine it changes things too much.</p>\n\n<pre>procedure TForm1.FormCreate(Sender: TObject);\nvar\n ResStream : TResourceStream;\n sFileName : string;\nbegin\n sFileName:=ExtractFilePath(Application.ExeName)+'SWISFONT.TTF';\n\n ResStream:=nil;\n try\n ResStream:=TResourceStream.Create(hInstance, 'Swisfont', RT_RCDATA);\n try\n ResStream.SaveToFile(sFileName);\n except\n on E:EFCreateError Do ShowMessage(E.Message);\n end;\n finally\n ResStream.Free;\n end;\n\n AddFontResource(PChar(sFileName));\n SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);\nend;\n\n\nprocedure TForm1.FormDestroy(Sender: TObject);\nvar\n sFile:string;\nbegin\n sFile:=ExtractFilePath(Application.ExeName)+'SWISFONT.TTF';\n if FileExists(sFile) then\n begin\n RemoveFontResource(PChar(sFile));\n SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);\n DeleteFile(sFile);\n end;\nend;\n</pre>\n" }, { "answer_id": 110705, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": true, "text": "<p>And here a Delphi version:</p>\n\n<pre><code>procedure LoadFontFromDll(const DllName, FontName: PWideChar);\nvar\n DllHandle: HMODULE;\n ResHandle: HRSRC;\n ResSize, NbFontAdded: Cardinal;\n ResAddr: HGLOBAL;\nbegin\n DllHandle := LoadLibrary(DllName);\n if DllHandle = 0 then\n RaiseLastOSError;\n ResHandle := FindResource(DllHandle, FontName, RT_FONT);\n if ResHandle = 0 then\n RaiseLastOSError;\n ResAddr := LoadResource(DllHandle, ResHandle);\n if ResAddr = 0 then\n RaiseLastOSError;\n ResSize := SizeOfResource(DllHandle, ResHandle);\n if ResSize = 0 then\n RaiseLastOSError;\n if 0 = AddFontMemResourceEx(Pointer(ResAddr), ResSize, nil, @NbFontAdded) then\n RaiseLastOSError;\nend;\n</code></pre>\n\n<p>to be used like:</p>\n\n<pre><code>var\n FontName: PChar;\n FontHandle: THandle;\n...\n FontName := 'DEJAVUSANS';\n LoadFontFromDll('Project1.dll' , FontName);\n FontHandle := CreateFont(0, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,\n OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH,\n FontName);\n if FontHandle = 0 then\n RaiseLastOSError;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13219/" ]
I need to load some fonts temporarily in my program. Preferably from a dll resource file.
And here a Delphi version: ``` procedure LoadFontFromDll(const DllName, FontName: PWideChar); var DllHandle: HMODULE; ResHandle: HRSRC; ResSize, NbFontAdded: Cardinal; ResAddr: HGLOBAL; begin DllHandle := LoadLibrary(DllName); if DllHandle = 0 then RaiseLastOSError; ResHandle := FindResource(DllHandle, FontName, RT_FONT); if ResHandle = 0 then RaiseLastOSError; ResAddr := LoadResource(DllHandle, ResHandle); if ResAddr = 0 then RaiseLastOSError; ResSize := SizeOfResource(DllHandle, ResHandle); if ResSize = 0 then RaiseLastOSError; if 0 = AddFontMemResourceEx(Pointer(ResAddr), ResSize, nil, @NbFontAdded) then RaiseLastOSError; end; ``` to be used like: ``` var FontName: PChar; FontHandle: THandle; ... FontName := 'DEJAVUSANS'; LoadFontFromDll('Project1.dll' , FontName); FontHandle := CreateFont(0, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, FontName); if FontHandle = 0 then RaiseLastOSError; ```
107,660
<p>What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?</p> <p>For example, if I have the following structure:</p> <pre><code> Node A (weight 3) / \ Node B (weight 4) Node D (weight 7) / \ Node E (weight 2) Node F (weight 3) </code></pre> <p>The critical path should be A->B->F (total weight: 10)</p>
[ { "answer_id": 107680, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 3, "selected": true, "text": "<p>I have no clue about \"critical paths\", but I assume you mean <a href=\"http://en.wikipedia.org/wiki/Critical_path_method\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>Finding the longest path in an acyclic graph with weights is only possible by traversing the whole tree and then comparing the lengths, as you never really know how the rest of the tree is weighted. You can find more about tree traversal at <a href=\"https://secure.wikimedia.org/wikipedia/en/wiki/Tree_traversal\" rel=\"nofollow noreferrer\">Wikipedia</a>. I suggest, you go with pre-order traversal, as it's easy and straight forward to implement.</p>\n\n<p>If you're going to query often, you may also wish to augment the edges between the nodes with information about the weight of their subtrees at insertion. This is relatively cheap, while repeated traversal can be extremely expensive.</p>\n\n<p>But there's nothing to really save you from a full traversal if you don't do it. The order doesn't really matter, as long as you do a <em>traversal</em> and never go the same path twice.</p>\n" }, { "answer_id": 107692, "author": "James Cook", "author_id": 19553, "author_profile": "https://Stackoverflow.com/users/19553", "pm_score": 3, "selected": false, "text": "<p>I would solve this with dynamic programming. To find the maximum cost from S to T:</p>\n\n<ul>\n<li>Topologically sort the nodes of the graph as S = x_0, x_1, ..., x_n = T. (Ignore any nodes that can reach S or be reached from T.)</li>\n<li>The maximum cost from S to S is the weight of S.</li>\n<li>Assuming you've computed the maximum cost from S to x_i for all i &lt; k, the maximum cost from S to x_k is the cost of x_k plus the maximum cost to any node with an edge to x_k.</li>\n</ul>\n" }, { "answer_id": 107697, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 0, "selected": false, "text": "<p>Try the A* method.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/A*_search_algorithm\" rel=\"nofollow noreferrer\">A* Search Algorithm</a></p>\n\n<p>At the end, to deal with the leaves, just make all of them lead on to a final point, to set as the goal.</p>\n" }, { "answer_id": 109977, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>There's a paper that purports to have an algorithm for this: \"Critical path in an activity network with time constraints\". Sadly, I couldn't find a link to a free copy. Short of that, I can only second the idea of modifying <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm</a> or <a href=\"http://en.wikipedia.org/wiki/A\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/A</a>*</p>\n\n<p>UPDATE: I apologize for the crappy formatting—the server-side markdown engine is apparently broken.</p>\n" }, { "answer_id": 37254469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>My first answer so please excuse for any non-standard thing by the culture of stackoverflow.</p>\n\n<p>I think the solution is simple. Just negate the weights and run the classic shortest path for DAG (modified for weights of vertices of course). It should run fairly fast. (Time complexity of O(V+E) maybe)</p>\n\n<p>I think it should work as when you will negate the weights, the biggest one will become smallest, second biggest will be second smallest and so on as if <code>a &gt; b</code> then <code>-a &lt; -b</code>. Then running DAG should suffice as it will find the solution for the smallest path of the negated one and thus finding longest path for the original one</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331/" ]
What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight? For example, if I have the following structure: ``` Node A (weight 3) / \ Node B (weight 4) Node D (weight 7) / \ Node E (weight 2) Node F (weight 3) ``` The critical path should be A->B->F (total weight: 10)
I have no clue about "critical paths", but I assume you mean [this](http://en.wikipedia.org/wiki/Critical_path_method). Finding the longest path in an acyclic graph with weights is only possible by traversing the whole tree and then comparing the lengths, as you never really know how the rest of the tree is weighted. You can find more about tree traversal at [Wikipedia](https://secure.wikimedia.org/wikipedia/en/wiki/Tree_traversal). I suggest, you go with pre-order traversal, as it's easy and straight forward to implement. If you're going to query often, you may also wish to augment the edges between the nodes with information about the weight of their subtrees at insertion. This is relatively cheap, while repeated traversal can be extremely expensive. But there's nothing to really save you from a full traversal if you don't do it. The order doesn't really matter, as long as you do a *traversal* and never go the same path twice.
107,674
<p>I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.</p> <p>How do you create a admin_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?</p> <p>The show, edit and index of the original resource are not usuable for the administrator.</p>
[ { "answer_id": 107715, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 3, "selected": false, "text": "<p>I have used Streamlined pretty extensively.</p>\n\n<p>To get Streamline working you create your own controllers - so you can actually run it completely apart from the rest of your application, and you can even run it in a separate 'admin' folder and namespace that can be secured with <em></em>.</p>\n\n<p>Here is the Customers controller from a recent app:</p>\n\n<pre><code>class CustomersController &lt; ApplicationController\n layout 'streamlined'\n acts_as_streamlined \n\n Streamlined.ui_for(Customer) do\n exporters :csv \n new_submit_button :ajax =&gt; false \n default_order_options :order =&gt; \"created_at desc\" \n list_columns :name, :email, :mobile, :comments, :action_required_yes_no \n end\nend\n</code></pre>\n" }, { "answer_id": 107736, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 7, "selected": true, "text": "<p>I think namespaces is the solution to the problem you have here:</p>\n\n<pre><code>map.namespace :admin do |admin|\n admin.resources :customers\nend\n</code></pre>\n\n<p>Which will create routes <code>admin_customers</code>, <code>new_admin_customers</code>, etc.</p>\n\n<p>Then inside the <code>app/controller</code> directory you can have an <code>admin</code> directory. Inside your admin directory, create an admin controller:</p>\n\n<pre><code>./script/generate rspec_controller admin/admin\n\nclass Admin::AdminController &lt; ApplicationController\n\n layout \"admin\"\n before_filter :login_required\nend\n</code></pre>\n\n<p>Then create an admin customers controller:</p>\n\n<pre><code>./script/generate rspec_controller admin/customers\n</code></pre>\n\n<p>And make this inhert from your ApplicationController:</p>\n\n<pre><code>class Admin::CustomersController &lt; Admin::AdminController\n</code></pre>\n\n<p>This will look for views in <code>app/views/admin/customers</code>\nand will expect a layout in <code>app/views/layouts/admin.html.erb</code>.</p>\n\n<p>You can then use whichever plugin or code you like to actually do your administration, streamline, ActiveScaffold, whatever personally I like to use <code>resourcecs_controller</code>, as it saves you a lot of time if you use a <a href=\"http://en.wikipedia.org/wiki/Representational_State_Transfer\" rel=\"nofollow noreferrer\">REST</a> style architecture, and forcing yourself down that route can save a lot of time elsewhere. Though if you inherited the application that's a moot point by now.</p>\n" }, { "answer_id": 4941226, "author": "rafamvc", "author_id": 474009, "author_profile": "https://Stackoverflow.com/users/474009", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://github.com/sferik/rails_admin\" rel=\"nofollow\">https://github.com/sferik/rails_admin</a>.</p>\n" }, { "answer_id": 6098222, "author": "phoet", "author_id": 100731, "author_profile": "https://Stackoverflow.com/users/100731", "pm_score": 3, "selected": false, "text": "<p>Do check out active_admin at <a href=\"https://github.com/gregbell/active_admin\" rel=\"nofollow\">https://github.com/gregbell/active_admin</a>.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ]
I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence. How do you create a admin\_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files? The show, edit and index of the original resource are not usuable for the administrator.
I think namespaces is the solution to the problem you have here: ``` map.namespace :admin do |admin| admin.resources :customers end ``` Which will create routes `admin_customers`, `new_admin_customers`, etc. Then inside the `app/controller` directory you can have an `admin` directory. Inside your admin directory, create an admin controller: ``` ./script/generate rspec_controller admin/admin class Admin::AdminController < ApplicationController layout "admin" before_filter :login_required end ``` Then create an admin customers controller: ``` ./script/generate rspec_controller admin/customers ``` And make this inhert from your ApplicationController: ``` class Admin::CustomersController < Admin::AdminController ``` This will look for views in `app/views/admin/customers` and will expect a layout in `app/views/layouts/admin.html.erb`. You can then use whichever plugin or code you like to actually do your administration, streamline, ActiveScaffold, whatever personally I like to use `resourcecs_controller`, as it saves you a lot of time if you use a [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) style architecture, and forcing yourself down that route can save a lot of time elsewhere. Though if you inherited the application that's a moot point by now.
107,675
<p>I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using <a href="http://code.google.com/p/gaeunit" rel="noreferrer">GAEUnit</a>. How can I do this? </p> <p>I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately <a href="http://pythonpaste.org/webtest/" rel="noreferrer">WebTest</a> does not work within the sandbox).</p>
[ { "answer_id": 107753, "author": "David Coffin", "author_id": 13049, "author_profile": "https://Stackoverflow.com/users/13049", "pm_score": 2, "selected": false, "text": "<p>Actually WebTest does work within the sandbox, as long as you comment out </p>\n\n<pre><code>import webbrowser\n</code></pre>\n\n<p>in webtest/__init__.py </p>\n" }, { "answer_id": 114449, "author": "Steve", "author_id": 7424, "author_profile": "https://Stackoverflow.com/users/7424", "pm_score": 4, "selected": false, "text": "<p>I have added a <a href=\"http://code.google.com/p/gaeunit/source/browse/#svn/trunk/sample_app\" rel=\"noreferrer\">sample application</a> to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the '<a href=\"http://pythonpaste.org/webtest/index.html\" rel=\"noreferrer\">webtest</a>' module ('import webbrowser' is commented out, as recommended by David Coffin).</p>\n\n<p>Here's the 'web_tests.py' file from the sample application 'test' directory:</p>\n\n<pre><code>import unittest\nfrom webtest import TestApp\nfrom google.appengine.ext import webapp\nimport index\n\nclass IndexTest(unittest.TestCase):\n\n def setUp(self):\n self.application = webapp.WSGIApplication([('/', index.IndexHandler)], debug=True)\n\n def test_default_page(self):\n app = TestApp(self.application)\n response = app.get('/')\n self.assertEqual('200 OK', response.status)\n self.assertTrue('Hello, World!' in response)\n\n def test_page_with_param(self):\n app = TestApp(self.application)\n response = app.get('/?name=Bob')\n self.assertEqual('200 OK', response.status)\n self.assertTrue('Hello, Bob!' in response)\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13049/" ]
I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using [GAEUnit](http://code.google.com/p/gaeunit). How can I do this? I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately [WebTest](http://pythonpaste.org/webtest/) does not work within the sandbox).
I have added a [sample application](http://code.google.com/p/gaeunit/source/browse/#svn/trunk/sample_app) to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the '[webtest](http://pythonpaste.org/webtest/index.html)' module ('import webbrowser' is commented out, as recommended by David Coffin). Here's the 'web\_tests.py' file from the sample application 'test' directory: ``` import unittest from webtest import TestApp from google.appengine.ext import webapp import index class IndexTest(unittest.TestCase): def setUp(self): self.application = webapp.WSGIApplication([('/', index.IndexHandler)], debug=True) def test_default_page(self): app = TestApp(self.application) response = app.get('/') self.assertEqual('200 OK', response.status) self.assertTrue('Hello, World!' in response) def test_page_with_param(self): app = TestApp(self.application) response = app.get('/?name=Bob') self.assertEqual('200 OK', response.status) self.assertTrue('Hello, Bob!' in response) ```
107,693
<p>I'm having trouble with global variables in php. I have a <code>$screen</code> var set in one file, which requires another file that calls an <code>initSession()</code> defined in yet another file. The <code>initSession()</code> declares <code>global $screen</code> and then processes $screen further down using the value set in the very first script.</p> <p>How is this possible?</p> <p>To make things more confusing, if you try to set $screen again then call the <code>initSession()</code>, it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?</p> <pre><code>$screen = "list1.inc"; // From model.php require "controller.php"; // From model.php initSession(); // From controller.php global $screen; // From Include.Session.inc echo $screen; // prints "list1.inc" // From anywhere $screen = "delete1.inc"; // From model2.php require "controller2.php" initSession(); global $screen; echo $screen; // prints "list1.inc" </code></pre> <p>Update:<br> If I declare <code>$screen</code> global again just before requiring the second model, $screen is updated properly for the <code>initSession()</code> method. Strange.</p>
[ { "answer_id": 107698, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 3, "selected": false, "text": "<p>You need to put \"global $screen\" in every function that references it, not just at the top of each file.</p>\n" }, { "answer_id": 107713, "author": "zobier", "author_id": 18469, "author_profile": "https://Stackoverflow.com/users/18469", "pm_score": 1, "selected": false, "text": "<p>The global scope spans included and required files, you don't need to use the global keyword unless using the variable from within a function. You could try using the $GLOBALS array instead.</p>\n" }, { "answer_id": 107759, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 7, "selected": true, "text": "<p><code>Global</code> DOES NOT make the variable global. I know it's tricky :-)</p>\n\n<p><code>Global</code> says that a local variable will be used <em>as if it was a variable with a higher scope</em>.</p>\n\n<p>E.G :</p>\n\n<pre><code>&lt;?php\n\n$var = \"test\"; // this is accessible in all the rest of the code, even an included one\n\nfunction foo2()\n{\n global $var;\n echo $var; // this print \"test\"\n $var = 'test2';\n}\n\nglobal $var; // this is totally useless, unless this file is included inside a class or function\n\nfunction foo()\n{\n echo $var; // this print nothing, you are using a local var\n $var = 'test3';\n}\n\nfoo();\nfoo2();\necho $var; // this will print 'test2'\n?&gt;\n</code></pre>\n\n<p>Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid <code>global</code> if you can.</p>\n" }, { "answer_id": 107760, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 4, "selected": false, "text": "<p><code>global $foo</code> doesn't mean \"make this variable global, so that everyone can use it\". <code>global $foo</code> means \"<em>within the scope of this function</em>, use the global variable <code>$foo</code>\". </p>\n\n<p>I am assuming from your example that each time, you are referring to $screen from within a function. If so you will need to use <code>global $screen</code> in each function.</p>\n" }, { "answer_id": 107821, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 2, "selected": false, "text": "<p>If you have a lot of variables you want to access during a task which uses many functions, consider making a 'context' object to hold the stuff:</p>\n\n<pre><code>//We're doing \"foo\", and we need importantString and relevantObject to do it\n$fooContext = new StdClass(); //StdClass is an empty class\n$fooContext-&gt;importantString = \"a very important string\";\n$fooContext-&gt;relevantObject = new RelevantObject();\n\ndoFoo($fooContext);\n</code></pre>\n\n<p>Now just pass this object as a parameter to all the functions. You won't need global variables, and your function signatures stay clean. It's also easy to later replace the empty StdClass with a class that actually has relevant methods in it.</p>\n" }, { "answer_id": 11284537, "author": "Brynner Ferreira", "author_id": 548727, "author_profile": "https://Stackoverflow.com/users/548727", "pm_score": 1, "selected": false, "text": "<p>You must declare a variable as global before define values for it.</p>\n" }, { "answer_id": 23926770, "author": "user3651145", "author_id": 3651145, "author_profile": "https://Stackoverflow.com/users/3651145", "pm_score": 0, "selected": false, "text": "<p>It is useless till it is in the function or a class. Global means that you can use a variable in any part of program. So if the global is not contained in the function or a class there is no use of using Global</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
I'm having trouble with global variables in php. I have a `$screen` var set in one file, which requires another file that calls an `initSession()` defined in yet another file. The `initSession()` declares `global $screen` and then processes $screen further down using the value set in the very first script. How is this possible? To make things more confusing, if you try to set $screen again then call the `initSession()`, it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this? ``` $screen = "list1.inc"; // From model.php require "controller.php"; // From model.php initSession(); // From controller.php global $screen; // From Include.Session.inc echo $screen; // prints "list1.inc" // From anywhere $screen = "delete1.inc"; // From model2.php require "controller2.php" initSession(); global $screen; echo $screen; // prints "list1.inc" ``` Update: If I declare `$screen` global again just before requiring the second model, $screen is updated properly for the `initSession()` method. Strange.
`Global` DOES NOT make the variable global. I know it's tricky :-) `Global` says that a local variable will be used *as if it was a variable with a higher scope*. E.G : ``` <?php $var = "test"; // this is accessible in all the rest of the code, even an included one function foo2() { global $var; echo $var; // this print "test" $var = 'test2'; } global $var; // this is totally useless, unless this file is included inside a class or function function foo() { echo $var; // this print nothing, you are using a local var $var = 'test3'; } foo(); foo2(); echo $var; // this will print 'test2' ?> ``` Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid `global` if you can.
107,701
<p>How can I remove those annoying Mac OS X <code>.DS_Store</code> files from a Git repository?</p>
[ { "answer_id": 107703, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": "<p>This will work:</p>\n\n<pre><code>find . -name \"*.DS_Store\" -type f -exec git-rm {} \\;\n</code></pre>\n\n<p>It deletes all files whose names end with <code>.DS_Store</code>, including <code>._.DS_Store</code>.</p>\n" }, { "answer_id": 107711, "author": "Nathan", "author_id": 6062, "author_profile": "https://Stackoverflow.com/users/6062", "pm_score": 3, "selected": false, "text": "<p>delete them using <code>git-rm</code>, and then add .DS_Store to <code>.gitignore</code> to stop them getting added again. You can also use <a href=\"http://www.zeroonetwenty.com/blueharvest/\" rel=\"noreferrer\">blueharvest</a> to stop them getting created all together</p>\n" }, { "answer_id": 107921, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 13, "selected": true, "text": "<p>Remove existing <code>.DS_Store</code> files from the repository:</p>\n<pre><code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch\n</code></pre>\n<p>Add this line:</p>\n<pre><code>.DS_Store\n</code></pre>\n<p>to the file <code>.gitignore</code>, which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory:</p>\n<pre><code>echo .DS_Store &gt;&gt; .gitignore\n</code></pre>\n<p>Then commit the file to the repo:</p>\n<pre><code>git add .gitignore\ngit commit -m '.DS_Store banished!'\n</code></pre>\n" }, { "answer_id": 108108, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 6, "selected": false, "text": "<p>In some situations you may also want to ignore some files globally. For me, .DS_Store is one of them. Here's how:</p>\n\n<pre><code>git config --global core.excludesfile /Users/mat/.gitignore\n</code></pre>\n\n<p>(Or any file of your choice)</p>\n\n<p>Then edit the file just like a repo's .gitignore. Note that I think you have to use an absolute path.</p>\n" }, { "answer_id": 1161174, "author": "manat", "author_id": 136492, "author_profile": "https://Stackoverflow.com/users/136492", "pm_score": 3, "selected": false, "text": "<p>I found that the following line from <a href=\"http://snipplr.com/view/5206/removing-dsstore-files-from-a-git-checkout/\" rel=\"nofollow noreferrer\">snipplr</a> does best on wiping all <code>.DS_Store</code>, including one that has local modifications.</p>\n\n<pre><code>find . -depth -name '.DS_Store' -exec git-rm --cached '{}' \\; -print\n</code></pre>\n\n<p><code>--cached</code> option, keeps your local <code>.DS_Store</code> since it gonna be reproduced anyway.</p>\n\n<p>And just like mentioned all above, add <code>.DS_Store</code> to .gitignore file on the root of your project. Then it will be no longer in your sight (of repos).</p>\n" }, { "answer_id": 3290774, "author": "David Kahn", "author_id": 396882, "author_profile": "https://Stackoverflow.com/users/396882", "pm_score": 4, "selected": false, "text": "<p>I had to change git-rm to git rm in the above to get it to work:</p>\n\n<pre><code>find . -depth -name '.DS_Store' -exec git rm --cached '{}' \\; -print\n</code></pre>\n" }, { "answer_id": 6701239, "author": "Turadg", "author_id": 46040, "author_profile": "https://Stackoverflow.com/users/46040", "pm_score": 8, "selected": false, "text": "<p>Combining benzado and webmat's answers, updating with <code>git rm</code>, not failing on files found that aren't in repo, and making it paste-able generically for any user:</p>\n\n<pre><code># remove any existing files from the repo, skipping over ones not in repo\nfind . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch\n# specify a global exclusion list\ngit config --global core.excludesfile ~/.gitignore\n# adding .DS_Store to that list\necho .DS_Store &gt;&gt; ~/.gitignore\n</code></pre>\n" }, { "answer_id": 7577219, "author": "jordantbro", "author_id": 505359, "author_profile": "https://Stackoverflow.com/users/505359", "pm_score": 3, "selected": false, "text": "<p>The following worked best for me. Handled unmatched files, and files with local modifications. For reference, this was on a Mac 10.7 system running git 1.7.4.4.</p>\n\n<p>Find and remove:</p>\n\n<pre><code>find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch -f\n</code></pre>\n\n<p>I also globally ignore .DS_Store across all repositories by setting a global core.excludesfile.</p>\n\n<p>First, create the file (if one doesn't already exist):</p>\n\n<pre><code>touch ~/.gitignore\n</code></pre>\n\n<p>Then add the following line and save:</p>\n\n<pre><code>.DS_Store\n</code></pre>\n\n<p>Now configure git to respect the file globally:</p>\n\n<pre><code>git config --global core.excludesfile ~/.gitignore\n</code></pre>\n" }, { "answer_id": 7815479, "author": "JZ.", "author_id": 165448, "author_profile": "https://Stackoverflow.com/users/165448", "pm_score": 2, "selected": false, "text": "<pre><code>$ git commit -m \"filter-branch --index-filter 'git rm --cached --ignore-unmatch .DS_Store\"\n$ git push origin master --force\n</code></pre>\n" }, { "answer_id": 11756787, "author": "vinny", "author_id": 1557383, "author_profile": "https://Stackoverflow.com/users/1557383", "pm_score": 2, "selected": false, "text": "<p>There are a few solutions to resolve this problem. \nTo avoid creating .DS_Store files, do not to use the OS X Finder to view folders. An alternative way to view folders is to use UNIX command line.\nTo remove the .DS_Store files a third-party product called DS_Store Terminator can be used.\nTo delete the .DS_Store files from the entire system a UNIX shell command can be used.\nLaunch Terminal from Applications:Utilities\nAt the UNIX shell prompt enter the following UNIX command:\nsudo find / -name \".DS_Store\" -depth -exec rm {} \\;\nWhen prompted for a password enter the Mac OS X Administrator password.</p>\n\n<p>This command is to find and remove all occurrences of .DS_Store starting from the root (/) of the file system through the entire machine.\nTo configure this command to run as a scheduled task follow the steps below:\nLaunch Terminal from Applications:Utilities\nAt the UNIX shell prompt enter the following UNIX command:</p>\n\n<p>sudo crontab -e\nWhen prompted for a password enter the Mac OS X Administrator password.\nOnce in the vi editor press the letter I on your keyboard once and enter the following:</p>\n\n<p>15 1 * * * root find / -name \".DS_Store\" -depth -exec rm {} \\;</p>\n\n<p>This is called crontab entry, which has the following format:</p>\n\n<p>Minute Hour DayOfMonth Month DayOfWeek User Command.</p>\n\n<p>The crontab entry means that the command will be executed by the system automatically at 1:15 AM everyday by the account called root.</p>\n\n<p>The command starts from find all the way to . If the system is not running this command will not get executed.</p>\n\n<p>To save the entry press the Esc key once, then simultaneously press Shift + z+ z.</p>\n\n<p>Note: Information in Step 4 is for the vi editor only.</p>\n" }, { "answer_id": 15921520, "author": "Invincible", "author_id": 968732, "author_profile": "https://Stackoverflow.com/users/968732", "pm_score": 3, "selected": false, "text": "<p>For some reason none of the above worked on my mac.</p>\n\n<p>My solution is from the terminal run:</p>\n\n<pre><code>rm .DS_Store\n</code></pre>\n\n<p>Then run following command:</p>\n\n<pre><code>git pull origin master\n</code></pre>\n" }, { "answer_id": 17628243, "author": "Nerve", "author_id": 1541507, "author_profile": "https://Stackoverflow.com/users/1541507", "pm_score": 8, "selected": false, "text": "<p>The best solution to tackle this issue is to Globally ignore these files from all the git repos on your system. This can be done by creating a global gitignore file like:</p>\n\n<pre><code>vi ~/.gitignore_global\n</code></pre>\n\n<p>Adding Rules for ignoring files like:</p>\n\n<pre><code># Compiled source #\n###################\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# Packages #\n############\n# it's better to unpack these files and commit the raw source\n# git has its own built in compression methods\n*.7z\n*.dmg\n*.gz\n*.iso\n*.jar\n*.rar\n*.tar\n*.zip\n\n# Logs and databases #\n######################\n*.log\n*.sql\n*.sqlite\n\n# OS generated files #\n######################\n.DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nehthumbs.db\nThumbs.db\n</code></pre>\n\n<p>Now, add this file to your global git config:</p>\n\n<pre><code>git config --global core.excludesfile ~/.gitignore_global\n</code></pre>\n\n<p>Edit:</p>\n\n<p>Removed Icons as they might need to be committed as application assets.</p>\n" }, { "answer_id": 23391733, "author": "dav1dhunt", "author_id": 3290784, "author_profile": "https://Stackoverflow.com/users/3290784", "pm_score": 2, "selected": false, "text": "<p>When initializing your repository, skip the git command that contains</p>\n\n<pre><code>-u\n</code></pre>\n\n<p>and it shouldn't be an issue.</p>\n" }, { "answer_id": 23599379, "author": "Reggie Pinkham", "author_id": 2927114, "author_profile": "https://Stackoverflow.com/users/2927114", "pm_score": 6, "selected": false, "text": "<p>If you are unable to remove the files because they have changes staged use: </p>\n\n<pre><code>git rm --cached -f *.DS_Store\n</code></pre>\n" }, { "answer_id": 31681879, "author": "JLunceford", "author_id": 5165885, "author_profile": "https://Stackoverflow.com/users/5165885", "pm_score": 2, "selected": false, "text": "<p>This worked for me, combo of two answers from above:</p>\n\n<ul>\n<li>$ git rm --cached -f *.DS_Store</li>\n<li>$ git commit -m \"filter-branch --index-filter 'git rm --cached\n--ignore-unmatch .DS_Store\"</li>\n<li>$ git push origin master --force</li>\n</ul>\n" }, { "answer_id": 37282582, "author": "Ezequiel García", "author_id": 5984091, "author_profile": "https://Stackoverflow.com/users/5984091", "pm_score": 2, "selected": false, "text": "<p>add this to your file .gitignore</p>\n\n<pre><code>#Ignore folder mac\n.DS_Store\n</code></pre>\n\n<p>save this and make commit </p>\n\n<pre><code>git add -A\ngit commit -m \"ignore .DS_Store\"\n</code></pre>\n\n<p>and now you ignore this for all your commits </p>\n" }, { "answer_id": 40782483, "author": "Karthick Vadivel", "author_id": 1920908, "author_profile": "https://Stackoverflow.com/users/1920908", "pm_score": 5, "selected": false, "text": "<p>Open terminal and type \"cd &lt; ProjectPath >\"</p>\n\n<ol>\n<li><p>Remove existing files:\n<code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch</code></p></li>\n<li><p><code>nano .gitignore</code></p></li>\n<li><p>Add this <code>.DS_Store</code></p></li>\n<li><p>type \"ctrl + x\"</p></li>\n<li><p>Type \"y\"</p></li>\n<li><p>Enter to save file</p></li>\n<li><p><code>git add .gitignore</code></p></li>\n<li><p><code>git commit -m '.DS_Store removed.'</code></p></li>\n</ol>\n" }, { "answer_id": 41011905, "author": "Sunny", "author_id": 6438500, "author_profile": "https://Stackoverflow.com/users/6438500", "pm_score": 4, "selected": false, "text": "<p>Use this command to remove the existing files:</p>\n\n<pre><code>find . -name '*.DS_Store' -type f -delete\n</code></pre>\n\n<p>Then add <code>.DS_Store</code> to <code>.gitignore</code></p>\n" }, { "answer_id": 47029298, "author": "Joshua Dance", "author_id": 1296746, "author_profile": "https://Stackoverflow.com/users/1296746", "pm_score": 5, "selected": false, "text": "<p>Top voted answer is awesome, but helping out the rookies like me, here is how to create the .gitignore file, edit it, save it, remove the files you might have already added to git, then push up the file to Github. </p>\n\n<p><strong>Create the .gitignore file</strong></p>\n\n<p>To create a .gitignore file, you can just <code>touch</code> the file which creates a blank file with the specified name. We want to create the file named .gitignore so we can use the command:</p>\n\n<p><code>touch .gitignore</code></p>\n\n<p><strong>Ignore the files</strong></p>\n\n<p>Now you have to add the line which tells git to ignore the DS Store files to your .gitignore. You can use the nano editor to do this. </p>\n\n<p><code>nano .gitignore</code></p>\n\n<p>Nano is nice because it includes instructions on how to get out of it. (<kbd>Ctrl</kbd>-<kbd>O</kbd> to save, <kbd>Ctrl</kbd>-<kbd>X</kbd> to exit)</p>\n\n<p>Copy and paste some of the ideas from this <a href=\"https://gist.github.com/octocat/9257657\" rel=\"noreferrer\">Github gist</a> which lists some common files to ignore. The most important ones, to answer this question, would be: </p>\n\n<pre><code># OS generated files #\n######################\n.DS_Store\n.DS_Store?\n</code></pre>\n\n<p>The # are comments, and will help you organize your file as it grows.</p>\n\n<p>This <a href=\"https://help.github.com/articles/ignoring-files/\" rel=\"noreferrer\">Github article</a> also has some general ideas and guidelines. </p>\n\n<p><strong>Remove the files already added to git</strong></p>\n\n<p>Finally, you need to actually remove those DS Store files from your directory. </p>\n\n<p>Use this great command from the top voted answer. This will go through all the folders in your directory, and remove those files from git.</p>\n\n<p><code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch</code></p>\n\n<p><strong>Push .gitignore up to Github</strong></p>\n\n<p>Last step, you need to actually commit your .gitignore file. </p>\n\n<p><code>git status</code></p>\n\n<p><code>git add .gitignore</code></p>\n\n<p><code>git commit -m '.DS_Store banished!'</code></p>\n" }, { "answer_id": 47966101, "author": "zeozod", "author_id": 9004603, "author_profile": "https://Stackoverflow.com/users/9004603", "pm_score": 3, "selected": false, "text": "<p>I'm a bit late to the party, but I have a good answer.\nTo remove the .DS_Store files, use the following commands from a terminal window, but be very careful deleting files with 'find'. Using a specific name with the -name option is one of the safer ways to use it:</p>\n\n<pre><code>cd directory/above/affected/workareas\nfind . -name .DS_Store -delete\n</code></pre>\n\n<p>You can leave off the \"-delete\" if you want to simply list them before and after. That will reassure you that they're gone.</p>\n\n<p>With regard to the ~/.gitignore_global advice: be careful here.\nYou want to place that nice file into .gitignore within the\ntop level of each workarea and commit it, so that anyone who clones your repo will gain the benefit of its use.</p>\n" }, { "answer_id": 49066965, "author": "Cubiczx", "author_id": 2053708, "author_profile": "https://Stackoverflow.com/users/2053708", "pm_score": 2, "selected": false, "text": "<p>Remove ignored files:</p>\n\n<p>(.DS_Store)</p>\n\n<pre><code>$ find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch\n</code></pre>\n" }, { "answer_id": 49970762, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>In case you want to remove DS_Store files to every folder and subfolder:\n<hr>\nIn case of already committed DS_Store:</p>\n\n<pre><code>find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch\n</code></pre>\n\n<p>Ignore them by:</p>\n\n<pre><code>echo \".DS_Store\" &gt;&gt; ~/.gitignore_global\necho \"._.DS_Store\" &gt;&gt; ~/.gitignore_global\necho \"**/.DS_Store\" &gt;&gt; ~/.gitignore_global\necho \"**/._.DS_Store\" &gt;&gt; ~/.gitignore_global\ngit config --global core.excludesfile ~/.gitignore_global\n</code></pre>\n" }, { "answer_id": 56650972, "author": "Wael Assaf", "author_id": 6241797, "author_profile": "https://Stackoverflow.com/users/6241797", "pm_score": 2, "selected": false, "text": "<p>No need to remove <code>.DS_STORE</code> locally</p>\n\n<p>Just add it to <code>.gitignore</code> file</p>\n\n<blockquote>\n <p>The .gitignore file is just a text file that tells Git which files or folders to ignore in a project.</p>\n</blockquote>\n\n<p>Commands</p>\n\n<ul>\n<li><code>nano .gitignore</code></li>\n<li>Write <code>.DS_Store</code> Then click <code>CTRL+X &gt; y &gt; Hit Return</code></li>\n<li><code>git status</code> To have a last look at your changes</li>\n<li><code>git add .gitignore</code></li>\n<li><code>git commit -m 'YOUR COMMIT MESSAGE'</code></li>\n<li><code>git push origin master</code></li>\n</ul>\n" }, { "answer_id": 58263198, "author": "2rahulsk", "author_id": 9949370, "author_profile": "https://Stackoverflow.com/users/9949370", "pm_score": 2, "selected": false, "text": "<p>create a <code>.gitignore</code> file using command <code>touch .gitignore</code></p>\n\n<p>and add the following lines in it</p>\n\n<pre><code>.DS_Store\n</code></pre>\n\n<p>save the <code>.gitignore</code> file and then push it in to your git repo.</p>\n" }, { "answer_id": 61207904, "author": "Kasem777", "author_id": 9190334, "author_profile": "https://Stackoverflow.com/users/9190334", "pm_score": 5, "selected": false, "text": "<p>The best way to get rid of this file forever:</p>\n<p>Make a global <code>.gitignore</code> file:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>echo .DS_Store &gt;&gt; ~/.gitignore_global\n</code></pre>\n<p>Let Git know that you want to use this file for all of your repositories:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git config --global core.excludesfile ~/.gitignore_global\n</code></pre>\n<p>That’s it! <code>.DS_Store</code> will be ignored in all repositories.</p>\n" }, { "answer_id": 64747901, "author": "Fernando Comet", "author_id": 1568267, "author_profile": "https://Stackoverflow.com/users/1568267", "pm_score": 0, "selected": false, "text": "<p>I made:</p>\n<pre><code>git checkout -- ../.DS_Store\n</code></pre>\n<p>(# Discarding local changes (permanently) to a file)\nAnd it worked ok!</p>\n" }, { "answer_id": 64850992, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 3, "selected": false, "text": "<h3>Step 1</h3>\n<p>This will remove every <code>.DS_Store</code> file in a directory (including subdirectories)</p>\n<pre class=\"lang-sh prettyprint-override\"><code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch\n</code></pre>\n<h3>Step 2</h3>\n<p>Add this to <code>.gitignore</code> to prevent any DS_Store files in the <strong>root directory <em>and</em> every subdirectory</strong> from going to git!</p>\n<pre><code>**/.DS_Store\n</code></pre>\n<p>From the <a href=\"https://git-scm.com/docs/gitignore\" rel=\"noreferrer\">git docs</a>:</p>\n<blockquote>\n<ul>\n<li>A leading &quot;**&quot; followed by a slash means match in all directories. For example, &quot;**/foo&quot; matches file or directory &quot;foo&quot; anywhere, the same as pattern &quot;foo&quot;. &quot;**/foo/bar&quot; matches file or directory &quot;bar&quot; anywhere that is directly under directory &quot;foo&quot;.</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 66825451, "author": "RajVimalC", "author_id": 8467381, "author_profile": "https://Stackoverflow.com/users/8467381", "pm_score": 5, "selected": false, "text": "<p>Sometimes .DS_Store files are there at remote repository, but not visible at your local project folders. To fix this, we need to remove all cached files and add again.</p>\n<p><strong>Step 1:</strong> Add this to .gitignore file.</p>\n<pre><code># Ignore Mac DS_Store files\n.DS_Store\n**/.DS_Store\n</code></pre>\n<p><strong>Step 2:</strong> Remove the cached files and add again using these commands.</p>\n<pre><code>git rm -r --cached .\ngit add .\ngit commit -am &quot;Removed git ignored files&quot;\ngit push -f origin master\n</code></pre>\n" }, { "answer_id": 74563580, "author": "Maksym Kosenko", "author_id": 11968199, "author_profile": "https://Stackoverflow.com/users/11968199", "pm_score": 0, "selected": false, "text": "<p>For those who have not been helped by any of the above methods - try to inspect your <em><strong>.gitignore</strong></em> more thoroughly, it could have some combination of rules between directories and subdirectories so the annoying <em><strong>.DS_Store</strong></em> files are not ignored in those folders only. For instance you want to ignore <em><strong>gensrc</strong></em> folders except ones in a <em><strong>custom</strong></em> directories, so you would have the following <em><strong>.gitignore</strong></em>:</p>\n<pre><code>.DS_Store\ngensrc\n!custom/**\n</code></pre>\n<p>So with this setup <em><strong>any/path/.DS_Store</strong></em> ignored, but not <em><strong>custom/gensrc/.DS_Store</strong></em> and the fix will be moving <em><strong>.DS_Store</strong></em> entry to the bottom of <em><strong>.gitignore</strong></em> file.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
How can I remove those annoying Mac OS X `.DS_Store` files from a Git repository?
Remove existing `.DS_Store` files from the repository: ``` find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch ``` Add this line: ``` .DS_Store ``` to the file `.gitignore`, which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory: ``` echo .DS_Store >> .gitignore ``` Then commit the file to the repo: ``` git add .gitignore git commit -m '.DS_Store banished!' ```
107,705
<p>Is output buffering enabled by default in Python's interpreter for <code>sys.stdout</code>?</p> <p>If the answer is positive, what are all the ways to disable it?</p> <p>Suggestions so far:</p> <ol> <li>Use the <code>-u</code> command line switch</li> <li>Wrap <code>sys.stdout</code> in an object that flushes after every write</li> <li>Set <code>PYTHONUNBUFFERED</code> env var</li> <li><code>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)</code></li> </ol> <p>Is there any other way to set some global flag in <code>sys</code>/<code>sys.stdout</code> programmatically during execution?</p>
[ { "answer_id": 107717, "author": "Seb", "author_id": 189, "author_profile": "https://Stackoverflow.com/users/189", "pm_score": 10, "selected": true, "text": "<p>From <a href=\"http://mail.python.org/pipermail/tutor/2003-November/026645.html\" rel=\"nofollow noreferrer\">Magnus Lycka answer on a mailing list</a>:</p>\n<blockquote>\n<p>You can skip buffering for a whole\npython process using <code>python -u</code>\nor by\nsetting the environment variable\nPYTHONUNBUFFERED.</p>\n<p>You could also replace sys.stdout with\nsome other stream like wrapper which\ndoes a flush after every call.</p>\n<pre><code>class Unbuffered(object):\n def __init__(self, stream):\n self.stream = stream\n def write(self, data):\n self.stream.write(data)\n self.stream.flush()\n def writelines(self, datas):\n self.stream.writelines(datas)\n self.stream.flush()\n def __getattr__(self, attr):\n return getattr(self.stream, attr)\n\nimport sys\nsys.stdout = Unbuffered(sys.stdout)\nprint 'Hello'\n</code></pre>\n</blockquote>\n" }, { "answer_id": 107720, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": false, "text": "<p>Yes, it is.</p>\n\n<p>You can disable it on the commandline with the \"-u\" switch.</p>\n\n<p>Alternatively, you could call .flush() on sys.stdout on every write (or wrap it with an object that does this automatically)</p>\n" }, { "answer_id": 107721, "author": "Nathan", "author_id": 6062, "author_profile": "https://Stackoverflow.com/users/6062", "pm_score": 4, "selected": false, "text": "<p>Yes, it is enabled by default. You can disable it by using the -u option on the command line when calling python.</p>\n" }, { "answer_id": 107746, "author": "stderr", "author_id": 19556, "author_profile": "https://Stackoverflow.com/users/19556", "pm_score": 2, "selected": false, "text": "<p>One way to get unbuffered output would be to use <code>sys.stderr</code> instead of <code>sys.stdout</code> or to simply call <code>sys.stdout.flush()</code> to explicitly force a write to occur.</p>\n\n<p>You could easily redirect everything printed by doing:</p>\n\n<pre><code>import sys; sys.stdout = sys.stderr\nprint \"Hello World!\"\n</code></pre>\n\n<p>Or to redirect just for a particular <code>print</code> statement:</p>\n\n<pre><code>print &gt;&gt;sys.stderr, \"Hello World!\"\n</code></pre>\n\n<p>To reset stdout you can just do:</p>\n\n<pre><code>sys.stdout = sys.__stdout__\n</code></pre>\n" }, { "answer_id": 107854, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>You can create an unbuffered file and assign this file to sys.stdout.</p>\n\n<pre><code>import sys \nmyFile= open( \"a.log\", \"w\", 0 ) \nsys.stdout= myFile\n</code></pre>\n\n<p>You can't magically change the system-supplied stdout; since it's supplied to your python program by the OS.</p>\n" }, { "answer_id": 181654, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 7, "selected": false, "text": "<pre><code># reopen stdout file descriptor with write mode\n# and 0 as the buffer size (unbuffered)\nimport io, os, sys\ntry:\n # Python 3, open as binary, then wrap in a TextIOWrapper with write-through.\n sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)\n # If flushing on newlines is sufficient, as of 3.7 you can instead just call:\n # sys.stdout.reconfigure(line_buffering=True)\nexcept TypeError:\n # Python 2\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n</code></pre>\n\n<p>Credits: \"Sebastian\", somewhere on the Python mailing list.</p>\n" }, { "answer_id": 1736047, "author": "jimx", "author_id": 47606, "author_profile": "https://Stackoverflow.com/users/47606", "pm_score": 2, "selected": false, "text": "<p>You can also use fcntl to change the file flags in-fly.</p>\n\n<pre><code>fl = fcntl.fcntl(fd.fileno(), fcntl.F_GETFL)\nfl |= os.O_SYNC # or os.O_DSYNC (if you don't care the file timestamp updates)\nfcntl.fcntl(fd.fileno(), fcntl.F_SETFL, fl)\n</code></pre>\n" }, { "answer_id": 3678114, "author": "Mark Seaborn", "author_id": 443562, "author_profile": "https://Stackoverflow.com/users/443562", "pm_score": 4, "selected": false, "text": "<pre><code>def disable_stdout_buffering():\n # Appending to gc.garbage is a way to stop an object from being\n # destroyed. If the old sys.stdout is ever collected, it will\n # close() stdout, which is not good.\n gc.garbage.append(sys.stdout)\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n\n# Then this will give output in the correct order:\ndisable_stdout_buffering()\nprint \"hello\"\nsubprocess.call([\"echo\", \"bye\"])\n</code></pre>\n\n<p>Without saving the old sys.stdout, disable_stdout_buffering() isn't idempotent, and multiple calls will result in an error like this:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"test/buffering.py\", line 17, in &lt;module&gt;\n print \"hello\"\nIOError: [Errno 9] Bad file descriptor\nclose failed: [Errno 9] Bad file descriptor\n</code></pre>\n\n<p>Another possibility is:</p>\n\n<pre><code>def disable_stdout_buffering():\n fileno = sys.stdout.fileno()\n temp_fd = os.dup(fileno)\n sys.stdout.close()\n os.dup2(temp_fd, fileno)\n os.close(temp_fd)\n sys.stdout = os.fdopen(fileno, \"w\", 0)\n</code></pre>\n\n<p>(Appending to gc.garbage is not such a good idea because it's where unfreeable cycles get put, and you might want to check for those.)</p>\n" }, { "answer_id": 11276965, "author": "Laimis", "author_id": 1493464, "author_profile": "https://Stackoverflow.com/users/1493464", "pm_score": 2, "selected": false, "text": "<p>Variant that works without crashing (at least on win32; python 2.7, ipython 0.12) then called subsequently (multiple times):</p>\n\n<pre><code>def DisOutBuffering():\n if sys.stdout.name == '&lt;stdout&gt;':\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n\n if sys.stderr.name == '&lt;stderr&gt;':\n sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)\n</code></pre>\n" }, { "answer_id": 14729823, "author": "Cristóvão D. Sousa", "author_id": 1062531, "author_profile": "https://Stackoverflow.com/users/1062531", "pm_score": 8, "selected": false, "text": "<p>I would rather put my answer in <a href=\"https://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print\">How to flush output of print function?</a> or in <a href=\"https://stackoverflow.com/questions/3895481/pythons-print-function-that-flushes-the-buffer-when-its-called\">Python&#39;s print function that flushes the buffer when it&#39;s called?</a>, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.</p>\n\n<p>Since Python 3.3, print() supports the keyword argument \"flush\" (<a href=\"http://docs.python.org/3/library/functions.html?highlight=print#print\" rel=\"noreferrer\">see documentation</a>):</p>\n\n<pre><code>print('Hello World!', flush=True)\n</code></pre>\n" }, { "answer_id": 17047064, "author": "tzp", "author_id": 1278711, "author_profile": "https://Stackoverflow.com/users/1278711", "pm_score": 2, "selected": false, "text": "<p>(I've posted a comment, but it got lost somehow. So, again:)</p>\n\n<ol>\n<li><p>As I noticed, CPython (at least on Linux) behaves differently depending on where the output goes. If it goes to a tty, then the output is flushed after each '<code>\\n'</code>\n<br/>If it goes to a pipe/process, then it is buffered and you can use the <code>flush()</code> based solutions or the <strong>-u</strong> option recommended above.</p></li>\n<li><p>Slightly related to output buffering:<br/>\nIf you iterate over the lines in the input with</p>\n\n<p><code>for line in sys.stdin:</code>\n<br/>...</p></li>\n</ol>\n\n<p>then the <strong>for</strong> implementation in <strong>CPython</strong> will collect the input for a while and then execute the loop body for a bunch of input lines. If your script is about to write output for each input line, this might look like output buffering but it's actually batching, and therefore, none of the <code>flush()</code>, etc. techniques will help that.\nInterestingly, you don't have this behaviour in <strong>pypy</strong>.\nTo avoid this, you can use</p>\n\n<p><code>while True:\n line=sys.stdin.readline()</code>\n<br/>...</p>\n" }, { "answer_id": 23034580, "author": "Gummbum", "author_id": 3527428, "author_profile": "https://Stackoverflow.com/users/3527428", "pm_score": 4, "selected": false, "text": "<p>The following works in Python 2.6, 2.7, and 3.2:</p>\n\n<pre><code>import os\nimport sys\nbuf_arg = 0\nif sys.version_info[0] == 3:\n os.environ['PYTHONUNBUFFERED'] = '1'\n buf_arg = 1\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)\nsys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)\n</code></pre>\n" }, { "answer_id": 31170728, "author": "dyomas", "author_id": 1329132, "author_profile": "https://Stackoverflow.com/users/1329132", "pm_score": 3, "selected": false, "text": "<p>You can also run Python with <a href=\"https://www.gnu.org/software/coreutils/manual/html_node/stdbuf-invocation.html\" rel=\"noreferrer\" title=\"stdbuf\">stdbuf</a> utility:</p>\n\n<p><code>stdbuf -oL python &lt;script&gt;</code></p>\n" }, { "answer_id": 40161931, "author": "Tim", "author_id": 3734258, "author_profile": "https://Stackoverflow.com/users/3734258", "pm_score": 5, "selected": false, "text": "<p>This relates to Cristóvão D. Sousa's answer, but I couldn't comment yet.</p>\n\n<p>A straight-forward way of using the <code>flush</code> keyword argument of <em>Python 3</em> in order to <strong>always</strong> have unbuffered output is:</p>\n\n<pre><code>import functools\nprint = functools.partial(print, flush=True)\n</code></pre>\n\n<p>afterwards, print will always flush the output directly (except <code>flush=False</code> is given).</p>\n\n<p>Note, (a) that this answers the question only partially as it doesn't redirect all the output. But I guess <code>print</code> is the most common way for creating output to <code>stdout</code>/<code>stderr</code> in python, so these 2 lines cover probably most of the use cases.</p>\n\n<p>Note (b) that it only works in the module/script where you defined it. This can be good when writing a module as it doesn't mess with the <code>sys.stdout</code>.</p>\n\n<p><em>Python 2</em> doesn't provide the <code>flush</code> argument, but you could emulate a Python 3-type <code>print</code> function as described here <a href=\"https://stackoverflow.com/a/27991478/3734258\">https://stackoverflow.com/a/27991478/3734258</a> .</p>\n" }, { "answer_id": 42461528, "author": "Vasily E.", "author_id": 7623015, "author_profile": "https://Stackoverflow.com/users/7623015", "pm_score": 2, "selected": false, "text": "<p>It is possible to override <em>only</em> <code>write</code> method of <code>sys.stdout</code> with one that calls <code>flush</code>. Suggested method implementation is below.</p>\n\n<pre><code>def write_flush(args, w=stdout.write):\n w(args)\n stdout.flush()\n</code></pre>\n\n<p>Default value of <code>w</code> argument will keep original <code>write</code> method reference. <em>After</em> <code>write_flush</code> is defined, the original <code>write</code> might be overridden.</p>\n\n<pre><code>stdout.write = write_flush\n</code></pre>\n\n<p>The code assumes that <code>stdout</code> is imported this way <code>from sys import stdout</code>.</p>\n" }, { "answer_id": 53488262, "author": "Oliver", "author_id": 869951, "author_profile": "https://Stackoverflow.com/users/869951", "pm_score": 4, "selected": false, "text": "<p>In Python 3, you can monkey-patch the print function, to always send flush=True:</p>\n\n<pre><code>_orig_print = print\n\ndef print(*args, **kwargs):\n _orig_print(*args, flush=True, **kwargs)\n</code></pre>\n\n<p>As pointed out in a comment, you can simplify this by binding the flush parameter to a value, via <code>functools.partial</code>:</p>\n\n<pre><code>print = functools.partial(print, flush=True)\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Is output buffering enabled by default in Python's interpreter for `sys.stdout`? If the answer is positive, what are all the ways to disable it? Suggestions so far: 1. Use the `-u` command line switch 2. Wrap `sys.stdout` in an object that flushes after every write 3. Set `PYTHONUNBUFFERED` env var 4. `sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)` Is there any other way to set some global flag in `sys`/`sys.stdout` programmatically during execution?
From [Magnus Lycka answer on a mailing list](http://mail.python.org/pipermail/tutor/2003-November/026645.html): > > You can skip buffering for a whole > python process using `python -u` > or by > setting the environment variable > PYTHONUNBUFFERED. > > > You could also replace sys.stdout with > some other stream like wrapper which > does a flush after every call. > > > > ``` > class Unbuffered(object): > def __init__(self, stream): > self.stream = stream > def write(self, data): > self.stream.write(data) > self.stream.flush() > def writelines(self, datas): > self.stream.writelines(datas) > self.stream.flush() > def __getattr__(self, attr): > return getattr(self.stream, attr) > > import sys > sys.stdout = Unbuffered(sys.stdout) > print 'Hello' > > ``` > >
107,772
<p>From my understanding the XMPP protocol is based on an always-on connection where you have no, immediate, indication of when an XML message ends.</p> <p>This means you have to evaluate the stream as it comes. This also means that, probably, you have to deal with asynchronous connections since the socket can block in the middle of an XML message, either due to message length or a connection being slow.</p> <p>I would appreciate one source per answer so we can mod them up and see what's the favourite.</p>
[ { "answer_id": 107820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Igniterealtime.org provides an open source XMPP-server and client written in java</p>\n" }, { "answer_id": 108307, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "<p><A HREF=\"http://www.ejabberd.im/\" rel=\"nofollow noreferrer\">ejabberd</A> is written in Erlang. I don't know the details of the ejabberd implementation, but one advantage of using Erlang is really inexpensive threads. I'll speculate they start a thread per XMPP connection. In Erlang terminology these would be called processes, but these are not protected-memory address spaces they are lightweight user-space threads.</p>\n" }, { "answer_id": 110215, "author": "Joe Hildebrand", "author_id": 8388, "author_profile": "https://Stackoverflow.com/users/8388", "pm_score": 2, "selected": true, "text": "<p>Are you wanting to deal with multiple connections at once? Good asynch socket processing is a must in that case, to avoid one thread per connection.</p>\n\n<p>Otherwise, you just need an XML parser that can deal with a chunk of bytes at a time. <a href=\"http://expat.sourceforge.net/\" rel=\"nofollow noreferrer\">Expat</a> is the canonical example; if you're in Java, try <a href=\"http://www.jclark.com/xml/xp/\" rel=\"nofollow noreferrer\">XP</a>. These types of XML parsers will fire events as possible, and buffer partial stanzas until the rest arrives.</p>\n\n<p>Now, to address your assertion that there is no notification when a <em>stanza</em> ends, that's not really true. The important thing is not to process the XML stream as if it is a sequence of documents. Use the following pseudo-code:</p>\n\n<pre><code>stanza = null\nwhile parser has more:\n switch on token type:\n START_TAG:\n elem = create element from parser state\n if stanza is not null:\n add elem as child of stanza\n stanza = elem\n END_TAG:\n parent = parent of stanza\n if parent is not null:\n fire OnStanza event\n stanza = parent\n</code></pre>\n\n<p>This approach should work with an event-based or pull parser. It only requires holding on to one pointer worth of state. Obviously, you'll also need to handle attributes, character data, entity references (like &amp;amp; and the like), and special-purpose the stream:stream tag, but this should get you started.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
From my understanding the XMPP protocol is based on an always-on connection where you have no, immediate, indication of when an XML message ends. This means you have to evaluate the stream as it comes. This also means that, probably, you have to deal with asynchronous connections since the socket can block in the middle of an XML message, either due to message length or a connection being slow. I would appreciate one source per answer so we can mod them up and see what's the favourite.
Are you wanting to deal with multiple connections at once? Good asynch socket processing is a must in that case, to avoid one thread per connection. Otherwise, you just need an XML parser that can deal with a chunk of bytes at a time. [Expat](http://expat.sourceforge.net/) is the canonical example; if you're in Java, try [XP](http://www.jclark.com/xml/xp/). These types of XML parsers will fire events as possible, and buffer partial stanzas until the rest arrives. Now, to address your assertion that there is no notification when a *stanza* ends, that's not really true. The important thing is not to process the XML stream as if it is a sequence of documents. Use the following pseudo-code: ``` stanza = null while parser has more: switch on token type: START_TAG: elem = create element from parser state if stanza is not null: add elem as child of stanza stanza = elem END_TAG: parent = parent of stanza if parent is not null: fire OnStanza event stanza = parent ``` This approach should work with an event-based or pull parser. It only requires holding on to one pointer worth of state. Obviously, you'll also need to handle attributes, character data, entity references (like &amp; and the like), and special-purpose the stream:stream tag, but this should get you started.
107,823
<p>(Jeopardy-style question, I wish the answer had been online when I had this issue)</p> <p>Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.</p> <p>But I found that my program would leak memory over time. What am I doing wrong?</p>
[ { "answer_id": 107832, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 7, "selected": true, "text": "<p>This is a known bug in Java 1.4:\n<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087\" rel=\"noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087</a></p>\n\n<p>It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.</p>\n\n<p>The issue is that, at construction time, a <code>Thread</code> is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.</p>\n\n<p>So, never create a thread unless you're definitely going to call its <code>start()</code> method. A <code>Thread</code> object's <code>run()</code> method should not be called directly.</p>\n\n<p>A better way to code it is to implement the <code>Runnable</code> interface rather than subclass <code>Thread</code>. When you don't need a thread, call</p>\n\n<pre><code>myRunnable.run();\n</code></pre>\n\n<p>When you do need a thread:</p>\n\n<pre><code>Thread myThread = new Thread(myRunnable);\nmyThread.start();\n</code></pre>\n" }, { "answer_id": 107835, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>Let's see if we could get nearer to the core of the problem:</p>\n\n<p>If you start your program (lets say) 1000 x using start(), then 1000 x using run() in a thread, do both loose memory? If so, then your algorithm should be checked (i.e. for outer objects such as Vectors used in your Runnable).</p>\n\n<p>If there is no such memory leak as described above then you should investigate about starting parameters and memory usage of threads regarding the JVM.</p>\n" }, { "answer_id": 107937, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>I doubt that constructing an instance of a Thread or a subclass thereof leaks memory. Firstly, there's nothing of the sorts mentioned in the Javadocs or the Java Language Specification. Secondly, I ran a simple test and it also shows that no memory is leaked (at least not on Sun's JDK 1.5.0_05 on 32-bit x86 Linux 2.6):</p>\n\n<pre><code>public final class Test {\n public static final void main(String[] params) throws Exception {\n final Runtime rt = Runtime.getRuntime();\n long i = 0;\n while(true) {\n new MyThread().run();\n i++;\n if ((i % 100) == 0) {\n System.out.println((i / 100) + \": \" + (rt.freeMemory() / 1024 / 1024) + \" \" + (rt.totalMemory() / 1024 / 1024));\n }\n }\n }\n\n static class MyThread extends Thread {\n private final byte[] tmp = new byte[10 * 1024 * 1024];\n\n public void run() {\n System.out.print(\".\");\n }\n }\n}\n</code></pre>\n\n<p>EDIT: Just to summarize the idea of the test above. Every instance of the MyThread subclass of a Thread references its own 10 MB array. If instances of MyThread weren't garbage-collected, the JVM would run out of memory pretty quickly. However, running the test code shows that the JVM is using a small constant amount of memory regardless of the number of MyThreads constructed so far. I claim this is because instances of MyThread are garbage-collected.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7512/" ]
(Jeopardy-style question, I wish the answer had been online when I had this issue) Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed. But I found that my program would leak memory over time. What am I doing wrong?
This is a known bug in Java 1.4: <http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087> It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4. The issue is that, at construction time, a `Thread` is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected. So, never create a thread unless you're definitely going to call its `start()` method. A `Thread` object's `run()` method should not be called directly. A better way to code it is to implement the `Runnable` interface rather than subclass `Thread`. When you don't need a thread, call ``` myRunnable.run(); ``` When you do need a thread: ``` Thread myThread = new Thread(myRunnable); myThread.start(); ```
107,828
<p>I don't want <code>PHP</code> errors to display /html, but I want them to display in <code>/html/beta/usercomponent</code>. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?</p>
[ { "answer_id": 107841, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 0, "selected": false, "text": "<p><strike>I don't believe there's a simple answer to this</strike>, but I'd certainly want to be proven wrong.</p>\n\n<p>edit: turns out this can be controlled from .htaccess files. Thanks people! :)</p>\n\n<p>You can use error_reporting() <a href=\"http://docs.php.net/manual/en/function.error-reporting.php\" rel=\"nofollow noreferrer\">http://docs.php.net/manual/en/function.error-reporting.php</a> to switch the setting on a script by script basis, though. If you happen to have a single script which is included every time at /html/beta/usercomponent, this will do the trick.</p>\n" }, { "answer_id": 107843, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 6, "selected": true, "text": "<p>In <code>.htaccess</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>php_value error_reporting 2147483647\n</code></pre>\n\n<p>This number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run </p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>php -r 'echo E_ALL | E_STRICT ;'\n</code></pre>\n\n<p>to let php compute the value for you.</p>\n\n<p>You need </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>AllowOverride All\n</code></pre>\n\n<p>in apaches master configuration to enable .htaccess files. </p>\n\n<p>More Reading on this can be found here: </p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting\" rel=\"noreferrer\">Php/Error Reporting Flag</a></li>\n<li><a href=\"http://php.net/manual/en/errorfunc.constants.php\" rel=\"noreferrer\">Php/Error Reporting values</a></li>\n<li><a href=\"http://php.net/manual/en/configuration.changes.php\" rel=\"noreferrer\">Php/Different Ways of Tuning Settings</a></li>\n</ul>\n\n<hr>\n\n<p><strong>Notice</strong> If you are using Php-CGI instead of mod_php, this may not work as advertised, and all you will get is an internal server error, and you will be left without much option other than enabling it either site-wide on a per-script basis with </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>error_reporting( E_ALL | E_STRICT ); \n</code></pre>\n\n<p>or similar constructs before the error occurs. </p>\n\n<p>My advice is to <strong>disable</strong> displaying errors to the user, and utilize heavily php's error_log feature. </p>\n\n<pre class=\"lang-ini prettyprint-override\"><code>display_errors = 0\nerror_logging = E_ALL | E_STRICT \nerror_log = /var/log/php \n</code></pre>\n\n<p>If you have problems with this being too noisy, this is not a sign you need to just take error reporting off selectively, this is a sign somebody should fix the code.</p>\n\n<hr>\n\n<p>@Roger</p>\n\n<p>Yes, you can use it in a <code>&lt;<code></code>Directory></code> construct in apaches configuration too, however, the .htaccess in this case is equivalent, and makes it more portable especially if you have multiple working checkout copies of the same codebase and you want to distribute this change to all of them.</p>\n\n<p>If you have multiple virtual hosts, you'll want the construct in the respective virtual hosts definition, otherwise, yes</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> &lt;Directory /path/to/wherever/on/filesystem&gt; \n &lt;IfModule mod_php5.c&gt;\n php_value error_reporting 214748364\n &lt;/IfModule&gt;\n &lt;/Directory&gt;\n</code></pre>\n\n<p>The Additional \"ifmodule\" commands are just a safety net so the above problem with apache dying if you don't have mod_php won't occur. </p>\n" }, { "answer_id": 107849, "author": "Twan", "author_id": 6702, "author_profile": "https://Stackoverflow.com/users/6702", "pm_score": 2, "selected": false, "text": "<p>The easiest way would be to control the error reporting from a .htaccess file. But this is assuming you are using Apache and the scripts in /html/beta/usercomponent are called from that directory and not included from elsewhere.</p>\n\n<p>.htacess</p>\n\n<pre><code>php_value error_reporting [int]\n</code></pre>\n\n<p>You will have to compose the integer value yourself from the list as described in the <a href=\"http://nl3.php.net/manual/en/function.error-reporting.php\" rel=\"nofollow noreferrer\">error_reporting</a> documentation, since the constants like E_ERROR aren't defined when Apache interprets the .htaccess.</p>\n\n<p>It's a simple bitwise flag, so a value of 12, for example, would be E_WARNING + E_PARSE + E_NOTICE.</p>\n" }, { "answer_id": 108982, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 2, "selected": false, "text": "<p>you could do this by using an Environment variable. this way you can have more choices than just turning Error reporting on/off for a special directory. in your code where ever you wanted to change any behaviour for a specific set of directoris, or running modes, check if a environment variable is set or not. like this:</p>\n\n<pre><code>if ($_ENV['MY_PHP_APP_MODE'] == 'devel') {\n // show errors and debugging info\n} elseif ($_ENV['MY_PHP_APP_MODE'] == 'production') {\n // show some cool message to the user so he won't freak out\n // log the errors and send email to the admin\n}\n</code></pre>\n\n<p>and when you are running your application in your development environment, you can set an env variable in your .htaccess file like this:</p>\n\n<pre><code> setenv MY_PHP_APP_MODE devel\n</code></pre>\n\n<p>or when you are in production evn:</p>\n\n<pre><code> setenv MY_PHP_APP_MODE production\n</code></pre>\n\n<p>the same technique applies to your situation. in directories where you want to do something special (turn on error reporting) set some env variable and in your code, check for that.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't want `PHP` errors to display /html, but I want them to display in `/html/beta/usercomponent`. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?
In `.htaccess`: ```none php_value error_reporting 2147483647 ``` This number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run ```bash php -r 'echo E_ALL | E_STRICT ;' ``` to let php compute the value for you. You need ```none AllowOverride All ``` in apaches master configuration to enable .htaccess files. More Reading on this can be found here: * [Php/Error Reporting Flag](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) * [Php/Error Reporting values](http://php.net/manual/en/errorfunc.constants.php) * [Php/Different Ways of Tuning Settings](http://php.net/manual/en/configuration.changes.php) --- **Notice** If you are using Php-CGI instead of mod\_php, this may not work as advertised, and all you will get is an internal server error, and you will be left without much option other than enabling it either site-wide on a per-script basis with ```php error_reporting( E_ALL | E_STRICT ); ``` or similar constructs before the error occurs. My advice is to **disable** displaying errors to the user, and utilize heavily php's error\_log feature. ```ini display_errors = 0 error_logging = E_ALL | E_STRICT error_log = /var/log/php ``` If you have problems with this being too noisy, this is not a sign you need to just take error reporting off selectively, this is a sign somebody should fix the code. --- @Roger Yes, you can use it in a `<Directory>` construct in apaches configuration too, however, the .htaccess in this case is equivalent, and makes it more portable especially if you have multiple working checkout copies of the same codebase and you want to distribute this change to all of them. If you have multiple virtual hosts, you'll want the construct in the respective virtual hosts definition, otherwise, yes ```xml <Directory /path/to/wherever/on/filesystem> <IfModule mod_php5.c> php_value error_reporting 214748364 </IfModule> </Directory> ``` The Additional "ifmodule" commands are just a safety net so the above problem with apache dying if you don't have mod\_php won't occur.
107,872
<p>I have <a href="http://laconi.ca/trac/" rel="nofollow noreferrer">Laconica</a> (self hosted <a href="http://twitter.com/home" rel="nofollow noreferrer">twitter</a>) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part. How can I do this?</p>
[ { "answer_id": 107874, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": true, "text": "<p>You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractive output.</p>\n<p><strong>Result screen shot:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/dMlja.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dMlja.jpg\" alt=\"Screenshot of Laconica update stream in SharePoint Team Site\" /></a></p>\n\n<p><strong>XSL transform:</strong></p>\n<pre><code>&lt;xsl:stylesheet xmlns:x=&quot;http://www.w3.org/2001/XMLSchema&quot; version=&quot;1.0&quot; exclude-result-prefixes=&quot;xsl ddwrt msxsl rssaggwrt&quot;\n xmlns:ddwrt=&quot;http://schemas.microsoft.com/WebParts/v2/DataView/runtime&quot;\n xmlns:rssaggwrt=&quot;http://schemas.microsoft.com/WebParts/v3/rssagg/runtime&quot;\n xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;\n xmlns:msxsl=&quot;urn:schemas-microsoft-com:xslt&quot;\n xmlns:rssFeed=&quot;urn:schemas-microsoft-com:sharepoint:RSSAggregatorWebPart&quot;\n xmlns:rdf=&quot;http://www.w3.org/1999/02/22-rdf-syntax-ns#&quot;\n xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot;\n xmlns:rss=&quot;http://purl.org/rss/1.0/&quot;\n xmlns:atom=&quot;http://www.w3.org/2005/Atom&quot;\n xmlns:itunes=&quot;http://www.itunes.com/dtds/podcast-1.0.dtd&quot;\n xmlns:atom2=&quot;http://purl.org/atom/ns#&quot;\n xmlns:ddwrt2=&quot;urn:frontpage:internal&quot;\n xmlns:laconica=&quot;http://laconi.ca/ont/&quot;&gt;\n &lt;xsl:param name=&quot;rss_FeedLimit&quot;&gt;5&lt;/xsl:param&gt;\n &lt;xsl:param name=&quot;rss_ExpandFeed&quot;&gt;false&lt;/xsl:param&gt;\n &lt;xsl:param name=&quot;rss_LCID&quot;&gt;1033&lt;/xsl:param&gt;\n &lt;xsl:param name=&quot;rss_WebPartID&quot;&gt;RSS_Viewer_WebPart&lt;/xsl:param&gt;\n &lt;xsl:param name=&quot;rss_alignValue&quot;&gt;left&lt;/xsl:param&gt;\n &lt;xsl:param name=&quot;rss_IsDesignMode&quot;&gt;True&lt;/xsl:param&gt;\n &lt;xsl:template match=&quot;rdf:RDF&quot;&gt;\n &lt;xsl:call-template name=&quot;RDFMainTemplate&quot;/&gt;\n &lt;/xsl:template&gt;\n &lt;xsl:template name=&quot;RDFMainTemplate&quot; xmlns:ddwrt=&quot;http://schemas.microsoft.com/WebParts/v2/DataView/runtime&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:msxsl=&quot;urn:schemas-microsoft-com:xslt&quot;&gt;\n &lt;xsl:variable name=&quot;Rows&quot; select=&quot;rss:item&quot;/&gt;\n &lt;xsl:variable name=&quot;RowCount&quot; select=&quot;count($Rows)&quot;/&gt;\n &lt;div class=&quot;slm-layout-main&quot; &gt;\n &lt;xsl:call-template name=&quot;RDFMainTemplate.body&quot;&gt;\n &lt;xsl:with-param name=&quot;Rows&quot; select=&quot;$Rows&quot;/&gt;\n &lt;xsl:with-param name=&quot;RowCount&quot; select=&quot;count($Rows)&quot;/&gt;\n &lt;/xsl:call-template&gt;\n &lt;/div&gt;\n &lt;/xsl:template&gt;\n &lt;xsl:template name=&quot;RDFMainTemplate.body&quot; xmlns:ddwrt=&quot;http://schemas.microsoft.com/WebParts/v2/DataView/runtime&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:msxsl=&quot;urn:schemas-microsoft-com:xslt&quot;&gt;\n &lt;xsl:param name=&quot;Rows&quot;/&gt;\n &lt;xsl:param name=&quot;RowCount&quot;/&gt;\n &lt;xsl:for-each select=&quot;$Rows&quot;&gt;\n &lt;xsl:variable name=&quot;CurPosition&quot; select=&quot;position()&quot; /&gt;\n &lt;xsl:variable name=&quot;RssFeedLink&quot; select=&quot;$rss_WebPartID&quot; /&gt;\n &lt;xsl:variable name=&quot;CurrentElement&quot; select=&quot;concat($RssFeedLink,$CurPosition)&quot; /&gt;\n &lt;xsl:if test=&quot;($CurPosition &amp;lt;= $rss_FeedLimit)&quot;&gt;\n &lt;xsl:element name=&quot;div&quot;&gt;\n &lt;xsl:if test=&quot;($CurPosition mod 2 = 1)&quot;&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[background-color:#F9F9F9;]]&gt;&lt;/xsl:attribute&gt;\n &lt;/xsl:if&gt;\n &lt;xsl:element name=&quot;table&quot;&gt;\n &lt;xsl:attribute name=&quot;cellpadding&quot;&gt;0&lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=&quot;border&quot;&gt;0&lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[margin:0px;padding:0px;border-spacing:0px;background-color:transparent;]]&gt;&lt;/xsl:attribute&gt;\n &lt;xsl:element name=&quot;tr&quot;&gt;\n &lt;xsl:element name=&quot;td&quot;&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]&gt;&lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=&quot;rowspan&quot;&gt;2&lt;/xsl:attribute&gt;\n &lt;xsl:element name=&quot;img&quot;&gt;\n &lt;xsl:attribute name=&quot;src&quot;&gt;&lt;xsl:value-of select=&quot;laconica:postIcon/@rdf:resource&quot;/&gt;&lt;/xsl:attribute&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[margin:3px;height:48px;width:48px;]]&gt;&lt;/xsl:attribute&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;xsl:element name=&quot;td&quot;&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]&gt;&lt;/xsl:attribute&gt;\n &lt;div&gt;\n &lt;strong&gt;&lt;xsl:value-of select=&quot;substring-before(rss:title, ':')&quot;/&gt;&lt;/strong&gt;\n &lt;/div&gt;\n &lt;div style=&quot;width:300px;overflow-x:hidden;&quot;&gt;\n &lt;div&gt;\n &lt;xsl:value-of select=&quot;substring-after(rss:title, ':')&quot;/&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;xsl:element name=&quot;tr&quot;&gt;\n &lt;xsl:element name=&quot;td&quot;&gt;\n &lt;xsl:attribute name=&quot;style&quot;&gt;&lt;![CDATA[padding:0px;background-color:transparent;]]&gt;&lt;/xsl:attribute&gt;\n &lt;xsl:element name=&quot;a&quot;&gt;\n &lt;xsl:attribute name=&quot;href&quot;&gt;&lt;xsl:value-of select=&quot;rss:link&quot;/&gt;&lt;/xsl:attribute&gt;\n &lt;xsl:value-of select=&quot;ddwrt:FormatDate(dc:date,number($rss_LCID),15)&quot;/&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 798356, "author": "Evan P.", "author_id": 95734, "author_profile": "https://Stackoverflow.com/users/95734", "pm_score": 0, "selected": false, "text": "<p>I like the RSS idea. Another option would be to create a Laconica plugin and hook the EndNoticeSave event to push notices to SharePoint.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I have [Laconica](http://laconi.ca/trac/) (self hosted [twitter](http://twitter.com/home)) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part. How can I do this?
You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractive output. **Result screen shot:** [![Screenshot of Laconica update stream in SharePoint Team Site](https://i.stack.imgur.com/dMlja.jpg)](https://i.stack.imgur.com/dMlja.jpg) **XSL transform:** ``` <xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" version="1.0" exclude-result-prefixes="xsl ddwrt msxsl rssaggwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:rssFeed="urn:schemas-microsoft-com:sharepoint:RSSAggregatorWebPart" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rss="http://purl.org/rss/1.0/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom2="http://purl.org/atom/ns#" xmlns:ddwrt2="urn:frontpage:internal" xmlns:laconica="http://laconi.ca/ont/"> <xsl:param name="rss_FeedLimit">5</xsl:param> <xsl:param name="rss_ExpandFeed">false</xsl:param> <xsl:param name="rss_LCID">1033</xsl:param> <xsl:param name="rss_WebPartID">RSS_Viewer_WebPart</xsl:param> <xsl:param name="rss_alignValue">left</xsl:param> <xsl:param name="rss_IsDesignMode">True</xsl:param> <xsl:template match="rdf:RDF"> <xsl:call-template name="RDFMainTemplate"/> </xsl:template> <xsl:template name="RDFMainTemplate" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <xsl:variable name="Rows" select="rss:item"/> <xsl:variable name="RowCount" select="count($Rows)"/> <div class="slm-layout-main" > <xsl:call-template name="RDFMainTemplate.body"> <xsl:with-param name="Rows" select="$Rows"/> <xsl:with-param name="RowCount" select="count($Rows)"/> </xsl:call-template> </div> </xsl:template> <xsl:template name="RDFMainTemplate.body" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <xsl:param name="Rows"/> <xsl:param name="RowCount"/> <xsl:for-each select="$Rows"> <xsl:variable name="CurPosition" select="position()" /> <xsl:variable name="RssFeedLink" select="$rss_WebPartID" /> <xsl:variable name="CurrentElement" select="concat($RssFeedLink,$CurPosition)" /> <xsl:if test="($CurPosition &lt;= $rss_FeedLimit)"> <xsl:element name="div"> <xsl:if test="($CurPosition mod 2 = 1)"> <xsl:attribute name="style"><![CDATA[background-color:#F9F9F9;]]></xsl:attribute> </xsl:if> <xsl:element name="table"> <xsl:attribute name="cellpadding">0</xsl:attribute> <xsl:attribute name="border">0</xsl:attribute> <xsl:attribute name="style"><![CDATA[margin:0px;padding:0px;border-spacing:0px;background-color:transparent;]]></xsl:attribute> <xsl:element name="tr"> <xsl:element name="td"> <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute> <xsl:attribute name="rowspan">2</xsl:attribute> <xsl:element name="img"> <xsl:attribute name="src"><xsl:value-of select="laconica:postIcon/@rdf:resource"/></xsl:attribute> <xsl:attribute name="style"><![CDATA[margin:3px;height:48px;width:48px;]]></xsl:attribute> </xsl:element> </xsl:element> <xsl:element name="td"> <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute> <div> <strong><xsl:value-of select="substring-before(rss:title, ':')"/></strong> </div> <div style="width:300px;overflow-x:hidden;"> <div> <xsl:value-of select="substring-after(rss:title, ':')"/> </div> </div> </xsl:element> </xsl:element> <xsl:element name="tr"> <xsl:element name="td"> <xsl:attribute name="style"><![CDATA[padding:0px;background-color:transparent;]]></xsl:attribute> <xsl:element name="a"> <xsl:attribute name="href"><xsl:value-of select="rss:link"/></xsl:attribute> <xsl:value-of select="ddwrt:FormatDate(dc:date,number($rss_LCID),15)"/> </xsl:element> </xsl:element> </xsl:element> </xsl:element> </xsl:element> </xsl:if> </xsl:for-each> </xsl:template> </xsl:stylesheet> ```
107,903
<p>On Mac OS X, you can create a zip archive from the Finder by selecting some files and selecting "Compress" from the contextual menu or the File menu. Unfortunately, the resulting file is not identical to the archive created by the <code>zip</code> command (with the default options).</p> <p>This distinction matters to at least one service operated by Apple, which fails to accept archives created with the <code>zip</code> command. Having to create archives manually is preventing me from fully automating my release build process.</p> <p>How can I create a zip archive in the correct format within a shell script?</p> <p>EDIT: Since writing this question long ago, I've figured out that the key difference between <code>ditto</code> and <code>zip</code> is how they handle symbolic links: because the code signature inside an app bundle contains a symlink, it needs to be preserved as a link and not stored as a regular file. <code>ditto</code> does this by default, but <code>zip</code> does not (option <code>-y</code> is required).</p>
[ { "answer_id": 107920, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The clue's in the tag 'automation'.</p>\n\n<p>Create an action in Automator.app that uses the 'Create Archive' action, invoke it from the command-line (see 'automator').</p>\n" }, { "answer_id": 107938, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 5, "selected": true, "text": "<p>Use the ditto command-line tool as follows:</p>\n\n<pre><code>ditto -ck --rsrc --sequesterRsrc folder file.zip\n</code></pre>\n\n<p>See the <a href=\"https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/ditto.1.html\" rel=\"noreferrer\">ditto man page</a> for more.</p>\n" }, { "answer_id": 2473201, "author": "Jared Egan", "author_id": 296900, "author_profile": "https://Stackoverflow.com/users/296900", "pm_score": 4, "selected": false, "text": "<p>I have a ruby script that makes iPhone App Store builds for me, but the zips it was generating wouldn't get accepted by iTunes Connect. They were accepted if I used Finder's \"Compress\" function.</p>\n\n<p>millenomi's answer came close for me, but this command is what ended up working. iTunes Connect accepted my build, and the app got approved and can be downloaded no problem, so it's tested.</p>\n\n<pre><code>ditto -c -k --sequesterRsrc --keepParent AppName.app AppName.zip\n</code></pre>\n" }, { "answer_id": 4230992, "author": "valexa", "author_id": 314546, "author_profile": "https://Stackoverflow.com/users/314546", "pm_score": 4, "selected": false, "text": "<p>man ditto states:</p>\n\n<blockquote>\n<pre><code> The command:\n ditto -c -k --sequesterRsrc --keepParent src_directory archive.zip\n will create a PKZip archive similarly to the Finder's Compress functionality.\n</code></pre>\n</blockquote>\n\n<p>notice --keepParent</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10947/" ]
On Mac OS X, you can create a zip archive from the Finder by selecting some files and selecting "Compress" from the contextual menu or the File menu. Unfortunately, the resulting file is not identical to the archive created by the `zip` command (with the default options). This distinction matters to at least one service operated by Apple, which fails to accept archives created with the `zip` command. Having to create archives manually is preventing me from fully automating my release build process. How can I create a zip archive in the correct format within a shell script? EDIT: Since writing this question long ago, I've figured out that the key difference between `ditto` and `zip` is how they handle symbolic links: because the code signature inside an app bundle contains a symlink, it needs to be preserved as a link and not stored as a regular file. `ditto` does this by default, but `zip` does not (option `-y` is required).
Use the ditto command-line tool as follows: ``` ditto -ck --rsrc --sequesterRsrc folder file.zip ``` See the [ditto man page](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/ditto.1.html) for more.
107,936
<p>Is there a way to add some custom font on a website without using images, <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> or some other graphics?</p> <p>For example, I was working on a wedding website, and I found a lot of nice fonts for that subject. But I can't find the right way to add that font on the server. And how do I include that font with CSS into the HTML? Is this possible to do without graphics?</p>
[ { "answer_id": 107945, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 3, "selected": false, "text": "<p>Or you could try <a href=\"http://en.wikipedia.org/wiki/Scalable_Inman_Flash_Replacement\" rel=\"nofollow noreferrer\">sIFR</a>. I know it uses Flash, but only if available. If Flash isn't available, it displays the original text in its original (CSS) font.</p>\n" }, { "answer_id": 107947, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 4, "selected": false, "text": "<p>I've found that the easiest way to have non-standard fonts on a website is to use <strong><a href=\"http://en.wikipedia.org/wiki/Scalable_Inman_Flash_Replacement\" rel=\"nofollow noreferrer\">sIFR</a></strong></p>\n\n<p>It does involve the use of a Flash object that contains the font, but it degrades nicely to standard text / font if Flash is not installed.</p>\n\n<p>The style is set in your CSS, and JavaScript sets up the Flash replacement for your text.</p>\n\n<p><strong>Edit: (I still recommend using images for non-standard fonts as sIFR adds time to a project and can require maintenance).</strong></p>\n" }, { "answer_id": 107951, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 10, "selected": true, "text": "<p>This could be done via CSS:</p>\n<pre><code>&lt;style type=&quot;text/css&quot;&gt;\n@font-face {\n font-family: &quot;My Custom Font&quot;;\n src: url(http://www.example.org/mycustomfont.ttf) format(&quot;truetype&quot;);\n}\np.customfont { \n font-family: &quot;My Custom Font&quot;, Verdana, Tahoma;\n}\n&lt;/style&gt;\n&lt;p class=&quot;customfont&quot;&gt;Hello world!&lt;/p&gt;\n</code></pre>\n<p>It is <a href=\"http://www.w3schools.com/cssref/css3_pr_font-face_rule.asp\" rel=\"noreferrer\">supported for all of the regular browsers</a> if you use TrueType-Fonts (TTF), the Web Open Font Format (WOFF) or Embedded Opentype (EOT).</p>\n" }, { "answer_id": 107955, "author": "James Muscat", "author_id": 11643, "author_profile": "https://Stackoverflow.com/users/11643", "pm_score": 2, "selected": false, "text": "<p>It looks like it only works in Internet Explorer, but a quick Google search for \"html embed fonts\" yields <a href=\"http://www.spoono.com/html/tutorials/tutorial.php?id=19\" rel=\"nofollow noreferrer\">http://www.spoono.com/html/tutorials/tutorial.php?id=19</a></p>\n\n<p>If you want to stay platform-agnostic (and you should!) you'll have to use images, or else just use a standard font.</p>\n" }, { "answer_id": 107956, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<p>The technique that the W3C has recommended for do this is called \"embedding\" and is well described by the three articles here: <a href=\"http://www.allgraphicdesign.com/downloadfonts/fontsarticles/embeddingfonts/csswebsitespages.html\" rel=\"nofollow noreferrer\">Embedding Fonts</a>. In my limited experiments, I have found this process error-prone and have had limited success in making it function in a multi-browser environment.</p>\n" }, { "answer_id": 107963, "author": "zobier", "author_id": 18469, "author_profile": "https://Stackoverflow.com/users/18469", "pm_score": 2, "selected": false, "text": "<p>Safari and Internet Explorer both support the CSS @font-face rule, however they support two different embedded font types. Firefox is planning to support the same type as Apple some time soon. SVG can embed fonts but isn't that widely supported yet (without a plugin).</p>\n\n<p>I think the most portable solution I've seen is to use a JavaScript function to replace headings etc. with an image generated and cached on the server with your font of choice -- that way you simply update the text and don't have to stuff around in Photoshop.</p>\n" }, { "answer_id": 107967, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>If you use ASP.NET, it's really easy to generate image based fonts without actually having to install (as in adding to the installed font base) fonts on the server by using:</p>\n\n<pre><code>PrivateFontCollection pfont = new PrivateFontCollection();\npfont.AddFontFile(filename);\nFontFamily ff = pfont.Families[0];\n</code></pre>\n\n<p>and then drawing with that font onto a <code>Graphics</code>.</p>\n" }, { "answer_id": 107976, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>I did a bit of research and dug up <em><a href=\"http://www.alistapart.com/articles/dynatext/\" rel=\"nofollow noreferrer\">Dynamic Text Replacement</a></em> (published 2004-06-15).</p>\n\n<p>This technique uses images, but it appears to be \"hands free\". You write your text, and you let a few automated scripts do automated find-and-replace on the page for you on the fly. </p>\n\n<p>It has some limitations, but it is probably one of the easier choices (and more browser compatible) than all the rest I've seen.</p>\n" }, { "answer_id": 588297, "author": "brendanjerwin", "author_id": 52972, "author_profile": "https://Stackoverflow.com/users/52972", "pm_score": 4, "selected": false, "text": "<p>The article <em><a href=\"http://jontangerine.com/log/2008/10/font-face-in-ie-making-web-fonts-work\" rel=\"nofollow noreferrer\">Font-face in IE: Making Web Fonts Work</a></em> says it works with all three major browsers.</p>\n\n<p>Here is a sample I got working: <a href=\"http://brendanjerwin.com/test_font.html\" rel=\"nofollow noreferrer\">http://brendanjerwin.com/test_font.html</a></p>\n\n<p>More discussion is in <em><a href=\"http://brendanjerwin.com/development/web/2009/03/03/embedding-fonts.html\" rel=\"nofollow noreferrer\">Embedding Fonts</a></em>.</p>\n" }, { "answer_id": 849036, "author": "Thomas", "author_id": 104914, "author_profile": "https://Stackoverflow.com/users/104914", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://typeface.neocracy.org/\" rel=\"nofollow noreferrer\">Typeface.js</a> and <a href=\"http://wiki.github.com/sorccu/cufon\" rel=\"nofollow noreferrer\">Cufon</a> are two other interesting options. They are JavaScript components that render special font data in JSON format (which you can convert from <a href=\"http://en.wikipedia.org/wiki/TrueType\" rel=\"nofollow noreferrer\">TrueType</a> or <a href=\"http://en.wikipedia.org/wiki/OpenType\" rel=\"nofollow noreferrer\">OpenType</a> formats on their web sites) via the new &lt;canvas> element in all newer browsers except Internet&nbsp;Explorer and via <a href=\"http://en.wikipedia.org/wiki/Vector_Markup_Language\" rel=\"nofollow noreferrer\">VML</a> in Internet&nbsp;Explorer.</p>\n\n<p>The main problem with both (as of now) is that selecting text does not work or at least works only quite awkwardly.</p>\n\n<p>Still, it is very nice for headlines. Body text... I don't know.</p>\n\n<p>And it's surprisingly fast.</p>\n" }, { "answer_id": 2582737, "author": "Blair", "author_id": 169164, "author_profile": "https://Stackoverflow.com/users/169164", "pm_score": 2, "selected": false, "text": "<p>See the article <em><a href=\"http://www.smashingmagazine.com/2009/01/27/css-typographic-tools-and-techniques/\" rel=\"nofollow noreferrer\">50 Useful Design Tools For Beautiful Web Typography</a></em> for alternative methods.</p>\n\n<p>I have only used <a href=\"http://wiki.github.com/sorccu/cufon/\" rel=\"nofollow noreferrer\">Cufon</a>. I have found it reliable and very easy to use, so I've stuck with it.</p>\n" }, { "answer_id": 2941236, "author": "bakkal", "author_id": 238639, "author_profile": "https://Stackoverflow.com/users/238639", "pm_score": 2, "selected": false, "text": "<p><strong>Typeface.js JavaScript Way:</strong></p>\n\n<blockquote>\n <p>With typeface.js you can embed custom\n fonts in your web pages so you don't\n have to render text to images</p>\n \n <p>Instead of creating images or using\n flash just to show your site's graphic\n text in the font you want, you can use\n typeface.js and write in plain HTML\n and CSS, just as if your visitors had\n the font installed locally.</p>\n</blockquote>\n\n<p><a href=\"http://typeface.neocracy.org/\" rel=\"nofollow noreferrer\">http://typeface.neocracy.org/</a></p>\n" }, { "answer_id": 3130621, "author": "Michał Pękała", "author_id": 298858, "author_profile": "https://Stackoverflow.com/users/298858", "pm_score": 7, "selected": false, "text": "<p>You can add some fonts via <a href=\"http://www.google.com/fonts/\" rel=\"noreferrer\">Google Web Fonts</a>.</p>\n\n<p>Technically, the fonts are hosted at Google and you link them in the HTML header. Then, you can use them freely in CSS with <a href=\"http://www.w3.org/TR/css3-fonts/#font-face-rule\" rel=\"noreferrer\"><code>@font-face</code></a> (<a href=\"http://www.css3.info/preview/web-fonts-with-font-face/\" rel=\"noreferrer\">read about it</a>).</p>\n\n<p>For example:</p>\n\n<p>In the <code>&lt;head&gt;</code> section:</p>\n\n<pre><code> &lt;link href=' http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'&gt;\n</code></pre>\n\n<p>Then in CSS:</p>\n\n<pre><code>h1 { font-family: 'Droid Sans', arial, serif; }\n</code></pre>\n\n<hr>\n\n<p>The solution seems quite reliable (even <a href=\"http://www.smashingmagazine.com/\" rel=\"noreferrer\">Smashing Magazine uses it for an article title.</a>). There are, however, not so many fonts available so far in <a href=\"http://www.google.com/fonts/\" rel=\"noreferrer\">Google Font Directory</a>.</p>\n" }, { "answer_id": 12391656, "author": "BiAiB", "author_id": 521257, "author_profile": "https://Stackoverflow.com/users/521257", "pm_score": 4, "selected": false, "text": "<p>If by non standard font, you mean custom font of a standard format, here's how I do it, and it works for all browsers I've checked so far:</p>\n\n<pre><code>@font-face {\n font-family: TempestaSevenCondensed;\n src: url(\"../fonts/pf_tempesta_seven_condensed.eot\") /* EOT file for IE */\n}\n@font-face {\n font-family: TempestaSevenCondensed;\n src: url(\"../fonts/pf_tempesta_seven_condensed.ttf\") /* TTF file for CSS3 browsers */\n}\n</code></pre>\n\n<p>so you'll just need both the ttf and eot fonts. Some tools available online can make the conversion.</p>\n\n<p>But if you want to attach font in a non standard format (bitmaps etc), I can't help you.</p>\n" }, { "answer_id": 21959207, "author": "Wilf", "author_id": 2943276, "author_profile": "https://Stackoverflow.com/users/2943276", "pm_score": 2, "selected": false, "text": "<p>It is also possible to use WOFF fonts - example <a href=\"https://encrypted.pcode.nl/blog/wp-content/themes/simplest-pcode/style.css\" rel=\"nofollow\">here</a></p>\n\n<pre><code>@font-face {\nfont-family: 'Plakat Fraktur';\nsrc: url('/resources/fonts/plakat-fraktur-black-modified.woff') format('woff');\nfont-weight: bold;\nfont-style: normal;\n }\n</code></pre>\n" }, { "answer_id": 22738998, "author": "Javier Cadiz", "author_id": 1373105, "author_profile": "https://Stackoverflow.com/users/1373105", "pm_score": 6, "selected": false, "text": "<p>The way to go is using the @font-face CSS declaration which allows authors to specify online fonts to display text on their web pages. By allowing authors to provide their own fonts, @font-face eliminates the need to depend on the limited number of fonts users have installed on their computers.</p>\n\n<p>Take a look at the following table:</p>\n\n<p><img src=\"https://i.stack.imgur.com/fFhYS.png\" alt=\"enter image description here\"> </p>\n\n<p>As you can see, there are several formats that you need to know about mainly due to cross-browser compatibility. The scenario in mobile devices isn't much different.</p>\n\n<h2>Solutions:</h2>\n\n<p><strong>1 - Full browser compatibility</strong></p>\n\n<p>This is the method with the deepest support possible right now:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>@font-face {\n font-family: 'MyWebFont';\n src: url('webfont.eot'); /* IE9 Compat Modes */\n src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */\n url('webfont.woff') format('woff'), /* Modern Browsers */\n url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */\n url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */\n}\n</code></pre>\n\n<p><strong>2 - Most of the browser</strong></p>\n\n<p>Things are <a href=\"http://caniuse.com/#feat=woff\" rel=\"noreferrer\">shifting heavily toward WOFF</a> though, so you can probably get away with:</p>\n\n<pre><code>@font-face {\n font-family: 'MyWebFont';\n src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */\n url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */\n}\n</code></pre>\n\n<p><strong>3 - Only the latest browsers</strong></p>\n\n<p>Or even just WOFF.<br>\nYou then use it like this:</p>\n\n<pre><code>body {\n font-family: 'MyWebFont', Fallback, sans-serif;\n}\n</code></pre>\n\n<h2>References and Further reading:</h2>\n\n<p>That's mainly what you need to know about implementing this feature. If you want to research more on the subject I'll encourage to take a look at the following resources. Most of what I put here is extracted from the following</p>\n\n<ul>\n<li><a href=\"http://css-tricks.com/snippets/css/using-font-face/\" rel=\"noreferrer\">Using Font Face</a> (Very recommended)</li>\n<li><a href=\"http://www.paulirish.com/2009/bulletproof-font-face-implementation-syntax/\" rel=\"noreferrer\">Bulletproof @font-face syntax</a></li>\n<li><a href=\"http://caniuse.com/fontface\" rel=\"noreferrer\">Can i use @font-face web fonts ?</a></li>\n<li><a href=\"http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/\" rel=\"noreferrer\">How to archive Cross-Browser @font-face support</a></li>\n<li><a href=\"http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/\" rel=\"noreferrer\">@font-face at the CSS Mozilla Developer Network</a></li>\n</ul>\n" }, { "answer_id": 35331561, "author": "saadeez", "author_id": 5906920, "author_profile": "https://Stackoverflow.com/users/5906920", "pm_score": 2, "selected": false, "text": "<p>If you have a file of your font, then you will need to add more formats of that font for other browsers. </p>\n\n<p>For this purpose I use font generator like <a href=\"http://www.fontsquirrel.com/tools/webfont-generator\" rel=\"nofollow\">Fontsquirrel</a> it provides all the font formats &amp; its @font-face CSS, you will only need to just drag &amp; drop it into your CSS file.</p>\n" }, { "answer_id": 47240004, "author": "Abhijeet Kumar", "author_id": 6207701, "author_profile": "https://Stackoverflow.com/users/6207701", "pm_score": 2, "selected": false, "text": "<p>Just simply provide the link to actual font like this and you will be good to go</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet'&gt;\n&lt;style&gt;\nbody {\nfont-family: 'Montserrat';font-size: 22px;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;h1&gt;Montserrat&lt;/h1&gt;\n&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit.&lt;/p&gt;\n\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 64129171, "author": "Hello Hack", "author_id": 8734258, "author_profile": "https://Stackoverflow.com/users/8734258", "pm_score": 1, "selected": false, "text": "<pre><code>@font-face {\nfont-family: &quot;CustomFont&quot;;\nsrc: url(&quot;CustomFont.eot&quot;);\nsrc: url(&quot;CustomFont.woff&quot;) format(&quot;woff&quot;),\nurl(&quot;CustomFont.otf&quot;) format(&quot;opentype&quot;),\nurl(&quot;CustomFont.svg#filename&quot;) format(&quot;svg&quot;);\n}\n</code></pre>\n" }, { "answer_id": 71880291, "author": "Ajay Sahu", "author_id": 12799742, "author_profile": "https://Stackoverflow.com/users/12799742", "pm_score": 0, "selected": false, "text": "<p>easy solution is to use @fontface in css</p>\n<pre><code>@font-face {\nfont-family: myFirstFont;\nsrc: url(fileLocation);} \n\ndiv{\n font-family: myfirstfont;}\n</code></pre>\n" }, { "answer_id": 74317500, "author": "github host2", "author_id": 20372154, "author_profile": "https://Stackoverflow.com/users/20372154", "pm_score": 0, "selected": false, "text": "<p>You can use <code>@import url(url)</code> to import web fonts. You must replace <code>url</code> with the font source (full web source).</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16039/" ]
Is there a way to add some custom font on a website without using images, [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) or some other graphics? For example, I was working on a wedding website, and I found a lot of nice fonts for that subject. But I can't find the right way to add that font on the server. And how do I include that font with CSS into the HTML? Is this possible to do without graphics?
This could be done via CSS: ``` <style type="text/css"> @font-face { font-family: "My Custom Font"; src: url(http://www.example.org/mycustomfont.ttf) format("truetype"); } p.customfont { font-family: "My Custom Font", Verdana, Tahoma; } </style> <p class="customfont">Hello world!</p> ``` It is [supported for all of the regular browsers](http://www.w3schools.com/cssref/css3_pr_font-face_rule.asp) if you use TrueType-Fonts (TTF), the Web Open Font Format (WOFF) or Embedded Opentype (EOT).
107,964
<p>I am using YUI reset/base, after the reset it sets the <code>ul</code> and <code>li</code> tags to list-style: disc outside;</p> <p>My markup looks like this:</p> <pre><code>&lt;div id="nav"&gt; &lt;ul class="links"&gt; &lt;li&gt;&lt;a href=""&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>My CSS is:</p> <pre><code>#nav {} #nav ul li { list-style: none; } </code></pre> <p>Now that makes the small disc beside each li disappear.</p> <p>Why doesn't this work though?</p> <pre><code> #nav {} #nav ul.links { list-style: none; } </code></pre> <p>It works if I remove the link to the base.css file, why?.</p> <p>Updated: <code>sidenav</code> -> <code>nav</code></p>
[ { "answer_id": 107965, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 1, "selected": false, "text": "<p>shouldn't it be:</p>\n\n<pre><code>#nav ul.links\n</code></pre>\n" }, { "answer_id": 107969, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 0, "selected": false, "text": "<p>Maybe the style is the base.css overrides your styles with \"!important\"? Did you try to add a class to this specific li and make an own style for it?</p>\n" }, { "answer_id": 107983, "author": "Josti", "author_id": 11231, "author_profile": "https://Stackoverflow.com/users/11231", "pm_score": 2, "selected": false, "text": "<p>In the first snippet you apply the list-style to the li element, in the second to the ul element.</p>\n\n<p>Try</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#nav ul.links li\n{\n list-style: none;\n}\n</code></pre>\n" }, { "answer_id": 107996, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>The latter example probably doesn't work because of <a href=\"http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html\" rel=\"nofollow noreferrer\">CSS specificity</a>. (A more serious explanation can be found <a href=\"http://www.htmldog.com/guides/cssadvanced/specificity/\" rel=\"nofollow noreferrer\">here</a>.) That is, YUI's base.css rule is:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>ul li{ list-style: disc outside; }\n</code></pre>\n\n<p>This is more 'specific' than yours, so the YUI rule is being used. As has been noted several times, you can make your rule more specific by targeting the <code>li</code> tags:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#nav ul li{ list-style: none; }\n</code></pre>\n\n<p>Hard to say for sure without looking at your code, but if you don't know about specificity it's certainly worth a read.</p>\n" }, { "answer_id": 108008, "author": "vaske", "author_id": 16039, "author_profile": "https://Stackoverflow.com/users/16039", "pm_score": 0, "selected": false, "text": "<p>Use this one:</p>\n\n<pre><code>.nav ul li {\n list-style: none;\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>.links li {\n list-style: none;\n}\n</code></pre>\n\n<p>it should work...</p>\n" }, { "answer_id": 110309, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": true, "text": "<p>I think that Dan was close with his answer, but this isn't an issue of specificity. <strong>You can set the list-style on the list (the UL) but you can also override that list-style for individual list items (the LIs).</strong></p>\n\n<p>You are telling the browser to not use bullets on the list, but YUI tells the browser to use them on individual list items (YUI wins):</p>\n\n<pre><code>ul li{ list-style: disc outside; } /* in YUI base.css */\n\n#nav ul.links {\n list-style: none; /* doesn't override styles for LIs, just the UL */\n}\n</code></pre>\n\n<p>What you want is to tell the browser not to use them on the list items:</p>\n\n<pre><code>ul li{ list-style: disc outside; } /* in YUI base.css */\n\n#nav ul.links li {\n list-style: none;\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I am using YUI reset/base, after the reset it sets the `ul` and `li` tags to list-style: disc outside; My markup looks like this: ``` <div id="nav"> <ul class="links"> <li><a href="">Testing</a></li> </ul> </div> ``` My CSS is: ``` #nav {} #nav ul li { list-style: none; } ``` Now that makes the small disc beside each li disappear. Why doesn't this work though? ``` #nav {} #nav ul.links { list-style: none; } ``` It works if I remove the link to the base.css file, why?. Updated: `sidenav` -> `nav`
I think that Dan was close with his answer, but this isn't an issue of specificity. **You can set the list-style on the list (the UL) but you can also override that list-style for individual list items (the LIs).** You are telling the browser to not use bullets on the list, but YUI tells the browser to use them on individual list items (YUI wins): ``` ul li{ list-style: disc outside; } /* in YUI base.css */ #nav ul.links { list-style: none; /* doesn't override styles for LIs, just the UL */ } ``` What you want is to tell the browser not to use them on the list items: ``` ul li{ list-style: disc outside; } /* in YUI base.css */ #nav ul.links li { list-style: none; } ```
107,971
<p>I'm using the following JavaScript code:</p> <pre><code>&lt;script language="JavaScript1.2" type="text/javascript"&gt; function CreateBookmarkLink(title, url) { if (window.sidebar) { window.sidebar.addPanel(title, url,""); } else if( window.external ) { window.external.AddFavorite( url, title); } else if(window.opera &amp;&amp; window.print) { return true; } } &lt;/script&gt; </code></pre> <p>This will create a bookmark for Firefox and IE. But the link for Firefox will show up in the sidepanel of the browser, instead of being displayed in the main screen. I personally find this very annoying and am looking for a better solution. It is of course possible to edit the bookmark manually to have it <em>not</em> show up in the side panel, but that requires extra steps. I just want to be able to have people bookmark a page (that has a lot of GET information in the URL which is used to build a certain scheme) the easy way.</p> <p>I'm afraid that it might not be possible to have Firefox present the page in the main screen at all (as Googling this subject resulted in practically nothing worth using), but I might have missed something. If anyone has an idea if this is possible, or if there's a workaround, I'd love to hear about it.</p>
[ { "answer_id": 107985, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>You have a special case for </p>\n\n<pre><code>if (window.sidebar) \n</code></pre>\n\n<p>and then a branch for 'else' - wouldn't firefox land in the first branch and hence only add the panel?</p>\n" }, { "answer_id": 107993, "author": "iBobo", "author_id": 10567, "author_profile": "https://Stackoverflow.com/users/10567", "pm_score": 3, "selected": true, "text": "<p>I think that's the only solution for Firefox... I have a better function for that action, it works even for Opera and shows a message for other \"unsupported\" browsers.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction addBookmark(url,name){\n if(window.sidebar &amp;&amp; window.sidebar.addPanel) {\n window.sidebar.addPanel(name,url,''); //obsolete from FF 23.\n} else if(window.opera &amp;&amp; window.print) { \n var e=document.createElement('a');\n e.setAttribute('href',url);\n e.setAttribute('title',name);\n e.setAttribute('rel','sidebar');\n e.click();\n} else if(window.external) {\n try {\n window.external.AddFavorite(url,name);\n }\n catch(e){}\n}\nelse\n alert(\"To add our website to your bookmarks use CTRL+D on Windows and Linux and Command+D on the Mac.\");\n}\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 108011, "author": "Michiel", "author_id": 18922, "author_profile": "https://Stackoverflow.com/users/18922", "pm_score": 0, "selected": false, "text": "<p>Hojou,</p>\n\n<p>It seems that is the only way to add a bookmark for Firefox. So FF needs to land in the first branch to have anything happening at all. I Googled some more but I'm really getting the idea this is impossible to properly address in FF...</p>\n" }, { "answer_id": 9080361, "author": "Atul Kushwah", "author_id": 1179998, "author_profile": "https://Stackoverflow.com/users/1179998", "pm_score": 3, "selected": false, "text": "<p>For Firefox no need to set any JavaScript for the bookmark an page by script, only an anchor tag with <strong>title</strong> and <strong>rel=\"sidebar\"</strong> can do this functionality</p>\n\n<pre><code>&lt;a href=\"http://www.google.com\" title=\"Google\" rel=\"sidebar\"&gt;Bookmark This Page&lt;/a&gt;\n</code></pre>\n\n<p>I have tested it on FF9 and its working fine. </p>\n\n<p>When you click on the link, Firefox will open an dialog box <strong>New Bookmark</strong> and if you wish to not load this bookmark on side bar then un-check <strong>Load this bookmark in the sidebar</strong> from dialog box. </p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18922/" ]
I'm using the following JavaScript code: ``` <script language="JavaScript1.2" type="text/javascript"> function CreateBookmarkLink(title, url) { if (window.sidebar) { window.sidebar.addPanel(title, url,""); } else if( window.external ) { window.external.AddFavorite( url, title); } else if(window.opera && window.print) { return true; } } </script> ``` This will create a bookmark for Firefox and IE. But the link for Firefox will show up in the sidepanel of the browser, instead of being displayed in the main screen. I personally find this very annoying and am looking for a better solution. It is of course possible to edit the bookmark manually to have it *not* show up in the side panel, but that requires extra steps. I just want to be able to have people bookmark a page (that has a lot of GET information in the URL which is used to build a certain scheme) the easy way. I'm afraid that it might not be possible to have Firefox present the page in the main screen at all (as Googling this subject resulted in practically nothing worth using), but I might have missed something. If anyone has an idea if this is possible, or if there's a workaround, I'd love to hear about it.
I think that's the only solution for Firefox... I have a better function for that action, it works even for Opera and shows a message for other "unsupported" browsers. ``` <script type="text/javascript"> function addBookmark(url,name){ if(window.sidebar && window.sidebar.addPanel) { window.sidebar.addPanel(name,url,''); //obsolete from FF 23. } else if(window.opera && window.print) { var e=document.createElement('a'); e.setAttribute('href',url); e.setAttribute('title',name); e.setAttribute('rel','sidebar'); e.click(); } else if(window.external) { try { window.external.AddFavorite(url,name); } catch(e){} } else alert("To add our website to your bookmarks use CTRL+D on Windows and Linux and Command+D on the Mac."); } </script> ```
107,972
<p>Is it possible under any set of circumstances to be able to accomplish this?</p> <p>My current circumstances are this:</p> <pre><code>public class CustomForm : Form { public class CustomGUIElement { ... public event MouseEventHandler Click; // etc, and so forth. ... } private List&lt;CustomGUIElement&gt; _elements; ... public void CustomForm_Click(object sender, MouseEventArgs e) { // we might want to call one of the _elements[n].Click in here // but we can't because we aren't in the same class. } } </code></pre> <p>My first thought was to have a function similar to:</p> <pre><code>internal enum GUIElementHandlers { Click, ... } internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) { switch (h) { case Click: this.Click(this, (EventArgs)args[0]); break; ... // etc and so forth } } </code></pre> <p>It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas?</p>
[ { "answer_id": 107978, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>You really should wrap the code you want to be able to execute from the outside in a method. That method can then do whatever your event would do - and that event would also instead call that method.</p>\n" }, { "answer_id": 107979, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": "<p>You just need to add a public method for invoking the event. Microsoft already does this for some events such as <em>PerformClick</em> for controls that expose a <em>Click</em> event.</p>\n\n<pre><code>public class CustomGUIElement \n{\n public void PerformClick()\n {\n OnClick(EventArgs.Empty);\n }\n\n protected virtual void OnClick(EventArgs e)\n {\n if (Click != null)\n Click(this, e);\n }\n}\n</code></pre>\n\n<p>You would then do the following inside your example event handler...</p>\n\n<pre><code>public void CustomForm_Click(object sender, MouseEventArgs e) \n{\n _elements[0].PerformClick();\n}\n</code></pre>\n" }, { "answer_id": 112125, "author": "Lee", "author_id": 13943, "author_profile": "https://Stackoverflow.com/users/13943", "pm_score": 3, "selected": false, "text": "<p>The event keyword in c# modifies the declaration of the delegate. It prevents direct assignment to the delegate (you can only use += and -= on an event), and it prevents invocation of the delegate from outside the class.</p>\n\n<p>So you could alter your code to look like this:</p>\n\n<pre><code>public class CustomGUIElement\n{\n...\n public MouseEventHandler Click;\n // etc, and so forth.\n...\n}\n</code></pre>\n\n<p>Then you can invoke the event from outside the class like this.</p>\n\n<pre><code>myCustomGUIElement.Click(sender,args);\n</code></pre>\n\n<p>The drawback is that code using the class can overwrite any registered handlers very easily with code like this:</p>\n\n<pre><code>myCustomGUIElement.Click = null;\n</code></pre>\n\n<p>which is not allowed if the Click delegate is declared as an event.</p>\n" }, { "answer_id": 57007130, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 2, "selected": false, "text": "<p>You can shorten the code suggested in the accepted answer a lot using the modern syntax feature of the .NET framework:</p>\n\n<pre><code>public event Action&lt;int&gt; RecipeSelected;\npublic void RaiseRecpeSelected(int recipe) =&gt; RecipeSelected?.Invoke(recipe);\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Is it possible under any set of circumstances to be able to accomplish this? My current circumstances are this: ``` public class CustomForm : Form { public class CustomGUIElement { ... public event MouseEventHandler Click; // etc, and so forth. ... } private List<CustomGUIElement> _elements; ... public void CustomForm_Click(object sender, MouseEventArgs e) { // we might want to call one of the _elements[n].Click in here // but we can't because we aren't in the same class. } } ``` My first thought was to have a function similar to: ``` internal enum GUIElementHandlers { Click, ... } internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) { switch (h) { case Click: this.Click(this, (EventArgs)args[0]); break; ... // etc and so forth } } ``` It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas?
You just need to add a public method for invoking the event. Microsoft already does this for some events such as *PerformClick* for controls that expose a *Click* event. ``` public class CustomGUIElement { public void PerformClick() { OnClick(EventArgs.Empty); } protected virtual void OnClick(EventArgs e) { if (Click != null) Click(this, e); } } ``` You would then do the following inside your example event handler... ``` public void CustomForm_Click(object sender, MouseEventArgs e) { _elements[0].PerformClick(); } ```
107,984
<p>In toad, I can see unicode characters that are coming from oracle db. But when I click one of the fields in the data grid into the edit mode, the unicode characters are converted to meaningless symbols, but this is not the big issue.</p> <p>While editing this field, the unicode characters are displayed correctly as I type. But as soon as I press enter and exit edit mode, they are converted to the nearest (most similar) non-unicode character. So I cannot type unicode characters on data grids. Copy &amp; pasting one of the unicode characters also does not work.</p> <p>How can I solve this?</p> <p>Edit: I am using toad 9.0.0.160.</p>
[ { "answer_id": 107978, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>You really should wrap the code you want to be able to execute from the outside in a method. That method can then do whatever your event would do - and that event would also instead call that method.</p>\n" }, { "answer_id": 107979, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": "<p>You just need to add a public method for invoking the event. Microsoft already does this for some events such as <em>PerformClick</em> for controls that expose a <em>Click</em> event.</p>\n\n<pre><code>public class CustomGUIElement \n{\n public void PerformClick()\n {\n OnClick(EventArgs.Empty);\n }\n\n protected virtual void OnClick(EventArgs e)\n {\n if (Click != null)\n Click(this, e);\n }\n}\n</code></pre>\n\n<p>You would then do the following inside your example event handler...</p>\n\n<pre><code>public void CustomForm_Click(object sender, MouseEventArgs e) \n{\n _elements[0].PerformClick();\n}\n</code></pre>\n" }, { "answer_id": 112125, "author": "Lee", "author_id": 13943, "author_profile": "https://Stackoverflow.com/users/13943", "pm_score": 3, "selected": false, "text": "<p>The event keyword in c# modifies the declaration of the delegate. It prevents direct assignment to the delegate (you can only use += and -= on an event), and it prevents invocation of the delegate from outside the class.</p>\n\n<p>So you could alter your code to look like this:</p>\n\n<pre><code>public class CustomGUIElement\n{\n...\n public MouseEventHandler Click;\n // etc, and so forth.\n...\n}\n</code></pre>\n\n<p>Then you can invoke the event from outside the class like this.</p>\n\n<pre><code>myCustomGUIElement.Click(sender,args);\n</code></pre>\n\n<p>The drawback is that code using the class can overwrite any registered handlers very easily with code like this:</p>\n\n<pre><code>myCustomGUIElement.Click = null;\n</code></pre>\n\n<p>which is not allowed if the Click delegate is declared as an event.</p>\n" }, { "answer_id": 57007130, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 2, "selected": false, "text": "<p>You can shorten the code suggested in the accepted answer a lot using the modern syntax feature of the .NET framework:</p>\n\n<pre><code>public event Action&lt;int&gt; RecipeSelected;\npublic void RaiseRecpeSelected(int recipe) =&gt; RecipeSelected?.Invoke(recipe);\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
In toad, I can see unicode characters that are coming from oracle db. But when I click one of the fields in the data grid into the edit mode, the unicode characters are converted to meaningless symbols, but this is not the big issue. While editing this field, the unicode characters are displayed correctly as I type. But as soon as I press enter and exit edit mode, they are converted to the nearest (most similar) non-unicode character. So I cannot type unicode characters on data grids. Copy & pasting one of the unicode characters also does not work. How can I solve this? Edit: I am using toad 9.0.0.160.
You just need to add a public method for invoking the event. Microsoft already does this for some events such as *PerformClick* for controls that expose a *Click* event. ``` public class CustomGUIElement { public void PerformClick() { OnClick(EventArgs.Empty); } protected virtual void OnClick(EventArgs e) { if (Click != null) Click(this, e); } } ``` You would then do the following inside your example event handler... ``` public void CustomForm_Click(object sender, MouseEventArgs e) { _elements[0].PerformClick(); } ```
107,995
<p>The <code>unzip</code> command doesn't have an option for recursively unzipping archives.</p> <p>If I have the following directory structure and archives:</p> <pre> /Mother/Loving.zip /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes.zip </pre> <p>And I want to unzip all of the archives into directories with the same name as each archive:</p> <pre> /Mother/Loving/1.txt /Mother/Loving.zip /Scurvy/Sea Dogs/2.txt /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes/3.txt /Scurvy/Cures/Limes.zip </pre> <p>What command or commands would I issue?</p> <p>It's important that this doesn't choke on filenames that have spaces in them.</p>
[ { "answer_id": 107999, "author": "chuckrector", "author_id": 10645, "author_profile": "https://Stackoverflow.com/users/10645", "pm_score": 5, "selected": false, "text": "<p>Here's one solution that extracts all zip files to the <em>working directory</em> and involves the find command and a while loop:</p>\n\n<pre><code>find . -name \"*.zip\" | while read filename; do unzip -o -d \"`basename -s .zip \"$filename\"`\" \"$filename\"; done;\n</code></pre>\n" }, { "answer_id": 108002, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Something like gunzip using the -r flag?....</p>\n\n<p>Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).</p>\n\n<p><a href=\"http://www.computerhope.com/unix/gzip.htm\" rel=\"nofollow noreferrer\">http://www.computerhope.com/unix/gzip.htm</a></p>\n" }, { "answer_id": 108019, "author": "Jahangir", "author_id": 6927, "author_profile": "https://Stackoverflow.com/users/6927", "pm_score": 2, "selected": false, "text": "<p>You could use find along with the -exec flag in a single command line to do the job</p>\n\n<pre><code>find . -name \"*.zip\" -exec unzip {} \\;\n</code></pre>\n" }, { "answer_id": 739171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you're using cygwin, the syntax is slightly different for the basename command.</p>\n\n<pre><code>find . -name \"*.zip\" | while read filename; do unzip -o -d \"`basename \"$filename\" .zip`\" \"$filename\"; done;\n</code></pre>\n" }, { "answer_id": 2318189, "author": "Vivek Thomas", "author_id": 279472, "author_profile": "https://Stackoverflow.com/users/279472", "pm_score": 8, "selected": true, "text": "<p>If you want to extract the files to the respective folder you can try this</p>\n\n<pre><code>find . -name \"*.zip\" | while read filename; do unzip -o -d \"`dirname \"$filename\"`\" \"$filename\"; done;\n</code></pre>\n\n<p>A multi-processed version for systems that can handle high I/O:</p>\n\n<pre><code>find . -name \"*.zip\" | xargs -P 5 -I fileName sh -c 'unzip -o -d \"$(dirname \"fileName\")/$(basename -s .zip \"fileName\")\" \"fileName\"'\n</code></pre>\n" }, { "answer_id": 16540353, "author": "Thor84no", "author_id": 692560, "author_profile": "https://Stackoverflow.com/users/692560", "pm_score": 1, "selected": false, "text": "<p>I realise this is very old, but it was among the first hits on Google when I was looking for a solution to something similar, so I'll post what I did here. My scenario is slightly different as I basically just wanted to fully explode a jar, along with all jars contained within it, so I wrote the following bash functions:</p>\n\n<pre><code>function explode {\n local target=\"$1\"\n echo \"Exploding $target.\"\n if [ -f \"$target\" ] ; then\n explodeFile \"$target\"\n elif [ -d \"$target\" ] ; then\n while [ \"$(find \"$target\" -type f -regextype posix-egrep -iregex \".*\\.(zip|jar|ear|war|sar)\")\" != \"\" ] ; do\n find \"$target\" -type f -regextype posix-egrep -iregex \".*\\.(zip|jar|ear|war|sar)\" -exec bash -c 'source \"&lt;file-where-this-function-is-stored&gt;\" ; explode \"{}\"' \\;\n done\n else\n echo \"Could not find $target.\"\n fi\n}\n\nfunction explodeFile {\n local target=\"$1\"\n echo \"Exploding file $target.\"\n mv \"$target\" \"$target.tmp\"\n unzip -q \"$target.tmp\" -d \"$target\"\n rm \"$target.tmp\"\n}\n</code></pre>\n\n<p>Note the <code>&lt;file-where-this-function-is-stored&gt;</code> which is needed if you're storing this in a file that is not read for a non-interactive shell as I happened to be. If you're storing the functions in a file loaded on non-interactive shells (e.g., <code>.bashrc</code> I believe) you can drop the whole <code>source</code> statement. Hopefully this will help someone.</p>\n\n<p>A little warning - <code>explodeFile</code> also deletes the ziped file, you can of course change that by commenting out the last line.</p>\n" }, { "answer_id": 22384233, "author": "robinst", "author_id": 305973, "author_profile": "https://Stackoverflow.com/users/305973", "pm_score": 6, "selected": false, "text": "<p>A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:</p>\n<pre><code>find . -iname '*.zip' -exec sh -c 'unzip -o -d &quot;${0%.*}&quot; &quot;$0&quot;' '{}' ';'\n</code></pre>\n<p>Note that you can easily make it handle more file types (such as <code>.jar</code>) by adding them using <code>-o</code>, e.g.:</p>\n<pre><code>find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...\n</code></pre>\n" }, { "answer_id": 23920166, "author": "Prometheus", "author_id": 2587178, "author_profile": "https://Stackoverflow.com/users/2587178", "pm_score": 0, "selected": false, "text": "<p>Another interesting solution would be:</p>\n\n<pre><code>DESTINY=[Give the output that you intend]\n\n# Don't forget to change from .ZIP to .zip.\n# In my case the files were in .ZIP.\n# The echo were for debug purpose.\n\nfind . -name \"*.ZIP\" | while read filename; do\nADDRESS=$filename\n#echo \"Address: $ADDRESS\"\nBASENAME=`basename $filename .ZIP`\n#echo \"Basename: $BASENAME\"\nunzip -d \"$DESTINY$BASENAME\" \"$ADDRESS\";\ndone;\n</code></pre>\n" }, { "answer_id": 49554119, "author": "Prabhav", "author_id": 7113627, "author_profile": "https://Stackoverflow.com/users/7113627", "pm_score": 2, "selected": false, "text": "<p>This works perfectly as we want:</p>\n\n<p>Unzip files:</p>\n\n<pre><code>find . -name \"*.zip\" | xargs -P 5 -I FILENAME sh -c 'unzip -o -d \"$(dirname \"FILENAME\")\" \"FILENAME\"'\n</code></pre>\n\n<p>Above command does not create duplicate directories.</p>\n\n<p>Remove all zip files:</p>\n\n<pre><code>find . -depth -name '*.zip' -exec rm {} \\;\n</code></pre>\n" }, { "answer_id": 68138355, "author": "Josué Martínez Morales", "author_id": 16318953, "author_profile": "https://Stackoverflow.com/users/16318953", "pm_score": -1, "selected": false, "text": "<p>this works for me</p>\n<pre><code>def unzip(zip_file, path_to_extract):\n &quot;&quot;&quot;\n Decompress zip archives recursively\n Args:\n zip_file: name of zip archive\n path_to_extract: folder where the files will be extracted\n &quot;&quot;&quot;\n try:\n if is_zipfile(zip_file):\n parent_file = ZipFile(zip_file)\n parent_file.extractall(path_to_extract)\n for file_inside in parent_file.namelist():\n if is_zipfile(os.path.join(os.getcwd(),file_inside)):\n unzip(file_inside,path_to_extract)\n os.remove(f&quot;{zip_file}&quot;)\n except Exception as e:\n print(e)\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/107995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10645/" ]
The `unzip` command doesn't have an option for recursively unzipping archives. If I have the following directory structure and archives: ``` /Mother/Loving.zip /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes.zip ``` And I want to unzip all of the archives into directories with the same name as each archive: ``` /Mother/Loving/1.txt /Mother/Loving.zip /Scurvy/Sea Dogs/2.txt /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes/3.txt /Scurvy/Cures/Limes.zip ``` What command or commands would I issue? It's important that this doesn't choke on filenames that have spaces in them.
If you want to extract the files to the respective folder you can try this ``` find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done; ``` A multi-processed version for systems that can handle high I/O: ``` find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"' ```
108,005
<p>first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this:</p> <pre><code> private int getFileTypeIconIndex(string fileName) { string fileLocation = Application.StartupPath + "\\Quarantine\\" + fileName; FileInfo fi = new FileInfo(fileLocation); switch (fi.Extension) { case ".pdf": return 1; case ".doc": case ".docx": case ".docm": case ".dotx":case ".dotm": case ".dot":case ".wpd": case ".wps": return 2; default: return 0; } } </code></pre> <p>The above code returns an integer that is used to select an icon from an imagelist that I populated with some common icons. It works fine but I'd need to add every extension under the sun! Is there a better way? Thanks!</p>
[ { "answer_id": 108015, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 3, "selected": false, "text": "<p>The file icons are held in the registry. It's a little convoluted but it works something like</p>\n\n<ul>\n<li>Take the file extension and lookup\nthe registry entry for it, for\nexample .DOC Get the default value\nfor that registry setting,\n\"Word.Document.8\" </li>\n<li>Now lookup that\nvalue in the registry. </li>\n<li>Look at the\ndefault value for the \"Default Icon\"\nregistry key, in this case,\nC:\\Windows\\Installer{91120000-002E-0000-0000-0000000FF1CE}\\wordicon.exe,1</li>\n<li>Open the file and get the icon,\nusing any number after the comma as\nthe indexer.</li>\n</ul>\n\n<p>There is some sample code at on <a href=\"http://www.codeproject.com/KB/cs/GetFileTypeAndIcon.aspx?display=Print\" rel=\"noreferrer\">CodeProject</a></p>\n" }, { "answer_id": 108056, "author": "eric", "author_id": 5798, "author_profile": "https://Stackoverflow.com/users/5798", "pm_score": 3, "selected": false, "text": "<p>I used the following solution from codeproject in one of recent my projects</p>\n<p><a href=\"http://www.codeproject.com/KB/files/fileicon.aspx\" rel=\"nofollow noreferrer\">Obtaining (and managing) file and folder icons using SHGetFileInfo in C#</a></p>\n<h2></h2>\n<p>The demo project is pretty self explanatory but basically you just have to do:</p>\n<pre><code>private System.Windows.Forms.ListView FileView;\n\nprivate ImageList _SmallImageList = new ImageList();\nprivate ImageList _LargeImageList = new ImageList();\nprivate IconListManager _IconListManager;\n</code></pre>\n<p>in the constructor:</p>\n<pre><code>_SmallImageList.ColorDepth = ColorDepth.Depth32Bit;\n_LargeImageList.ColorDepth = ColorDepth.Depth32Bit;\n\n_SmallImageList.ImageSize = new System.Drawing.Size(16, 16);\n_LargeImageList.ImageSize = new System.Drawing.Size(32, 32);\n\n_IconListManager = new IconListManager(_SmallImageList, _LargeImageList);\n\nFileView.SmallImageList = _SmallImageList;\nFileView.LargeImageList = _LargeImageList;\n</code></pre>\n<p>and then finally when you create the ListViewItem:</p>\n<pre><code>ListViewItem item = new ListViewItem(file.Name, _IconListManager.AddFileIcon(file.FullName));\n</code></pre>\n<p>Worked great for me.</p>\n" }, { "answer_id": 108062, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 2, "selected": false, "text": "<p>Edit: <a href=\"https://stackoverflow.com/questions/462270/get-file-icon-used-by-shell\">Here</a> is a version without PInvoke.</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential)]\npublic struct SHFILEINFO\n{\n public IntPtr hIcon;\n public IntPtr iIcon;\n public uint dwAttributes;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]\n public string szDisplayName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]\n public string szTypeName;\n};\n\npublic const uint SHGFI_ICON = 0x100;\npublic const uint SHGFI_LARGEICON = 0x0; // 'Large icon\npublic const uint SHGFI_SMALLICON = 0x1; // 'Small icon\n\n[DllImport(\"shell32.dll\")]\npublic static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);\n\n[DllImport(\"User32.dll\")]\npublic static extern int DestroyIcon(IntPtr hIcon);\n\npublic static System.Drawing.Icon GetSystemIcon(string sFilename)\n{\n //Use this to get the small Icon\n IntPtr hImgSmall; //the handle to the system image list\n //IntPtr hImgLarge; //the handle to the system image list\n APIFuncs.SHFILEINFO shinfo = new APIFuncs.SHFILEINFO();\n hImgSmall = APIFuncs.SHGetFileInfo(sFilename, 0, ref shinfo,\n (uint)Marshal.SizeOf(shinfo), APIFuncs.SHGFI_ICON | APIFuncs.SHGFI_SMALLICON);\n\n //Use this to get the large Icon\n //hImgLarge = SHGetFileInfo(fName, 0, \n // ref shinfo, (uint)Marshal.SizeOf(shinfo), \n // Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);\n\n //The icon is returned in the hIcon member of the shinfo struct\n System.Drawing.Icon myIcon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shinfo.hIcon).Clone();\n DestroyIcon(shinfo.hIcon); // Cleanup\n return myIcon;\n}\n</code></pre>\n" }, { "answer_id": 492856, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 5, "selected": true, "text": "<p>You might find the use of <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx\" rel=\"noreferrer\">Icon.ExtractAssociatedIcon</a> a much simpler (an managed) approach than using SHGetFileInfo. But watch out: two files with the same extension may have different icons.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333/" ]
first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this: ``` private int getFileTypeIconIndex(string fileName) { string fileLocation = Application.StartupPath + "\\Quarantine\\" + fileName; FileInfo fi = new FileInfo(fileLocation); switch (fi.Extension) { case ".pdf": return 1; case ".doc": case ".docx": case ".docm": case ".dotx":case ".dotm": case ".dot":case ".wpd": case ".wps": return 2; default: return 0; } } ``` The above code returns an integer that is used to select an icon from an imagelist that I populated with some common icons. It works fine but I'd need to add every extension under the sun! Is there a better way? Thanks!
You might find the use of [Icon.ExtractAssociatedIcon](http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx) a much simpler (an managed) approach than using SHGetFileInfo. But watch out: two files with the same extension may have different icons.
108,009
<p>I'm writing a C parser using PLY, and recently ran into a problem. This code:</p> <pre><code>typedef int my_type; my_type x; </code></pre> <p>Is correct C code, because my_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers.</p> <p>However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token <code>my_type</code> from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it sees my_type as an identifier and not a type.</p> <p>Any ideas for a fix ?</p> <p>The full code is at: <a href="http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py" rel="nofollow noreferrer">http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py</a> Not sure how I can create a smaller example out of this. </p> <p><strong>Edit:</strong></p> <p>Problem solved. See my solution below.</p>
[ { "answer_id": 108033, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 1, "selected": false, "text": "<p>I think you need to move the check for whether an ID is a TYPEID from c_lexer.py to c_parser.py.</p>\n\n<p>As you said, since the parser is looking ahead 1 token, you can't make that decision in the lexer.</p>\n\n<p>Instead, alter your parser to check ID's to see if they are TYPEID's in declarations, and, if they aren't, generate an error.</p>\n\n<p>As Pax Diablo said in his excellent answer, the lexer/tokenizer's job isn't to make those kinds of decisions about tokens. That's the parser's job.</p>\n" }, { "answer_id": 108054, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>Not sure why you're doing that level of analysis in your lexer.</p>\n\n<p>Lexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such.</p>\n\n<p>That's the way I've always separated the duties between lexx and yacc, my tools of choice.</p>\n" }, { "answer_id": 108482, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": true, "text": "<p>With <a href=\"http://groups.google.com/group/ply-hack/tree/browse_frm/thread/cf31e8334801eabd/b9cdf4a6682635c1?rnum=1&amp;_done=%2Fgroup%2Fply-hack%2Fbrowse_frm%2Fthread%2Fcf31e8334801eabd%3F#doc_5c415da045e77a6e\" rel=\"nofollow noreferrer\">some help</a> from Dave Beazley (PLY's creator), my problem was solved.</p>\n\n<p>The idea is to use special sub-rules and do the actions in them. In my case, I split the <code>declaration</code> rule to:</p>\n\n<pre><code>def p_decl_body(self, p):\n \"\"\" decl_body : declaration_specifiers init_declarator_list_opt\n \"\"\"\n # &lt;&lt;Handle the declaration here&gt;&gt; \n\ndef p_declaration(self, p):\n \"\"\" declaration : decl_body SEMI \n \"\"\"\n p[0] = p[1]\n</code></pre>\n\n<p><code>decl_body</code> is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
I'm writing a C parser using PLY, and recently ran into a problem. This code: ``` typedef int my_type; my_type x; ``` Is correct C code, because my\_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers. However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token `my_type` from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it sees my\_type as an identifier and not a type. Any ideas for a fix ? The full code is at: <http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py> Not sure how I can create a smaller example out of this. **Edit:** Problem solved. See my solution below.
With [some help](http://groups.google.com/group/ply-hack/tree/browse_frm/thread/cf31e8334801eabd/b9cdf4a6682635c1?rnum=1&_done=%2Fgroup%2Fply-hack%2Fbrowse_frm%2Fthread%2Fcf31e8334801eabd%3F#doc_5c415da045e77a6e) from Dave Beazley (PLY's creator), my problem was solved. The idea is to use special sub-rules and do the actions in them. In my case, I split the `declaration` rule to: ``` def p_decl_body(self, p): """ decl_body : declaration_specifiers init_declarator_list_opt """ # <<Handle the declaration here>> def p_declaration(self, p): """ declaration : decl_body SEMI """ p[0] = p[1] ``` `decl_body` is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time.
108,010
<p>Greetings.</p> <p>I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element.</p> <p>Example XML file 1:</p> <pre><code>&lt;file&gt; &lt;title&gt;Title 1&lt;/title&gt; &lt;someContent&gt;Content&lt;/someContent&gt; &lt;filter&gt;filter&lt;/filter&gt; &lt;/file&gt; </code></pre> <p>Example XML file 2:</p> <pre><code>&lt;file&gt; &lt;title&gt;Title 2&lt;/title&gt; &lt;someContent&gt;Content&lt;/someContent&gt; &lt;filter&gt;filter, different filter&lt;/filter&gt; &lt;/file&gt; </code></pre> <p>Example case 1:</p> <p>Give me all XML that has a filter of 'filter'.</p> <p>Example case 2:</p> <p>Give me all XML that has a title of 'Title 1'.</p> <p>Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case.</p> <p>I would prefer that this be done on the server-side, so that I can cache on that end.</p> <p>Functionality from any version of the .NET Framework can be used.</p> <p>Thanks!</p> <p>~James</p>
[ { "answer_id": 108012, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 1, "selected": false, "text": "<p>Use XPath?<br>\n<a href=\"http://www.w3schools.com/XPath/default.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/XPath/default.asp</a></p>\n" }, { "answer_id": 108044, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>You might want to create your own iterator class that iterate over those files.</p>\n\n<p>Say, make a XMLContentEnumerator : IEnumerable. that would iterate over files in a specific directory and parse its content, and then you would be able to make a normal LINQ filtering query such as:</p>\n\n<pre><code>var xc = new XMLContentEnumerator(@\"C:\\dir\");\n\nvar filesWithHello = xc.Where(x =&gt; x.title.Contains(\"hello\"));\n</code></pre>\n\n<p>I don't have the environment to provide a full example, but this should give some ideas.</p>\n" }, { "answer_id": 108045, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 4, "selected": true, "text": "<p>If you are using .Net 3.5, this is extremely easy with LINQ:</p>\n\n<pre><code>//get the files\nXElement xe1 = XElement.Load(string_file_path_1);\nXElement xe2 = XElement.Load(string_file_path_2);\n\n//Give me all XML that has a filter of 'filter'.\nvar filter_elements1 = from p in xe1.Descendants(\"filter\") select p;\nvar filter_elements2 = from p in xe2.Descendants(\"filter\") select p;\nvar filter_elements = filter_elements1.Union(filter_elements2);\n\n//Give me all XML that has a title of 'Title 1'.\nvar title1 = from p in xe1.Descendants(\"title\") where p.Value.Equals(\"Title 1\") select p;\nvar title2 = from p in xe2.Descendants(\"title\") where p.Value.Equals(\"Title 1\") select p;\nvar titles = title1.Union(title2);\n</code></pre>\n\n<p>This can all be written shorthand and get you your results in just 4 lines total:</p>\n\n<pre><code>XElement xe1 = XElement.Load(string_file_path_1);\nXElement xe2 = XElement.Load(string_file_path_2);\nvar _filter_elements = (from p1 in xe1.Descendants(\"filter\") select p1).Union(from p2 in xe2.Descendants(\"filter\") select p2);\nvar _titles = (from p1 in xe1.Descendants(\"title\") where p1.Value.Equals(\"Title 1\") select p1).Union(from p2 in xe2.Descendants(\"title\") where p2.Value.Equals(\"Title 1\") select p2);\n</code></pre>\n\n<p>These will all be IEnumerable lists, so they are super easy to work with:</p>\n\n<pre><code>foreach (var v in filter_elements)\n Response.Write(\"value of filter element\" + v.Value + \"&lt;br /&gt;\");\n</code></pre>\n\n<p>LINQ rules!</p>\n" }, { "answer_id": 108426, "author": "Mattio", "author_id": 19626, "author_profile": "https://Stackoverflow.com/users/19626", "pm_score": 2, "selected": false, "text": "<p>Here's one way using Framework 2.0. You can make this cleaner by using regular expressions rather than a simple string test. You can also try compiling your XPath expressions if you need to squeeze more for performance.</p>\n\n<pre><code>static void Main(string[] args)\n{\n string[] myFiles = { @\"C:\\temp\\XMLFile1.xml\", \n @\"C:\\temp\\XMLFile2.xml\", \n @\"C:\\temp\\XMLFile3.xml\" };\n foreach (string file in myFiles)\n {\n System.Xml.XPath.XPathDocument myDoc = \n new System.Xml.XPath.XPathDocument(file);\n System.Xml.XPath.XPathNavigator myNav = \n myDoc.CreateNavigator();\n\n if(myNav.SelectSingleNode(\"/file/filter[1]\") != null &amp;&amp;\n myNav.SelectSingleNode(\"/file/filter[1]\").InnerXml.Contains(\"filter\"))\n Console.WriteLine(file + \" Contains 'filter'\");\n\n if (myNav.SelectSingleNode(\"/file/title[1]\") != null &amp;&amp;\n myNav.SelectSingleNode(\"/file/title[1]\").InnerXml.Contains(\"Title 1\"))\n Console.WriteLine(file + \" Contains 'Title 1'\");\n }\n\n Console.ReadLine();\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11912/" ]
Greetings. I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element. Example XML file 1: ``` <file> <title>Title 1</title> <someContent>Content</someContent> <filter>filter</filter> </file> ``` Example XML file 2: ``` <file> <title>Title 2</title> <someContent>Content</someContent> <filter>filter, different filter</filter> </file> ``` Example case 1: Give me all XML that has a filter of 'filter'. Example case 2: Give me all XML that has a title of 'Title 1'. Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case. I would prefer that this be done on the server-side, so that I can cache on that end. Functionality from any version of the .NET Framework can be used. Thanks! ~James
If you are using .Net 3.5, this is extremely easy with LINQ: ``` //get the files XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); //Give me all XML that has a filter of 'filter'. var filter_elements1 = from p in xe1.Descendants("filter") select p; var filter_elements2 = from p in xe2.Descendants("filter") select p; var filter_elements = filter_elements1.Union(filter_elements2); //Give me all XML that has a title of 'Title 1'. var title1 = from p in xe1.Descendants("title") where p.Value.Equals("Title 1") select p; var title2 = from p in xe2.Descendants("title") where p.Value.Equals("Title 1") select p; var titles = title1.Union(title2); ``` This can all be written shorthand and get you your results in just 4 lines total: ``` XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); var _filter_elements = (from p1 in xe1.Descendants("filter") select p1).Union(from p2 in xe2.Descendants("filter") select p2); var _titles = (from p1 in xe1.Descendants("title") where p1.Value.Equals("Title 1") select p1).Union(from p2 in xe2.Descendants("title") where p2.Value.Equals("Title 1") select p2); ``` These will all be IEnumerable lists, so they are super easy to work with: ``` foreach (var v in filter_elements) Response.Write("value of filter element" + v.Value + "<br />"); ``` LINQ rules!
108,081
<p>Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?</p>
[ { "answer_id": 108142, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://www.peter-herth.de/ltk/\" rel=\"noreferrer\">Ltk</a> is quite popular, very portable, and reasonably well documented through the Tk docs. Installation on SBCL is as easy as saying:</p>\n\n<pre><code>(require :asdf-install)\n(asdf-install:install :ltk)\n</code></pre>\n\n<p>There's also <a href=\"http://common-lisp.net/project/cells-gtk/\" rel=\"noreferrer\">Cells-Gtk</a>, which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.</p>\n\n<p>EDIT: Note that ASDF-INSTALL is integrated this well with SBCL <em>only</em>. Installing libraries from within other Lisp implementations may prove harder. (Personally, I always install my libraries from within SBCL and then use them from all implementations.) Sorry about any confusion this may have caused.</p>\n" }, { "answer_id": 118973, "author": "Nowhere man", "author_id": 400277, "author_profile": "https://Stackoverflow.com/users/400277", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://sourceforge.net/projects/clg\" rel=\"noreferrer\">clg</a> is a binding of GTK for Common Lisp. Both complete and lispish.</p>\n\n<p>If you want to design graphical interfaces in CL, you might want to take a look at CLIM, too, which some kind of standard API for GUIs. Allegro and Lispworks have their own implementation of it, and there's a free software one, <a href=\"http://common-lisp.net/project/mcclim/\" rel=\"noreferrer\">McCLIM</a>.</p>\n" }, { "answer_id": 666266, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 3, "selected": false, "text": "<p>Also, just found a Smoke library QT bindings, called <a href=\"http://common-lisp.net/project/commonqt/\" rel=\"noreferrer\">CommonQt</a> for CL</p>\n" }, { "answer_id": 991438, "author": "Frank Shearar", "author_id": 10259, "author_profile": "https://Stackoverflow.com/users/10259", "pm_score": 2, "selected": false, "text": "<p>There's also <a href=\"http://www.wxcl-project.org/\" rel=\"nofollow noreferrer\">wxCL</a>, providing CFFI bindings for <a href=\"http://www.wxwidgets.org/\" rel=\"nofollow noreferrer\">wxWidgets</a>.</p>\n" }, { "answer_id": 2042553, "author": "Friedrich", "author_id": 15068, "author_profile": "https://Stackoverflow.com/users/15068", "pm_score": 2, "selected": false, "text": "<p>LispWorks comes with CAPI, it's portable accross Mac, Windows and Linux and even has some GUI-Builder. It's free for personal use. </p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?
[Ltk](http://www.peter-herth.de/ltk/) is quite popular, very portable, and reasonably well documented through the Tk docs. Installation on SBCL is as easy as saying: ``` (require :asdf-install) (asdf-install:install :ltk) ``` There's also [Cells-Gtk](http://common-lisp.net/project/cells-gtk/), which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells. EDIT: Note that ASDF-INSTALL is integrated this well with SBCL *only*. Installing libraries from within other Lisp implementations may prove harder. (Personally, I always install my libraries from within SBCL and then use them from all implementations.) Sorry about any confusion this may have caused.
108,094
<p>Is there anyway to disable the rather annoying feature that Visual Studio (2008 in my case) has of copying the line (with text on it) the cursor is on when <kbd>CTRL</kbd>-<kbd>C</kbd> is pressed and no selection is made?</p> <p>I know of the option to disable copying blank lines. But this is driving me crazy as well.</p> <p>ETA: I'm not looking to customize the keyboard shortcut.</p> <p>ETA-II: I am NOT looking for "Tools->Options->Text Editor->All Languages->Apply cut or copy to blank lines...".</p>
[ { "answer_id": 108139, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 1, "selected": false, "text": "<p>I'm pretty sure the way to do it in 2008 is the same as the way in 2005... check out this tutorial on 'customizing keyboard shortcuts' (about 1/3 of the way down)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb245788(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb245788(VS.80).aspx</a></p>\n" }, { "answer_id": 108212, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 1, "selected": false, "text": "<p>I don't believe it is possible to do this without some type of 3rd party clip board manager that would prevent you from overwriting the clipboard content with the empty string.</p>\n" }, { "answer_id": 152426, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 1, "selected": false, "text": "<p>I've the free SlickEdit add-in installed, and its CommandSpy feature shows that <kbd>Ctrl</kbd>+<kbd>C</kbd> executes Edit.Copy whether you've got text highlighted or not. Therefore I guess the answer to your question is No. </p>\n\n<p>However, I do remember this feature annoying the hell out of me when I first encountered it; now I rely on it and get annoyed when I try the same trick in other programs and nothing happens.</p>\n" }, { "answer_id": 256384, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 5, "selected": false, "text": "<p>The real problem you probably experience is that you go to paste, with <kbd>CTRL</kbd>+<kbd>V</kbd>. And you accidentally type<kbd> CTRL</kbd>+<kbd>C</kbd>, and end up overwriting the stuff that's on your clipboard. You can't disable this as far as I know, however, the work around for this, is that you can press <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>V</kbd> multiple times to go back up the stack of things you have copied in visual studio. Not only does this allow you to recover what you originally copied, but you'll also find that <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>V</kbd> very useful in a lot of other situations.</p>\n" }, { "answer_id": 2509622, "author": "David Walthall", "author_id": 301019, "author_profile": "https://Stackoverflow.com/users/301019", "pm_score": 5, "selected": true, "text": "<p>If you aren't willing to customize the keyboard settings, then <kbd>Ctrl</kbd>+<kbd>C</kbd> will always be Edit.Copy, which will copy the current line if nothing is selected. If you aren't willing to use the tools VS provides to customize the interface, then you can't do it. </p>\n\n<p>However, the following works:\nAssign this macro to <kbd>Ctrl</kbd>+<kbd>C</kbd>:</p>\n\n<pre><code>Sub CopyOnlyIfSelection()\n Dim s As String = DTE.ActiveDocument.Selection.Text\n Dim n As Integer = Len(s)\n If n &gt; 0 Then\n DTE.ActiveDocument.Selection.Copy()\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 67789336, "author": "user886079", "author_id": 886079, "author_profile": "https://Stackoverflow.com/users/886079", "pm_score": 2, "selected": false, "text": "<p>There's an extension called CopyOnlySelection for visual studio 2019 and 2017:</p>\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=KiwiProductions.CopyOnlySelection\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=KiwiProductions.CopyOnlySelection</a></p>\n<p>This won't solve it immediately, but will add another command called Edit.CopyOnlySelection, which you can bind to Ctrl+C (and remove Ctrl+C from the normal Edit.Copy).</p>\n" }, { "answer_id": 72202063, "author": "Irq Mishell", "author_id": 2996743, "author_profile": "https://Stackoverflow.com/users/2996743", "pm_score": 0, "selected": false, "text": "<p>I have the same problem, but I found a workaround of it.\nWhen I click one time on word in text editor, all occurrences of it are highlighted.</p>\n<p>Then I think I will copy this word. But double-click will select text to copy only.</p>\n<p>I copy then whole line instead wanted text.</p>\n<p>Problem Is: Color of highlighted text parts are very similar to selected text.</p>\n<p>I changed these colors to make it easy to distinguish between the situations.</p>\n<p>Tools -&gt; Options -&gt; Environment -&gt; Font and colors -&gt; Selected Text</p>\n<p>Tools -&gt; Options -&gt; Environment -&gt;Font and colors -&gt; Highlighted references</p>\n" }, { "answer_id": 74039373, "author": "Nils", "author_id": 4876453, "author_profile": "https://Stackoverflow.com/users/4876453", "pm_score": 0, "selected": false, "text": "<p>This is fixed in the latest preview of VS2022 (17.4.0 Preview 3.0)</p>\n<p>It now has the option: 'Cut or Copy the current line without selection' and I can confirm that it works.</p>\n<p>As for the original question, I don't think it will be fixed in VS2008 :-)</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4192/" ]
Is there anyway to disable the rather annoying feature that Visual Studio (2008 in my case) has of copying the line (with text on it) the cursor is on when `CTRL`-`C` is pressed and no selection is made? I know of the option to disable copying blank lines. But this is driving me crazy as well. ETA: I'm not looking to customize the keyboard shortcut. ETA-II: I am NOT looking for "Tools->Options->Text Editor->All Languages->Apply cut or copy to blank lines...".
If you aren't willing to customize the keyboard settings, then `Ctrl`+`C` will always be Edit.Copy, which will copy the current line if nothing is selected. If you aren't willing to use the tools VS provides to customize the interface, then you can't do it. However, the following works: Assign this macro to `Ctrl`+`C`: ``` Sub CopyOnlyIfSelection() Dim s As String = DTE.ActiveDocument.Selection.Text Dim n As Integer = Len(s) If n > 0 Then DTE.ActiveDocument.Selection.Copy() End If End Sub ```
108,104
<p>Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"</p> <p>So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?</p> <p>So I have</p> <pre><code>typeof(int) typeof(DateTime) System.Type t = something; </code></pre> <p>and I want</p> <pre><code>int? DateTime? </code></pre> <p>or</p> <pre><code>Nullable&lt;int&gt; (which is the same) if (t is primitive) then Nullable&lt;T&gt; else just T </code></pre> <p>Is there a built-in method?</p>
[ { "answer_id": 108122, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 8, "selected": true, "text": "<p>Here is the code I use:</p>\n\n<pre><code>Type GetNullableType(Type type) {\n // Use Nullable.GetUnderlyingType() to remove the Nullable&lt;T&gt; wrapper if type is already nullable.\n type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null\n if (type.IsValueType)\n return typeof(Nullable&lt;&gt;).MakeGenericType(type);\n else\n return type;\n}\n</code></pre>\n" }, { "answer_id": 108129, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 2, "selected": false, "text": "<p>There isn't anything built in that I know of, as the <code>int?</code>, etc. is just syntactic sugar for <code>Nullable&lt;T&gt;</code>; and isn't given special treatment beyond that. It's especially unlikely given you're attempting to obtain this from the type information of a given type. Typically that always necessitates some 'roll your own' code as a given. You would have to use Reflection to create a new <code>Nullable</code> type with type parameter of the input type.</p>\n\n<p><strong>Edit:</strong> As the comments suggest actually <code>Nullable&lt;&gt;</code> <em>is</em> treated specially, and in the runtime to boot as explained in <a href=\"http://blogs.msdn.com/somasegar/archive/2005/08/11/450640.aspx\" rel=\"nofollow noreferrer\">this article</a>.</p>\n" }, { "answer_id": 2473675, "author": "Thracx", "author_id": 296924, "author_profile": "https://Stackoverflow.com/users/296924", "pm_score": 4, "selected": false, "text": "<p>Lyman's answer is great and has helped me, however, there's one more bug which needs to be fixed.</p>\n\n<p><code>Nullable.GetUnderlyingType(type)</code> should only be called iff the type isn't already a <code>Nullable</code> type. Otherwise, it seems to erroneously return null when the type derives from <code>System.RuntimeType</code> (such as when I pass in <code>typeof(System.Int32)</code> ). The below version avoids needing to call <code>Nullable.GetUnderlyingType(type)</code> by checking if the type is <code>Nullable</code> instead.</p>\n\n<p>Below you'll find an <code>ExtensionMethod</code> version of this method which will immediately return the type <em>unless</em> it's a <code>ValueType</code> that's not already <code>Nullable</code>.</p>\n\n<pre><code>Type NullableVersion(this Type sourceType)\n{\n if(sourceType == null)\n {\n // Throw System.ArgumentNullException or return null, your preference\n }\n else if(sourceType == typeof(void))\n { // Special Handling - known cases where Exceptions would be thrown\n return null; // There is no Nullable version of void\n }\n\n return !sourceType.IsValueType\n || (sourceType.IsGenericType\n &amp;&amp; sourceType.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;) )\n ? sourceType\n : typeof(Nullable&lt;&gt;).MakeGenericType(sourceType);\n}\n</code></pre>\n\n<p>(I'm sorry, but I couldn't simply post a comment to Lyman's answer because I was new and didn't have enough rep yet.)</p>\n" }, { "answer_id": 7759487, "author": "Mark Jones", "author_id": 703178, "author_profile": "https://Stackoverflow.com/users/703178", "pm_score": 4, "selected": false, "text": "<p>I have a couple of methods I've written in my utility library that I've heavily relied on. The first is a method that converts any Type to its corresponding Nullable&lt;Type&gt; form:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// [ &lt;c&gt;public static Type GetNullableType(Type TypeToConvert)&lt;/c&gt; ]\n /// &lt;para&gt;&lt;/para&gt;\n /// Convert any Type to its Nullable&amp;lt;T&amp;gt; form, if possible\n /// &lt;/summary&gt;\n /// &lt;param name=\"TypeToConvert\"&gt;The Type to convert&lt;/param&gt;\n /// &lt;returns&gt;\n /// The Nullable&amp;lt;T&amp;gt; converted from the original type, the original type if it was already nullable, or null \n /// if either &lt;paramref name=\"TypeToConvert\"/&gt; could not be converted or if it was null.\n /// &lt;/returns&gt;\n /// &lt;remarks&gt;\n /// To qualify to be converted to a nullable form, &lt;paramref name=\"TypeToConvert\"/&gt; must contain a non-nullable value \n /// type other than System.Void. Otherwise, this method will return a null.\n /// &lt;/remarks&gt;\n /// &lt;seealso cref=\"Nullable&amp;lt;T&amp;gt;\"/&gt;\n public static Type GetNullableType(Type TypeToConvert)\n {\n // Abort if no type supplied\n if (TypeToConvert == null)\n return null;\n\n // If the given type is already nullable, just return it\n if (IsTypeNullable(TypeToConvert))\n return TypeToConvert;\n\n // If the type is a ValueType and is not System.Void, convert it to a Nullable&lt;Type&gt;\n if (TypeToConvert.IsValueType &amp;&amp; TypeToConvert != typeof(void))\n return typeof(Nullable&lt;&gt;).MakeGenericType(TypeToConvert);\n\n // Done - no conversion\n return null;\n }\n</code></pre>\n\n<p>The second method simply reports whether a given Type is nullable. This method is called by the first and is useful separately:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// [ &lt;c&gt;public static bool IsTypeNullable(Type TypeToTest)&lt;/c&gt; ]\n /// &lt;para&gt;&lt;/para&gt;\n /// Reports whether a given Type is nullable (Nullable&amp;lt; Type &amp;gt;)\n /// &lt;/summary&gt;\n /// &lt;param name=\"TypeToTest\"&gt;The Type to test&lt;/param&gt;\n /// &lt;returns&gt;\n /// true = The given Type is a Nullable&amp;lt; Type &amp;gt;; false = The type is not nullable, or &lt;paramref name=\"TypeToTest\"/&gt; \n /// is null.\n /// &lt;/returns&gt;\n /// &lt;remarks&gt;\n /// This method tests &lt;paramref name=\"TypeToTest\"/&gt; and reports whether it is nullable (i.e. whether it is either a \n /// reference type or a form of the generic Nullable&amp;lt; T &amp;gt; type).\n /// &lt;/remarks&gt;\n /// &lt;seealso cref=\"GetNullableType\"/&gt;\n public static bool IsTypeNullable(Type TypeToTest)\n {\n // Abort if no type supplied\n if (TypeToTest == null)\n return false;\n\n // If this is not a value type, it is a reference type, so it is automatically nullable\n // (NOTE: All forms of Nullable&lt;T&gt; are value types)\n if (!TypeToTest.IsValueType)\n return true;\n\n // Report whether TypeToTest is a form of the Nullable&lt;&gt; type\n return TypeToTest.IsGenericType &amp;&amp; TypeToTest.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;);\n }\n</code></pre>\n\n<p>The above IsTypeNullable implementation works like a champ every time, but it's slightly verbose and slow in its last code line. The following code body is the same as above for IsTypeNullable, except the last code line is simpler and faster:</p>\n\n<pre><code> // Abort if no type supplied\n if (TypeToTest == null)\n return false;\n\n // If this is not a value type, it is a reference type, so it is automatically nullable\n // (NOTE: All forms of Nullable&lt;T&gt; are value types)\n if (!TypeToTest.IsValueType)\n return true;\n\n // Report whether an underlying Type exists (if it does, TypeToTest is a nullable Type)\n return Nullable.GetUnderlyingType(TypeToTest) != null;\n</code></pre>\n\n<p>Enjoy!</p>\n\n<p>Mark</p>\n\n<p>P.S. - About \"nullability\"</p>\n\n<p>I should repeat a statement about nullability I made in a separate post, which applies directly to properly addressing this topic. That is, I believe the focus of the discussion here should not be how to check to see if an object is a generic Nullable type, but rather whether one can assign a value of null to an object of its type. In other words, I think we should be determining whether an object type is nullable, not whether it is Nullable. The difference is in semantics, namely the practical reasons for determining nullability, which is usually all that matters.</p>\n\n<p>In a system using objects with types possibly unknown until run-time (web services, remote calls, databases, feeds, etc.), a common requirement is to determine whether a null can be assigned to the object, or whether the object might contain a null. Performing such operations on non-nullable types will likely produce errors, usually exceptions, which are very expensive both in terms of performance and coding requirements. To take the highly-preferred approach of proactively avoiding such problems, it is necessary to determine whether an object of an arbitrary Type is capable of containing a null; i.e., whether it is generally 'nullable'.</p>\n\n<p>In a very practical and typical sense, nullability in .NET terms does not at all necessarily imply that an object's Type is a form of Nullable. In many cases in fact, objects have reference types, can contain a null value, and thus are all nullable; none of these have a Nullable type. Therefore, for practical purposes in most scenarios, testing should be done for the general concept of nullability, vs. the implementation-dependent concept of Nullable. So we should not be hung up by focusing solely on the .NET Nullable type but rather incorporate our understanding of its requirements and behavior in the process of focusing on the general, practical concept of nullability.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?" So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type? So I have ``` typeof(int) typeof(DateTime) System.Type t = something; ``` and I want ``` int? DateTime? ``` or ``` Nullable<int> (which is the same) if (t is primitive) then Nullable<T> else just T ``` Is there a built-in method?
Here is the code I use: ``` Type GetNullableType(Type type) { // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable. type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null if (type.IsValueType) return typeof(Nullable<>).MakeGenericType(type); else return type; } ```
108,134
<p>I am using <code>pyexcelerator</code> Python module to generate Excel files. I want to apply bold style to part of cell text, but not to the whole cell. How to do it?</p>
[ { "answer_id": 108204, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>This is an example from Excel documentation:</p>\n\n<pre><code>With Worksheets(\"Sheet1\").Range(\"B1\")\n .Value = \"New Title\"\n .Characters(5, 5).Font.Bold = True\nEnd With\n</code></pre>\n\n<p>So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(<em>start</em>, <em>length</em>).</p>\n\n<p>PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com.</p>\n" }, { "answer_id": 109724, "author": "Greg", "author_id": 13009, "author_profile": "https://Stackoverflow.com/users/13009", "pm_score": 2, "selected": false, "text": "<p>Found example here: <a href=\"http://www.answermysearches.com/generate-an-excel-formatted-file-right-in-python/122/\" rel=\"nofollow noreferrer\">Generate an Excel Formatted File Right in Python</a></p>\n\n<p>Notice that you make a font object and then give it to a style object, and then provide that style object when writing to the sheet:</p>\n\n<pre><code>import pyExcelerator as xl\n\ndef save_in_excel(headers,values):\n #Open new workbook\n mydoc=xl.Workbook()\n #Add a worksheet\n mysheet=mydoc.add_sheet(\"test\")\n #write headers\n header_font=xl.Font() #make a font object\n header_font.bold=True\n header_font.underline=True\n #font needs to be style actually\n header_style = xl.XFStyle(); header_style.font = header_font\n for col,value in enumerate(headers):\n mysheet.write(0,col,value,header_style)\n #write values and highlight those that match my criteria\n highlighted_row_font=xl.Font() #no real highlighting available?\n highlighted_row_font.bold=True\n highlighted_row_font.colour_index=2 #2 is red,\n highlighted_row_style = xl.XFStyle(); highlighted_row_style.font = highlighted_row_font\n for row_num,row_values in enumerate(values):\n row_num+=1 #start at row 1\n if row_values[1]=='Manatee':\n for col,value in enumerate(row_values):\n #make Manatee's (sp) red\n mysheet.write(row_num,col,value,highlighted_row_style)\n else:\n for col,value in enumerate(row_values):\n #normal row\n mysheet.write(row_num,col,value)\n #save file\n mydoc.save(r'C:testpyexel.xlt')\n\nheaders=['Date','Name','Localatity']\ndata=[\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Manatee','San Jose'],\n['June 11, 2006','Greg','San Jose'],\n['June 11, 2006','Manatee','San Jose'],\n]\n\nsave_in_excel(headers,data)\n</code></pre>\n" }, { "answer_id": 66246157, "author": "ItsPrinceAk", "author_id": 10730446, "author_profile": "https://Stackoverflow.com/users/10730446", "pm_score": 1, "selected": false, "text": "<p>Here is one solution which i had used for the same problem.</p>\n<pre><code> import xlsxwriter\n workbook = xlsxwriter.Workbook(r'C:\\workspace\\NMSAutomation_001\\FMGGUIAutomation\\Libraries\\Frontend\\new_STICKERS_Final.xlsx')\n####### two different formats\n bold = workbook.add_format({'font_name':'Tahoma', 'bold': True, 'font_size':14})\n normal = workbook.add_format({'font_name':'Tahoma', 'font_size':11})\n\n######## value is my string, bold and normal are my two different formats\n segments = [bold, value[:9], normal, value[9:]]\n worksheet.write_rich_string('A1', *segments) # 'A1' is cell position\n workbook.close()\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19607/" ]
I am using `pyexcelerator` Python module to generate Excel files. I want to apply bold style to part of cell text, but not to the whole cell. How to do it?
This is an example from Excel documentation: ``` With Worksheets("Sheet1").Range("B1") .Value = "New Title" .Characters(5, 5).Font.Bold = True End With ``` So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(*start*, *length*). PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com.
108,169
<p>Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?</p> <h3>EDIT:</h3> <p>Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.</p>
[ { "answer_id": 108248, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 4, "selected": true, "text": "<p>The following code will do what you want:</p>\n\n<pre><code>(define get-n-items\n (lambda (lst num)\n (if (&gt; num 0)\n (cons (car lst) (get-n-items (cdr lst) (- num 1)))\n '()))) ;'\n\n(define slice\n (lambda (lst start count)\n (if (&gt; start 1)\n (slice (cdr lst) (- start 1) count)\n (get-n-items lst count))))\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt; (define l '(2 3 4 5 6 7 8 9)) ;'\n()\n&gt; l\n(2 3 4 5 6 7 8 9)\n&gt; (slice l 2 4)\n(3 4 5 6)\n&gt; \n</code></pre>\n" }, { "answer_id": 108265, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "<pre><code>(define (sublist list start number)\n (cond ((&gt; start 0) (sublist (cdr list) (- start 1) number))\n ((&gt; number 0) (cons (car list)\n (sublist (cdr list) 0 (- number 1))))\n (else '())))\n</code></pre>\n" }, { "answer_id": 108266, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 1, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code> (define (slice l offset length)\n (if (null? l)\n l\n (if (&gt; offset 0)\n (slice (cdr l) (- offset 1) length)\n (if (&gt; length 0)\n (cons (car l) (slice (cdr l) 0 (- length 1)))\n '()))))\n</code></pre>\n" }, { "answer_id": 116452, "author": "Josh Gagnon", "author_id": 7944, "author_profile": "https://Stackoverflow.com/users/7944", "pm_score": 3, "selected": false, "text": "<p>You can try this function:</p>\n\n<blockquote>\n <p><strong>subseq</strong> <em>sequence start &amp;optional end</em></p>\n</blockquote>\n\n<p>The <em>start</em> parameter is your offset. The <em>end</em> parameter can be easily turned into the number of elements to grab by simply adding start + number-of-elements.</p>\n\n<p>A small bonus is that <strong>subseq</strong> works on all sequences, this includes not only lists but also string and vectors.</p>\n\n<p>Edit: It seems that not all lisp implementations have subseq, though it will do the job just fine if you have it.</p>\n" }, { "answer_id": 121976, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 4, "selected": false, "text": "<p>Strangely, <code>slice</code> is not provided with <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html\" rel=\"noreferrer\">SRFI-1</a> but you can make it shorter by using SRFI-1's <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html#take\" rel=\"noreferrer\"><code>take</code> and <code>drop</code></a>:</p>\n\n<pre><code>(define (slice l offset n)\n (take (drop l offset) n))\n</code></pre>\n\n<p>I thought that one of the extensions I've used with Scheme, like the PLT Scheme library or Swindle, would have this built-in, but it doesn't seem to be the case. It's not even defined in the new R6RS libraries.</p>\n" }, { "answer_id": 35534477, "author": "Mulan", "author_id": 633183, "author_profile": "https://Stackoverflow.com/users/633183", "pm_score": 1, "selected": false, "text": "<p>Here's my implementation of <code>slice</code> that uses a proper tail call</p>\n\n<pre><code>(define (slice a b xs (ys null))\n (cond ((&gt; a 0) (slice (- a 1) b (cdr xs) ys))\n ((&gt; b 0) (slice a (- b 1) (cdr xs) (cons (car xs) ys)))\n (else (reverse ys))))\n\n(slice 0 3 '(A B C D E F G)) ;=&gt; '(A B C)\n(slice 2 4 '(A B C D E F G)) ;=&gt; '(C D E F)\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ? ### EDIT: Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.
The following code will do what you want: ``` (define get-n-items (lambda (lst num) (if (> num 0) (cons (car lst) (get-n-items (cdr lst) (- num 1))) '()))) ;' (define slice (lambda (lst start count) (if (> start 1) (slice (cdr lst) (- start 1) count) (get-n-items lst count)))) ``` Example: ``` > (define l '(2 3 4 5 6 7 8 9)) ;' () > l (2 3 4 5 6 7 8 9) > (slice l 2 4) (3 4 5 6) > ```
108,183
<p>I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.</p> <p>The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a <code>SIGPIPE</code> and make my server crash.</p> <p>What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (<code>select()</code> doesn't seem to work here as it always says the socket is writable). Or should I just catch the <code>SIGPIPE</code> with a handler and ignore it?</p>
[ { "answer_id": 108190, "author": "Sam Reynolds", "author_id": 9192, "author_profile": "https://Stackoverflow.com/users/9192", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Or should I just catch the SIGPIPE with a handler and ignore it?</p>\n</blockquote>\n\n<p>I believe that is right on. You want to know when the other end has closed their descriptor and that's what SIGPIPE tells you.</p>\n\n<p>Sam</p>\n" }, { "answer_id": 108192, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 9, "selected": true, "text": "<p>You generally want to ignore the <code>SIGPIPE</code> and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do.</p>\n\n<p>The most portable way to do this is to set the <code>SIGPIPE</code> handler to <code>SIG_IGN</code>. This will prevent any socket or pipe write from causing a <code>SIGPIPE</code> signal.</p>\n\n<p>To ignore the <code>SIGPIPE</code> signal, use the following code:</p>\n\n<pre><code>signal(SIGPIPE, SIG_IGN);\n</code></pre>\n\n<p>If you're using the <code>send()</code> call, another option is to use the <code>MSG_NOSIGNAL</code> option, which will turn the <code>SIGPIPE</code> behavior off on a per call basis. Note that not all operating systems support the <code>MSG_NOSIGNAL</code> flag.</p>\n\n<p>Lastly, you may also want to consider the <code>SO_SIGNOPIPE</code> socket flag that can be set with <code>setsockopt()</code> on some operating systems. This will prevent <code>SIGPIPE</code> from being caused by writes just to the sockets it is set on.</p>\n" }, { "answer_id": 108358, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": false, "text": "<p>You cannot prevent the process on the far end of a pipe from exiting, and if it exits before you've finished writing, you will get a SIGPIPE signal. If you SIG_IGN the signal, then your write will return with an error - and you need to note and react to that error. Just catching and ignoring the signal in a handler is not a good idea -- you must note that the pipe is now defunct and modify the program's behaviour so it does not write to the pipe again (because the signal will be generated again, and ignored again, and you'll try again, and the whole process could go on for a <em>long</em> time and waste a lot of CPU power).</p>\n" }, { "answer_id": 450130, "author": "user55807", "author_id": 55807, "author_profile": "https://Stackoverflow.com/users/55807", "pm_score": 7, "selected": false, "text": "<p>Another method is to change the socket so it never generates SIGPIPE on write(). This is more convenient in libraries, where you might not want a global signal handler for SIGPIPE.</p>\n\n<p>On most BSD-based (MacOS, FreeBSD...) systems, (assuming you are using C/C++), you can do this with:</p>\n\n<pre><code>int set = 1;\nsetsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&amp;set, sizeof(int));\n</code></pre>\n\n<p>With this in effect, instead of the SIGPIPE signal being generated, EPIPE will be returned.</p>\n" }, { "answer_id": 1705705, "author": "sklnd", "author_id": 204462, "author_profile": "https://Stackoverflow.com/users/204462", "pm_score": 7, "selected": false, "text": "<p>I'm super late to the party, but <code>SO_NOSIGPIPE</code> isn't portable, and might not work on your system (it seems to be a BSD thing).</p>\n\n<p>A nice alternative if you're on, say, a Linux system without <code>SO_NOSIGPIPE</code> would be to set the <code>MSG_NOSIGNAL</code> flag on your send(2) call. </p>\n\n<p>Example replacing <code>write(...)</code> by <code>send(...,MSG_NOSIGNAL)</code> (see <a href=\"https://stackoverflow.com/users/86967/nobar\">nobar</a>'s comment)</p>\n\n<pre><code>char buf[888];\n//write( sockfd, buf, sizeof(buf) );\nsend( sockfd, buf, sizeof(buf), MSG_NOSIGNAL );\n</code></pre>\n" }, { "answer_id": 2347848, "author": "kroki", "author_id": 282730, "author_profile": "https://Stackoverflow.com/users/282730", "pm_score": 5, "selected": false, "text": "<p>In this <a href=\"http://krokisplace.blogspot.com/2010/02/suppressing-sigpipe-in-library.html\" rel=\"noreferrer\">post</a> I described possible solution for Solaris case when neither SO_NOSIGPIPE nor MSG_NOSIGNAL is available.</p>\n\n<blockquote>\n <p>Instead, we have to temporarily suppress SIGPIPE in the current thread that executes library code. Here's how to do this: to suppress SIGPIPE we first check if it is pending. If it does, this means that it is blocked in this thread, and we have to do nothing. If the library generates additional SIGPIPE, it will be merged with the pending one, and that's a no-op. If SIGPIPE is not pending then we block it in this thread, and also check whether it was already blocked. Then we are free to execute our writes. When we are to restore SIGPIPE to its original state, we do the following: if SIGPIPE was pending originally, we do nothing. Otherwise we check if it is pending now. If it does (which means that out actions have generated one or more SIGPIPEs), then we wait for it in this thread, thus clearing its pending status (to do this we use sigtimedwait() with zero timeout; this is to avoid blocking in a scenario where malicious user sent SIGPIPE manually to a whole process: in this case we will see it pending, but other thread may handle it before we had a change to wait for it). After clearing pending status we unblock SIGPIPE in this thread, but only if it wasn't blocked originally.</p>\n</blockquote>\n\n<p>Example code at <a href=\"https://github.com/kroki/XProbes/blob/1447f3d93b6dbf273919af15e59f35cca58fcc23/src/libxprobes.c#L156\" rel=\"noreferrer\">https://github.com/kroki/XProbes/blob/1447f3d93b6dbf273919af15e59f35cca58fcc23/src/libxprobes.c#L156</a></p>\n" }, { "answer_id": 9036323, "author": "Sam", "author_id": 590956, "author_profile": "https://Stackoverflow.com/users/590956", "pm_score": 5, "selected": false, "text": "<h2>Handle SIGPIPE Locally</h2>\n\n<p>It's usually best to handle the error locally rather than in a global signal event handler since locally you will have more context as to what's going on and what recourse to take.</p>\n\n<p>I have a communication layer in one of my apps that allows my app to communicate with an external accessory. When a write error occurs I throw and exception in the communication layer and let it bubble up to a try catch block to handle it there.</p>\n\n<h2>Code:</h2>\n\n<p>The code to ignore a SIGPIPE signal so that you can handle it locally is:</p>\n\n<pre><code>// We expect write failures to occur but we want to handle them where \n// the error occurs rather than in a SIGPIPE handler.\nsignal(SIGPIPE, SIG_IGN);\n</code></pre>\n\n<p>This code will prevent the SIGPIPE signal from being raised, but you will get a read / write error when trying to use the socket, so you will need to check for that.</p>\n" }, { "answer_id": 22664170, "author": "talash", "author_id": 3022232, "author_profile": "https://Stackoverflow.com/users/3022232", "pm_score": 2, "selected": false, "text": "<p>Linux manual said:</p>\n\n<blockquote>\n <p>EPIPE The local end has been shut down on a connection oriented\n socket. In this case the process will also receive a SIGPIPE\n unless MSG_NOSIGNAL is set.</p>\n</blockquote>\n\n<p>But for Ubuntu 12.04 it isn't right. I wrote a test for that case and I always receive EPIPE withot SIGPIPE. SIGPIPE is genereated if I try to write to the same broken socket second time. So you don't need to ignore SIGPIPE if this signal happens it means logic error in your program.</p>\n" }, { "answer_id": 32597537, "author": "Ben Aveling", "author_id": 2817542, "author_profile": "https://Stackoverflow.com/users/2817542", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>What's the best practice to prevent the crash here? </p>\n</blockquote>\n\n<p>Either disable sigpipes as per everybody, or catch and ignore the error.</p>\n\n<blockquote>\n <p>Is there a way to check if the other side of the line is still reading? </p>\n</blockquote>\n\n<p>Yes, use select().</p>\n\n<blockquote>\n <p>select() doesn't seem to work here as it always says the socket is writable.</p>\n</blockquote>\n\n<p>You need to select on the <em>read</em> bits. You can probably ignore the <em>write</em> bits.</p>\n\n<p>When the far end closes its file handle, select will tell you that there is data ready to read. When you go and read that, you will get back 0 bytes, which is how the OS tells you that the file handle has been closed.</p>\n\n<p>The only time you can't ignore the write bits is if you are sending large volumes, and there is a risk of the other end getting backlogged, which can cause your buffers to fill. If that happens, then trying to write to the file handle can cause your program/thread to block or fail. Testing select before writing will protect you from that, but it doesn't guarantee that the other end is healthy or that your data is going to arrive.</p>\n\n<p>Note that you can get a sigpipe from close(), as well as when you write.</p>\n\n<p>Close flushes any buffered data. If the other end has already been closed, then close will fail, and you will receive a sigpipe. </p>\n\n<p>If you are using buffered TCPIP, then a successful write just means your data has been queued to send, it doesn't mean it has been sent. Until you successfully call close, you don't know that your data has been sent.</p>\n\n<p>Sigpipe tells you something has gone wrong, it doesn't tell you what, or what you should do about it.</p>\n" }, { "answer_id": 35354069, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 2, "selected": false, "text": "<p>Under a modern POSIX system (i.e. Linux), you can use the <code>sigprocmask()</code> function.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;signal.h&gt;\n\nvoid block_signal(int signal_to_block /* i.e. SIGPIPE */ )\n{\n sigset_t set;\n sigset_t old_state;\n\n // get the current state\n //\n sigprocmask(SIG_BLOCK, NULL, &amp;old_state);\n\n // add signal_to_block to that existing state\n //\n set = old_state;\n sigaddset(&amp;set, signal_to_block);\n\n // block that signal also\n //\n sigprocmask(SIG_BLOCK, &amp;set, NULL);\n\n // ... deal with old_state if required ...\n}\n</code></pre>\n\n<p>If you want to restore the previous state later, make sure to save the <code>old_state</code> somewhere safe. If you call that function multiple times, you need to either use a stack or only save the first or last <code>old_state</code>... or maybe have a function which removes a specific blocked signal.</p>\n\n<p>For more info read the <a href=\"http://linux.die.net/man/2/sigprocmask\" rel=\"nofollow noreferrer\">man page</a>.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12523/" ]
I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply. The problem is that the client may have no interest in the answer and sometimes exits early. So writing to that socket will cause a `SIGPIPE` and make my server crash. What's the best practice to prevent the crash here? Is there a way to check if the other side of the line is still reading? (`select()` doesn't seem to work here as it always says the socket is writable). Or should I just catch the `SIGPIPE` with a handler and ignore it?
You generally want to ignore the `SIGPIPE` and handle the error directly in your code. This is because signal handlers in C have many restrictions on what they can do. The most portable way to do this is to set the `SIGPIPE` handler to `SIG_IGN`. This will prevent any socket or pipe write from causing a `SIGPIPE` signal. To ignore the `SIGPIPE` signal, use the following code: ``` signal(SIGPIPE, SIG_IGN); ``` If you're using the `send()` call, another option is to use the `MSG_NOSIGNAL` option, which will turn the `SIGPIPE` behavior off on a per call basis. Note that not all operating systems support the `MSG_NOSIGNAL` flag. Lastly, you may also want to consider the `SO_SIGNOPIPE` socket flag that can be set with `setsockopt()` on some operating systems. This will prevent `SIGPIPE` from being caused by writes just to the sockets it is set on.
108,193
<pre><code>class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) </code></pre> <p>Simple models just to ask my question.</p> <p>I wonder how can i query blogs using tags in two different ways.</p> <ul> <li>Blog entries that are tagged with "tag1" or "tag2": <code>Blog.objects.filter(tags_in=[1,2]).distinct()</code></li> <li>Blog objects that are tagged with "tag1" and "tag2" : <strong>?</strong></li> <li>Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : <strong>??</strong></li> </ul> <hr> <p>Tag and Blog is just used for an example.</p>
[ { "answer_id": 108404, "author": "Clint Ecker", "author_id": 13668, "author_profile": "https://Stackoverflow.com/users/13668", "pm_score": 6, "selected": true, "text": "<p>You could use Q objects for #1:</p>\n\n<pre><code># Blogs who have either hockey or django tags.\nfrom django.db.models import Q\nBlog.objects.filter(\n Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')\n)\n</code></pre>\n\n<p>Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The following examples are from a Django application called called <a href=\"http://code.google.com/p/django-tagging/\" rel=\"noreferrer\">django-tagging</a> that provides the functionality. <a href=\"http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#346\" rel=\"noreferrer\">Line 346 of models.py</a>: </p>\n\n<p>For part two, you're looking for a union of two queries, basically</p>\n\n<pre><code>def get_union_by_model(self, queryset_or_model, tags):\n \"\"\"\n Create a ``QuerySet`` containing instances of the specified\n model associated with *any* of the given list of tags.\n \"\"\"\n tags = get_tag_list(tags)\n tag_count = len(tags)\n queryset, model = get_queryset_and_model(queryset_or_model)\n\n if not tag_count:\n return model._default_manager.none()\n\n model_table = qn(model._meta.db_table)\n # This query selects the ids of all objects which have any of\n # the given tags.\n query = \"\"\"\n SELECT %(model_pk)s\n FROM %(model)s, %(tagged_item)s\n WHERE %(tagged_item)s.content_type_id = %(content_type_id)s\n AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)\n AND %(model_pk)s = %(tagged_item)s.object_id\n GROUP BY %(model_pk)s\"\"\" % {\n 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),\n 'model': model_table,\n 'tagged_item': qn(self.model._meta.db_table),\n 'content_type_id': ContentType.objects.get_for_model(model).pk,\n 'tag_id_placeholders': ','.join(['%s'] * tag_count),\n }\n\n cursor = connection.cursor()\n cursor.execute(query, [tag.pk for tag in tags])\n object_ids = [row[0] for row in cursor.fetchall()]\n if len(object_ids) &gt; 0:\n return queryset.filter(pk__in=object_ids)\n else:\n return model._default_manager.none()\n</code></pre>\n\n<p>For part #3 I believe you're looking for an intersection. See <a href=\"http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#307\" rel=\"noreferrer\">line 307 of models.py</a> </p>\n\n<pre><code>def get_intersection_by_model(self, queryset_or_model, tags):\n \"\"\"\n Create a ``QuerySet`` containing instances of the specified\n model associated with *all* of the given list of tags.\n \"\"\"\n tags = get_tag_list(tags)\n tag_count = len(tags)\n queryset, model = get_queryset_and_model(queryset_or_model)\n\n if not tag_count:\n return model._default_manager.none()\n\n model_table = qn(model._meta.db_table)\n # This query selects the ids of all objects which have all the\n # given tags.\n query = \"\"\"\n SELECT %(model_pk)s\n FROM %(model)s, %(tagged_item)s\n WHERE %(tagged_item)s.content_type_id = %(content_type_id)s\n AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)\n AND %(model_pk)s = %(tagged_item)s.object_id\n GROUP BY %(model_pk)s\n HAVING COUNT(%(model_pk)s) = %(tag_count)s\"\"\" % {\n 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),\n 'model': model_table,\n 'tagged_item': qn(self.model._meta.db_table),\n 'content_type_id': ContentType.objects.get_for_model(model).pk,\n 'tag_id_placeholders': ','.join(['%s'] * tag_count),\n 'tag_count': tag_count,\n }\n\n cursor = connection.cursor()\n cursor.execute(query, [tag.pk for tag in tags])\n object_ids = [row[0] for row in cursor.fetchall()]\n if len(object_ids) &gt; 0:\n return queryset.filter(pk__in=object_ids)\n else:\n return model._default_manager.none()\n</code></pre>\n" }, { "answer_id": 108500, "author": "Ycros", "author_id": 10495, "author_profile": "https://Stackoverflow.com/users/10495", "pm_score": 4, "selected": false, "text": "<p>I've tested these out with Django 1.0:</p>\n\n<p>The \"or\" queries:</p>\n\n<pre><code>Blog.objects.filter(tags__name__in=['tag1', 'tag2']).distinct()\n</code></pre>\n\n<p>or you could use the Q class:</p>\n\n<pre><code>Blog.objects.filter(Q(tags__name='tag1') | Q(tags__name='tag2')).distinct()\n</code></pre>\n\n<p>The \"and\" query:</p>\n\n<pre><code>Blog.objects.filter(tags__name='tag1').filter(tags__name='tag2')\n</code></pre>\n\n<p>I'm not sure about the third one, you'll probably need to drop to SQL to do it.</p>\n" }, { "answer_id": 110437, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 3, "selected": false, "text": "<p>Please don't reinvent the wheel and use <a href=\"http://code.google.com/p/django-tagging/\" rel=\"noreferrer\">django-tagging application</a> which was made exactly for your use case. It can do all queries you describe, and much more.</p>\n\n<p>If you need to add custom fields to your Tag model, you can also take a look at <a href=\"http://www.bitbucket.org/zuber/django-newtagging\" rel=\"noreferrer\">my branch of django-tagging</a>.</p>\n" }, { "answer_id": 4604096, "author": "amit", "author_id": 563925, "author_profile": "https://Stackoverflow.com/users/563925", "pm_score": 3, "selected": false, "text": "<p>This will do the trick for you</p>\n\n<pre><code>Blog.objects.filter(tags__name__in=['tag1', 'tag2']).annotate(tag_matches=models.Count(tags)).filter(tag_matches=2)\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12785/" ]
``` class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) ``` Simple models just to ask my question. I wonder how can i query blogs using tags in two different ways. * Blog entries that are tagged with "tag1" or "tag2": `Blog.objects.filter(tags_in=[1,2]).distinct()` * Blog objects that are tagged with "tag1" and "tag2" : **?** * Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : **??** --- Tag and Blog is just used for an example.
You could use Q objects for #1: ``` # Blogs who have either hockey or django tags. from django.db.models import Q Blog.objects.filter( Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django') ) ``` Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The following examples are from a Django application called called [django-tagging](http://code.google.com/p/django-tagging/) that provides the functionality. [Line 346 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#346): For part two, you're looking for a union of two queries, basically ``` def get_union_by_model(self, queryset_or_model, tags): """ Create a ``QuerySet`` containing instances of the specified model associated with *any* of the given list of tags. """ tags = get_tag_list(tags) tag_count = len(tags) queryset, model = get_queryset_and_model(queryset_or_model) if not tag_count: return model._default_manager.none() model_table = qn(model._meta.db_table) # This query selects the ids of all objects which have any of # the given tags. query = """ SELECT %(model_pk)s FROM %(model)s, %(tagged_item)s WHERE %(tagged_item)s.content_type_id = %(content_type_id)s AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s) AND %(model_pk)s = %(tagged_item)s.object_id GROUP BY %(model_pk)s""" % { 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)), 'model': model_table, 'tagged_item': qn(self.model._meta.db_table), 'content_type_id': ContentType.objects.get_for_model(model).pk, 'tag_id_placeholders': ','.join(['%s'] * tag_count), } cursor = connection.cursor() cursor.execute(query, [tag.pk for tag in tags]) object_ids = [row[0] for row in cursor.fetchall()] if len(object_ids) > 0: return queryset.filter(pk__in=object_ids) else: return model._default_manager.none() ``` For part #3 I believe you're looking for an intersection. See [line 307 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#307) ``` def get_intersection_by_model(self, queryset_or_model, tags): """ Create a ``QuerySet`` containing instances of the specified model associated with *all* of the given list of tags. """ tags = get_tag_list(tags) tag_count = len(tags) queryset, model = get_queryset_and_model(queryset_or_model) if not tag_count: return model._default_manager.none() model_table = qn(model._meta.db_table) # This query selects the ids of all objects which have all the # given tags. query = """ SELECT %(model_pk)s FROM %(model)s, %(tagged_item)s WHERE %(tagged_item)s.content_type_id = %(content_type_id)s AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s) AND %(model_pk)s = %(tagged_item)s.object_id GROUP BY %(model_pk)s HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % { 'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)), 'model': model_table, 'tagged_item': qn(self.model._meta.db_table), 'content_type_id': ContentType.objects.get_for_model(model).pk, 'tag_id_placeholders': ','.join(['%s'] * tag_count), 'tag_count': tag_count, } cursor = connection.cursor() cursor.execute(query, [tag.pk for tag in tags]) object_ids = [row[0] for row in cursor.fetchall()] if len(object_ids) > 0: return queryset.filter(pk__in=object_ids) else: return model._default_manager.none() ```
108,200
<p>I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?</p>
[ { "answer_id": 108220, "author": "Joshua", "author_id": 6013, "author_profile": "https://Stackoverflow.com/users/6013", "pm_score": 0, "selected": false, "text": "<p>Extract the data from the header using some sort of substring or regular expression. Parse the date with a SimpleDateFormatter to create a Date object.</p>\n" }, { "answer_id": 108239, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 1, "selected": false, "text": "<p>Probably easiest to parse with JodaTime as it supports ISO8601 see <a href=\"http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html\" rel=\"nofollow noreferrer\">Date and Time Parsing and Formatting in Java with Joda Time</a>.</p>\n\n<pre><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();\nSystem.out.println(parser2.parseDateTime(your_date_string));\n</code></pre>\n\n<p>Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone.</p>\n\n<p>You must store the date with the timezone after converting to UTC.</p>\n\n<p>If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone.</p>\n" }, { "answer_id": 108263, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 0, "selected": false, "text": "<p>The timezone in the email will not show in which timezone it was send. Some programs use ever UTC or GMT. Of course the time zone is part of the date time value and must also be parse.</p>\n\n<p>Why do you want know it. \n - Do you want normalize the timestamp? Then use a DateFormat for parsing it.\n - Do you want detect the timezome of the user that send the email? This will not correctly work.</p>\n" }, { "answer_id": 108431, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 0, "selected": false, "text": "<p>It looks like you already mentioned this in one of your comments, but I think it's your best answer. The JavaMail library contains RFC822 Date header parsing code in <code>javax.mail.internet.MailDateFormat</code>. Unfortunately it doesn't expose the TimeZone parsing directly, so you will need to copy the necessary code directly from <code>javax.mail.internet.MailDateParser</code>, but it's worth taking advantage of the careful work already done.</p>\n\n<p>As for storing it, the parser will give you the date as an offset, so you should be able to store it just fine as an <code>int</code> (letting Hibernate translate that to your database for you).</p>\n" }, { "answer_id": 11689182, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 1, "selected": false, "text": "<p><strong>I recommend you use <a href=\"http://james.apache.org/mime4j/\" rel=\"nofollow\">Mime4J</a>.</strong> </p>\n\n<p>The library is designed for parsing all kinds of email crap.\nFor parsing dates you would use its <a href=\"http://james.apache.org/mime4j/apidocs/org/apache/james/mime4j/field/datetime/parser/DateTimeParser.html\" rel=\"nofollow\">DateTimeParser</a>.</p>\n\n<pre><code>int zone = new DateTimeParser(new StringReader(\"Fri, 27 Jul 2012 09:13:15 -0400\")).zone();\n</code></pre>\n\n<p>After that I usually convert the datetimes to <strong><a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow\">Joda's DateTime</a></strong>. Don't use SimpleDateFormatter as will not cover all the cases for RFC822.</p>\n\n<p>Below will get you the <strong>Joda TimeZone</strong> (from the int zone above) which is superior to Java's TZ.</p>\n\n<pre><code>// Stupid hack in case the zone is not in [-+]zzzz format\nfinal int hours;\nfinal int minutes;\nif (zone &gt; 24 || zone &lt; -24 ) {\n hours = zone / 100;\n minutes = minutes = Math.abs(zone % 100);\n}\nelse {\n hours = zone;\n minutes = 0;\n}\nDateTimeZone.forOffsetHoursMinutes(hours, minutes);\n</code></pre>\n\n<p>Now the only issue is that the Time Zone you will get always be a numeric time zone which may still not be the correct time zone of the user sending the email (assuming the mail app sent the users TZ and not just UTC).</p>\n\n<p>For example -0400 is not EDT (ie America/New_York) because it does not take Daylight savings into account. </p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15231/" ]
I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?
Probably easiest to parse with JodaTime as it supports ISO8601 see [Date and Time Parsing and Formatting in Java with Joda Time](http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html). ``` DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); System.out.println(parser2.parseDateTime(your_date_string)); ``` Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone. You must store the date with the timezone after converting to UTC. If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone.
108,207
<p>I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.</p> <p>BTW, this is an on-page <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> search, so it has no button.</p>
[ { "answer_id": 108218, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 4, "selected": false, "text": "<p>You can add and remove a special CSS class and modify the input value <code>onfocus</code>/<code>onblur</code> with JavaScript:</p>\n\n<pre><code>&lt;input type=\"text\" class=\"hint\" value=\"Search...\"\n onfocus=\"if (this.className=='hint') { this.className = ''; this.value = ''; }\"\n onblur=\"if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }\"&gt;\n</code></pre>\n\n<p>Then specify a <strong>hint</strong> class with the styling you want in your CSS for example:</p>\n\n<pre><code>input.hint {\n color: grey;\n}\n</code></pre>\n" }, { "answer_id": 108222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could easily have a box read \"Search\" then when the focus is changed to it have the text be removed. Something like this:</p>\n\n<p><code>&lt;input onfocus=\"this.value=''\" type=\"text\" value=\"Search\" /&gt;</code></p>\n\n<p>Of course if you do that the user's own text will disappear when they click. So you probably want to use something more robust:</p>\n\n<pre><code>&lt;input name=\"keyword_\" type=\"text\" size=\"25\" style=\"color:#999;\" maxlength=\"128\" id=\"keyword_\"\nonblur=\"this.value = this.value || this.defaultValue; this.style.color = '#999';\"\nonfocus=\"this.value=''; this.style.color = '#000';\"\nvalue=\"Search Term\"&gt;\n</code></pre>\n" }, { "answer_id": 108223, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 3, "selected": false, "text": "<p>The best way is to wire up your JavaScript events using some kind of JavaScript library like <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a> or <a href=\"http://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"nofollow noreferrer\">YUI</a> and put your code in an external .js-file.</p>\n\n<p>But if you want a quick-and-dirty solution this is your inline HTML-solution:</p>\n\n<pre><code>&lt;input type=\"text\" id=\"textbox\" value=\"Search\"\n onclick=\"if(this.value=='Search'){this.value=''; this.style.color='#000'}\" \n onblur=\"if(this.value==''){this.value='Search'; this.style.color='#555'}\" /&gt;\n</code></pre>\n\n<p><strong>Updated</strong>: Added the requested coloring-stuff.</p>\n" }, { "answer_id": 108224, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>Use a background image to render the text:</p>\n\n<pre><code> input.foo { }\n input.fooempty { background-image: url(\"blah.png\"); }\n</code></pre>\n\n<p>Then all you have to do is detect <code>value == 0</code> and apply the right class:</p>\n\n<pre><code> &lt;input class=\"foo fooempty\" value=\"\" type=\"text\" name=\"bar\" /&gt;\n</code></pre>\n\n<p>And the jQuery JavaScript code looks like this:</p>\n\n<pre><code>jQuery(function($)\n{\n var target = $(\"input.foo\");\n target.bind(\"change\", function()\n {\n if( target.val().length &gt; 1 )\n {\n target.addClass(\"fooempty\");\n }\n else\n {\n target.removeClass(\"fooempty\");\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 108230, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>You want to assign something like this to onfocus:</p>\n\n<pre><code>if (this.value == this.defaultValue)\n this.value = ''\nthis.className = ''\n</code></pre>\n\n<p>and this to onblur:</p>\n\n<pre><code>if (this.value == '')\n this.value = this.defaultValue\nthis.className = 'placeholder'\n</code></pre>\n\n<p>(You can use something a bit cleverer, like a framework function, to do the classname switching if you want.)</p>\n\n<p>With some CSS like this:</p>\n\n<pre><code>input.placeholder{\n color: gray;\n font-style: italic;\n}\n</code></pre>\n" }, { "answer_id": 108232, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 7, "selected": false, "text": "<p>That is known as a textbox watermark, and it is done via JavaScript.</p>\n\n<ul>\n<li><a href=\"http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx\" rel=\"noreferrer\">http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx</a></li>\n</ul>\n\n<p>or if you use jQuery, a much better approach:</p>\n\n<ul>\n<li><a href=\"http://digitalbush.com/projects/watermark-input-plugin/\" rel=\"noreferrer\">http://digitalbush.com/projects/watermark-input-plugin/</a></li>\n<li>or <a href=\"http://code.google.com/p/jquery-watermark\" rel=\"noreferrer\">code.google.com/p/jquery-watermark</a></li>\n</ul>\n" }, { "answer_id": 108262, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>When the page first loads, have Search appear in the text box, colored gray if you want it to be.</p>\n\n<p>When the input box receives focus, select all of the text in the search box so that the user can just start typing, which will delete the selected text in the process. This will also work nicely if the user wants to use the search box a second time since they won't have to manually highlight the previous text to delete it.</p>\n\n<pre><code>&lt;input type=\"text\" value=\"Search\" onfocus=\"this.select();\" /&gt;\n</code></pre>\n" }, { "answer_id": 108437, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": false, "text": "<p>Here's a functional example with Google Ajax library cache and some jQuery magic.</p>\n\n<p>This would be the CSS:</p>\n\n<pre><code>&lt;style type=\"text/stylesheet\" media=\"screen\"&gt;\n .inputblank { color:gray; } /* Class to use for blank input */\n&lt;/style&gt;\n</code></pre>\n\n<p>This would would be the JavaScript code:</p>\n\n<pre><code>&lt;script language=\"javascript\"\n type=\"text/javascript\"\n src=\"http://www.google.com/jsapi\"&gt;\n&lt;/script&gt;\n&lt;script&gt;\n // Load jQuery\n google.load(\"jquery\", \"1\");\n\n google.setOnLoadCallback(function() {\n $(\"#search_form\")\n .submit(function() {\n alert(\"Submitted. Value= \" + $(\"input:first\").val());\n return false;\n });\n\n $(\"#keywords\")\n .focus(function() {\n if ($(this).val() == 'Search') {\n $(this)\n .removeClass('inputblank')\n .val('');\n }\n })\n .blur(function() {\n if ($(this).val() == '') {\n $(this)\n .addClass('inputblank')\n .val('Search');\n }\n });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>And this would be the HTML:</p>\n\n<pre><code>&lt;form id=\"search_form\"&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Search the site&lt;/legend&gt;\n &lt;label for=\"keywords\"&gt;Keywords:&lt;/label&gt;\n &lt;input id=\"keywords\" type=\"text\" class=\"inputblank\" value=\"Search\"/&gt;\n &lt;/fieldset&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>I hope it's enough to make you interested in both the GAJAXLibs and in jQuery.</p>\n" }, { "answer_id": 176991, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>User AJAXToolkit from <a href=\"http://asp.net\" rel=\"nofollow noreferrer\">http://asp.net</a></p>\n\n<p>\n \n </p>\n" }, { "answer_id": 845658, "author": "tuomassalo", "author_id": 95357, "author_profile": "https://Stackoverflow.com/users/95357", "pm_score": 2, "selected": false, "text": "<p>For jQuery users: naspinski's jQuery link seems broken, but try this one:\n<a href=\"http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/\" rel=\"nofollow noreferrer\">http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/</a></p>\n\n<p>You get a free jQuery plugin tutorial as a bonus. :)</p>\n" }, { "answer_id": 949345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<pre><code>$('input[value=\"text\"]').focus(function(){ \nif ($(this).attr('class')=='hint') \n{ \n $(this).removeClass('hint'); \n $(this).val(''); \n}\n});\n\n$('input[value=\"text\"]').blur(function(){\n if($(this).val() == '')\n {\n $(this).addClass('hint');\n $(this).val($(this).attr('title'));\n } \n});\n\n&lt;input type=\"text\" value=\"\" title=\"Default Watermark Text\"&gt;\n</code></pre>\n" }, { "answer_id": 1091567, "author": "elcuco", "author_id": 78712, "author_profile": "https://Stackoverflow.com/users/78712", "pm_score": 2, "selected": false, "text": "<p>This is called \"watermark\".</p>\n\n<p>I found the jQuery plugin <em><a href=\"http://plugins.jquery.com/project/jquery-watermark\" rel=\"nofollow noreferrer\">jQuery watermark</a></em> which, unlike the first answer, does not require extra setup (the original answer also needs a special call to before the form is submitted).</p>\n" }, { "answer_id": 2658328, "author": "Dustin", "author_id": 292709, "author_profile": "https://Stackoverflow.com/users/292709", "pm_score": 2, "selected": false, "text": "<p>I found the jQuery plugin <em><a href=\"http://code.google.com/p/jquery-watermark/\" rel=\"nofollow noreferrer\">jQuery Watermark</a></em> to be better than the one listed in the top answer. Why better? Because it supports password input fields. Also, setting the color of the watermark (or other attributes) is as easy as creating a <code>.watermark</code> reference in your CSS file.</p>\n" }, { "answer_id": 2994702, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 2, "selected": false, "text": "<p>I posted <a href=\"http://www.drewnoakes.com/code/javascript/hintTextbox.html\" rel=\"nofollow noreferrer\">a solution for this on my website</a> some time ago. To use it, import a single <code>.js</code> file:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"/hint-textbox.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Then annotate whatever inputs you want to have hints with the CSS class <code>hintTextbox</code>:</p>\n\n<pre><code>&lt;input type=\"text\" name=\"email\" value=\"enter email\" class=\"hintTextbox\" /&gt;\n</code></pre>\n\n<p>More information and example are available <a href=\"http://www.drewnoakes.com/code/javascript/hintTextbox.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 3302835, "author": "0b10011", "author_id": 526741, "author_profile": "https://Stackoverflow.com/users/526741", "pm_score": 5, "selected": false, "text": "<p>You can set the <strong>placeholder</strong> using the <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-placeholder-attribute\" rel=\"noreferrer\"><code>placeholder</code> attribute</a> in HTML (<a href=\"http://caniuse.com/input-placeholder\" rel=\"noreferrer\">browser support</a>). The <code>font-style</code> and <code>color</code> can be <a href=\"http://css-tricks.com/snippets/css/style-placeholder-text/\" rel=\"noreferrer\">changed with CSS</a> (although browser support is limited).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */\r\n color:gray;\r\n font-style:italic;\r\n}\r\ninput[type=search]:-moz-placeholder { /* Firefox 18- */\r\n color:gray;\r\n font-style:italic;\r\n}\r\ninput[type=search]::-moz-placeholder { /* Firefox 19+ */\r\n color:gray;\r\n font-style:italic;\r\n}\r\ninput[type=search]:-ms-input-placeholder { /* IE (10+?) */\r\n color:gray;\r\n font-style:italic;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input placeholder=\"Search\" type=\"search\" name=\"q\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 3568964, "author": "Kimball Robinson", "author_id": 116810, "author_profile": "https://Stackoverflow.com/users/116810", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://code.google.com/p/jquery-formnotifier/\" rel=\"nofollow noreferrer\">jQuery Form Notifier</a> - it is one of the most popular jQuery plugins and doesn't suffer from the bugs some of the other jQuery suggestions here do (for example, you can freely style the watermark, without worrying if it will get saved to the database).</p>\n\n<p>jQuery Watermark uses a single CSS style directly on the form elements (I noticed that CSS font-size properties applied to the watermark also affected the text boxes -- not what I wanted). The plus with jQuery Watermark is you can drag-drop text into fields (jQuery Form Notifier doesn't allow this).</p>\n\n<p>Another one suggested by some others (the one at digitalbrush.com), will accidentally submit the watermark value to your form, so I strongly recommend against it.</p>\n" }, { "answer_id": 3612949, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 10, "selected": true, "text": "<p>Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's <strong>placeholder</strong> attribute:</p>\n\n<pre><code>&lt;input name=\"email\" placeholder=\"Email Address\"&gt;\n</code></pre>\n\n<p>In the absence of any styles, in Chrome this looks like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tZcmY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tZcmY.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can try demos out <a href=\"http://diveintohtml5.info/examples/input-placeholder.html\" rel=\"noreferrer\">here</a> and in <em><a href=\"http://davidwalsh.name/html5-placeholder-css\" rel=\"noreferrer\">HTML5 Placeholder Styling with CSS</a></em>.</p>\n\n<p>Be sure to check the <a href=\"http://caniuse.com/#feat=input-placeholder\" rel=\"noreferrer\">browser compatibility of this feature</a>. Support in Firefox was added in 3.7. Chrome is fine. Internet&nbsp;Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called <a href=\"https://github.com/mathiasbynens/jquery-placeholder\" rel=\"noreferrer\">jQuery HTML5 Placeholder</a>, and then just add the following JavaScript code to enable it.</p>\n\n<pre><code>$('input[placeholder], textarea[placeholder]').placeholder();\n</code></pre>\n" }, { "answer_id": 8813551, "author": "Isaac Liu", "author_id": 927512, "author_profile": "https://Stackoverflow.com/users/927512", "pm_score": 0, "selected": false, "text": "<p>I like the solution of \"Knowledge Chikuse\" - simple and clear. Only need to add a call to blur when the page load is ready which will set the initial state:</p>\n\n<pre><code>$('input[value=\"text\"]').blur();\n</code></pre>\n" }, { "answer_id": 37670822, "author": "Pradeep", "author_id": 2159249, "author_profile": "https://Stackoverflow.com/users/2159249", "pm_score": -1, "selected": false, "text": "<p>Simple Html 'required' tag is useful.</p>\n\n<pre><code>&lt;form&gt;\n&lt;input type=\"text\" name=\"test\" id=\"test\" required&gt;\n&lt;input type=\"submit\" value=\"enter\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>It specifies that an input field must be filled out before submitting the form or press the button submit.\n<a href=\"https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_required\" rel=\"nofollow noreferrer\">Here is example</a></p>\n" }, { "answer_id": 38664150, "author": "apm", "author_id": 2982121, "author_profile": "https://Stackoverflow.com/users/2982121", "pm_score": 2, "selected": false, "text": "<p>Now it become very easy.\nIn html we can give the <strong>placeholder</strong> attribute for <em>input</em> elements.</p>\n\n<p><strong>e.g.</strong></p>\n\n<pre><code>&lt;input type=\"text\" name=\"fst_name\" placeholder=\"First Name\"/&gt;\n</code></pre>\n\n<p>check for more details :<a href=\"http://www.w3schools.com/tags/att_input_placeholder.asp\" rel=\"nofollow\">http://www.w3schools.com/tags/att_input_placeholder.asp</a></p>\n" }, { "answer_id": 61569608, "author": "Kosem", "author_id": 6159404, "author_profile": "https://Stackoverflow.com/users/6159404", "pm_score": 0, "selected": false, "text": "<p>I'm using a simple, one line javascript solution which works great. Here is an example both for textbox and for textarea:</p>\n\n<pre><code> &lt;textarea onfocus=\"if (this.value == 'Text') { this.value = ''; }\" onblur=\"if (this.value == '') { this.value = 'Text'; }\"&gt;Text&lt;/textarea&gt;\n\n &lt;input type=\"text\" value=\"Text\" onfocus=\"if (this.value == 'Text') { this.value = ''; }\" onblur=\"if (this.value == '') { this.value = 'Text'; }\"&gt;\n</code></pre>\n\n<p>only \"downside\" is to validate at $_POST or in Javascript validation before doing anything with the value of the field. Meaning, checking that the field's value isn't \"Text\".</p>\n" }, { "answer_id": 64685537, "author": "Green", "author_id": 13262204, "author_profile": "https://Stackoverflow.com/users/13262204", "pm_score": 0, "selected": false, "text": "<hr />\n<p>You can use a attribute called <code>placeholder=&quot;&quot;</code>\nHere's a demo:</p>\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n// try this out!\n&lt;input placeholder=&quot;This is my placeholder&quot;/&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<hr />\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7668/" ]
I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label. BTW, this is an on-page [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) search, so it has no button.
Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's **placeholder** attribute: ``` <input name="email" placeholder="Email Address"> ``` In the absence of any styles, in Chrome this looks like: [![enter image description here](https://i.stack.imgur.com/tZcmY.png)](https://i.stack.imgur.com/tZcmY.png) You can try demos out [here](http://diveintohtml5.info/examples/input-placeholder.html) and in *[HTML5 Placeholder Styling with CSS](http://davidwalsh.name/html5-placeholder-css)*. Be sure to check the [browser compatibility of this feature](http://caniuse.com/#feat=input-placeholder). Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called [jQuery HTML5 Placeholder](https://github.com/mathiasbynens/jquery-placeholder), and then just add the following JavaScript code to enable it. ``` $('input[placeholder], textarea[placeholder]').placeholder(); ```
108,211
<p>I want to add a <em>column</em> to an existing legacy <em>database</em> and write a <em>procedure</em> by which I can assign each record a different value. Something like adding a <em>column</em> and autogenerate the data for it.</p> <p>Like, if I add a new <em>column</em> called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID <em>column</em> will have records from say <code>1 to 1000</code>.<br> How do I do that?</p>
[ { "answer_id": 108227, "author": "Simon Johnson", "author_id": 854, "author_profile": "https://Stackoverflow.com/users/854", "pm_score": 9, "selected": true, "text": "<p>This will depend on the database but for SQL Server, this could be achieved as follows:</p>\n\n<pre><code>alter table Example\nadd NewColumn int identity(1,1)\n</code></pre>\n" }, { "answer_id": 108235, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "<p>Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick</p>\n\n<p>Check out this MSDN article <a href=\"http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx</a> on the ALTER TABLE syntax</p>\n" }, { "answer_id": 108236, "author": "Joshua", "author_id": 6013, "author_profile": "https://Stackoverflow.com/users/6013", "pm_score": 0, "selected": false, "text": "<p>Depends on the database as each database has a different way to add sequence numbers. I would alter the table to add the column then write a db script in groovy/python/etc to read in the data and update the id with a sequence. Once the data has been set, I would add a sequence to the table that starts after the top number. Once the data has been set, set the primary keys correctly.</p>\n" }, { "answer_id": 108237, "author": "Roy Tang", "author_id": 18494, "author_profile": "https://Stackoverflow.com/users/18494", "pm_score": 4, "selected": false, "text": "<p>for oracle you could do something like below</p>\n\n<pre><code>alter table mytable add (myfield integer);\n\nupdate mytable set myfield = rownum;\n</code></pre>\n" }, { "answer_id": 108253, "author": "Tom Martin", "author_id": 5303, "author_profile": "https://Stackoverflow.com/users/5303", "pm_score": 5, "selected": false, "text": "<p>It would help if you posted what SQL database you're using. For MySQL you probably want auto_increment:</p>\n\n<pre><code>ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY</code></pre>\n\n<p>Not sure if this applies the values retroactively though. If it doesn't you should just be able to iterate over your values with a stored procedure or in a simple program (as long as no one else is writing to the database) and set use the <code>LAST_INSERT_ID()</code> function to generate the id value.</p>\n" }, { "answer_id": 7333178, "author": "Flavien Volken", "author_id": 532695, "author_profile": "https://Stackoverflow.com/users/532695", "pm_score": 3, "selected": false, "text": "<p>And the Postgres equivalent (second line is mandatory only if you want \"id\" to be a key):</p>\n\n<pre><code>ALTER TABLE tableName ADD id SERIAL;\nALTER TABLE tableName ADD PRIMARY KEY (id);\n</code></pre>\n" }, { "answer_id": 43544856, "author": "Jinlye", "author_id": 3328536, "author_profile": "https://Stackoverflow.com/users/3328536", "pm_score": 0, "selected": false, "text": "<p>If you don't want your new column to be of type <code>IDENTITY</code> (auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of type <code>INT NULL</code> and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE MyTable\nSET MyTable.MyNewColumn = AutoTable.AutoNum\nFROM\n(\n SELECT MyPrimaryKey, \n ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum\n FROM MyTable \n) AutoTable\nWHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey \n</code></pre>\n\n<p>This works in SQL Sever 2005 and later, i.e. versions that support <code>ROW_NUMBER()</code></p>\n" }, { "answer_id": 47993046, "author": "Snziv Gupta", "author_id": 4412545, "author_profile": "https://Stackoverflow.com/users/4412545", "pm_score": 2, "selected": false, "text": "<p>for UNIQUEIDENTIFIER datatype in sql server try this</p>\n\n<pre><code>Alter table table_name\nadd ID UNIQUEIDENTIFIER not null unique default(newid())\n</code></pre>\n\n<p>If you want to create primary key out of that column use this</p>\n\n<pre><code>ALTER TABLE table_name\nADD CONSTRAINT PK_name PRIMARY KEY (ID);\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ]
I want to add a *column* to an existing legacy *database* and write a *procedure* by which I can assign each record a different value. Something like adding a *column* and autogenerate the data for it. Like, if I add a new *column* called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID *column* will have records from say `1 to 1000`. How do I do that?
This will depend on the database but for SQL Server, this could be achieved as follows: ``` alter table Example add NewColumn int identity(1,1) ```
108,251
<p>On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though:</p> <pre> root# ls -la /dev/tty1 crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1 </pre> <p>Even weirder, this doesn't work:</p> <pre> root# cat &lt;/dev/tty1 bash: /dev/tty1: Permission denied </pre> <p>I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges?</p> <p>Update: I've made sure SELinux has been disabled; yet, the issue is still there....</p> <p>Update: The strace dump:</p> <pre> 32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0 32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0 32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000 32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35 </pre> <p>Can't say it's making much sense to me... </p>
[ { "answer_id": 108442, "author": "Martin OConnor", "author_id": 18233, "author_profile": "https://Stackoverflow.com/users/18233", "pm_score": 1, "selected": false, "text": "<p>I suspect that SELinux may be the problem. Try temporarily disabling it to see if it works.</p>\n" }, { "answer_id": 172441, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "<p>I dont have an exact answer, but I have a suggestion.</p>\n\n<p>Use ltrace and strace to get an impression of what is used \"under the hood\" like this:</p>\n\n<pre><code>strace -f -o LOG bash -c 'cat &lt; /dev/tty1'\n</code></pre>\n\n<p>(same args for \"ltrace\"). Examine LOG to find out which syscall triggers the \"permission denied\". Maybe it will give you one more keyword to feed to google or useful snippet of log to add to your question here.</p>\n" }, { "answer_id": 8039115, "author": "Ryaner", "author_id": 99215, "author_profile": "https://Stackoverflow.com/users/99215", "pm_score": 0, "selected": false, "text": "<p>Go into your /etc/inittab and comment out the following lines (or others like it). You may need to reboot to stop the re-spawns</p>\n\n<pre><code>c1:12345:respawn:/sbin/agetty 38400 tty1 linux\nc2:2345:respawn:/sbin/agetty 38400 tty2 linux\nc3:2345:respawn:/sbin/agetty 38400 tty3 linux\nc4:2345:respawn:/sbin/agetty 38400 tty4 linux\nc5:2345:respawn:/sbin/agetty 38400 tty5 linux\nc6:2345:respawn:/sbin/agetty 38400 tty6 linux\n</code></pre>\n" }, { "answer_id": 18305570, "author": "isam amin", "author_id": 2694963, "author_profile": "https://Stackoverflow.com/users/2694963", "pm_score": 0, "selected": false, "text": "<p>i'm not sure if this will help you, but have to check first....\ni found that - in many cases the system administrator disabled access to such stuff\nso try to look for this file : /etc/security/access.conf, and find the line \"#-:ALL EXCEPT root:tty1\".This line if active ( mean no # in first ) will disallow non-root logins on tty1\nBut be care DON'T CHNAGE - better to check with your system admin.</p>\n\n<p>hope this help</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19627/" ]
On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though: ``` root# ls -la /dev/tty1 crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1 ``` Even weirder, this doesn't work: ``` root# cat </dev/tty1 bash: /dev/tty1: Permission denied ``` I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges? Update: I've made sure SELinux has been disabled; yet, the issue is still there.... Update: The strace dump: ``` 32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0 32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0 32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000 32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35 ``` Can't say it's making much sense to me...
I suspect that SELinux may be the problem. Try temporarily disabling it to see if it works.
108,276
<p>I have a project with a bunch of external sounds to a SWF. I want to play them, but any time I attempt load a new URL into the sound object it fails with either,</p> <blockquote> <p>Error #2068: Invalid Sound</p> </blockquote> <p>or raises an ioError with </p> <blockquote> <p>Error #2032 Stream Error</p> </blockquote> <p>// Tried with path prefixed with "http://.." "file://.." "//.." and "..")</p> <pre><code>var path:String = "http://../assets/the_song.mp3"; var url:URLRequest = new URLRequest( path ); var sound:Sound = new Sound(); sound.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler); sound.addEventListener( SecurityErrorEvent.SECURITY_ERROR, secHandler); sound.load(url); </code></pre>
[ { "answer_id": 108698, "author": "ZorroDeLaArena", "author_id": 19696, "author_profile": "https://Stackoverflow.com/users/19696", "pm_score": 2, "selected": false, "text": "<p>Unless you're going to put a full url, don't use http:// or file://</p>\n\n<p>Sound can load an mp3 file from a full or relative url. You just need to make sure your url is correct and valid.</p>\n\n<p>For example, if the full path to the file is <a href=\"http://www.something.com/assets/the_song.mp3\" rel=\"nofollow noreferrer\">http://www.something.com/assets/the_song.mp3</a>, a path of \"/assets/the_song.mp3\" would work.</p>\n" }, { "answer_id": 111372, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 3, "selected": true, "text": "<p>Well, I've just done a test by putting an mp3 in a directory: <code>soundTest/assets/song.mp3</code> then creating a swf that calls the mp3 in another directory: <code>soundTest/swfs/soundTest.swf</code> and when I use <code>var path:String = \"../assets/song.mp3\";</code> then it compiles with no errors.</p>\n\n<p>What is your actual directory structure?</p>\n" }, { "answer_id": 138592, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 2, "selected": false, "text": "<p>You should really download httpfox for FireFox. This SNIFFER allows you to see what data is flowing through the browswer. You can see the files its loading, including the paths to each, and you can even sniff POST and GET variables. This will show you where the files are being pulled from and based off of that you can fix your relative paths accordingly.</p>\n\n<p><a href=\"https://addons.mozilla.org/en-US/firefox/addon/6647\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/6647</a></p>\n\n<p><strong>Important:</strong></p>\n\n<p>All external assets called from the SWF are relative to the html file loading them when loaded on the web, not the SWF. The only exception, and this is something that started with AS3, FLV's are relative to the SWF, not the HTML document loading the SWF like every other asset. This is why SNIFFERS are an important tool, I scratched my head for a while until I noticed the URL in the sniffer was calling a weird path.</p>\n\n<p>Below is how you can load sound.<pre><code>var soundRequest:URLRequest = \"path/to/file.mp3\";\nvar s:Sound = new Sound(soundRequest);\nvar sChannel = s.play(0, int.MAX_VALUE); //Causes it to repeat by the highest possible number to flash.\n//Above starts the sound immediatly (Streaming);</p>\n\n<p>//Now to wait for completion instead, pretend we didnt start it before.\n<code>s.addEventLister(Event.SOUND_COMPLETE, onSComplete, false, 0, true);</code>\nfunction onSComplete(e:Event):void\n{\n var sChannel = s.play(0, int.MAX_VALUE); //Causes it to repeat by the highest possible\n}</code>\n</pre></p>\n" }, { "answer_id": 275694, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In both protocol, RTMP &amp; HTTP, the path should be -- \"path/to/mp3:file.mp3\" or \"path/to/mp3:file\". I can remember. Please check both.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
I have a project with a bunch of external sounds to a SWF. I want to play them, but any time I attempt load a new URL into the sound object it fails with either, > > Error #2068: Invalid Sound > > > or raises an ioError with > > Error #2032 Stream Error > > > // Tried with path prefixed with "http://.." "file://.." "//.." and "..") ``` var path:String = "http://../assets/the_song.mp3"; var url:URLRequest = new URLRequest( path ); var sound:Sound = new Sound(); sound.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler); sound.addEventListener( SecurityErrorEvent.SECURITY_ERROR, secHandler); sound.load(url); ```
Well, I've just done a test by putting an mp3 in a directory: `soundTest/assets/song.mp3` then creating a swf that calls the mp3 in another directory: `soundTest/swfs/soundTest.swf` and when I use `var path:String = "../assets/song.mp3";` then it compiles with no errors. What is your actual directory structure?
108,281
<p>I have a table <code>y</code> Which has two columns <code>a</code> and <code>b</code></p> <p>Entries are:</p> <pre><code>a b 1 2 1 3 1 4 0 5 0 2 0 4 </code></pre> <p>I want to get 2,3,4 if I search column <code>a</code> for 1, and 5,2,4 if I search column <code>a</code>.</p> <p>So, if I search A for something that is in A, (1) I get those rows, and if there are no entries A for given value, give me the 'Defaults' (<code>a</code> = '0')</p> <p>Here is how I would know how to do it:</p> <pre><code>$r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'1\';'); //This gives desired results, 3 rows $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'2\';'); //This does not give desired results yet. //Get the number of rows, and then get the 'defaults' if(mysql_num_rows($r) === 0) $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = 0;'); </code></pre> <p>So, now that it's sufficiently explained, how do I do that in one query, and what about performance concerns? </p> <p>The most used portion would be the third query, because there would only be values in <code>a</code> for a number IF you stray from the defaults.</p>
[ { "answer_id": 108313, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>You can do all this in a single stored procedure with a single parameter.</p>\n\n<p>I have to run out, but I'll try to write one up for you and add it here as soon as I get back from my errand.</p>\n" }, { "answer_id": 108607, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 0, "selected": false, "text": "<p>I don't know why this was marked down - please educate me. It is a valid, tested stored procedure, and I answered the question. The OP didn't require that the answer be in php. ??</p>\n\n<p>Here's a stored proc to do what you want that works in SQL Server. I'm not sure about MySQL.</p>\n\n<pre><code>create proc GetRealElseGetDefault (@key as int)\nas\nbegin\n\n-- Use this default if the correct data is not found\ndeclare @default int\nselect @default = 0\n\n-- See if the desired data exists, and if so, get it. \n-- Otherwise, get defaults.\nif exists (select * from TableY where a = @key)\n select b from TableY where a = @key\nelse\n select b from TableY where a = @default\n\nend -- GetRealElseGetDefault\n</code></pre>\n\n<p>You would run this (in sql server) with </p>\n\n<p>GetRealElseGetDefault 1</p>\n\n<p>Based on a quick google search, exists is fast in MySQL. It would be especially fast is column A is indexed. If your table is large enough for you to be worried about performance, it is probably large enough to index.</p>\n" }, { "answer_id": 108729, "author": "Lawrence Barsanti", "author_id": 13054, "author_profile": "https://Stackoverflow.com/users/13054", "pm_score": 2, "selected": false, "text": "<p>You can try something like this. I'm not 100% sure it will work because count() is a aggregate function but its worth a shot.</p>\n\n<pre><code>SELECT b\nFROM table1 \nWHERE a = (\n SELECT\n CASE count(b)\n WHEN 0 THEN :default_value\n ELSE :passed_value \n END\n FROM table1\n WHERE a = :passed_value\n)\n</code></pre>\n" }, { "answer_id": 108824, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 1, "selected": false, "text": "<p>What about</p>\n\n<pre><code>$rows = $db-&gt;fetchAll('select a, b FROM y WHERE a IN (2, 0) ORDER BY a DESC');\nif(count($rows) &gt; 0) {\n $a = $rows[0]['a'];\n $i = 0;\n while($rows[$i]['a'] === $a) {\n echo $rows[$i++]['b'].\"\\n\";\n }\n}\n</code></pre>\n\n<p>One query, but overhead if there are a lot of 'zero' values.<br />\nDepends if you care about the overhead...</p>\n" }, { "answer_id": 108913, "author": "Jonathan", "author_id": 19272, "author_profile": "https://Stackoverflow.com/users/19272", "pm_score": 3, "selected": true, "text": "<p>I think I have it:</p>\n\n<pre><code>SELECT b FROM y where a=if(@value IN (select a from y group by a),@value,0);\n</code></pre>\n\n<p>It checks if @value exists in the table, if not, then it uses 0 as a default.\n@value can be a php value too.</p>\n\n<p>Hope it helps :)</p>\n" }, { "answer_id": 118127, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 1, "selected": false, "text": "<p>I think Michal Kralik best answer in my opinion based on server performance. Doing subselects or stored procedures for such simple logic really is not worth it.</p>\n\n<p>The only way I would improve on Michal's logic is if you are doing this query multiple times in one script. In this case I would query for the 0's first, and then run each individual query, then checking if there was any value.</p>\n\n<p>Pseudo-code</p>\n\n<pre><code>// get the value for hte zero's\n$zeros = $db-&gt;fetchAll('select a, b FROM y WHERE a = 0');\n\n//checking for 1's\n$ones = $db-&gt;fetchAll('select a, b FROM y WHERE a = 1');\nif(empty($ones)) $ones = $zeros;\n\n//checking for 2's\n$twos = $db-&gt;fetchAll('select a, b FROM y WHERE a = 2');\nif(empty($twos)) $twos = $zeros;\n\n//checking for 3's\n$threes = $db-&gt;fetchAll('select a, b FROM y WHERE a = 3');\nif(empty($threes)) $threes = $zeros;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
I have a table `y` Which has two columns `a` and `b` Entries are: ``` a b 1 2 1 3 1 4 0 5 0 2 0 4 ``` I want to get 2,3,4 if I search column `a` for 1, and 5,2,4 if I search column `a`. So, if I search A for something that is in A, (1) I get those rows, and if there are no entries A for given value, give me the 'Defaults' (`a` = '0') Here is how I would know how to do it: ``` $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'1\';'); //This gives desired results, 3 rows $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = \'2\';'); //This does not give desired results yet. //Get the number of rows, and then get the 'defaults' if(mysql_num_rows($r) === 0) $r = mysql_query('SELECT `b` FROM `y` WHERE `a` = 0;'); ``` So, now that it's sufficiently explained, how do I do that in one query, and what about performance concerns? The most used portion would be the third query, because there would only be values in `a` for a number IF you stray from the defaults.
I think I have it: ``` SELECT b FROM y where a=if(@value IN (select a from y group by a),@value,0); ``` It checks if @value exists in the table, if not, then it uses 0 as a default. @value can be a php value too. Hope it helps :)
108,292
<p>When developing an application that sends out notification email messages, what are the best practices for </p> <ol> <li>not getting flagged as a spammer by your hosting company. (Cover any of:) <ul> <li>best technique for not flooding a mail server</li> <li>best mail server products, if you were to set up your own</li> <li>sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette</li> <li>any other lessons learned</li> </ul></li> <li>not getting flagged as spam by the receiver's client? (Cover any of:) <ul> <li>configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified</li> <li>best SMTP header techniques to avoid getting flagged as spam when sending emails for users (for example, using Sender and From headers together)</li> <li>any other lessons learned</li> </ul></li> </ol> <p>An additional requirement: this application would be sending a single message to a single recipient based upon an event. So, techniques for sending the same messages to multiple recipients will not apply.</p>
[ { "answer_id": 112607, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>best technique for not flooding a mail server</p>\n</blockquote>\n\n<p>not a lot you can do about this beyond checking with your mail server admin (if it's a shared hosting account / not in your control). but if the requirement is one email to a single recipient per event, that shouldn't be too much of an issue. the things that tend to clog mail systems are emails with hundreds (or more) of recipients.</p>\n\n<p>if you have events firing off all the time, perhaps consider consolidating them and having an email sent that summarizes them periodically.</p>\n\n<blockquote>\n <p>sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette</p>\n</blockquote>\n\n<p>you can accomplish this by using the \"Reply-To\" header, which will then have clients use that address instead of the From address when an email message is being composed.</p>\n\n<p>you should also set the \"Return-Path\" header of any email, as email without this will often get filtered off.</p>\n\n<p>ex.</p>\n\n<pre><code>From: [email protected]\nReturn-Path: [email protected]\nReply-To: [email protected]\n</code></pre>\n\n<blockquote>\n <p>configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified</p>\n</blockquote>\n\n<p>this is all highly dependent on how much ownership you have of your mail and DNS servers. spf/sender-id etc... are all DNS issues, so you would need to have access to DNS.</p>\n\n<p>in your example this could present quite the problem. as you are setting mail to be from a specific user, that user would have to have SPF (for example) set in their DNS to allow your mail server as a valid sender. you can imagine how messy (if not outright impossible) this would get with a number of users with various domain names.</p>\n\n<p>as for reverse DNS and the like, it really depends. most client ISP's, etc... will just check to see that reverse DNS is set. (ie, 1.2.3.4 resolves to host.here.domain.com, even if host.here.domain.com doesn't resolve back to 1.2.3.4). this is due to the amount of shared hosting out there (where mail servers will often report themselves as the client's domain name, and not the real mail server).</p>\n\n<p>there are a few stringent networks that require matching reverse DNS, but this requires that you have control over the mail server if it doesn't match in the first place.</p>\n\n<p>if you can be a bit more specific i may be able to provide a bit more advice, but generally, for people who need to send application mail, and don't have a pile of control over their environment, i'd suggest the following:</p>\n\n<ul>\n<li>make sure to set a \"Return-Path\"</li>\n<li>it's nice to add your app and abuse info as well in headers ie: \"X-Mailer\" and \"X-Abuse-To\" (these are custom headers, for informational purposes only really)</li>\n<li>make sure reverse DNS is set for the IP address of your outgoing mail server</li>\n</ul>\n" }, { "answer_id": 490220, "author": "Alan Doherty", "author_id": 59995, "author_profile": "https://Stackoverflow.com/users/59995", "pm_score": 0, "selected": false, "text": "<p>first a quick correction to the previous</p>\n\n<p>return-path: is a header added by recieving system based on the envelope-sender of the incomming message</p>\n\n<p>for spf to work the return-path/envelope-sender needs to be [email protected]</p>\n\n<p>and ensure the spf record for yourdomain.com {or if per-user spf} for [email protected] allows mails to originate on the server that hosts the app/sends the email</p>\n\n<p>this envelope-sender is the address that will recieve all bounces/errors</p>\n\n<p>now sender-id is different entirely it checks the return-path/envelope-sender\nand the\nfrom: address {stored inside the message}\nif sending \nfrom: hisname [email protected]\nreply-to: hisname [email protected]</p>\n\n<p>this will be a non-issue\nif sending\nfrom: hisname [email protected]</p>\n\n<p>it will be and you must add a\nResent-From: hisname [email protected]\nas this specifies to ignore the from: for sender-id checks use this instead as it has been sent by you on his behalf</p>\n" }, { "answer_id": 490253, "author": "Alan Doherty", "author_id": 59995, "author_profile": "https://Stackoverflow.com/users/59995", "pm_score": 0, "selected": false, "text": "<p>now for the other bits that are worthwhile</p>\n\n<p>ip's mentioned are your mailservers</p>\n\n<p>a have your ip's ptr point to a name that also resolves to the same ip\nFQDNS</p>\n\n<p>b have your server helo/ehlo with whatever.domain.com where domain.com is the same as the domain of the name in step A {not the same name for resons below}</p>\n\n<p>c have that helo/ehlo servername also resolve to the ip of your server</p>\n\n<p>d add the following spf record to that helo/ehlo name \"v=spf1 a -all\"\n{meaning allow helo/ehlo with this name from ip's this name points to only}</p>\n\n<p>e add the following sender-id lines to the helo/ehlo name {purely for completeness\n\"spf2.0/mfrom,pra -all\" {ie there are no users@this-domain}</p>\n\n<p>f add the following spf to the FQDNS-name and any other hostnames for your server\n\"v=spf1 -all\" {ie no machines will ever helo/ehlo as this name and no users@this-domain}</p>\n\n<p>{as the fqdns name can be determined by bots/infections its better to never allow this name to be used in helo/ehlo greetings directly it is enough that it be from the same domain as the helo/ehlo identity to prove the validity of both}</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16099/" ]
When developing an application that sends out notification email messages, what are the best practices for 1. not getting flagged as a spammer by your hosting company. (Cover any of:) * best technique for not flooding a mail server * best mail server products, if you were to set up your own * sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette * any other lessons learned 2. not getting flagged as spam by the receiver's client? (Cover any of:) * configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified * best SMTP header techniques to avoid getting flagged as spam when sending emails for users (for example, using Sender and From headers together) * any other lessons learned An additional requirement: this application would be sending a single message to a single recipient based upon an event. So, techniques for sending the same messages to multiple recipients will not apply.
> > best technique for not flooding a mail server > > > not a lot you can do about this beyond checking with your mail server admin (if it's a shared hosting account / not in your control). but if the requirement is one email to a single recipient per event, that shouldn't be too much of an issue. the things that tend to clog mail systems are emails with hundreds (or more) of recipients. if you have events firing off all the time, perhaps consider consolidating them and having an email sent that summarizes them periodically. > > sending messages as if from a specific user but still clearly from your application (to ensure complaints, etc come back to you) without breaking good email etiquette > > > you can accomplish this by using the "Reply-To" header, which will then have clients use that address instead of the From address when an email message is being composed. you should also set the "Return-Path" header of any email, as email without this will often get filtered off. ex. ``` From: [email protected] Return-Path: [email protected] Reply-To: [email protected] ``` > > configuring and using sender-id, domain-keys, SPF, reverse-dns, etc to make sure your emails are properly identified > > > this is all highly dependent on how much ownership you have of your mail and DNS servers. spf/sender-id etc... are all DNS issues, so you would need to have access to DNS. in your example this could present quite the problem. as you are setting mail to be from a specific user, that user would have to have SPF (for example) set in their DNS to allow your mail server as a valid sender. you can imagine how messy (if not outright impossible) this would get with a number of users with various domain names. as for reverse DNS and the like, it really depends. most client ISP's, etc... will just check to see that reverse DNS is set. (ie, 1.2.3.4 resolves to host.here.domain.com, even if host.here.domain.com doesn't resolve back to 1.2.3.4). this is due to the amount of shared hosting out there (where mail servers will often report themselves as the client's domain name, and not the real mail server). there are a few stringent networks that require matching reverse DNS, but this requires that you have control over the mail server if it doesn't match in the first place. if you can be a bit more specific i may be able to provide a bit more advice, but generally, for people who need to send application mail, and don't have a pile of control over their environment, i'd suggest the following: * make sure to set a "Return-Path" * it's nice to add your app and abuse info as well in headers ie: "X-Mailer" and "X-Abuse-To" (these are custom headers, for informational purposes only really) * make sure reverse DNS is set for the IP address of your outgoing mail server
108,301
<p>I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in <code>JSP</code> development, but it appears to be common practice in <code>PHP</code>. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into consideration?</p>
[ { "answer_id": 108309, "author": "Issac Kelly", "author_id": 144, "author_profile": "https://Stackoverflow.com/users/144", "pm_score": 1, "selected": false, "text": "<p>Well, This is to prevent sensitive includes from being sent to the web-server directly. It's certainly not an all-inclusive security measure, but it could help with your particular setup.</p>\n\n<p>If however, your user was in a position to include the file from their own script, it won't help at all</p>\n" }, { "answer_id": 108317, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 0, "selected": false, "text": "<p>It also isn't just a security feature in php but more of how many MVC based PHP sites function. If for example in SugarCRM you were to call a module file directly the page load would fail because the controller, view and model were not previously loaded and you'd have no db config/connection information either, so to make sure all dependencies are loaded the users is forced through a known entry point - i.e. index.php</p>\n" }, { "answer_id": 108336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I emit a 404 page, not as a serious security measure but only because I don't like leaking information about the internals of a site, even the names of internal files.</p>\n\n<p>But if the file just contains functions then there's no real harm in omitting the check.</p>\n" }, { "answer_id": 108478, "author": "Paul Shannon", "author_id": 11503, "author_profile": "https://Stackoverflow.com/users/11503", "pm_score": 0, "selected": false, "text": "<p>I just found an approach in the .Net MVC system that you could replicate for PHP using Apache Rewrites, .htaccess files or if you are using IIS, a web.config file.</p>\n\n<p>As the MVC pattern doens't need the user to directly access aspx files these are not served and a 404 is sent instead. If you have a naming convention for included files \"inc.php\" for example you could redirect *.inc.php requests to a 404 for specific folders - in Apache Rewrite supply R=404 at the end of the rule will return that HTTP status to your client.</p>\n\n<p>Some of these examples may help: <a href=\"http://httpd.apache.org/docs/1.3/misc/rewriteguide.html\" rel=\"nofollow noreferrer\">Apache Rewrite Examples</a></p>\n" }, { "answer_id": 110026, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 4, "selected": true, "text": "<p>The reason this is more common in PHP than other similar languages has to do with PHP's history. Early versions of PHP had the \"register_globals\" setting on as a default (in fact, it may not have even been a setting in really early versions). Register_globals tells PHP to define global variables according to the query string. So if you queried such a script thusly:</p>\n\n<pre><code>http://site.com/script.php?hello=world&amp;foo=bar\n</code></pre>\n\n<p>... the script would automatically define a variable $hello with value \"world\" and $foo with value \"bar.\"</p>\n\n<p>For such a script, if you knew the names of key variables, it was possible to exploit the script by specifying those variables on the query string. The solution? Define some magic string in the core script and then make all the ancilliary scripts check for the magic string and bail out if it's not there.</p>\n\n<p>Thankfully, almost nobody uses register_variables anymore, but many scripts are still very poorly written and make stupid assumptions that cause them to do damage if they are called out of context.</p>\n\n<p>Personally, I avoid the whole thing by using the Symfony framework, which (at least in its default setup) keeps the controllers and templates out of the web root altogether. The only entry point is the front controller.</p>\n" }, { "answer_id": 110286, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 2, "selected": false, "text": "<p>If you include everything from outside web root then it's not an issue as nothing <strong>can be</strong> loaded directly.</p>\n" }, { "answer_id": 110770, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>As already mentioned in some of the other answers, you shouldn't need to do this. If a file isn't supposed to be served up by the web server, you shouldn't leave it within the web folder. Includes should be placed in a directory outside the web root.</p>\n\n<p>Apart from that, the proper way to tell the user that a page doesn't exist, is by emitting a status 404, using:</p>\n\n<pre><code>header(\"HTTP/1.0 404 Not Found\");\nexit;\n</code></pre>\n\n<p>If you don't do this, it is hard for non-humans (Eg. search-engines) to distinguish between a regular page and a non-page.</p>\n" }, { "answer_id": 565776, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is very important because if you are editing your site running Google Toolbar, it will find your inner php files and then put them into search results. At best this will create an awkward experience for users but if you are a sloppy programmer, could reveal database connection information.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I was going to ask what the best way to do this is, but then decided I should ask whether or not it is even necessary. I have never seen it done in `JSP` development, but it appears to be common practice in `PHP`. What is the reasoning behind this, and if I do not protect against this, what else should I be taking into consideration?
The reason this is more common in PHP than other similar languages has to do with PHP's history. Early versions of PHP had the "register\_globals" setting on as a default (in fact, it may not have even been a setting in really early versions). Register\_globals tells PHP to define global variables according to the query string. So if you queried such a script thusly: ``` http://site.com/script.php?hello=world&foo=bar ``` ... the script would automatically define a variable $hello with value "world" and $foo with value "bar." For such a script, if you knew the names of key variables, it was possible to exploit the script by specifying those variables on the query string. The solution? Define some magic string in the core script and then make all the ancilliary scripts check for the magic string and bail out if it's not there. Thankfully, almost nobody uses register\_variables anymore, but many scripts are still very poorly written and make stupid assumptions that cause them to do damage if they are called out of context. Personally, I avoid the whole thing by using the Symfony framework, which (at least in its default setup) keeps the controllers and templates out of the web root altogether. The only entry point is the front controller.
108,318
<p>I need a function like this:</p> <pre><code>// return true if 'n' is a power of 2, e.g. // is_power_of_2(16) =&gt; true // is_power_of_2(3) =&gt; false bool is_power_of_2(int n); </code></pre> <p>Can anyone suggest how I could write this?</p>
[ { "answer_id": 108329, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 6, "selected": false, "text": "<p>A power of two will have just one bit set (for unsigned numbers). Something like</p>\n\n<pre><code>bool powerOfTwo = !(x == 0) &amp;&amp; !(x &amp; (x - 1));\n</code></pre>\n\n<p>Will work fine; one less than a power of two is all 1s in the less significant bits, so must AND to 0 bitwise.</p>\n\n<p>As I was assuming unsigned numbers, the == 0 test (that I originally forgot, sorry) is adequate. You may want a > 0 test if you're using signed integers.</p>\n" }, { "answer_id": 108338, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 3, "selected": false, "text": "<pre><code>bool is_power_of_2(int i) {\n if ( i &lt;= 0 ) {\n return 0;\n }\n return ! (i &amp; (i-1));\n}\n</code></pre>\n" }, { "answer_id": 108340, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 6, "selected": false, "text": "<p>Powers of two in binary look like this:</p>\n\n<pre><code>1: 0001\n2: 0010\n4: 0100\n8: 1000\n</code></pre>\n\n<p>Note that there is always exactly 1 bit set. The only exception is with a signed integer. e.g. An 8-bit signed integer with a value of -128 looks like:</p>\n\n<pre><code>10000000\n</code></pre>\n\n<p>So after checking that the number is greater than zero, we can use a clever little bit hack to test that one and only one bit is set.</p>\n\n<pre><code>bool is_power_of_2(int x) {\n return x &gt; 0 &amp;&amp; !(x &amp; (x−1));\n}\n</code></pre>\n\n<p>For more bit twiddling see <a href=\"http://graphics.stanford.edu/~seander/bithacks.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 108345, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 1, "selected": false, "text": "<p>This isn't the fastest or shortest way, but I think it is very readable. So I would do something like this:</p>\n\n<pre><code>bool is_power_of_2(int n)\n int bitCounter=0;\n while(n) {\n if ((n &amp; 1) == 1) {\n ++bitCounter;\n }\n n &gt;&gt;= 1;\n }\n return (bitCounter == 1);\n}\n</code></pre>\n\n<p>This works since binary is based on powers of two. Any number with only one bit set must be a power of two.</p>\n" }, { "answer_id": 108360, "author": "Anonymous", "author_id": 19650, "author_profile": "https://Stackoverflow.com/users/19650", "pm_score": 8, "selected": false, "text": "<p><code>(n &amp; (n - 1)) == 0</code> is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly.</p>\n\n<p><a href=\"http://www.graphics.stanford.edu/~seander/bithacks.html\" rel=\"noreferrer\">http://www.graphics.stanford.edu/~seander/bithacks.html</a> has a large collection of clever bit-twiddling algorithms, including this one.</p>\n" }, { "answer_id": 108412, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": -1, "selected": false, "text": "<p>Another way to go (maybe not fastest) is to determine if ln(x) / ln(2) is a whole number. </p>\n" }, { "answer_id": 14657714, "author": "Jesse Roberge", "author_id": 2034341, "author_profile": "https://Stackoverflow.com/users/2034341", "pm_score": -1, "selected": false, "text": "<p>This is the bit-shift method in T-SQL (SQL Server):</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT CASE WHEN @X&gt;0 AND (@X) &amp; (@X-1)=0 THEN 1 ELSE 0 END AS IsPowerOfTwo\n</code></pre>\n\n<p>It is a lot faster than doing a logarithm four times (first set to get decimal result, 2nd set to get integer set &amp; compare)</p>\n" }, { "answer_id": 16198046, "author": "Chethan", "author_id": 377762, "author_profile": "https://Stackoverflow.com/users/377762", "pm_score": 0, "selected": false, "text": "<p>Here is another method, in this case using <code>|</code> instead of <code>&amp;</code> :</p>\n\n<pre><code>bool is_power_of_2(int x) {\n return x &gt; 0 &amp;&amp; (x&lt;&lt;1 == (x|(x-1)) +1));\n}\n</code></pre>\n" }, { "answer_id": 32565217, "author": "Jay Ponkia", "author_id": 3189385, "author_profile": "https://Stackoverflow.com/users/3189385", "pm_score": -1, "selected": false, "text": "<p>It is possible through c++</p>\n\n<pre><code>int IsPowOf2(int z) {\ndouble x=log2(z);\nint y=x;\nif (x==(double)y)\nreturn 1;\nelse\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 33083952, "author": "Margus", "author_id": 97754, "author_profile": "https://Stackoverflow.com/users/97754", "pm_score": 2, "selected": false, "text": "<p>Following would be faster then most up-voted answer due to boolean short-circuiting and fact that comparison is slow.</p>\n\n<pre><code>int isPowerOfTwo(unsigned int x)\n{\n return x &amp;&amp; !(x &amp; (x – 1));\n}\n</code></pre>\n\n<p>If you know that x can not be 0 then </p>\n\n<pre><code>int isPowerOfTwo(unsigned int x)\n{\n return !(x &amp; (x – 1));\n}\n</code></pre>\n" }, { "answer_id": 34890248, "author": "Raj Dixit", "author_id": 5561159, "author_profile": "https://Stackoverflow.com/users/5561159", "pm_score": 4, "selected": false, "text": "<p><strong>Approach #1:</strong></p>\n\n<p>Divide number by 2 reclusively to check it.</p>\n\n<p><strong>Time complexity :</strong> O(log2n).</p>\n\n<p><strong>Approach #2:</strong></p>\n\n<p>Bitwise AND the number with its just previous number should be equal to ZERO.</p>\n\n<p><strong>Example:</strong> Number = 8\nBinary of 8: 1 0 0 0\nBinary of 7: 0 1 1 1 and the bitwise AND of both the numbers is 0 0 0 0 = 0.</p>\n\n<p><strong>Time complexity :</strong> O(1).</p>\n\n<p><strong>Approach #3:</strong></p>\n\n<p>Bitwise XOR the number with its just previous number should be sum of both numbers.</p>\n\n<p><strong>Example:</strong> Number = 8\nBinary of 8: 1 0 0 0\nBinary of 7: 0 1 1 1 and the bitwise XOR of both the numbers is 1 1 1 1 = 15.</p>\n\n<p><strong>Time complexity :</strong> O(1).</p>\n\n<p><a href=\"http://javaexplorer03.blogspot.in/2016/01/how-to-check-number-is-power-of-two.html\" rel=\"noreferrer\">http://javaexplorer03.blogspot.in/2016/01/how-to-check-number-is-power-of-two.html</a></p>\n" }, { "answer_id": 37512919, "author": "FReeze FRancis", "author_id": 4108292, "author_profile": "https://Stackoverflow.com/users/4108292", "pm_score": 3, "selected": false, "text": "<p>for any power of 2, the following also holds.</p>\n\n<h2>n&(-n)==n</h2>\n\n<p>NOTE: The condition is true for n=0 ,though its not a power of 2.\n<br>\nReason why this works is: <br>\n-n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.</p>\n" }, { "answer_id": 39602456, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>What's the simplest way to test whether a number is a power of 2 in C++?</p>\n</blockquote>\n\n<p>If you have a modern Intel processor with the <a href=\"https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets\" rel=\"nofollow noreferrer\">Bit Manipulation Instructions</a>, then you can perform the following. It omits the straight C/C++ code because others have already answered it, but you need it if BMI is not available or enabled.</p>\n\n<pre><code>bool IsPowerOf2_32(uint32_t x)\n{\n#if __BMI__ || ((_MSC_VER &gt;= 1900) &amp;&amp; defined(__AVX2__))\n return !!((x &gt; 0) &amp;&amp; _blsr_u32(x));\n#endif\n // Fallback to C/C++ code\n}\n\nbool IsPowerOf2_64(uint64_t x)\n{\n#if __BMI__ || ((_MSC_VER &gt;= 1900) &amp;&amp; defined(__AVX2__))\n return !!((x &gt; 0) &amp;&amp; _blsr_u64(x));\n#endif\n // Fallback to C/C++ code\n}\n</code></pre>\n\n<p>GCC, ICC, and Clang signal BMI support with <code>__BMI__</code>. It's available in Microsoft compilers in Visual Studio 2015 and above when <a href=\"https://blogs.msdn.microsoft.com/vcblog/2014/02/28/avx2-support-in-visual-studio-c-compiler/\" rel=\"nofollow noreferrer\">AVX2 is available and enabled</a>. For the headers you need, see <a href=\"https://stackoverflow.com/q/11228855\">Header files for SIMD intrinsics</a>.</p>\n\n<p>I usually guard the <code>_blsr_u64</code> with an <code>_LP64_</code> in case compiling on i686. Clang needs a little workaround because it uses a slightly different intrinsic symbol nam:</p>\n\n<pre><code>#if defined(__GNUC__) &amp;&amp; defined(__BMI__)\n# if defined(__clang__)\n# ifndef _tzcnt_u32\n# define _tzcnt_u32(x) __tzcnt_u32(x)\n# endif\n# ifndef _blsr_u32\n# define _blsr_u32(x) __blsr_u32(x)\n# endif\n# ifdef __x86_64__\n# ifndef _tzcnt_u64\n# define _tzcnt_u64(x) __tzcnt_u64(x)\n# endif\n# ifndef _blsr_u64\n# define _blsr_u64(x) __blsr_u64(x)\n# endif\n# endif // x86_64\n# endif // Clang\n#endif // GNUC and BMI\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Can you tell me a good web site where this sort of algorithm can be found?</p>\n</blockquote>\n\n<p>This website is often cited: <a href=\"http://graphics.stanford.edu/~seander/bithacks.html\" rel=\"nofollow noreferrer\">Bit Twiddling Hacks</a>.</p>\n" }, { "answer_id": 40073700, "author": "Yuxiang Zhang", "author_id": 7011475, "author_profile": "https://Stackoverflow.com/users/7011475", "pm_score": 2, "selected": false, "text": "<pre><code>return n &gt; 0 &amp;&amp; 0 == (1 &lt;&lt; 30) % n;\n</code></pre>\n" }, { "answer_id": 55259357, "author": "F10PPY", "author_id": 4739686, "author_profile": "https://Stackoverflow.com/users/4739686", "pm_score": 3, "selected": false, "text": "<p>This is probably the fastest, if using GCC. It only uses a POPCNT cpu instruction and one comparison. Binary representation of any power of 2 number, has always only one bit set, other bits are always zero. So we count the number of set bits with POPCNT, and if it's equal to 1, the number is power of 2. I don't think there is any possible faster methods. And it's very simple, if you understood it once:</p>\n\n<pre><code>if(1==__builtin_popcount(n))\n</code></pre>\n" }, { "answer_id": 56312164, "author": "Rakete1111", "author_id": 3980929, "author_profile": "https://Stackoverflow.com/users/3980929", "pm_score": 4, "selected": false, "text": "<p>In C++20 there is <a href=\"https://en.cppreference.com/w/cpp/numeric/has_single_bit\" rel=\"nofollow noreferrer\"><code>std::has_single_bit</code></a> which you can use for exactly this purpose if you don't need to implement it yourself:</p>\n<pre><code>#include &lt;bit&gt;\nstatic_assert(std::has_single_bit(16));\nstatic_assert(!std::has_single_bit(15));\n</code></pre>\n<p>Note that this requires the argument to be an unsigned integer type.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19641/" ]
I need a function like this: ``` // return true if 'n' is a power of 2, e.g. // is_power_of_2(16) => true // is_power_of_2(3) => false bool is_power_of_2(int n); ``` Can anyone suggest how I could write this?
`(n & (n - 1)) == 0` is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly. <http://www.graphics.stanford.edu/~seander/bithacks.html> has a large collection of clever bit-twiddling algorithms, including this one.
108,346
<p>Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version.</p> <p>I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?</p>
[ { "answer_id": 108372, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 0, "selected": false, "text": "<p>You should trap the error outside of your main loop.<br>\nOr if you want to ship/locate your own assemblies you can try overriding the assembly probing: <a href=\"https://blogs.msdn.com/junfeng/archive/2006/03/27/561775.aspx\" rel=\"nofollow noreferrer\">Link</a>.</p>\n" }, { "answer_id": 108378, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": true, "text": "<p>What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it.</p>\n\n<pre><code>Try\n Assembly.Load(\"System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139\");\nCatch ex As FileNotFoundException\n //do something here\nEnd Try\n</code></pre>\n" }, { "answer_id": 108379, "author": "lesscode", "author_id": 18482, "author_profile": "https://Stackoverflow.com/users/18482", "pm_score": 0, "selected": false, "text": "<p>You could use a setup project to build an installer for your app. This would analyze all of the static dependencies and produce an installer that ensures that the target machine gets everything it needs.</p>\n" }, { "answer_id": 108457, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 1, "selected": false, "text": "<p><em>(I've set the community-owned flag on this one, because this is mostly all from my gut instinct, and I've probably missed a crucial step in there somewhere)</em></p>\n\n<p><strong>Short answer:</strong> It's generally a good idea to deploy your dependencies along-side your application, using an installer. Without them, as you've noticed, there is very little chance of your application working.</p>\n\n<p><strong>Long answer:</strong> Ok, say you have <em>extra</em> functionality you want to provide if something else is installed on the target machine. Here's some general guidelines to do it:</p>\n\n<ol>\n<li>For any type that has a field, property, event, parameter, or return-value that references a type defined in the possibly uninstalled assembly: must be wrapped with an interface, and replace all other field, parameter, return-value, or local variable declarations to use the interface.</li>\n<li><p>Any time you go to construct one of the previously wrapped classes, you must use the <code>System.Activator.CreateInstance</code> method, and wrap it in a try/catch filtering on 7 different exception types:</p>\n\n<ul>\n<li><code>FileNotFoundException</code></li>\n<li><code>FileLoadException</code></li>\n<li><code>BadImageFormatException</code></li>\n<li><code>TypeLoadException</code></li>\n<li><code>MissingMethodException</code></li>\n<li><code>MissingMemberException</code></li>\n<li><code>MissingFieldException</code></li>\n</ul>\n\n<p>If one of those is caught, you must either provide an alternative implementation of the previously created interface, or write your code so that it checks for null any time it references that object.</p></li>\n</ol>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19638/" ]
Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version. I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?
What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it. ``` Try Assembly.Load("System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139"); Catch ex As FileNotFoundException //do something here End Try ```
108,389
<pre><code>class MyContainedClass { }; class MyClass { public: MyContainedClass * getElement() { // ... std::list&lt;MyContainedClass&gt;::iterator it = ... // retrieve somehow return &amp;(*it); } // other methods private: std::list&lt;MyContainedClass&gt; m_contained; }; </code></pre> <p>Though msdn says <code>std::list</code> should not perform relocations of elements on deletion or insertion, is it a good and common way to return pointer to a list element?</p> <p>PS: I know that I can use collection of pointers (and will have to <code>delete</code> elements in destructor), collection of shared pointers (which I don't like), etc.</p>
[ { "answer_id": 108409, "author": "Andrew Queisser", "author_id": 18321, "author_profile": "https://Stackoverflow.com/users/18321", "pm_score": 0, "selected": false, "text": "<p>I think the bigger problem is that you're hiding the type of collection so even if you use a collection that doesn't move elements you may change your mind in the future. Externally that's not visible so I'd say it's not a good idea to do this.</p>\n" }, { "answer_id": 108450, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p>I don't see the use of encapsulating this, but that may be just me. In any case, returning a reference instead of a pointer makes a lot more sense to me.</p>\n" }, { "answer_id": 108458, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 1, "selected": false, "text": "<p>In a general sort of way, if your \"contained class\" is truly contained in your \"MyClass\", then MyClass should not be allowing outsiders to touch its private contents.</p>\n\n<p>So, MyClass should be providing methods to manipulate the contained class objects, not returning pointers to them. So, for example, a method such as \"increment the value of the umpteenth contained object\", rather than \"here is a pointer to the umpteenth contained object, do with it as you wish\".</p>\n" }, { "answer_id": 108467, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "<h2>It depends...</h2>\n<p>It depends on how much encapsulated you want your class to be, and what you want to hide, or show.</p>\n<p>The code I see seems ok for me. You're right about the fact the std::list's data and iterators won't be invalidated in case of another data/iterator's modification/deletion.</p>\n<p>Now, returning the pointer would hide the fact you're using a std::list as an internal container, and would not let the user to navigate its list. Returning the iterator would let more freedom to navigate this list for the users of the class, but they would &quot;know&quot; they are accessing a STL container.</p>\n<p>It's your choice, there, I guess.</p>\n<p>Note that if it == std::list&lt;&gt;.end(), then you'll have a problem with this code, but I guess you already know that, and that this is not the subject of this discussion.</p>\n<p>Still, there are alternative I summarize below:</p>\n<h2>Using <code>const</code> will help...</h2>\n<p>The fact you return a non-const pointer lets the user of you object silently modify any MyContainedClass he/she can get his/her hands on, without telling your object.</p>\n<p>Instead or returning a pointer, you could return a const pointer (and suffix your method with const) to stop the user from modifying the data inside the list without using an accessor approved by you (a kind of <code>setElement</code> ?).</p>\n<pre><code> const MyContainedClass * getElement() const {\n // ...\n std::list&lt;MyContainedClass&gt;::const_iterator it = ... // retrieve somehow\n return &amp;(*it);\n }\n</code></pre>\n<p>This will increase somewhat the encapsulation.</p>\n<h2>What about a reference?</h2>\n<p>If your method cannot fail (i.e. it always return a valid pointer), then you should consider returning the reference instead of the pointer. Something like:</p>\n<pre><code> const MyContainedClass &amp; getElement() const {\n // ...\n std::list&lt;MyContainedClass&gt;::const_iterator it = ... // retrieve somehow\n return *it;\n }\n</code></pre>\n<p>This has nothing to do with encapsulation, though..\n:-p</p>\n<h2>Using an iterator?</h2>\n<p>Why not return the iterator instead of the pointer? If for you, navigating the list up and down is ok, then the iterator would be better than the pointer, and is used mostly the same way.</p>\n<p>Make the iterator a const_iterator if you want to avoid the user modifying the data.</p>\n<pre><code> std::list&lt;MyContainedClass&gt;::const_iterator getElement() const {\n // ...\n std::list&lt;MyContainedClass&gt;::const_iterator it = ... // retrieve somehow\n return it;\n }\n</code></pre>\n<p>The good side would be that the user would be able to navigate the list. The bad side is that the user would know it is a std::list, so...</p>\n" }, { "answer_id": 108472, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 1, "selected": false, "text": "<p>Scott Meyers in his book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201749629\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library</a> says it's just not worth trying to encapsulate your containers since none of them are completely replaceable for another.</p>\n" }, { "answer_id": 108494, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 0, "selected": false, "text": "<p>std::list will not invalidate any iterators, pointers or references when you add or remove things from the list (apart from any that point the item being removed, obviously), so using a list in this way isn't going to break.</p>\n\n<p>As others have pointed out, you may want not want to be handing out direct access to the private bits of this class. So changing the function to:</p>\n\n<pre><code> const MyContainedClass * getElement() const {\n // ...\n std::list&lt;MyContainedClass&gt;::const_iterator it = ... // retrieve somehow\n return &amp;(*it);\n }\n</code></pre>\n\n<p>may be better, or if you always return a valid MyContainedClass object then you could use</p>\n\n<pre><code> const MyContainedClass&amp; getElement() const {\n // ...\n std::list&lt;MyContainedClass&gt;::const_iterator it = ... // retrieve somehow\n return *it;\n }\n</code></pre>\n\n<p>to avoid the calling code having to cope with NULL pointers.</p>\n" }, { "answer_id": 108668, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 0, "selected": false, "text": "<p>STL will be more familiar to a future programmer than your custom encapsulation, so you should avoid doing this if you can. There will be edge cases that you havent thought about which will come up later in the app's lifetime, wheras STL is failry well reviewed and documented. </p>\n\n<p>Additionally most containers support somewhat similar operations like begin end push etc. So it should be fairly trivial to change the container type in your code should you change the container. eg vector to deque or map to hash_map etc. </p>\n\n<p>Assuming you still want to do this for a more deeper reason, i would say the correct way to do this is to implement all the methods and iterator classes that list implements. Forward the calls to the member list calls when you need no changes. Modify and forward or do some custom actions where you need to do something special (the reason why you decide to this in the first place)</p>\n\n<p>It would be easier if STl classes where designed to be inherited from but for efficiency sake it was decided not to do so. Google for \"inherit from STL classes\" for more thoughts on this. </p>\n" }, { "answer_id": 108790, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "<p>Think <em>good and hard</em> about what you really want <code>MyClass</code> for. I've noticed that some programmers write wrappers for their collections just as a matter of habit, regardless of whether they have any specific needs above and beyond those met by the standard STL collections. If that's your situation, then <code>typedef std::list&lt;MyContainedClass&gt; MyClass</code> and be done with it.</p>\n\n<p>If you <em>do</em> have operations you intend to implement in <code>MyClass</code>, then the success of your encapsulation will depend more on the interface you provide for them than on how you provide access to the underlying list. </p>\n\n<p>No offense meant, but... With the limited information you've provided, it <em>smells</em> like you're punting: exposing internal data because you can't figure out how to implement the operations your client code requires in <code>MyClass</code>... or possibly, because you don't even <em>know</em> yet what operations will be required by your client code. This is a classic problem with trying to write low-level code before the high-level code that requires it; you know what data you'll be working with, but haven't really nailed down exactly what you'll be doing with it yet, so you write a class structure that exposes the raw data all the way to the top. You'd do well to re-think your strategy here.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/108389/is-it-a-good-correct-way-to-encapsulate-a-collection#113052\">@cos</a>: </p>\n\n<blockquote>\n <p>Of course I'm encapsulating\n MyContainedClass not just for the sake\n of encapsulation. Let's take more\n specific example:</p>\n</blockquote>\n\n<p>Your example does little to allay my fear that you are writing your containers before you know what they'll be used for. Your example container wrapper - <code>Document</code> - has a total of three methods: <code>NewParagraph()</code>, <code>DeleteParagraph()</code>, and <code>GetParagraph()</code>, all of which operate on the contained collection (<code>std::list</code>), <em>and all of which</em> closely mirror operations that <code>std::list</code> provides \"out of the box\". <code>Document</code> encapsulates std::list in the sense that clients need not be aware of its use in the implementation... but realistically, it is little more than a facade - since you are providing clients raw pointers to the objects stored in the list, the client is still tied implicitly to the implementation.</p>\n\n<blockquote>\n <p>If we put objects (not pointers) to\n container they will be destroyed\n automatically (which is good).</p>\n</blockquote>\n\n<p>Good or bad depends on the needs of your system. What this implementation means is simple: the document owns the <code>Paragraph</code>s, and when a <code>Paragraph</code> is removed from the document any pointers to it immediately become invalid. Which means you must be <em>very</em> careful when implementing something like:</p>\n\n<blockquote>\n <p>other objects than use collections of\n paragraphs, but don't own them.</p>\n</blockquote>\n\n<p>Now you have a problem. Your object, <code>ParagraphSelectionDialog</code>, has a list of pointers to <code>Paragraph</code> objects owned by the <code>Document</code>. If you are not careful to coordinate these two objects, the <code>Document</code> - or another client by way of the <code>Document</code> - could invalidate some or all of the pointers held by an instance of <code>ParagraphSelectionDialog</code>! There's no easy way to catch this - a pointer to a valid <code>Paragraph</code> looks the same as a pointer to a deallocated <code>Paragraph</code>, and may even end up pointing to a valid - but different - <code>Paragraph</code> instance! Since clients are allowed, and even expected, to retain and dereference these pointers, the <code>Document</code> loses control over them as soon as they are returned from a public method, even while it retains ownership of the <code>Paragraph</code> objects.</p>\n\n<p>This... is bad. You've end up with an incomplete, superficial, encapsulation, a leaky abstraction, and in some ways it is worse than having no abstraction at all. Because you hide the implementation, your clients have no idea of the lifetime of the objects pointed to by your interface. You would probably get lucky most of the time, since most <code>std::list</code> operations do not invalidate references to items they don't modify. And all would be well... until the wrong <code>Paragraph</code> gets deleted, and you find yourself stuck with the task of tracing through the callstack looking for the client that kept that pointer around a little bit too long. </p>\n\n<p>The fix is simple enough: return values or objects that can be stored for as long as they need to be, and verified prior to use. That could be something as simple as an ordinal or ID value that must be passed to the <code>Document</code> in exchange for a usable reference, or as complex as a reference-counted smart pointer or weak pointer... it really depends on the specific needs of your clients. Spec out the client code first, then write your <code>Document</code> to serve.</p>\n" }, { "answer_id": 119457, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 1, "selected": false, "text": "<p><strong>The Easy way</strong></p>\n\n<p>@cos, For the example you have shown, i would say the easiest way to create this system in C++ would be to not trouble with the reference counting. All you have to do would be to make sure that the program flow first destroys the objects (views) which holds the direct references to the objects (paragraphs) in the collection, before the root Document get destroyed. </p>\n\n<p><strong>The Tough Way</strong></p>\n\n<p>However if you still want to control the lifetimes by reference tracking, you might have to hold references deeper into the hierarchy such that Paragraph objects holds reverse references to the root Document object such that, only when the last paragraph object gets destroyed will the Document object get destructed. </p>\n\n<p>Additionally the paragraph references when used inside the Views class and when passed to other classes, would also have to passed around as reference counted interfaces.</p>\n\n<p><strong>Toughness</strong></p>\n\n<p>This is too much overhead, compared to the simple scheme i listed in the beginning. It avoids all kinds of object counting overheads and more importantly someone who inherits your program does not get trapped in the reference dependency threads traps that criss cross your system. </p>\n\n<p><strong>Alternative Platforms</strong></p>\n\n<p>This kind-of tooling might be easier to perform in a platform that supports and promotes this style of programming like .NET or Java. </p>\n\n<p><strong>You still have to worry about memory</strong></p>\n\n<p>Even with a platform such as this you would still have to ensure your objects get de-referenced in a proper manner. Else outstanding references could eat up your memory in the blink of an eye. So you see, reference counting is not the panacea to good programming practices, though it helps avoid lots of error checks and cleanups, which when applied the whole system considerably eases the programmers task.</p>\n\n<p><strong>Recommendation</strong></p>\n\n<p>That said, coming back to your original question which gave raise to all the reference counting doubts - Is it ok to expose your objects directly from the collection? </p>\n\n<p>Programs cannot exist where all classes / all parts of the program are truly interdependent of each other. No, that would be impossible, as a program is the running manifestation of how your classes / modules interact. The ideal design can only minimize the dependencies and not remove them totally. </p>\n\n<p>So my opinion would be, <em>yes it is not a bad practice to expose the references to the objects from your collection, to other objects that need to work with them, provided you do this in a sane manner</em></p>\n\n<ol>\n<li><p>Ensure that only a few classes / parts of your program can get such references to ensure minimum interdependency.</p></li>\n<li><p>Ensure that the references / pointers passed are interfaces and not concrete objects so that the interdependency is avoided between concrete classes. </p></li>\n<li><p>Ensure that the references are not further passed along deeper into the program. </p></li>\n<li><p>Ensure that the program logic takes care of destroying the dependent objects, before cleaning up the actual objects that satisfy those references. </p></li>\n</ol>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
``` class MyContainedClass { }; class MyClass { public: MyContainedClass * getElement() { // ... std::list<MyContainedClass>::iterator it = ... // retrieve somehow return &(*it); } // other methods private: std::list<MyContainedClass> m_contained; }; ``` Though msdn says `std::list` should not perform relocations of elements on deletion or insertion, is it a good and common way to return pointer to a list element? PS: I know that I can use collection of pointers (and will have to `delete` elements in destructor), collection of shared pointers (which I don't like), etc.
I don't see the use of encapsulating this, but that may be just me. In any case, returning a reference instead of a pointer makes a lot more sense to me.
108,396
<p>I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. </p> <pre><code>public class Person { public Person() { GroupsOwned = new List&lt;Groups&gt;(); } public virtual IList&lt;Groups&gt; GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List&lt;Person&gt;(); } public virtual IList&lt;Person&gt; Admins{ get; set; } } </code></pre> <p>With the mapping looking like this</p> <p>Person: ...</p> <pre><code>HasManyToMany&lt;Groups&gt;(x =&gt; x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); </code></pre> <p>Groups: ...</p> <pre><code> HasManyToMany&lt;Person&gt;(x =&gt; x.Admins) .WithTableName("GroupAdministrators") .WithParentKeyColumn("GroupID") .WithChildKeyColumn("PersonID") .Cascade.SaveUpdate(); </code></pre> <p>When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. </p> <p>Thanks for any advice you may have.</p>
[ { "answer_id": 108694, "author": "emeryc", "author_id": 3900, "author_profile": "https://Stackoverflow.com/users/3900", "pm_score": 0, "selected": false, "text": "<p>Are you making sure to add the Person to the Groups.Admin? You have to make both links.</p>\n" }, { "answer_id": 108864, "author": "emeryc", "author_id": 3900, "author_profile": "https://Stackoverflow.com/users/3900", "pm_score": 0, "selected": false, "text": "<p>You have three tables right?</p>\n\n<p>People, Groups, and GroupAdministrators</p>\n\n<p>when you add to both sides you get</p>\n\n<p>People (with an id of p1)\nGroups (with an id of g1)</p>\n\n<p>and in GroupAdministrators you have two columns and a table that has</p>\n\n<p>(p1,g1)</p>\n\n<p>(p1,g1)</p>\n\n<p>and your unit test code looks like the following.</p>\n\n<pre><code>Context hibContext //Built here\nTransaction hibTrans //build and start the transaction.\n\nPerson p1 = new Person()\nGroups g1 = new Groups()\n\np1.getGroupsOwned().add(g1)\ng1.getAdmins().add(p1)\n\nhibTrans.commit();\nhibContext.close();\n</code></pre>\n\n<p>And then in your test you make a new context, and test to see what's in the context, and you get back the right thing, but your tables are all mucked up?</p>\n" }, { "answer_id": 108879, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 6, "selected": true, "text": "<p>The fact that it is adding two records to the table looks like you are missing an <a href=\"http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#example-many-to-many-mapping-file\" rel=\"noreferrer\">inverse attribute</a>. Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this.</p>\n\n<p>I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.</p>\n" }, { "answer_id": 108895, "author": "emeryc", "author_id": 3900, "author_profile": "https://Stackoverflow.com/users/3900", "pm_score": 3, "selected": false, "text": "<p>@Santiago I think you're right.</p>\n\n<p>The answer might just be that you need to remove one of your ManyToMany declarations, looking more at Fluent it looks like it might be smart enough to just do it for you.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. ``` public class Person { public Person() { GroupsOwned = new List<Groups>(); } public virtual IList<Groups> GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List<Person>(); } public virtual IList<Person> Admins{ get; set; } } ``` With the mapping looking like this Person: ... ``` HasManyToMany<Groups>(x => x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); ``` Groups: ... ``` HasManyToMany<Person>(x => x.Admins) .WithTableName("GroupAdministrators") .WithParentKeyColumn("GroupID") .WithChildKeyColumn("PersonID") .Cascade.SaveUpdate(); ``` When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. Thanks for any advice you may have.
The fact that it is adding two records to the table looks like you are missing an [inverse attribute](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#example-many-to-many-mapping-file). Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this. I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.
108,403
<p>Assume a table structure of <code>MyTable(KEY, datafield1, datafield2...)</code>.</p> <p>Often I want to either update an existing record, or insert a new record if it doesn't exist.</p> <p>Essentially:</p> <pre><code>IF (key exists) run update command ELSE run insert command </code></pre> <p>What's the best performing way to write this?</p>
[ { "answer_id": 108408, "author": "Clint Ecker", "author_id": 13668, "author_profile": "https://Stackoverflow.com/users/13668", "pm_score": -1, "selected": false, "text": "<p>Do a select, if you get a result, update it, if not, create it.</p>\n" }, { "answer_id": 108410, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 6, "selected": false, "text": "<pre><code>IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)\nUPDATE [Table] SET propertyOne = propOne, property2 . . .\nELSE\nINSERT INTO [Table] (propOne, propTwo . . .)\n</code></pre>\n\n<p><strong>Edit:</strong> </p>\n\n<p>Alas, even to my own detriment, I must admit the solutions that do this without a select seem to be better since they accomplish the task with one less step.</p>\n" }, { "answer_id": 108416, "author": "Beau Crawford", "author_id": 19413, "author_profile": "https://Stackoverflow.com/users/19413", "pm_score": 8, "selected": false, "text": "<p>Do an UPSERT:</p>\n\n<pre>\nUPDATE MyTable SET FieldA=@FieldA WHERE Key=@Key\n\nIF @@ROWCOUNT = 0\n INSERT INTO MyTable (FieldA) VALUES (@FieldA)\n</pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Upsert\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Upsert</a></p>\n" }, { "answer_id": 108420, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 10, "selected": true, "text": "<p>don't forget about transactions. Performance is good, but simple (IF EXISTS..) approach is very dangerous.<br>\nWhen multiple threads will try to perform Insert-or-update you can easily \nget primary key violation.</p>\n\n<p>Solutions provided by @Beau Crawford &amp; @Esteban show general idea but error-prone.</p>\n\n<p>To avoid deadlocks and PK violations you can use something like this: </p>\n\n<pre><code>begin tran\nif exists (select * from table with (updlock,serializable) where key = @key)\nbegin\n update table set ...\n where key = @key\nend\nelse\nbegin\n insert into table (key, ...)\n values (@key, ...)\nend\ncommit tran\n</code></pre>\n\n<p>or</p>\n\n<pre><code>begin tran\n update table with (serializable) set ...\n where key = @key\n\n if @@rowcount = 0\n begin\n insert into table (key, ...) values (@key,..)\n end\ncommit tran\n</code></pre>\n" }, { "answer_id": 108425, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": -1, "selected": false, "text": "<p>Doing an if exists ... else ... involves doing two requests minimum (one to check, one to take action). The following approach requires only one where the record exists, two if an insert is required:</p>\n\n<pre><code>DECLARE @RowExists bit\nSET @RowExists = 0\nUPDATE MyTable SET DataField1 = 'xxx', @RowExists = 1 WHERE Key = 123\nIF @RowExists = 0\n INSERT INTO MyTable (Key, DataField1) VALUES (123, 'xxx')\n</code></pre>\n" }, { "answer_id": 108427, "author": "Micky McQuade", "author_id": 12908, "author_profile": "https://Stackoverflow.com/users/12908", "pm_score": -1, "selected": false, "text": "<p>I usually do what several of the other posters have said with regard to checking for it existing first and then doing whatever the correct path is. One thing you should remember when doing this is that the execution plan cached by sql could be nonoptimal for one path or the other. I believe the best way to do this is to call two different stored procedures.</p>\n\n<pre>\nFirstSP:\nIf Exists\n Call SecondSP (UpdateProc)\nElse\n Call ThirdSP (InsertProc)\n</pre>\n\n<p>Now, I don't follow my own advice very often, so take it with a grain of salt.</p>\n" }, { "answer_id": 108428, "author": "nruessmann", "author_id": 10329, "author_profile": "https://Stackoverflow.com/users/10329", "pm_score": -1, "selected": false, "text": "<p>If you use ADO.NET, the DataAdapter handles this.</p>\n\n<p>If you want to handle it yourself, this is the way:</p>\n\n<p>Make sure there is a primary key constraint on your key column.</p>\n\n<p>Then you:</p>\n\n<ol>\n<li>Do the update</li>\n<li>If the update fails because a record with the key already exists, do the insert. If the update does not fail, you are finished.</li>\n</ol>\n\n<p>You can also do it the other way round, i.e. do the insert first, and do the update if the insert fails. Normally the first way is better, because updates are done more often than inserts.</p>\n" }, { "answer_id": 108516, "author": "Bart", "author_id": 16980, "author_profile": "https://Stackoverflow.com/users/16980", "pm_score": -1, "selected": false, "text": "<p>In SQL Server 2008 you can use the MERGE statement</p>\n" }, { "answer_id": 108540, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 5, "selected": false, "text": "<p>If you want to UPSERT more than one record at a time you can use the ANSI SQL:2003 DML statement MERGE.</p>\n\n<pre><code>MERGE INTO table_name WITH (HOLDLOCK) USING table_name ON (condition)\nWHEN MATCHED THEN UPDATE SET column1 = value1 [, column2 = value2 ...]\nWHEN NOT MATCHED THEN INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])\n</code></pre>\n\n<p>Check out <a href=\"http://sqlserver-tips.blogspot.com/2006/09/mimicking-merge-statement-in-sql.html\" rel=\"noreferrer\">Mimicking MERGE Statement in SQL Server 2005</a>.</p>\n" }, { "answer_id": 195426, "author": "bjorsig", "author_id": 27195, "author_profile": "https://Stackoverflow.com/users/27195", "pm_score": 2, "selected": false, "text": "<p>MS SQL Server 2008 introduces the MERGE statement, which I believe is part of the SQL:2003 standard. As many have shown it is not a big deal to handle one row cases, but when dealing with large datasets, one needs a cursor, with all the performance problems that come along. The MERGE statement will be much welcomed addition when dealing with large datasets.</p>\n" }, { "answer_id": 243670, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 9, "selected": false, "text": "<p>See my <a href=\"https://stackoverflow.com/questions/234\">detailed answer to a very similar previous question</a></p>\n\n<p><a href=\"https://stackoverflow.com/a/108416/1165522\">@Beau Crawford's</a> is a good way in SQL 2005 and below, though if you're granting rep it should go to the <a href=\"https://stackoverflow.com/questions/13540\">first guy to SO it</a>. The only problem is that for inserts it's still two IO operations.</p>\n\n<p>MS Sql2008 introduces <code>merge</code> from the SQL:2003 standard:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>merge tablename with(HOLDLOCK) as target\nusing (values ('new value', 'different value'))\n as source (field1, field2)\n on target.idfield = 7\nwhen matched then\n update\n set field1 = source.field1,\n field2 = source.field2,\n ...\nwhen not matched then\n insert ( idfield, field1, field2, ... )\n values ( 7, source.field1, source.field2, ... )\n</code></pre>\n\n<p>Now it's really just one IO operation, but awful code :-(</p>\n" }, { "answer_id": 2107205, "author": "user243131", "author_id": 243131, "author_profile": "https://Stackoverflow.com/users/243131", "pm_score": 4, "selected": false, "text": "<p>Although its pretty late to comment on this I want to add a more complete example using MERGE.</p>\n\n<p>Such Insert+Update statements are usually called \"Upsert\" statements and can be implemented using MERGE in SQL Server.</p>\n\n<p>A very good example is given here:\n<a href=\"http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx\" rel=\"noreferrer\">http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx</a></p>\n\n<p>The above explains locking and concurrency scenarios as well.</p>\n\n<p>I will be quoting the same for reference:</p>\n\n<pre><code>ALTER PROCEDURE dbo.Merge_Foo2\n @ID int\nAS\n\nSET NOCOUNT, XACT_ABORT ON;\n\nMERGE dbo.Foo2 WITH (HOLDLOCK) AS f\nUSING (SELECT @ID AS ID) AS new_foo\n ON f.ID = new_foo.ID\nWHEN MATCHED THEN\n UPDATE\n SET f.UpdateSpid = @@SPID,\n UpdateTime = SYSDATETIME()\nWHEN NOT MATCHED THEN\n INSERT\n (\n ID,\n InsertSpid,\n InsertTime\n )\n VALUES\n (\n new_foo.ID,\n @@SPID,\n SYSDATETIME()\n );\n\nRETURN @@ERROR;\n</code></pre>\n" }, { "answer_id": 3295625, "author": "ZXX", "author_id": 374835, "author_profile": "https://Stackoverflow.com/users/374835", "pm_score": 2, "selected": false, "text": "<p>Before everyone jumps to HOLDLOCK-s out of fear from these nafarious users running your sprocs directly :-) let me point out that <strong>you have to guarantee uniqueness of new PK-s by design</strong> (identity keys, sequence generators in Oracle, unique indexes for external ID-s, queries covered by indexes). That's the alpha and omega of the issue. If you don't have that, no HOLDLOCK-s of the universe are going to save you and if you do have that then you don't need anything beyond UPDLOCK on the first select (or to use update first).</p>\n\n<p>Sprocs normally run under very controlled conditions and with the assumption of a trusted caller (mid tier). Meaning that if a simple upsert pattern (update+insert or merge) ever sees duplicate PK that means a bug in your mid-tier or table design and it's good that SQL will yell a fault in such case and reject the record. Placing a HOLDLOCK in this case equals eating exceptions and taking in potentially faulty data, besides reducing your perf.</p>\n\n<p>Having said that, Using MERGE, or UPDATE then INSERT is easier on your server and less error prone since you don't have to remember to add (UPDLOCK) to first select. Also, if you are doing inserts/updates in small batches you need to know your data in order to decide whether a transaction is appropriate or not. It it's just a collection of unrelated records then additional \"enveloping\" transaction will be detrimental.</p>\n" }, { "answer_id": 6760940, "author": "runec", "author_id": 448420, "author_profile": "https://Stackoverflow.com/users/448420", "pm_score": 2, "selected": false, "text": "<p>Does the race conditions really matter if you first try an update followed by an insert? \nLets say you have two threads that want to set a value for key <strong>key</strong>:</p>\n\n<p>Thread 1: value = 1<br>\nThread 2: value = 2 </p>\n\n<p>Example race condition scenario</p>\n\n<ol>\n<li><strong>key</strong> is not defined</li>\n<li>Thread 1 fails with update</li>\n<li>Thread 2 fails with update</li>\n<li>Exactly one of thread 1 or thread 2 succeeds with insert. E.g. thread 1</li>\n<li><p>The other thread fails with insert (with error duplicate key) - thread 2.</p>\n\n<ul>\n<li>Result: The \"first\" of the two treads to insert, decides value.</li>\n<li>Wanted result: The last of the 2 threads to write data (update or insert) should decide value</li>\n</ul></li>\n</ol>\n\n<p>But; in a multithreaded environment, the OS scheduler decides on the order of the thread execution - in the above scenario, where we have this race condition, it was the OS that decided on the sequence of execution. Ie: It is wrong to say that \"thread 1\" or \"thread 2\" was \"first\" from a system viewpoint.</p>\n\n<p>When the time of execution is so close for thread 1 and thread 2, the outcome of the race condition doesn't matter. The only requirement should be that one of the threads should define the resulting value.</p>\n\n<p>For the implementation: If update followed by insert results in error \"duplicate key\", this should be treated as success. </p>\n\n<p>Also, one should of course never assume that value in the database is the same as the value you wrote last.</p>\n" }, { "answer_id": 7186101, "author": "Kristen", "author_id": 65703, "author_profile": "https://Stackoverflow.com/users/65703", "pm_score": 2, "selected": false, "text": "<p>If going the UPDATE if-no-rows-updated then INSERT route, consider doing the INSERT first to prevent a race condition (assuming no intervening DELETE)</p>\n\n<pre><code>INSERT INTO MyTable (Key, FieldA)\n SELECT @Key, @FieldA\n WHERE NOT EXISTS\n (\n SELECT *\n FROM MyTable\n WHERE Key = @Key\n )\nIF @@ROWCOUNT = 0\nBEGIN\n UPDATE MyTable\n SET FieldA=@FieldA\n WHERE Key=@Key\n IF @@ROWCOUNT = 0\n ... record was deleted, consider looping to re-run the INSERT, or RAISERROR ...\nEND\n</code></pre>\n\n<p>Apart from avoiding a race condition, if in most cases the record will already exist then this will cause the INSERT to fail, wasting CPU.</p>\n\n<p>Using MERGE probably preferable for SQL2008 onwards. </p>\n" }, { "answer_id": 11931778, "author": "Victor Sanchez", "author_id": 192389, "author_profile": "https://Stackoverflow.com/users/192389", "pm_score": 0, "selected": false, "text": "<p>You can use this query. Work in all SQL Server editions. It's simple, and clear. But you need use 2 queries. You can use if you can't use MERGE</p>\n\n<pre><code> BEGIN TRAN\n\n UPDATE table\n SET Id = @ID, Description = @Description\n WHERE Id = @Id\n\n INSERT INTO table(Id, Description)\n SELECT @Id, @Description\n WHERE NOT EXISTS (SELECT NULL FROM table WHERE Id = @Id)\n\n COMMIT TRAN\n</code></pre>\n\n<p>NOTE: Please explain answer negatives</p>\n" }, { "answer_id": 21209295, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 7, "selected": false, "text": "<p>Many people will suggest you use <code>MERGE</code>, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, and it introduces other dangers:</p>\n<ul>\n<li><a href=\"http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/?utm_source=AaronBertrand\" rel=\"noreferrer\">Use Caution with SQL Server's MERGE Statement</a></li>\n<li><a href=\"https://sqlblog.org/merge\" rel=\"noreferrer\">So, you want to use MERGE, eh?</a></li>\n</ul>\n<p>Even with this &quot;simpler&quot; syntax available, I still prefer this approach (error handling omitted for brevity):</p>\n<pre><code>BEGIN TRANSACTION;\n\nUPDATE dbo.table WITH (UPDLOCK, SERIALIZABLE) \n SET ... WHERE PK = @PK;\n\nIF @@ROWCOUNT = 0\nBEGIN\n INSERT dbo.table(PK, ...) SELECT @PK, ...;\nEND\n\nCOMMIT TRANSACTION;\n</code></pre>\n<ul>\n<li><a href=\"https://sqlperformance.com/2020/09/locking/upsert-anti-pattern\" rel=\"noreferrer\">Please stop using this UPSERT anti-pattern</a></li>\n</ul>\n<p>A lot of folks will suggest this way:</p>\n<pre><code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n\nBEGIN TRANSACTION;\n\nIF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)\nBEGIN\n UPDATE ...\nEND\nELSE\nBEGIN\n INSERT ...\nEND\nCOMMIT TRANSACTION;\n</code></pre>\n<p>But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)</p>\n<p>Others will suggest this way:</p>\n<pre><code>BEGIN TRY\n INSERT ...\nEND TRY\nBEGIN CATCH\n IF ERROR_NUMBER() = 2627\n UPDATE ...\nEND CATCH\n</code></pre>\n<p>However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:</p>\n<ul>\n<li><a href=\"http://www.mssqltips.com/sqlservertip/2632/checking-for-potential-constraint-violations-before-entering-sql-server-try-and-catch-logic/?utm_source=AaronBertrand\" rel=\"noreferrer\">Checking for potential constraint violations before entering TRY/CATCH</a></li>\n<li><a href=\"http://www.sqlperformance.com/2012/08/t-sql-queries/error-handling\" rel=\"noreferrer\">Performance impact of different error handling techniques</a></li>\n</ul>\n" }, { "answer_id": 26612200, "author": "Denver", "author_id": 4190548, "author_profile": "https://Stackoverflow.com/users/4190548", "pm_score": 3, "selected": false, "text": "<pre><code>/*\nCREATE TABLE ApplicationsDesSocietes (\n id INT IDENTITY(0,1) NOT NULL,\n applicationId INT NOT NULL,\n societeId INT NOT NULL,\n suppression BIT NULL,\n CONSTRAINT PK_APPLICATIONSDESSOCIETES PRIMARY KEY (id)\n)\nGO\n--*/\n\nDECLARE @applicationId INT = 81, @societeId INT = 43, @suppression BIT = 0\n\nMERGE dbo.ApplicationsDesSocietes WITH (HOLDLOCK) AS target\n--set the SOURCE table one row\nUSING (VALUES (@applicationId, @societeId, @suppression))\n AS source (applicationId, societeId, suppression)\n --here goes the ON join condition\n ON target.applicationId = source.applicationId and target.societeId = source.societeId\nWHEN MATCHED THEN\n UPDATE\n --place your list of SET here\n SET target.suppression = source.suppression\nWHEN NOT MATCHED THEN\n --insert a new line with the SOURCE table one row\n INSERT (applicationId, societeId, suppression)\n VALUES (source.applicationId, source.societeId, source.suppression);\nGO\n</code></pre>\n\n<p>Replace table and field names by whatever you need.\nTake care of the <em>using ON</em> condition.\nThen set the appropriate value (and type) for the variables on the DECLARE line.</p>\n\n<p>Cheers.</p>\n" }, { "answer_id": 31206622, "author": "Dev", "author_id": 5077561, "author_profile": "https://Stackoverflow.com/users/5077561", "pm_score": 1, "selected": false, "text": "<p>I had tried below solution and it works for me, when concurrent request for insert statement occurs.</p>\n\n<pre><code>begin tran\nif exists (select * from table with (updlock,serializable) where key = @key)\nbegin\n update table set ...\n where key = @key\nend\nelse\nbegin\n insert table (key, ...)\n values (@key, ...)\nend\ncommit tran\n</code></pre>\n" }, { "answer_id": 33588589, "author": "Saleh Najar", "author_id": 5537967, "author_profile": "https://Stackoverflow.com/users/5537967", "pm_score": 3, "selected": false, "text": "<p>That depends on the usage pattern. One has to look at the usage big picture without getting lost in the details. For example, if the usage pattern is 99% updates after the record has been created, then the 'UPSERT' is the best solution.</p>\n\n<p>After the first insert (hit), it will be all single statement updates, no ifs or buts. The 'where' condition on the insert is necessary otherwise it will insert duplicates, and you don't want to deal with locking.</p>\n\n<pre><code>UPDATE &lt;tableName&gt; SET &lt;field&gt;=@field WHERE key=@key;\n\nIF @@ROWCOUNT = 0\nBEGIN\n INSERT INTO &lt;tableName&gt; (field)\n SELECT @field\n WHERE NOT EXISTS (select * from tableName where key = @key);\nEND\n</code></pre>\n" }, { "answer_id": 40005414, "author": "Daniel Acosta", "author_id": 7009558, "author_profile": "https://Stackoverflow.com/users/7009558", "pm_score": 3, "selected": false, "text": "<p>You can use <code>MERGE</code> Statement, This statement is used to insert data if not exist or update if does exist.</p>\n\n<pre><code>MERGE INTO Employee AS e\nusing EmployeeUpdate AS eu\nON e.EmployeeID = eu.EmployeeID`\n</code></pre>\n" }, { "answer_id": 63689042, "author": "Nenad", "author_id": 186822, "author_profile": "https://Stackoverflow.com/users/186822", "pm_score": 0, "selected": false, "text": "<p>Assuming that you want to insert/update single row, most optimal approach is to use SQL Server's <code>REPEATABLE READ</code> transaction isolation level:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;\nBEGIN TRANSACTION\n\n IF (EXISTS (SELECT * FROM myTable WHERE key=@key)\n UPDATE myTable SET ...\n WHERE key=@key\n ELSE\n INSERT INTO myTable (key, ...)\n VALUES (@key, ...)\n\nCOMMIT TRANSACTION\n</code></pre>\n<p>This isolation level will <strong>prevent/block subsequent repeatable read transactions</strong> from accessing same row (<code>WHERE key=@key</code>) while currently running transaction is open.\nOn the other hand, <strong>operations on another row won't be blocked</strong> (<code>WHERE key=@key2</code>).</p>\n" }, { "answer_id": 72134891, "author": "Jay", "author_id": 17137922, "author_profile": "https://Stackoverflow.com/users/17137922", "pm_score": -1, "selected": false, "text": "<p>You can use:</p>\n<pre><code>INSERT INTO tableName (...) VALUES (...) \nON DUPLICATE KEY \nUPDATE ...\n</code></pre>\n<p>Using this, if there is already an entry for the particular key, then it will UPDATE, else, it will INSERT.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
Assume a table structure of `MyTable(KEY, datafield1, datafield2...)`. Often I want to either update an existing record, or insert a new record if it doesn't exist. Essentially: ``` IF (key exists) run update command ELSE run insert command ``` What's the best performing way to write this?
don't forget about transactions. Performance is good, but simple (IF EXISTS..) approach is very dangerous. When multiple threads will try to perform Insert-or-update you can easily get primary key violation. Solutions provided by @Beau Crawford & @Esteban show general idea but error-prone. To avoid deadlocks and PK violations you can use something like this: ``` begin tran if exists (select * from table with (updlock,serializable) where key = @key) begin update table set ... where key = @key end else begin insert into table (key, ...) values (@key, ...) end commit tran ``` or ``` begin tran update table with (serializable) set ... where key = @key if @@rowcount = 0 begin insert into table (key, ...) values (@key,..) end commit tran ```
108,439
<p>I'm looking to get the result of a command as a variable in a Windows batch script (see <a href="https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash#58214">how to get the result of a command in bash</a> for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome. </p>
[ { "answer_id": 108462, "author": "Jack B Nimble", "author_id": 3800, "author_profile": "https://Stackoverflow.com/users/3800", "pm_score": -1, "selected": false, "text": "<p>Please refer to this <a href=\"http://technet.microsoft.com/en-us/library/bb490982.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/bb490982.aspx</a> which explains what you can do with command output.</p>\n" }, { "answer_id": 108465, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": false, "text": "<p>you need to use the <code>SET</code> command with parameter <code>/P</code> and direct your output to it.\nFor example see <a href=\"http://www.ss64.com/nt/set.html\" rel=\"noreferrer\">http://www.ss64.com/nt/set.html</a>. Will work for CMD, not sure about .BAT files</p>\n\n<p>From a comment to this post:</p>\n\n<blockquote>\n <p>That link has the command \"<code>Set /P\n _MyVar=&lt;MyFilename.txt</code>\" which says it will set <code>_MyVar</code> to the first line\n from <code>MyFilename.txt</code>. This could be\n used as \"<code>myCmd &gt; tmp.txt</code>\" with \"<code>set\n /P myVar=&lt;tmp.txt</code>\". But it will only\n get the first line of the output, not\n all the output</p>\n</blockquote>\n" }, { "answer_id": 108480, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "<p>Example to set in the \"V\" environment variable the most recent file </p>\n\n<pre><code>FOR /F %I IN ('DIR *.* /O:D /B') DO SET V=%I\n</code></pre>\n\n<p>in a batch file you have to use double prefix in the loop variable:</p>\n\n<pre><code>FOR /F %%I IN ('DIR *.* /O:D /B') DO SET V=%%I\n</code></pre>\n" }, { "answer_id": 108511, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 7, "selected": false, "text": "<p>The humble <strong>for</strong> command has accumulated some interesting capabilities over the years:</p>\n\n<pre><code>D:\\&gt; FOR /F \"delims=\" %i IN ('date /t') DO set today=%i\nD:\\&gt; echo %today%\nSat 20/09/2008\n</code></pre>\n\n<p>Note that <code>\"delims=\"</code> overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.</p>\n\n<p>To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):</p>\n\n<pre><code>REM NB:in a batch file, need to use %%i not %i\nsetlocal EnableDelayedExpansion\nSET lf=-\nFOR /F \"delims=\" %%i IN ('dir \\ /b') DO if (\"!out!\"==\"\") (set out=%%i) else (set out=!out!%lf%%%i)\nECHO %out%\n</code></pre>\n\n<p>To capture a piped expression, use <code>^|</code>:</p>\n\n<pre><code>FOR /F \"delims=\" %%i IN ('svn info . ^| findstr \"Root:\"') DO set \"URL=%%i\"\n</code></pre>\n" }, { "answer_id": 108515, "author": "Evil Activity", "author_id": 15520, "author_profile": "https://Stackoverflow.com/users/15520", "pm_score": 5, "selected": false, "text": "<p>To get the current directory, you can use this:</p>\n\n<pre><code>CD &gt; tmpFile\nSET /p myvar= &lt; tmpFile\nDEL tmpFile\necho test: %myvar%\n</code></pre>\n\n<p>It's using a temp-file though, so it's not the most pretty, but it certainly works! 'CD' puts the current directory in 'tmpFile', 'SET' loads the content of tmpFile.</p>\n\n<p>Here is a solution for multiple lines with \"array's\":</p>\n\n<pre><code>@echo off\n\nrem ---------\nrem Obtain line numbers from the file\nrem ---------\n\nrem This is the file that is being read: You can replace this with %1 for dynamic behaviour or replace it with some command like the first example i gave with the 'CD' command.\nset _readfile=test.txt\n\nfor /f \"usebackq tokens=2 delims=:\" %%a in (`find /c /v \"\" %_readfile%`) do set _max=%%a\nset /a _max+=1\nset _i=0\nset _filename=temp.dat\n\nrem ---------\nrem Make the list\nrem ---------\n\n:makeList\nfind /n /v \"\" %_readfile% &gt;%_filename%\n\nrem ---------\nrem Read the list\nrem ---------\n\n:readList\nif %_i%==%_max% goto printList\n\nrem ---------\nrem Read the lines into the array\nrem ---------\nfor /f \"usebackq delims=] tokens=2\" %%a in (`findstr /r \"\\[%_i%]\" %_filename%`) do set _data%_i%=%%a\nset /a _i+=1\ngoto readList\n\n:printList\ndel %_filename%\nset _i=1\n:printMore\nif %_i%==%_max% goto finished\nset _data%_i%\nset /a _i+=1\ngoto printMore\n\n:finished\n</code></pre>\n\n<p>But you might want to consider moving to another more powerful shell or create an application for this stuff. It's stretching the possibilities of the batch files quite a bit.</p>\n" }, { "answer_id": 108615, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 6, "selected": true, "text": "<p>If you have to capture all the command output you can use a batch like this:</p>\n<pre><code>@ECHO OFF\nIF NOT &quot;%1&quot;==&quot;&quot; GOTO ADDV\nSET VAR=\nFOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I\nSET VAR\nGOTO END\n\n:ADDV\nSET VAR=%VAR%!%1\n\n:END\n</code></pre>\n<p>All output lines are stored in VAR separated with &quot;!&quot;.</p>\n<p>But if only a single-line console-output is expected, try:</p>\n<pre><code>@ECHO off\n@SET MY_VAR=\nFOR /F %%I IN ('npm prefix') DO @SET &quot;MY_VAR=%%I&quot;\n\n@REM Do something with MY_VAR variable...\n</code></pre>\n<p>@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)</p>\n" }, { "answer_id": 108656, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 1, "selected": false, "text": "<p>You can capture all output in one variable, but the lines will be separated by a character of your choice (# in the example below) instead of an actual CR-LF.</p>\n\n<pre><code>@echo off\nsetlocal EnableDelayedExpansion\nfor /f \"delims=\" %%i in ('dir /b') do (\n if \"!DIR!\"==\"\" (set DIR=%%i) else (set DIR=!DIR!#%%i)\n)\necho directory contains:\necho %DIR%\n</code></pre>\n\n<p>Second version, if you need to print the contents out line-by-line. This takes advanted of the fact that there won't be duplicate lines of output from \"dir /b\", so it may not work in the general case.</p>\n\n<pre><code>@echo off\nsetlocal EnableDelayedExpansion\nset count=0\nfor /f \"delims=\" %%i in ('dir /b') do (\n if \"!DIR!\"==\"\" (set DIR=%%i) else (set DIR=!DIR!#%%i)\n set /a count = !count! + 1\n)\n\necho directory contains:\necho %DIR%\n\nfor /l %%c in (1,1,%count%) do (\n for /f \"delims=#\" %%i in (\"!DIR!\") do (\n echo %%i\n set DIR=!DIR:%%i=!\n )\n)\n</code></pre>\n" }, { "answer_id": 108716, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": false, "text": "<p>If you're looking for the solution provided in <a href=\"https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash\">Using the result of a command as an argument in bash?</a></p>\n\n<p>then here is the code:</p>\n\n<pre><code>@echo off\nif not \"%1\"==\"\" goto get_basename_pwd\nfor /f \"delims=X\" %%i in ('cd') do call %0 %%i\nfor /f \"delims=X\" %%i in ('dir /o:d /b') do echo %%i&gt;&gt;%filename%.txt\ngoto end\n\n:get_basename_pwd\nset filename=%~n1\n\n:end\n</code></pre>\n\n<ul>\n<li>This will call itself with the result of the CD command, same as pwd.</li>\n<li>String extraction on parameters will return the filename/folder.</li>\n<li>Get the contents of this folder and append to the filename.txt</li>\n</ul>\n\n<p><strong>[Credits]</strong>: Thanks to all the other answers and some digging on the <a href=\"http://www.ss64.com/nt/\" rel=\"nofollow noreferrer\">Windows XP commands</a> page.</p>\n" }, { "answer_id": 12755627, "author": "Hike", "author_id": 1724296, "author_profile": "https://Stackoverflow.com/users/1724296", "pm_score": 2, "selected": false, "text": "<pre><code>@echo off\n\nver | find \"6.1.\" &gt; nul\nif %ERRORLEVEL% == 0 (\necho Win7\nfor /f \"delims=\" %%a in ('DIR \"C:\\Program Files\\Microsoft Office\\*Outlook.EXE\" /B /P /S') do call set findoutlook=%%a\n%findoutlook%\n)\n\nver | find \"5.1.\" &gt; nul\nif %ERRORLEVEL% == 0 (\necho WinXP\nfor /f \"delims=\" %%a in ('DIR \"C:\\Program Files\\Microsoft Office\\*Outlook.EXE\" /B /P /S') do call set findoutlook=%%a\n%findoutlook%\n)\necho Outlook dir: %findoutlook%\n\"%findoutlook%\"\n</code></pre>\n" }, { "answer_id": 23385707, "author": "Raceableability", "author_id": 3568856, "author_profile": "https://Stackoverflow.com/users/3568856", "pm_score": 2, "selected": false, "text": "<p>Just use the result from the <code>FOR</code> command. For example (inside a batch file):</p>\n\n<pre><code>for /F \"delims=\" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)\n</code></pre>\n\n<p>You can use the <code>%%I</code> as the value you want. Just like this: <code>%%I</code>.</p>\n\n<p>And in advance the <code>%%I</code> does not have any spaces or CR characters and can be used for comparisons!!</p>\n" }, { "answer_id": 48305783, "author": "Gilles Maisonneuve", "author_id": 3676932, "author_profile": "https://Stackoverflow.com/users/3676932", "pm_score": 2, "selected": false, "text": "<p>I would like to add a remark to the above solutions:</p>\n\n<p>All these syntaxes work perfectly well IF YOUR COMMAND IS FOUND WITHIN THE PATH or IF THE COMMAND IS A cmdpath WITHOUT SPACES OR SPECIAL CHARACTERS.</p>\n\n<p>But if you try to use an executable command located in a folder which path contains special characters then you would need to enclose your command path into double quotes (\") and then the FOR /F syntax does not work.</p>\n\n<p>Examples:</p>\n\n<pre><code>$ for /f \"tokens=* USEBACKQ\" %f in (\n `\"\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" Hello '\"F:\\GLW7\\Distrib\\System\\Shells and scripting\"'`\n) do echo %f\nThe filename, directory name, or volume label syntax is incorrect.\n</code></pre>\n\n<p>or </p>\n\n<pre><code>$ for /f \"tokens=* USEBACKQ\" %f in (\n `\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\" \"Hello World\" \"F:\\GLW7\\Distrib\\System\\Shells and scripting\"`\n) do echo %f\n'F:\\GLW7\\Distrib\\System\\Shells' is not recognized as an internal or external command, operable program or batch file.\n</code></pre>\n\n<p>or </p>\n\n<pre><code>`$ for /f \"tokens=* USEBACKQ\" %f in (\n `\"\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" \"Hello World\" \"F:\\GLW7\\Distrib\\System\\Shells and scripting\"`\n) do echo %f\n'\"F:\\GLW7\\Distrib\\System\\Shells and scripting\\f2ko.de\\folderbrowse.exe\"\" \"Hello' is not recognized as an internal or external command, operable program or batch file.\n</code></pre>\n\n<p>In that case, the only solution I found to use a command and store its result in a variable is to set (temporarily) the default directory to the one of command itself :</p>\n\n<pre><code>pushd \"%~d0%~p0\"\nFOR /F \"tokens=* USEBACKQ\" %%F IN (\n `FOLDERBROWSE \"Hello world!\" \"F:\\GLW7\\Distrib\\System\\Layouts (print,display...)\"`\n) DO (SET MyFolder=%%F)\npopd\necho My selected folder: %MyFolder%\n</code></pre>\n\n<p>The result is then correct:</p>\n\n<pre><code>My selected folder: F:\\GLW7\\Distrib\\System\\OS install, recovery, VM\\\nPress any key to continue . . .\n</code></pre>\n\n<p>Of course in the above example, I assume that my batch script is located in the same folder as the one of my executable command so that I can use the \"%~d0%~p0\" syntax. If this is not your case, then you have to find a way to locate your command path and change the default directory to its path.</p>\n\n<p>NB: For those who wonder, the sample command used here (to select a folder) is FOLDERBROWSE.EXE. I found it on the web site f2ko.de (<a href=\"http://f2ko.de/en/cmd.php\" rel=\"nofollow noreferrer\">http://f2ko.de/en/cmd.php</a>).</p>\n\n<p>If anyone has a better solution for that kind of commands accessible through a complex path, I will be very glad to hear of it.</p>\n\n<p>Gilles</p>\n" }, { "answer_id": 54670814, "author": "ivan rc", "author_id": 10806969, "author_profile": "https://Stackoverflow.com/users/10806969", "pm_score": 1, "selected": false, "text": "<pre><code>@echo off\nsetlocal EnableDelayedExpansion\nFOR /F \"tokens=1 delims= \" %%i IN ('echo hola') DO (\n set TXT=%%i\n)\necho 'TXT: %TXT%'\n</code></pre>\n\n<p>the result is 'TXT: hola'</p>\n" }, { "answer_id": 55245989, "author": "Hayz", "author_id": 11085919, "author_profile": "https://Stackoverflow.com/users/11085919", "pm_score": 0, "selected": false, "text": "<p>You should use the <code>for</code> command, here is an example:</p>\n\n<pre><code>@echo off\nrem Commands go here\nexit /b\n:output\nfor /f \"tokens=* useback\" %%a in (`%~1`) do set \"output=%%a\"\n</code></pre>\n\n<p>and you can use <code>call :output \"Command goes here\"</code> then the output will be in the <code>%output%</code> variable.</p>\n\n<p><strong>Note:</strong> If you have a command output that is multiline, this tool will <code>set</code> the output to the last line of your multiline command.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3535/" ]
I'm looking to get the result of a command as a variable in a Windows batch script (see [how to get the result of a command in bash](https://stackoverflow.com/questions/58207/using-the-result-of-a-command-as-an-argument-in-bash#58214) for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome.
If you have to capture all the command output you can use a batch like this: ``` @ECHO OFF IF NOT "%1"=="" GOTO ADDV SET VAR= FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I SET VAR GOTO END :ADDV SET VAR=%VAR%!%1 :END ``` All output lines are stored in VAR separated with "!". But if only a single-line console-output is expected, try: ``` @ECHO off @SET MY_VAR= FOR /F %%I IN ('npm prefix') DO @SET "MY_VAR=%%I" @REM Do something with MY_VAR variable... ``` @John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)
108,443
<p>I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this?</p> <p>Should I use structs to link the structure into a program flow. Are objects better?</p> <pre><code>struct asm_code { int type; int value; int optimized; asm_code *next_to_execute; } asm_imp; </code></pre> <p>Update: I think it will turn out, like a linked list.</p> <p>Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves.</p> <p>Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished?</p>
[ { "answer_id": 108493, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>It is possible. Dynamic code generation is even mainstream in some areas like software rendering and graphics. You find a lot of use in all kinds of script languages, in dynamic compilation of byte-code in machine code (.NET, Java, as far as I know Perl. Recently JavaScript joined the club as well).</p>\n\n<p>You also find it used in very math-heavy applications as well, It makes a difference if you for example remove all multiplication with zero out of a matrix multiplication if you plan to do such a multiplication several thousand times.</p>\n\n<p>I strongly suggest that you read on the SSA representation of code. That's a representation where each primitive is turned into the so called three operand form, and each variable is only assigned once (hence the same Static Single Assignment form).</p>\n\n<p>You can run high order optimizations on such code, and it's straight forward to turn that code into executable code. You won't write that code-generation backend on a weekend though... </p>\n\n<p>To get a feeling how the SSA looks like you can try out the LLVM compiler. On their web-site they have a little \"Try Out\" widget to play with. You paste C code into a window and you get something out that is close to the SSA form.</p>\n\n<p>Little example how it looks like:</p>\n\n<p>Lets take this integer square root algorithm in C. (arbitrary example, I just took something simple yet non-trivial):</p>\n\n<pre><code>unsigned int isqrt32 (unsigned int value) \n{\n unsigned int g = 0;\n unsigned int bshift = 15;\n unsigned int b = 1&lt;&lt;bshift;\n do {\n unsigned int temp = (g+g+b)&lt;&lt;bshift;\n if (value &gt;= temp) {\n g += b;\n value -= temp;\n }\n b&gt;&gt;=1;\n } while (bshift--);\n return g;\n}\n</code></pre>\n\n<p>LLVM turns it into:</p>\n\n<pre><code>define i32 @isqrt32(i32 %value) nounwind {\nentry:\n br label %bb\n\nbb: ; preds = %bb, %entry\n %indvar = phi i32 [ 0, %entry ], [ %indvar.next, %bb ] \n %b.0 = phi i32 [ 32768, %entry ], [ %tmp23, %bb ]\n %g.1 = phi i32 [ 0, %entry ], [ %g.0, %bb ] \n %value_addr.1 = phi i32 [ %value, %entry ], [ %value_addr.0, %bb ] \n %bshift.0 = sub i32 15, %indvar \n %tmp5 = shl i32 %g.1, 1 \n %tmp7 = add i32 %tmp5, %b.0 \n %tmp9 = shl i32 %tmp7, %bshift.0 \n %tmp12 = icmp ult i32 %value_addr.1, %tmp9 \n %tmp17 = select i1 %tmp12, i32 0, i32 %b.0 \n %g.0 = add i32 %tmp17, %g.1 \n %tmp20 = select i1 %tmp12, i32 0, i32 %tmp9 \n %value_addr.0 = sub i32 %value_addr.1, %tmp20 \n %tmp23 = lshr i32 %b.0, 1 \n %indvar.next = add i32 %indvar, 1 \n %exitcond = icmp eq i32 %indvar.next, 16 \n br i1 %exitcond, label %bb30, label %bb\n\nbb30: ; preds = %bb\n ret i32 %g.0\n}\n</code></pre>\n\n<p>I know it looks horrible at first. It's not even pure SSA-Form. The more you read on that representation the more sense it will make. And you will also find out why this representation is so widely used these days.</p>\n\n<p>Encapsulating all the info you need into a data-structure is easy. In the end you have to decide if you want to use enums or strings for opcode names ect.</p>\n\n<p>Btw - I know I didn't gave you a data-structure but more a formal yet practical language and the advice where to look further. </p>\n\n<p>It's a very nice and interesting research field.</p>\n\n<p>Edit: And before I forget it: Don't overlook the built in features of .NET and Java. These languates allow you to compile from byte-code or source code from within the program and execute the result. </p>\n\n<p>Cheers,\n Nils</p>\n\n<hr>\n\n<p>Regarding your edit: How to execute a binary blob with code: </p>\n\n<p>Jumping into your binary blob is OS and platform dependent. In a nutshell you have invalide the instruction cache, <em>maybe</em> you have to writeback the data-cache and you may have to enable execution rights on the memory-region you've wrote your code into.</p>\n\n<p>On win32 it's relative easy as instruction cache flushing seems to be sufficient if you place your code on the heap. </p>\n\n<p>You can use this stub to get started:</p>\n\n<pre><code>typedef void (* voidfunc) (void);\n\nvoid * generate_code (void)\n{\n // reserve some space\n unsigned char * buffer = (unsigned char *) malloc (1024);\n\n\n // write a single RET-instruction\n buffer[0] = 0xc3; \n\n return buffer;\n}\n\nint main (int argc, char **args)\n{\n // generate some code:\n voidfunc func = (voidfunc) generate_code();\n\n // flush instruction cache:\n FlushInstructionCache(GetCurrentProcess(), func, 1024);\n\n // execute the code (it does nothing atm)\n func();\n\n // free memory and exit.\n free (func);\n}\n</code></pre>\n" }, { "answer_id": 108502, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 0, "selected": false, "text": "<p>In 99% of the cases, the difference in performance is negligible. The main advantage of classes is that the code produced by OOP is better and easier to understand than procedural code.</p>\n\n<p>I'm not sure in what language you're coding - note that in C# the major difference between classes and structs is that structs are value types while classes are reference types. In this case, you might want to start with structs, but still add behavior (constructor, methods) to them.</p>\n" }, { "answer_id": 108510, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "<p>Not discussing the technical value of optimize yourself your code, in a C++ code, choosing between a POD struct or a full object is mostly a point of encapsulation.</p>\n<p>Inlining the code will let the compiler optimize (or not) the constructors/accessors used. There will be no loss of performance.</p>\n<h2>First, set a constructor</h2>\n<p>If you're working with a C++ compiler, create at least one constructor:</p>\n<pre><code>struct asm_code {\n asm_code()\n : type(0), value(0), optimized(0) {}\n\n asm_code(int type_, int value_, int optimized_)\n : type(type_), value(value_), optimized(_optimized) {}\n\n int type;\n int value;\n int optimized;\n };\n</code></pre>\n<p>At least, you won't have undefined structs in your code.</p>\n<h2>Are every combination of data possible?</h2>\n<p>Using a struct like you use means that any type is possible, with any value, and any optimized. For example, if I set type = 25, value = 1205 and optimized = -500, then it is Ok.</p>\n<p>If you don't want the user to put random values inside your structure, add inline accessors:</p>\n<pre><code>struct asm_code {\n\n int getType() { return type ; }\n void setType(int type_) { VERIFY_TYPE(type_) ; type = type_ ; }\n\n // Etc.\n\n private :\n int type;\n int value;\n int optimized;\n };\n</code></pre>\n<p>This will let you control what is set inside your structure, and debug your code more easily (or even do runtime verification of you code)</p>\n" }, { "answer_id": 108578, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 1, "selected": false, "text": "<p>I assume you want a data structure to hold some kind of instruction template, probably parsed from existing machine code, similar to:</p>\n<pre><code>add r1, r2, &lt;int&gt;\n</code></pre>\n<p>You will have an array of this structure and you will perform some optimization on this array, probably changing its size or building a new one, and generate corresponding machine code.</p>\n<p>If your target machine uses variable width instructions (x86 for example), you can't determine your array size without actually finishing parsing the instructions which you build the array from. Also you can't determine exactly how much buffer you need before actually generating all the instructions from optimized array. You can make a good estimate though.</p>\n<p>Check out <a href=\"http://www.gnu.org/software/lightning/manual/lightning.html\" rel=\"nofollow noreferrer\">GNU Lightning</a>. It may be useful to you.</p>\n" }, { "answer_id": 5021776, "author": "FlinkmanSV", "author_id": 15054, "author_profile": "https://Stackoverflow.com/users/15054", "pm_score": 0, "selected": false, "text": "<p>After some reading, my conclusion is that common lisp is the best fit for this task.\nWith lisp macros I have enormous power.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
I'm planning to create a data structure optimized to hold assembly code. That way I can be totally responsible for the optimization algorithms that will be working on this structure. If I can compile while running. It will be kind of dynamic execution. Is this possible? Have any one seen something like this? Should I use structs to link the structure into a program flow. Are objects better? ``` struct asm_code { int type; int value; int optimized; asm_code *next_to_execute; } asm_imp; ``` Update: I think it will turn out, like a linked list. Update: I know there are other compilers out there. But this is a military top secret project. So we can't trust any code. We have to do it all by ourselves. Update: OK, I think I will just generate basic i386 machine code. But how do I jump into my memory blob when it is finished?
It is possible. Dynamic code generation is even mainstream in some areas like software rendering and graphics. You find a lot of use in all kinds of script languages, in dynamic compilation of byte-code in machine code (.NET, Java, as far as I know Perl. Recently JavaScript joined the club as well). You also find it used in very math-heavy applications as well, It makes a difference if you for example remove all multiplication with zero out of a matrix multiplication if you plan to do such a multiplication several thousand times. I strongly suggest that you read on the SSA representation of code. That's a representation where each primitive is turned into the so called three operand form, and each variable is only assigned once (hence the same Static Single Assignment form). You can run high order optimizations on such code, and it's straight forward to turn that code into executable code. You won't write that code-generation backend on a weekend though... To get a feeling how the SSA looks like you can try out the LLVM compiler. On their web-site they have a little "Try Out" widget to play with. You paste C code into a window and you get something out that is close to the SSA form. Little example how it looks like: Lets take this integer square root algorithm in C. (arbitrary example, I just took something simple yet non-trivial): ``` unsigned int isqrt32 (unsigned int value) { unsigned int g = 0; unsigned int bshift = 15; unsigned int b = 1<<bshift; do { unsigned int temp = (g+g+b)<<bshift; if (value >= temp) { g += b; value -= temp; } b>>=1; } while (bshift--); return g; } ``` LLVM turns it into: ``` define i32 @isqrt32(i32 %value) nounwind { entry: br label %bb bb: ; preds = %bb, %entry %indvar = phi i32 [ 0, %entry ], [ %indvar.next, %bb ] %b.0 = phi i32 [ 32768, %entry ], [ %tmp23, %bb ] %g.1 = phi i32 [ 0, %entry ], [ %g.0, %bb ] %value_addr.1 = phi i32 [ %value, %entry ], [ %value_addr.0, %bb ] %bshift.0 = sub i32 15, %indvar %tmp5 = shl i32 %g.1, 1 %tmp7 = add i32 %tmp5, %b.0 %tmp9 = shl i32 %tmp7, %bshift.0 %tmp12 = icmp ult i32 %value_addr.1, %tmp9 %tmp17 = select i1 %tmp12, i32 0, i32 %b.0 %g.0 = add i32 %tmp17, %g.1 %tmp20 = select i1 %tmp12, i32 0, i32 %tmp9 %value_addr.0 = sub i32 %value_addr.1, %tmp20 %tmp23 = lshr i32 %b.0, 1 %indvar.next = add i32 %indvar, 1 %exitcond = icmp eq i32 %indvar.next, 16 br i1 %exitcond, label %bb30, label %bb bb30: ; preds = %bb ret i32 %g.0 } ``` I know it looks horrible at first. It's not even pure SSA-Form. The more you read on that representation the more sense it will make. And you will also find out why this representation is so widely used these days. Encapsulating all the info you need into a data-structure is easy. In the end you have to decide if you want to use enums or strings for opcode names ect. Btw - I know I didn't gave you a data-structure but more a formal yet practical language and the advice where to look further. It's a very nice and interesting research field. Edit: And before I forget it: Don't overlook the built in features of .NET and Java. These languates allow you to compile from byte-code or source code from within the program and execute the result. Cheers, Nils --- Regarding your edit: How to execute a binary blob with code: Jumping into your binary blob is OS and platform dependent. In a nutshell you have invalide the instruction cache, *maybe* you have to writeback the data-cache and you may have to enable execution rights on the memory-region you've wrote your code into. On win32 it's relative easy as instruction cache flushing seems to be sufficient if you place your code on the heap. You can use this stub to get started: ``` typedef void (* voidfunc) (void); void * generate_code (void) { // reserve some space unsigned char * buffer = (unsigned char *) malloc (1024); // write a single RET-instruction buffer[0] = 0xc3; return buffer; } int main (int argc, char **args) { // generate some code: voidfunc func = (voidfunc) generate_code(); // flush instruction cache: FlushInstructionCache(GetCurrentProcess(), func, 1024); // execute the code (it does nothing atm) func(); // free memory and exit. free (func); } ```
108,461
<p>I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible.</p>
[ { "answer_id": 108479, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p>Eric Meyer's <a href=\"http://meyerweb.com/eric/css/edge/popups/demo2.html\" rel=\"nofollow noreferrer\">Pure CSS Popups 2</a> demo sounds similar enough to what you want.</p>\n" }, { "answer_id": 108492, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 0, "selected": false, "text": "<p>Here are a few examples:</p>\n\n<ul>\n<li><a href=\"http://www.dynamicdrive.com/style/csslibrary/item/css-image-gallery/\" rel=\"nofollow noreferrer\">CSS Image gallery</a></li>\n<li><a href=\"http://www.cssplay.co.uk/menu/lightbox.html\" rel=\"nofollow noreferrer\">Cross Browser Multi-Page Photograph Gallery</a></li>\n<li><a href=\"http://designsignature.co.za/blog/?p=29\" rel=\"nofollow noreferrer\">A CSS-only Image Gallery: Explained</a></li>\n<li><a href=\"http://www.designsignature.co.za/web.php\" rel=\"nofollow noreferrer\">A CSS-only Image Gallery: Example</a></li>\n</ul>\n\n<p>This last one acts upon click. Just to be complete in behaviours.</p>\n" }, { "answer_id": 108496, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://meyerweb.com/eric/css/edge/popups/demo2.html\" rel=\"noreferrer\">Pure CSS Popups2</a>, from the same site that brings us Complexspiral. Note that this example is using actual navigational links as the rolled-over element. If you don't want that, it may cause some stickiness regarding versions of IE.</p>\n\n<p>The basic technique is to stick each image inside a link tag with an actual href (Otherwise some IE versions will neglect :hover)</p>\n\n<pre><code>&lt;a href=\"#\"&gt;Text &lt;img class=\"popup\" src=\"pic.gif\" /&gt;&lt;/a&gt;\n</code></pre>\n\n<p>and position it cleverly using absolute position. Hide the image initially</p>\n\n<pre><code>a img.popup { display: none }\n</code></pre>\n\n<p>and then on the link rollover, set it up to appear. </p>\n\n<pre><code>a:hover img.popup { display: block }\n</code></pre>\n\n<p>That's the basic technique, but there are always going to be major positioning limitations since the image tag dwells inside the link tag. See the link for details; he uses something a little more tricky than display: none to hide the image.</p>\n" }, { "answer_id": 108498, "author": "Paul Shannon", "author_id": 11503, "author_profile": "https://Stackoverflow.com/users/11503", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.cssplay.co.uk\" rel=\"nofollow noreferrer\">CSS Playground</a> uses pure CSS for this type of thing, one of the demos is surely to help you and as it's all CSS just view source to learn - you probably want to use the :hover pseudo class but there are limitations to it depending on your browser targeting.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18748/" ]
I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible.
[Pure CSS Popups2](http://meyerweb.com/eric/css/edge/popups/demo2.html), from the same site that brings us Complexspiral. Note that this example is using actual navigational links as the rolled-over element. If you don't want that, it may cause some stickiness regarding versions of IE. The basic technique is to stick each image inside a link tag with an actual href (Otherwise some IE versions will neglect :hover) ``` <a href="#">Text <img class="popup" src="pic.gif" /></a> ``` and position it cleverly using absolute position. Hide the image initially ``` a img.popup { display: none } ``` and then on the link rollover, set it up to appear. ``` a:hover img.popup { display: block } ``` That's the basic technique, but there are always going to be major positioning limitations since the image tag dwells inside the link tag. See the link for details; he uses something a little more tricky than display: none to hide the image.
108,523
<p>I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?</p> <p>Class code here:</p> <pre><code>class Enum(object): '''Simple Enum Class Example Usage: &gt;&gt;&gt; codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) </code></pre>
[ { "answer_id": 108547, "author": "Ycros", "author_id": 10495, "author_profile": "https://Stackoverflow.com/users/10495", "pm_score": 3, "selected": false, "text": "<p>Enums have been proposed for inclusion into the language before, but were rejected (see <a href=\"http://www.python.org/dev/peps/pep-0354/\" rel=\"nofollow noreferrer\" title=\"PEP 354\">http://www.python.org/dev/peps/pep-0354/</a>), though there are existing packages you could use instead of writing your own implementation:</p>\n\n<ul>\n<li>enum: <a href=\"http://pypi.python.org/pypi/enum\" rel=\"nofollow noreferrer\" title=\"enum\">http://pypi.python.org/pypi/enum</a></li>\n<li>SymbolType (not quite the same as enums, but still useful): <a href=\"http://pypi.python.org/pypi/SymbolType\" rel=\"nofollow noreferrer\" title=\"SymbolType\">http://pypi.python.org/pypi/SymbolType</a></li>\n<li><a href=\"http://pypi.python.org/pypi?:action=search&amp;term=enum&amp;submit=search\" rel=\"nofollow noreferrer\">Or just do a search</a></li>\n</ul>\n" }, { "answer_id": 108549, "author": "tsg", "author_id": 15685, "author_profile": "https://Stackoverflow.com/users/15685", "pm_score": 2, "selected": false, "text": "<p>The builtin way to do enums is:</p>\n\n<pre><code>(FOO, BAR, BAZ) = range(3)\n</code></pre>\n\n<p>which works fine for small sets, but has some drawbacks:</p>\n\n<ul>\n<li>you need to count the number of elements by hand</li>\n<li>you can't skip values </li>\n<li>if you add one name, you also need to update the range number</li>\n</ul>\n\n<p>For a complete enum implementation in python, see:\n<a href=\"http://code.activestate.com/recipes/67107/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/67107/</a></p>\n" }, { "answer_id": 108556, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 2, "selected": false, "text": "<p>What I see more often is this, in top-level module context:</p>\n\n<pre><code>FOO_BAR = 'FOO_BAR'\nFOO_BAZ = 'FOO_BAZ'\nFOO_QUX = 'FOO_QUX'\n</code></pre>\n\n<p>...and later...</p>\n\n<pre><code>if something is FOO_BAR: pass # do something here\nelif something is FOO_BAZ: pass # do something else\nelif something is FOO_QUX: pass # do something else\nelse: raise Exception('Invalid value for something')\n</code></pre>\n\n<p>Note that the use of <code>is</code> rather than <code>==</code> is taking a risk here -- it assumes that folks are using <code>your_module.FOO_BAR</code> rather than the string <code>'FOO_BAR'</code> (which will <I>normally</I> be interned such that <code>is</code> will match, but that certainly can't be counted on), and so may not be appropriate depending on context.</p>\n\n<p>One advantage of doing it this way is that by looking anywhere a reference to that string is being stored, it's immediately obvious where it came from; <code>FOO_BAZ</code> is much less ambiguous than <code>2</code>.</p>\n\n<p>Besides that, the other thing that offends my Pythonic sensibilities re the class you propose is the use of <code>split()</code>. Why not just pass in a tuple, list or other enumerable to start with?</p>\n" }, { "answer_id": 108557, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": true, "text": "<p>There's a lot of good discussion <a href=\"https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python\">here</a>. </p>\n" }, { "answer_id": 108816, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>The most common enum case is enumerated values that are part of a State or Strategy design pattern. The enums are specific states or specific optional strategies to be used. In this case, they're almost always part and parcel of some class definition</p>\n\n<pre><code>class DoTheNeedful( object ):\n ONE_CHOICE = 1\n ANOTHER_CHOICE = 2 \n YET_ANOTHER = 99\n def __init__( self, aSelection ):\n assert aSelection in ( self.ONE_CHOICE, self.ANOTHER_CHOICE, self.YET_ANOTHER )\n self.selection= aSelection\n</code></pre>\n\n<p>Then, in a client of this class.</p>\n\n<pre><code>dtn = DoTheNeeful( DoTheNeeful.ONE_CHOICE )\n</code></pre>\n" }, { "answer_id": 674652, "author": "Spell", "author_id": 7185, "author_profile": "https://Stackoverflow.com/users/7185", "pm_score": 1, "selected": false, "text": "<p>I started with something that looks a lot like S.Lott's answer but I only overloaded 'str' and 'eq' (instead of the whole object class) so I could print and compare the enum's value.</p>\n\n<pre><code>class enumSeason():\n Spring = 0\n Summer = 1\n Fall = 2\n Winter = 3\n def __init__(self, Type):\n self.value = Type\n def __str__(self):\n if self.value == enumSeason.Spring:\n return 'Spring'\n if self.value == enumSeason.Summer:\n return 'Summer'\n if self.value == enumSeason.Fall:\n return 'Fall'\n if self.value == enumSeason.Winter:\n return 'Winter'\n def __eq__(self,y):\n return self.value==y.value\n</code></pre>\n\n<p>Print(x) will yield the name instead of the value and two values holding Spring will be equal to one another.</p>\n\n<pre><code> &gt;&gt;&gt; x = enumSeason(enumSeason.Spring)\n &gt;&gt;&gt; print(x)\n Spring\n &gt;&gt;&gt; y = enumSeason(enumSeason.Spring)\n &gt;&gt;&gt; x == y\n True\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9127/" ]
I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations? Class code here: ``` class Enum(object): '''Simple Enum Class Example Usage: >>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) ```
There's a lot of good discussion [here](https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python).
108,558
<p>Can a cookie be shared between two sites on the same top level domain? Say <code>www.example.com</code> and <code>secure.example.com</code> ? We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain. What parameters does the cookie need? I'm using asp.net</p>
[ { "answer_id": 108569, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 6, "selected": true, "text": "<p>Yes, you can. Use:</p>\n\n<pre><code>Response.Cookies(\"UID\").Domain = \".myserver.com\"\n</code></pre>\n" }, { "answer_id": 108681, "author": "Jess Chadwick", "author_id": 13960, "author_profile": "https://Stackoverflow.com/users/13960", "pm_score": 3, "selected": false, "text": "<p>The easiest way to apply a cookie domain that can be shared across subdomains is to put it in your web.config:</p>\n\n<pre><code>&lt;forms cookieDomain=\"example.com\"&gt;\n</code></pre>\n" }, { "answer_id": 5294426, "author": "FYA", "author_id": 614098, "author_profile": "https://Stackoverflow.com/users/614098", "pm_score": 1, "selected": false, "text": "<p>Yes, but beware don't set same-named cookies in various subdomains, as the resulting cookie appears to be random; instead, set one cookie in the .maindomain.com only (not in any .sub.domain.com)</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
Can a cookie be shared between two sites on the same top level domain? Say `www.example.com` and `secure.example.com` ? We are looking into implementing a cache for non-secure content, and need to segregate secure content to another domain. What parameters does the cookie need? I'm using asp.net
Yes, you can. Use: ``` Response.Cookies("UID").Domain = ".myserver.com" ```
108,567
<p>I have a SVN structure like this:</p> <pre><code>/Projects /Project1 /Project2 /someFolder /Project3 /Project4 </code></pre> <p>I would like to move all the projects into the /Projects folder, which means I want to move Projects 3 and 4 from /someFolder into the /projects folder.</p> <p>The caveat: I'd like to keep the full history. I assume that every client would have to check out the stuff from the new location again, which is fine, but I still wonder what the simplest approach is to move directories without completely destroying the history?</p> <p>Subversion 1.5 if that matters.</p>
[ { "answer_id": 108571, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 2, "selected": false, "text": "<p>Moving directories in Subversion doesn't destroy history, AFAIK.</p>\n" }, { "answer_id": 108573, "author": "binco", "author_id": 19671, "author_profile": "https://Stackoverflow.com/users/19671", "pm_score": 2, "selected": false, "text": "<p>You can use the svn copy command. It keeps your history. You just have to deselect the Option \"Stop on copy/rename\" while showing the Log (Example for Tortoise).</p>\n\n<p>Take a closer look at the Subversion-Book <a href=\"http://svnbook.red-bean.com/en/1.1/re07.html\" rel=\"nofollow noreferrer\">svn copy</a></p>\n" }, { "answer_id": 108576, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": -1, "selected": false, "text": "<p>As far as I know, only Bazaar allow to keep history on directories, espacially when talking about moving directories. SVN allows you to keep history when moving files, but not directories.</p>\n" }, { "answer_id": 108581, "author": "Geekygecko", "author_id": 6009, "author_profile": "https://Stackoverflow.com/users/6009", "pm_score": 5, "selected": false, "text": "<pre>svn move SRC DST</pre>\n\n<pre>$ svn move -m \"Move a file\" http://svn.red-bean.com/repos/foo.c http://svn.red-bean.com/repos/bar.c</pre>\n\n<p>svn move will keep your history.</p>\n" }, { "answer_id": 108583, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 7, "selected": true, "text": "<pre><code>svn help rename\n</code></pre>\n\n<p>Moving/renaming in subversion keeps history intact.</p>\n" }, { "answer_id": 108608, "author": "ljubomir", "author_id": 11506, "author_profile": "https://Stackoverflow.com/users/11506", "pm_score": 2, "selected": false, "text": "<p>IN order to do that, you'll have to use svn's specific move/rename functions (check TortoiseSVN help if you use this for example). If you move the files by yourself and then commit the changes i'm not sure that history will be kept. </p>\n" }, { "answer_id": 1200994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Drag-drop it using the repo-browser and rebind your local folder to your SVN server.</p>\n" }, { "answer_id": 9782862, "author": "Simon Byholm", "author_id": 153061, "author_profile": "https://Stackoverflow.com/users/153061", "pm_score": 3, "selected": false, "text": "<p>If you move Project 3 into the project folder using the svn move command the history will be preserved for the Project 3 folder but interestingly the Projects folder will not show the history of Project 3 that was created before Project 3 was moved into Projects. </p>\n\n<p>I find this confusing, I thought a folder would show all history below itself in the hierachy but it seems like this is not the case (just tested this myself)</p>\n" }, { "answer_id": 38178638, "author": "Abhilash", "author_id": 6546114, "author_profile": "https://Stackoverflow.com/users/6546114", "pm_score": 4, "selected": false, "text": "<p>Tortoise SVN supports 'Right Click' move in the Repo-Browser. When you drag the source file/directory into the destination using 'mouse right click' a context menu will appear. You can select the appropriate menu option for copy/move/move-rename etc. This option will preserve the history as well.</p>\n\n<p>Note: There is a nice fature called 'Repair Move' in Tortoise SVN - by using this feature you can rename the file/directory when you move it. (Refer to <a href=\"https://tortoisesvn.net/repairmoves.html\" rel=\"noreferrer\">Documentation</a> for more details)</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I have a SVN structure like this: ``` /Projects /Project1 /Project2 /someFolder /Project3 /Project4 ``` I would like to move all the projects into the /Projects folder, which means I want to move Projects 3 and 4 from /someFolder into the /projects folder. The caveat: I'd like to keep the full history. I assume that every client would have to check out the stuff from the new location again, which is fine, but I still wonder what the simplest approach is to move directories without completely destroying the history? Subversion 1.5 if that matters.
``` svn help rename ``` Moving/renaming in subversion keeps history intact.
108,586
<p>Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... </p> <pre><code>A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } </code></pre> <p>I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': a, c, d, e, g, f, b</p> <p>So, right now (a non-generator solution):</p> <pre><code>def get_all(D,k): L = [] def get2(D,k): L.append(k) for ii in D.get(k,[]): get2(D, ii) get2(D,k) return L </code></pre> <p>Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.</p>
[ { "answer_id": 108606, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 3, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>#!/usr/bin/env python\n\ndef get_all(D, k):\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii):\n yield jj\n\nA = { 'a' : dict(b=1, c=1),\n 'c' : dict(d=1),\n 'd' : dict(e=1,f=1,g=1),\n 'h' : dict(j=1)\n }\n\nfor ii in get_all(A,'a'):\n print ii\n</code></pre>\n\n<p>Gives me </p>\n\n<pre>\nsteve@rei:~/code/tmp\n$ python recur.py\na\nc\nd\ne\ng\nf\nb\n</pre>\n" }, { "answer_id": 108852, "author": "HenryR", "author_id": 2827, "author_profile": "https://Stackoverflow.com/users/2827", "pm_score": 3, "selected": false, "text": "<p>Both answers give the same result, but if my reading of the question is correct give the wrong answer to a simple alteration to the given graph - if you add a dependency on 'c' from 'b' (which doesn't introduce a cycle as the graph is directed) the output is: <code>\na\nc\nd\ne\ng\nf\nb\nd\ne\ng\nf\n</code></p>\n\n<p>which isn't totally helpful. Try this small variation, which keeps track of which nodes of the graph have already been visited:</p>\n\n<pre><code>def get_all(D, k, seen=None):\n if not seen:\n seen = set( )\n if k not in seen:\n seen.add(k)\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii, seen):\n yield jj\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... ``` A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } ``` I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': a, c, d, e, g, f, b So, right now (a non-generator solution): ``` def get_all(D,k): L = [] def get2(D,k): L.append(k) for ii in D.get(k,[]): get2(D, ii) get2(D,k) return L ``` Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.
Try this: ``` #!/usr/bin/env python def get_all(D, k): yield k for ii in D.get(k, []): for jj in get_all(D, ii): yield jj A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } for ii in get_all(A,'a'): print ii ``` Gives me ``` steve@rei:~/code/tmp $ python recur.py a c d e g f b ```
108,598
<p>Considering the following architecture:</p> <ul> <li>a base object 'Entity'</li> <li>a derived object 'Entry:Base'</li> <li>and a further derived object 'CancelledEntry:Entry'</li> </ul> <p>In EntitySQL I can write the following: </p> <pre><code>[...] where it is of (only MyEntities.Entry) [...] </code></pre> <p>to return only objects of type Entry and no Entity or CancelledEntry.</p> <p>In linq to sql, the following command will return objects of type Entry and CancelledEntry. </p> <pre><code>EntityContext.EntitySet.OfType&lt;Entry&gt;() </code></pre> <p>What is the syntax/function to use to return only objects of type Entry?</p>
[ { "answer_id": 108644, "author": "ADB", "author_id": 3610, "author_profile": "https://Stackoverflow.com/users/3610", "pm_score": 1, "selected": false, "text": "<p>Ok, I have found a partial solution:</p>\n\n<pre><code>EntityContext.EntitySet.OfType&lt;Entry&gt;().Where( obj =&gt; !(obj is CancelledEntry) )\n</code></pre>\n\n<p>This is quite awful however, since if I create a new derived object, I have to go in all the queries and specifically add a condition to remove it.</p>\n\n<p>There has to be a better solution</p>\n" }, { "answer_id": 177416, "author": "Keith Patton", "author_id": 25255, "author_profile": "https://Stackoverflow.com/users/25255", "pm_score": 3, "selected": true, "text": "<p>Why don't you apply an extension method on IQueryable&lt; Entry > called ApplyBaseEntryFilter() which would apply this filter and return an IQueryable&lt; Entry >. </p>\n\n<p>This is an example of how to reuse linq query fragments. Using extension methods on IQueryable&lt; Entity > is a great way to re-use queries as you should neve rneed to copy and paste query fragments around your application, hope that helps.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610/" ]
Considering the following architecture: * a base object 'Entity' * a derived object 'Entry:Base' * and a further derived object 'CancelledEntry:Entry' In EntitySQL I can write the following: ``` [...] where it is of (only MyEntities.Entry) [...] ``` to return only objects of type Entry and no Entity or CancelledEntry. In linq to sql, the following command will return objects of type Entry and CancelledEntry. ``` EntityContext.EntitySet.OfType<Entry>() ``` What is the syntax/function to use to return only objects of type Entry?
Why don't you apply an extension method on IQueryable< Entry > called ApplyBaseEntryFilter() which would apply this filter and return an IQueryable< Entry >. This is an example of how to reuse linq query fragments. Using extension methods on IQueryable< Entity > is a great way to re-use queries as you should neve rneed to copy and paste query fragments around your application, hope that helps.
108,682
<p><a href="http://svnbook.red-bean.com/nightly/en/svn.tour.importing.html#svn.tour.importing.layout" rel="nofollow noreferrer"><em>Version Control with Subversion</em></a> recommends the following layout for (single-project) repositories (complemented by <a href="https://stackoverflow.com/questions/49356/what-is-a-good-repository-layout-for-releases-and-projects-in-subversion"><em>this question</em></a>):</p> <pre><code>/trunk /tags /rel.1 (approximately) ... /branches /rel1fixes </code></pre> <p>What are the relative merits of this arrangement when compared with a (perhaps) more process-oriented one?:</p> <pre><code>/development /current /stable /qa (maybe) ... /production /stable /Prod.2 /Prod.1 /vendor /Rel.5.1 /Rel.5.2 </code></pre> <p>Please note that I'm thinking of in-house deployment, rather than building a product.</p> <p>Disclaimer: although I'm a Subversion user, I've never had to deploy with it in a real live environment. </p>
[ { "answer_id": 108700, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 0, "selected": false, "text": "<p>Whenever you deal with real live environments, you would want your developers to be able to understand your repository as easily as possible. A good way to do this is by adhering to the recommended Subversion standard layout.</p>\n" }, { "answer_id": 108721, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 5, "selected": true, "text": "<p>The main difference between the recommended layout and your proposed layout is that the recommended layout is somewhat self-documenting as to where to commit things, and how it behaves.</p>\n\n<p>For example, in the recommended layout, it's obvious that all new development is committed to trunk, and most branches are made from trunk. Also, it's obvious that you should never commit anything into /tags. Finally, it's safe to assume that branches are truly branches, which may contain changes specific to that particular branch purpose.</p>\n\n<p>With the proposed layout, some of these things are less certain. Is /development/stable branched from /current? What's the relation between /development/stable and /production/stable? Which of these directories are tags, and which ones can I actually check stuff into? </p>\n\n<p>Certainly this behavior can be documented, but by sticking to the accepted layout that everybody uses, you'll have an easier time getting new hires up to speed on how it works.</p>\n" }, { "answer_id": 108736, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": -1, "selected": false, "text": "<p>I think your plan is pretty good, really. How will you account for branches where a programmer is wandering off on their own just trying something? Maybe like /development/jfm3-messing-around ?</p>\n" }, { "answer_id": 108742, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 2, "selected": false, "text": "<p>I think flexibility and avoiding ambiguity is your answer.</p>\n\n<p>By using version numbers you do not tie yourself to where that version is deployed.</p>\n\n<p>For example you might have version 1.3 which is deployed as development, 1.2 which is in test and 1.1 which is in production. If you wanted you could easily add another staging environment for another version without having to change your subversion layout.</p>\n\n<p>Nobody can argument what version 1.1 of the code is, but \"production-stable\" version is ambiguous. </p>\n" }, { "answer_id": 108761, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 0, "selected": false, "text": "<p>Although I personally use the layout recommended in the SVN book, you probably should not restrict yourself to it if your layout works better for you. I would keep the <strong>branch</strong> directory since its usage and purpose is pretty clear from the name. Apart from that, really, anything goes if it works for you.</p>\n" }, { "answer_id": 108764, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 3, "selected": false, "text": "<p>You've described the two pretty much standard models for repository organization: dev-test-prod and trunk-branch. Eric Sink does a nice job of describing them in his <a href=\"http://www.ericsink.com/scm/scm_branches.html\" rel=\"noreferrer\">Source Control HOWTO</a>. One thing to note is that the way most people use trunk-branch is to create a branch for each version as it is released to customers, which then becomes the maintenance branch.</p>\n\n<p>I would tend to prefer trunk-branch since it doesn't require migrating every single change from development to test to production. Only changes that need to be backported to maintance branches or bugfixes that migrate from the maintance branch to the trunk need to be migrated.</p>\n\n<p>However, one circumstance were dev-test-prod might be preferable is in web development, where the concept of versions released to customers doesn't really exist. Prod, in this case, would be whatever's running on the server right now, while code is being worked on in dev and test and constantly migrated into the application, rather than being released in one big chunk.</p>\n" }, { "answer_id": 111017, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 3, "selected": false, "text": "<p>I'll try and sum up the answers so far:</p>\n\n<hr>\n\n<h2>Simple</h2>\n\n<ol>\n<li>The \"classic\" layout (<em>trunk/</em> +\n<em>branches/</em> + <em>tags/</em>) has the advantage\nof growable simplicity</li>\n<li>The Trunk is (usually) the main\ndevelopment line</li>\n<li>Branches attend to special\ndevelopment needs such as complex\nsubprojects and post-release\nmaintenance</li>\n<li>Tags are fixed, immutable marker\nposts</li>\n<li>This classic layout is well-known so\nyour developers get up to speed\nfaster</li>\n</ol>\n\n<h2>Expandable</h2>\n\n<ol>\n<li>Vendor development of products\nintegrated into your development\n(perhaps with adaptations) can, if\nrequired be handled as a vendor\nbranch (normally one is enough)</li>\n<li>The \"Process\" axis (Eg. Development,\nTest if done separately, QA if used, and\nProduction) can be handled by\nappropriate branch or tag\nconventions (depending on whether\nany changes are required or\npermitted outside \"Development\"). </li>\n<li>These additional sets of branches\ncan be handled by naming\nconventions, or by an additional\ndirectory level within <em>tags/</em> or\n<em>branches/</em>.</li>\n</ol>\n\n<h2>See Other Questions</h2>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/16142/what-does-branch-tag-and-trunk-really-mean\">What does branch, tag and trunk really mean?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/49356/what-is-a-good-repository-layout-for-releases-and-projects-in-subversion\">What is a good repository layout for releases and projects in Subversion?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/123295/do-you-use-the-branchestagstrunk-convention\">Do you use the branches-tags-trunk convention?</a></li>\n</ol>\n\n<hr>\n\n<p>I have made this a community answer; please feel free to correct or extend any deficiencies, for which I apologise.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9634/" ]
[*Version Control with Subversion*](http://svnbook.red-bean.com/nightly/en/svn.tour.importing.html#svn.tour.importing.layout) recommends the following layout for (single-project) repositories (complemented by [*this question*](https://stackoverflow.com/questions/49356/what-is-a-good-repository-layout-for-releases-and-projects-in-subversion)): ``` /trunk /tags /rel.1 (approximately) ... /branches /rel1fixes ``` What are the relative merits of this arrangement when compared with a (perhaps) more process-oriented one?: ``` /development /current /stable /qa (maybe) ... /production /stable /Prod.2 /Prod.1 /vendor /Rel.5.1 /Rel.5.2 ``` Please note that I'm thinking of in-house deployment, rather than building a product. Disclaimer: although I'm a Subversion user, I've never had to deploy with it in a real live environment.
The main difference between the recommended layout and your proposed layout is that the recommended layout is somewhat self-documenting as to where to commit things, and how it behaves. For example, in the recommended layout, it's obvious that all new development is committed to trunk, and most branches are made from trunk. Also, it's obvious that you should never commit anything into /tags. Finally, it's safe to assume that branches are truly branches, which may contain changes specific to that particular branch purpose. With the proposed layout, some of these things are less certain. Is /development/stable branched from /current? What's the relation between /development/stable and /production/stable? Which of these directories are tags, and which ones can I actually check stuff into? Certainly this behavior can be documented, but by sticking to the accepted layout that everybody uses, you'll have an easier time getting new hires up to speed on how it works.
108,687
<p>I want to create a box shape and I am having trouble. I want the box to have a background color, and then different color inside the box.<br> The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box. Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible.</p> <p>Here is a rough sketch of what I am trying to do:</p> <p><a href="https://i.stack.imgur.com/aZ2W7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aZ2W7.png" alt=""></a></p>
[ { "answer_id": 108708, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "<p>So if you have source:</p>\n\n<pre><code>&lt;div class=\"panel\"&gt;\n &lt;div&gt;Some other stuff&lt;/div&gt;\n &lt;ul&gt;\n &lt;li&gt;Item 1&lt;/li&gt;\n &lt;li&gt;Item 2&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You can use CSS:</p>\n\n<pre><code>div.panel { background-color: #A74; border: solid 0.5em #520; width: 10em; \n border-width: 0.75em 0.25em 0.75em 0.25em; }\ndiv.panel div { padding: 2px; height: 4em; }\ndiv.panel ul li { display: block; background-color: white; \n margin: 2px; padding: 1px 4px 1px 4px; }\ndiv.panel ul { margin: 0; padding-left: 0; }\n</code></pre>\n\n<p>To get the CSS to work properly (particularly on Internet Explorer), make sure you have an appropriate DOCTYPE definition in your document. See <a href=\"http://www.w3.org/QA/2002/04/valid-dtd-list.html\" rel=\"nofollow noreferrer\">w3c recommended doctypes</a> for a list.</p>\n" }, { "answer_id": 108710, "author": "spinodal", "author_id": 11374, "author_profile": "https://Stackoverflow.com/users/11374", "pm_score": 0, "selected": false, "text": "<p>Maybe those two will help:</p>\n\n<ul>\n<li><a href=\"http://css.maxdesign.com.au/listutorial/\" rel=\"nofollow noreferrer\">Listutorial</a></li>\n<li><a href=\"http://www.cssplay.co.uk/menus/\" rel=\"nofollow noreferrer\">CssPlay Menus</a></li>\n</ul>\n" }, { "answer_id": 108778, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 4, "selected": true, "text": "<p>You can do this pretty cleanly with this css:</p>\n\n<pre><code>.box {\n width: 100px;\n border: solid #884400;\n border-width: 8px 3px 8px 3px;\n background-color: #ccaa77;\n}\n\n.box ul {\n margin: 0px;\n padding: 0px;\n padding-top: 50px; /* presuming the non-list header space at the top of\n your box is desirable */\n}\n\n.box ul li {\n margin: 0px 2px 2px 2px; /* reduce to 1px if you find the separation\n sufficiently visible */\n background-color: #ffffff;\n list-style-type: none;\n padding-left: 2px;\n}\n</code></pre>\n\n<p>and this html:</p>\n\n<pre><code>&lt;div class=\"box\"&gt;\n &lt;ul&gt;\n &lt;li&gt;Lorem&lt;/li&gt;\n &lt;li&gt;Ipsum&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/0b7w65qv/\" rel=\"nofollow noreferrer\">DEMO</a></p>\n" }, { "answer_id": 675332, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<h2>Html:</h2>\n\n<pre><code>&lt;div id=\"content\"&gt;\n &lt;a&gt;&lt;div class=\"title\"&gt;Title&lt;/div&gt;Text&lt;/a&gt;\n &lt;ul&gt;\n &lt;li&gt;Text&lt;/li&gt;\n &lt;li&gt;More Text...&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<h2>CSS:</h2>\n\n<pre><code>#content{\n text-align:left;\n width:200px;\n background:#e0c784;\n border-top:solid 10px #7f4200;\n border-bottom:solid 10px #7f4200;\n border-right:solid 5px #7f4200;\n border-left:solid 5px #7f4200;\n }\n #content a{\n margin-left:20px;\n }\n\n #content ul{\n list-style-type:none;\n margin-bottom:0px;\n }\n #content ul li{\n padding-left:20px;\n margin:0px 0px 1px -40px;\n text-align:left;\n width:180px;\n list-style-type:none;\n background-color:white;\n }\n #content .title{\n text-align:center;\n font-weight:bolder;\n text-align:center;\n font-size:20px;\n border-bottom:solid 2px #ffcc99;\n background:#996633;\n color:#ffffff;\n margin-bottom:20px;\n }\n</code></pre>\n\n<p><br>\n<br>\nHope this helps.... I also added a title to it, if you dont like it just delete it...</p>\n" }, { "answer_id": 5762047, "author": "bryant jaquez", "author_id": 721400, "author_profile": "https://Stackoverflow.com/users/721400", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"&gt;\n&lt;HTML&gt;\n &lt;HEAD&gt;\n &lt;TITLE&gt;Examples of margins, padding, and borders&lt;/TITLE&gt;\n &lt;STYLE type=\"text/css\"&gt;\n UL { \n background: yellow; \n margin: 12px 12px 12px 12px;\n padding: 3px 3px 3px 3px;\n /* No borders set */\n }\n LI { \n color: white; /* text color is white */ \n background: blue; /* Content, padding will be blue */\n margin: 12px 12px 12px 12px;\n padding: 12px 0px 12px 12px; /* Note 0px padding right */\n list-style: none /* no glyphs before a list item */\n /* No borders set */\n }\n LI.withborder {\n border-style: dashed;\n border-width: medium; /* sets border width on all sides */\n border-color: lime;\n }\n &lt;/STYLE&gt;\n &lt;/HEAD&gt;\n &lt;BODY&gt;\n &lt;UL&gt;\n &lt;LI&gt;First element of list\n &lt;LI class=\"withborder\"&gt;Second element of list is\n a bit longer to illustrate wrapping.\n &lt;/UL&gt;\n &lt;/BODY&gt;\n&lt;/HTML&gt;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I want to create a box shape and I am having trouble. I want the box to have a background color, and then different color inside the box. The box will then have a list of items using ul and li, and each list item will have a background of white, and the list item's background color is too stretch the entire distance of the inner box. Also, the list items should have a 1 px spacing between each one, so that the background color of the inside box color is visible. Here is a rough sketch of what I am trying to do: [![](https://i.stack.imgur.com/aZ2W7.png)](https://i.stack.imgur.com/aZ2W7.png)
You can do this pretty cleanly with this css: ``` .box { width: 100px; border: solid #884400; border-width: 8px 3px 8px 3px; background-color: #ccaa77; } .box ul { margin: 0px; padding: 0px; padding-top: 50px; /* presuming the non-list header space at the top of your box is desirable */ } .box ul li { margin: 0px 2px 2px 2px; /* reduce to 1px if you find the separation sufficiently visible */ background-color: #ffffff; list-style-type: none; padding-left: 2px; } ``` and this html: ``` <div class="box"> <ul> <li>Lorem</li> <li>Ipsum</li> </ul> </div> ``` [DEMO](http://jsfiddle.net/0b7w65qv/)
108,768
<p>I got a comment to my answer on this thread:</p> <p><a href="https://stackoverflow.com/questions/105477">Malloc inside a function call appears to be getting freed on return?</a></p> <p>In short I had code like this:</p> <pre><code>int * somefunc (void) { int * temp = (int*) malloc (sizeof (int)); temp[0] = 0; return temp; } </code></pre> <p>I got this comment:</p> <blockquote> <p>Can I just say, please don't cast the return value of malloc? It is not required and can hide errors.</p> </blockquote> <p>I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.</p> <p>However, I wonder how casts like this can hide errors. Any ideas?</p> <h1>Edit:</h1> <p>Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.</p>
[ { "answer_id": 108780, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 0, "selected": false, "text": "<p>Casting a function which returns (void *) to instead be an (int *) is harmless: you're casting one type of pointer to another.</p>\n\n<p>Casting a function which returns an integer to instead be a pointer is most likely incorrect. The compiler would have flagged it had you not explicitly cast it.</p>\n" }, { "answer_id": 108781, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": true, "text": "<p>It seems fitting I post an answer, since I left the comment :P</p>\n<p>Basically, if you forget to include <code>stdlib.h</code> the compiler will assume <code>malloc</code> returns an <code>int</code>. Without casting, you will get a warning. With casting you won't.</p>\n<p>So by casting you get nothing, and run the risk of suppressing legitimate warnings.</p>\n<p>Much is written about this, a quick google search will turn up more detailed explanations.</p>\n<h2>edit</h2>\n<p>It has been argued that</p>\n<pre><code>TYPE * p;\np = (TYPE *)malloc(n*sizeof(TYPE));\n</code></pre>\n<p>makes it obvious when you accidentally don't allocate enough memory because say, you thought <code>p</code> was <code>TYPe</code> not <code>TYPE</code>, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.</p>\n<p>I would like to point out 2 things:</p>\n<ol>\n<li>you should write <code>p = malloc(sizeof(*p)*n);</code> to always ensure you malloc the right amount of space</li>\n<li>with the above approach, you need to make changes in 3 places if you ever change the type of <code>p</code>: once in the declaration, once in the <code>malloc</code>, and once in the cast.</li>\n</ol>\n<p>In short, I still personally believe there is no need for casting the return value of <code>malloc</code> and it is certainly not best practice.</p>\n" }, { "answer_id": 108785, "author": "jbl", "author_id": 2353001, "author_profile": "https://Stackoverflow.com/users/2353001", "pm_score": 0, "selected": false, "text": "<p>One possible error could (depending on this is whether what you really want or not) be mallocing with one size scale, and assigning to a pointer of a different type. E.g.,</p>\n\n<pre><code>int *temp = (int *)malloc(sizeof(double));\n</code></pre>\n\n<p>There may be cases where you want to do this, but I suspect that they are rare.</p>\n" }, { "answer_id": 108786, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 3, "selected": false, "text": "<p>Well, I think it's the exact opposite - always directly cast it to the needed type. <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type?focusedCommentId=15630941\" rel=\"nofollow noreferrer\">Read on here!</a></p>\n" }, { "answer_id": 108792, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": -1, "selected": false, "text": "<p>On the other hand, if you ever need to port the code to C++, it is much better to use the 'new' operator.</p>\n" }, { "answer_id": 108803, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "<p>Actually, the only way a cast could hide an error is if you were converting from one datatype to an smaller datatype and lost data, or if you were converting pears to apples. Take the following example:</p>\n\n<pre><code>int int_array[10];\n/* initialize array */\nint *p = &amp;(int_array[3]);\nshort *sp = (short *)p;\nshort my_val = *sp;\n</code></pre>\n\n<p>in this case the conversion to short would be dropping some data from the int. And then this case:</p>\n\n<pre><code>struct {\n /* something */\n} my_struct[100];\n\nint my_int_array[100];\n/* initialize array */\nstruct my_struct *p = &amp;(my_int_array[99]);\n</code></pre>\n\n<p>in which you'd end up pointing to the wrong kind of data, or even to invalid memory.</p>\n\n<p>But in general, and if you know what you are doing, it's OK to do the casting. Even more so when you are getting memory from malloc, which happens to return a void pointer which you can't use at all unless you cast it, and most compilers will warn you if you are casting to something the lvalue (the value to the left side of the assignment) can't take anyway.</p>\n" }, { "answer_id": 108840, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 0, "selected": false, "text": "<p>I think you should put the cast in. Consider that there are three locations for types:</p>\n\n<pre><code>T1 *p;\np = (T2*) malloc(sizeof(T3));\n</code></pre>\n\n<p>The two lines of code might be widely separated. Therefore it's good that the compiler will <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type?focusedCommentId=15630941\" rel=\"nofollow noreferrer\">enforce</a> that T1 == T2. It is easier to visually verify that T2 == T3.</p>\n\n<p>If you miss out the T2 cast, then you have to hope that T1 == T3.</p>\n\n<p>On the other hand you have the missing stdlib.h argument - but I think it's less likely to be a problem.</p>\n" }, { "answer_id": 108979, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "<p>One possible error it can introduce is if you are compiling on a 64-bit system using C (not C++).</p>\n\n<p>Basically, if you forget to include <code>stdlib.h</code>, the default int rule will apply. Thus the compiler will happily assume that <code>malloc</code> has the prototype of <code>int malloc();</code> On Many 64-bit systems an int is 32-bits and a pointer is 64-bits.</p>\n\n<p>Uh oh, the value gets truncated and you only get the lower 32-bits of the pointer! Now if you cast the return value of <code>malloc</code>, this error is hidden by the cast. But if you don't you will get an error (something to the nature of \"cannot convert int to T *\").</p>\n\n<p>This does not apply to C++ of course for 2 reasons. Firstly, it has no default int rule, secondly it requires the cast.</p>\n\n<p>All in all though, you should just new in c++ code anyway :-P.</p>\n" }, { "answer_id": 108995, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "<p>This question is tagged both for C and C++, so it has at least two answers, IMHO:</p>\n\n<h1>C</h1>\n\n<p>Ahem... Do whatever you want.</p>\n\n<p>I believe the reason given above \"If you don't include \"stdlib\" then you won't get a warning\" is not a valid one because one should not rely on this kind of hacks to not forget to include an header.</p>\n\n<p>The real reason that could make you <strong>not</strong> write the cast is that the C compiler already silently cast a <code>void *</code> into whatever pointer type you want, and so, doing it yourself is overkill and useless.</p>\n\n<p>If you want to have type safety, you can either switch to C++ or write your own wrapper function, like:</p>\n\n<pre><code>int * malloc_Int(size_t p_iSize) /* number of ints wanted */\n{\n return malloc(sizeof(int) * p_iSize) ;\n}\n</code></pre>\n\n<h1>C++</h1>\n\n<p>Sometimes, even in C++, you have to make profit of the malloc/realloc/free utils. Then you'll have to cast. But you already knew that. Using static_cast&lt;&gt;() will be better, as always, than C-style cast.</p>\n\n<p>And in C, you could override malloc (and realloc, etc.) through templates to achieve type-safety:</p>\n\n<pre><code>template &lt;typename T&gt;\nT * myMalloc(const size_t p_iSize)\n{\n return static_cast&lt;T *&gt;(malloc(sizeof(T) * p_iSize)) ;\n}\n</code></pre>\n\n<p>Which would be used like:</p>\n\n<pre><code>int * p = myMalloc&lt;int&gt;(25) ;\nfree(p) ;\n\nMyStruct * p2 = myMalloc&lt;MyStruct&gt;(12) ;\nfree(p2) ;\n</code></pre>\n\n<p>and the following code:</p>\n\n<pre><code>// error: cannot convert ‘int*’ to ‘short int*’ in initialization\nshort * p = myMalloc&lt;int&gt;(25) ;\nfree(p) ;\n</code></pre>\n\n<p>won't compile, so, <em>no problemo</em>.</p>\n\n<p>All in all, in pure C++, you now have no excuse if someone finds more than one C malloc inside your code...\n:-)</p>\n\n<h1>C + C++ crossover</h1>\n\n<p>Sometimes, you want to produce code that will compile both in C and in C++ (for whatever reasons... Isn't it the point of the C++ <code>extern \"C\" {}</code> block?). In this case, C++ demands the cast, but C won't understand the static_cast keyword, so the solution is the C-style cast (which is still legal in C++ for exactly this kind of reasons).</p>\n\n<p>Note that even with writing pure C code, compiling it with a C++ compiler will get you a lot more warnings and errors (for example attempting to use a function without declaring it first won't compile, unlike the error mentioned above).</p>\n\n<p>So, to be on the safe side, write code that will compile cleanly in C++, study and correct the warnings, and then use the C compiler to produce the final binary. This means, again, write the cast, in a C-style cast.</p>\n" }, { "answer_id": 109002, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 2, "selected": false, "text": "<p>The \"forgot stdlib.h\" argument is a straw man. Modern compilers will detect and warn of the problem (gcc -Wall).</p>\n\n<p>You should always cast the result of malloc immediately. Not doing so should be considered an error, and not just because it will fail as C++. If you're targeting a machine architecture with different kinds of pointers, for example, you could wind up with a very tricky bug if you don't put in the cast.</p>\n\n<p><strong>Edit</strong>: The commentor <a href=\"https://stackoverflow.com/users/13430/evan-teran\">Evan Teran</a> is correct. My mistake was thinking that the compiler didn't have to do any work on a void pointer in any context. I freak when I think of FAR pointer bugs, so my intuition is to cast everything. Thanks Evan!</p>\n" }, { "answer_id": 145050, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<pre><code>#if CPLUSPLUS\n#define MALLOC_CAST(T) (T)\n#else\n#define MALLOC_CAST(T)\n#endif\n...\nint * p;\np = MALLOC_CAST(int *) malloc(sizeof(int) * n);\n</code></pre>\n\n<p>or, alternately</p>\n\n<pre><code>#if CPLUSPLUS\n#define MYMALLOC(T, N) static_cast&lt;T*&gt;(malloc(sizeof(T) * N))\n#else\n#define MYMALLOC(T, N) malloc(sizeof(T) * N)\n#endif\n...\nint * p;\np = MYMALLOC(int, n);\n</code></pre>\n" }, { "answer_id": 2239357, "author": "Chris Lutz", "author_id": 60777, "author_profile": "https://Stackoverflow.com/users/60777", "pm_score": 1, "selected": false, "text": "<p>People have already cited the reasons I usually trot out: the old (no longer applicable to most compilers) argument about not including <code>stdlib.h</code> and using <code>sizeof *p</code> to make sure the types and sizes always match regardless of later updating. I do want to point out one other argument against casting. It's a small one, but I think it applies.</p>\n\n<p>C is fairly weakly typed. Most safe type conversions happen automatically, and most unsafe ones require a cast. Consider:</p>\n\n<pre><code>int from_f(float f)\n{\n return *(int *)&amp;f;\n}\n</code></pre>\n\n<p>That's dangerous code. It's technically undefined behavior, though in practice it's going to do the same thing on nearly every platform you run it on. And the cast helps tell you <strong>\"This code is a terrible hack.\"</strong></p>\n\n<p>Consider:</p>\n\n<pre><code>int *p = (int *)malloc(sizeof(int) * 10);\n</code></pre>\n\n<p>I see a cast, and I wonder, \"Why is this necessary? Where is the hack?\" It raises hairs on my neck that there's something evil going on, when in fact the code is completely harmless.</p>\n\n<p>As long as we're using C, casts (especially pointer casts) are a way of saying \"There's something evil and easily breakable going on here.\" They may accomplish what you need accomplished, but they indicate to you and future maintainers that the kids aren't alright.</p>\n\n<p>Using casts on every <code>malloc</code> diminishes the \"hack\" indication of pointer casting. It makes it less jarring to see things like <code>*(int *)&amp;f;</code>.</p>\n\n<p>Note: C and C++ are different languages. C is weakly typed, C++ is more strongly typed. The casts <em>are</em> necessary in C++, even though they don't indicate a hack at all, because of (in my humble opinion) the unnecessarily strong C++ type system. (Really, this particular case is the only place I think the C++ type system is \"too strong,\" but I can't think of any place where it's \"too weak,\" which makes it overall too strong for my tastes.)</p>\n\n<p>If you're worried about C++ compatibility, don't. If you're writing C, use a C compiler. There are plenty really good ones avaliable for every platform. If, for some inane reason, you <em>have</em> to write C code that compiles cleanly as C++, you're not really writing C. If you need to port C to C++, you should be making lots of changes to make your C code more idiomatic C++.</p>\n\n<p>If you can't do any of that, your code won't be pretty no matter what you do, so it doesn't really matter how you decide to cast at that point. I do like the idea of using templates to make a new allocator that returns the correct type, although that's basically just reinventing the <code>new</code> keyword.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
I got a comment to my answer on this thread: [Malloc inside a function call appears to be getting freed on return?](https://stackoverflow.com/questions/105477) In short I had code like this: ``` int * somefunc (void) { int * temp = (int*) malloc (sizeof (int)); temp[0] = 0; return temp; } ``` I got this comment: > > Can I just say, please don't cast the > return value of malloc? It is not > required and can hide errors. > > > I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day. However, I wonder how casts like this can hide errors. Any ideas? Edit: ===== Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.
It seems fitting I post an answer, since I left the comment :P Basically, if you forget to include `stdlib.h` the compiler will assume `malloc` returns an `int`. Without casting, you will get a warning. With casting you won't. So by casting you get nothing, and run the risk of suppressing legitimate warnings. Much is written about this, a quick google search will turn up more detailed explanations. edit ---- It has been argued that ``` TYPE * p; p = (TYPE *)malloc(n*sizeof(TYPE)); ``` makes it obvious when you accidentally don't allocate enough memory because say, you thought `p` was `TYPe` not `TYPE`, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings. I would like to point out 2 things: 1. you should write `p = malloc(sizeof(*p)*n);` to always ensure you malloc the right amount of space 2. with the above approach, you need to make changes in 3 places if you ever change the type of `p`: once in the declaration, once in the `malloc`, and once in the cast. In short, I still personally believe there is no need for casting the return value of `malloc` and it is certainly not best practice.
108,813
<p>How can I Handler 404 errors without the framework throwing an Exception 500 error code?</p>
[ { "answer_id": 108830, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx\" rel=\"noreferrer\">http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx</a> gives the following explanation:</p>\n\n<p>Add a wildcard routing rule as your final rule:</p>\n\n<pre><code>routes.MapRoute(\"Error\", \n \"{*url}\", \n new { controller = \"Error\", action = \"Http404\" });\n</code></pre>\n\n<p>Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:</p>\n\n<pre><code>public ActionResult Http404(string url) {\n Response.StatusCode = 404;\n ViewData[\"url\"] = url;\n return View();\n}\n</code></pre>\n" }, { "answer_id": 111532, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 3, "selected": false, "text": "<p>You can also override HandleUnknownAction within your controller in the cases where a request does match a controller, but doesn't match an action. The default implementation does raise a 404 error.</p>\n" }, { "answer_id": 2803428, "author": "Adam", "author_id": 337336, "author_profile": "https://Stackoverflow.com/users/337336", "pm_score": 2, "selected": false, "text": "<p>throw new HttpException(404, \"Resource Not Found\");</p>\n" }, { "answer_id": 8525665, "author": "Bryan Legend", "author_id": 52771, "author_profile": "https://Stackoverflow.com/users/52771", "pm_score": 0, "selected": false, "text": "<p>With MVC 3 you can return HttpNotFound() to properly return a 404.</p>\n\n<p>Like this:</p>\n\n<pre><code>public ActionResult Download(string fontName)\n{\n FontCache.InitalizeFonts();\n\n fontName = HttpUtility.UrlDecode(fontName);\n\n var font = FontCache.GetFontByName(fontName);\n if (font == null)\n return HttpNotFound();\n\n return View(font);\n}\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19710/" ]
How can I Handler 404 errors without the framework throwing an Exception 500 error code?
<http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx> gives the following explanation: Add a wildcard routing rule as your final rule: ``` routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "Http404" }); ``` Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure: ``` public ActionResult Http404(string url) { Response.StatusCode = 404; ViewData["url"] = url; return View(); } ```
108,819
<p>What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new <code>Array</code> with the same strings but in a random order.</p> <p>Please include a C# example in your answer.</p>
[ { "answer_id": 108828, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target array.</p>\n\n<p>This yields a truly independent sort.</p>\n" }, { "answer_id": 108831, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 2, "selected": false, "text": "<p>Randomizing the array is intensive as you have to shift around a bunch of strings. Why not just randomly read from the array? In the worst case you could even create a wrapper class with a getNextString(). If you really do need to create a random array then you could do something like</p>\n\n<pre><code>for i = 0 -&gt; i= array.length * 5\n swap two strings in random places\n</code></pre>\n\n<p>The *5 is arbitrary. </p>\n" }, { "answer_id": 108835, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>This algorithm is simple but not efficient, O(N<sup>2</sup>). All the \"order by\" algorithms are typically O(N log N). It probably doesn't make a difference below hundreds of thousands of elements but it would for large lists.</p>\n\n<pre><code>var stringlist = ... // add your values to stringlist\n\nvar r = new Random();\n\nvar res = new List&lt;string&gt;(stringlist.Count);\n\nwhile (stringlist.Count &gt;0)\n{\n var i = r.Next(stringlist.Count);\n res.Add(stringlist[i]);\n stringlist.RemoveAt(i);\n}\n</code></pre>\n\n<p>The reason why it's O(N<sup>2</sup>) is subtle: <a href=\"https://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.110).aspx\" rel=\"nofollow noreferrer\">List.RemoveAt()</a> is a O(N) operation unless you remove in order from the end.</p>\n" }, { "answer_id": 108836, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 9, "selected": true, "text": "<p>If you're on .NET 3.5, you can use the following IEnumerable coolness:</p>\n<pre><code>Random rnd=new Random();\nstring[] MyRandomArray = MyArray.OrderBy(x =&gt; rnd.Next()).ToArray(); \n</code></pre>\n<p>Edit: and here's the corresponding VB.NET code:</p>\n<pre><code>Dim rnd As New System.Random\nDim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()\n</code></pre>\n<p>Second edit, in response to remarks that System.Random &quot;isn't threadsafe&quot; and &quot;only suitable for toy apps&quot; due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like <code>lock (MyRandomArray)</code> anyway in order not to corrupt your data, which will protect <code>rnd</code> as well.</p>\n<p>Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the <a href=\"http://msdn.microsoft.com/en-us/library/system.random.aspx\" rel=\"noreferrer\">MSDN documentation</a>, you should use something derived from <code>System.Security.Cryptography.RandomNumberGenerator</code> if you're doing anything security-related. For example:</p>\n<pre><code>using System.Security.Cryptography;\n</code></pre>\n<p>...</p>\n<pre><code>RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();\nstring[] MyRandomArray = MyArray.OrderBy(x =&gt; GetNextInt32(rnd)).ToArray();\n</code></pre>\n<p>...</p>\n<pre><code>static int GetNextInt32(RNGCryptoServiceProvider rnd)\n {\n byte[] randomInt = new byte[4];\n rnd.GetBytes(randomInt);\n return Convert.ToInt32(randomInt[0]);\n }\n</code></pre>\n" }, { "answer_id": 108845, "author": "Tarsier", "author_id": 19357, "author_profile": "https://Stackoverflow.com/users/19357", "pm_score": 2, "selected": false, "text": "<p>Just thinking off the top of my head, you could do this:</p>\n\n<pre><code>public string[] Randomize(string[] input)\n{\n List&lt;string&gt; inputList = input.ToList();\n string[] output = new string[input.Length];\n Random randomizer = new Random();\n int i = 0;\n\n while (inputList.Count &gt; 0)\n {\n int index = r.Next(inputList.Count);\n output[i++] = inputList[index];\n inputList.RemoveAt(index);\n }\n\n return (output);\n}\n</code></pre>\n" }, { "answer_id": 108851, "author": "nullDev", "author_id": 6621, "author_profile": "https://Stackoverflow.com/users/6621", "pm_score": 0, "selected": false, "text": "<pre><code>Random r = new Random();\nList&lt;string&gt; list = new List(originalArray);\nList&lt;string&gt; randomStrings = new List();\n\nwhile(list.Count &gt; 0)\n{\nint i = r.Random(list.Count);\nrandomStrings.Add(list[i]);\nlist.RemoveAt(i);\n}\n</code></pre>\n" }, { "answer_id": 108874, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 4, "selected": false, "text": "<p>You're looking for a shuffling algorithm, right?</p>\n\n<p>Okay, there are two ways to do this: the clever-but-people-always-seem-to-misunderstand-it-and-get-it-wrong-so-maybe-its-not-that-clever-after-all way, and the dumb-as-rocks-but-who-cares-because-it-works way.</p>\n\n<h3>Dumb way</h3>\n\n<blockquote>\n <ul>\n <li>Create a duplicate of your first array, but tag each string should with a random number.</li>\n <li>Sort the duplicate array with respect to the random number.</li>\n </ul>\n</blockquote>\n\n<p>This algorithm works well, but make sure that your random number generator is unlikely to tag two strings with the same number. Because of the so-called <a href=\"http://en.wikipedia.org/wiki/Birthday_paradox\" rel=\"noreferrer\">Birthday Paradox</a>, this happens more often than you might expect. Its time complexity is O(<em>n</em> log <em>n</em>).</p>\n\n<h3>Clever way</h3>\n\n<p>I'll describe this as a recursive algorithm:</p>\n\n<blockquote>\n <p>To shuffle an array of size <em>n</em> (indices in the range [0..<em>n</em>-1]):</p>\n \n if <em>n</em> = 0\n \n <ul>\n <li>do nothing</li>\n </ul>\n \n if <em>n</em> > 0\n \n <ul>\n <li><em>(recursive step)</em> shuffle the first <em>n</em>-1 elements of the array</li>\n <li>choose a random index, <em>x</em>, in the range [0..<em>n</em>-1]</li>\n <li>swap the element at index <em>n</em>-1 with the element at index <em>x</em></li>\n </ul>\n</blockquote>\n\n<p>The iterative equivalent is to walk an iterator through the array, swapping with random elements as you go along, but notice that you cannot swap with an element <strong>after</strong> the one that the iterator points to. This is a very common mistake, and leads to a biased shuffle.</p>\n\n<p>Time complexity is O(<em>n</em>).</p>\n" }, { "answer_id": 109019, "author": "Seth Morris", "author_id": 13434, "author_profile": "https://Stackoverflow.com/users/13434", "pm_score": -1, "selected": false, "text": "<p>Here's a simple way using OLINQ:</p>\n\n<pre><code>// Input array\nList&lt;String&gt; lst = new List&lt;string&gt;();\nfor (int i = 0; i &lt; 500; i += 1) lst.Add(i.ToString());\n\n// Output array\nList&lt;String&gt; lstRandom = new List&lt;string&gt;();\n\n// Randomize\nRandom rnd = new Random();\nlstRandom.AddRange(from s in lst orderby rnd.Next(100) select s);\n</code></pre>\n" }, { "answer_id": 110570, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 8, "selected": false, "text": "<p>The following implementation uses the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\">Fisher-Yates algorithm</a> AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the 'sort by random' technique, although it is more lines of code. See <a href=\"https://web.archive.org/web/20210510014810/http://aspnet.4guysfromrolla.com/articles/070208-1.aspx\" rel=\"noreferrer\">here</a> for some comparative performance measurements. I have used System.Random, which is fine for non-cryptographic purposes.*</p>\n\n<pre><code>static class RandomExtensions\n{\n public static void Shuffle&lt;T&gt; (this Random rng, T[] array)\n {\n int n = array.Length;\n while (n &gt; 1) \n {\n int k = rng.Next(n--);\n T temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var array = new int[] {1, 2, 3, 4};\nvar rng = new Random();\nrng.Shuffle(array);\nrng.Shuffle(array); // different order from first call to Shuffle\n</code></pre>\n\n<p>* For longer arrays, in order to make the (extremely large) number of permutations equally probable it would be necessary to run a pseudo-random number generator (PRNG) through many iterations for each swap to produce enough entropy. For a 500-element array only a very small fraction of the possible 500! permutations will be possible to obtain using a PRNG. Nevertheless, the Fisher-Yates algorithm is unbiased and therefore the shuffle will be as good as the RNG you use.</p>\n" }, { "answer_id": 111029, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Jacco, your solution ising a custom IComparer isn't safe. The Sort routines require the comparer to conform to several requirements in order to function properly. First among them is consistency. If the comparer is called on the same pair of objects, it must always return the same result. (the comparison must also be transitive).</p>\n\n<p>Failure to meet these requirements can cause any number of problems in the sorting routine including the possibility of an infinite loop. </p>\n\n<p>Regarding the solutions that associate a random numeric value with each entry and then sort by that value, these are lead to an inherent bias in the output because any time two entries are assigned the same numeric value, the randomness of the output will be compromised. (In a \"stable\" sort routine, whichever is first in the input will be first in the output. Array.Sort doesn't happen to be stable, but there is still a bias based on the partitioning done by the Quicksort algorithm).</p>\n\n<p>You need to do some thinking about what level of randomness you require. If you are running a poker site where you need cryptographic levels of randomness to protect against a determined attacker you have very different requirements from someone who just wants to randomize a song playlist.</p>\n\n<p>For song-list shuffling, there's no problem using a seeded PRNG (like System.Random). For a poker site, it's not even an option and you need to think about the problem a lot harder than anyone is going to do for you on stackoverflow. (using a cryptographic RNG is only the beginning, you need to ensure that your algorithm doesn't introduce a bias, that you have sufficient sources of entropy, and that you don't expose any internal state that would compromise subsequent randomness).</p>\n" }, { "answer_id": 111507, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 0, "selected": false, "text": "<p>This post has already been pretty well answered - use a Durstenfeld implementation of the Fisher-Yates shuffle for a fast and unbiased result. There have even been some implementations posted, though I note some are actually incorrect.</p>\n\n<p>I wrote a couple of posts a while back about <a href=\"http://gregbeech.com/blogs/tech/archive/2008/09/03/shuffle-and-takerandom-extension-methods-for-ienumerable-lt-t-gt.aspx\" rel=\"nofollow noreferrer\">implementing full and partial shuffles using this technique</a>, and (this second link is where I'm hoping to add value) also <a href=\"http://gregbeech.com/blogs/tech/archive/2008/09/09/determining-the-bias-of-a-shuffle-algorithm.aspx\" rel=\"nofollow noreferrer\">a follow-up post about how to check whether your implementation is unbiased</a>, which can be used to check any shuffle algorithm. You can see at the end of the second post the effect of a simple mistake in the random number selection can make.</p>\n" }, { "answer_id": 3513921, "author": "Aaron", "author_id": 424209, "author_profile": "https://Stackoverflow.com/users/424209", "pm_score": 2, "selected": false, "text": "<p>You can also make an extention method out of Matt Howells. Example.</p>\n\n<pre><code> namespace System\n {\n public static class MSSystemExtenstions\n {\n private static Random rng = new Random();\n public static void Shuffle&lt;T&gt;(this T[] array)\n {\n rng = new Random();\n int n = array.Length;\n while (n &gt; 1)\n {\n int k = rng.Next(n);\n n--;\n T temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n }\n }\n }\n</code></pre>\n\n<p>Then you can just use it like: </p>\n\n<pre><code> string[] names = new string[] {\n \"Aaron Moline1\", \n \"Aaron Moline2\", \n \"Aaron Moline3\", \n \"Aaron Moline4\", \n \"Aaron Moline5\", \n \"Aaron Moline6\", \n \"Aaron Moline7\", \n \"Aaron Moline8\", \n \"Aaron Moline9\", \n };\n names.Shuffle&lt;string&gt;();\n</code></pre>\n" }, { "answer_id": 10397345, "author": "Himalaya Garg", "author_id": 1129978, "author_profile": "https://Stackoverflow.com/users/1129978", "pm_score": -1, "selected": false, "text": "<pre><code>private ArrayList ShuffleArrayList(ArrayList source)\n{\n ArrayList sortedList = new ArrayList();\n Random generator = new Random();\n\n while (source.Count &gt; 0)\n {\n int position = generator.Next(source.Count);\n sortedList.Add(source[position]);\n source.RemoveAt(position);\n } \n return sortedList;\n}\n</code></pre>\n" }, { "answer_id": 13052597, "author": "jlarsson", "author_id": 1057524, "author_profile": "https://Stackoverflow.com/users/1057524", "pm_score": 1, "selected": false, "text": "<p>Ok, this is clearly a bump from my side (apologizes...), but I often use a quite general and cryptographically strong method.</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n static readonly RNGCryptoServiceProvider RngCryptoServiceProvider = new RNGCryptoServiceProvider();\n public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable)\n {\n var randomIntegerBuffer = new byte[4];\n Func&lt;int&gt; rand = () =&gt;\n {\n RngCryptoServiceProvider.GetBytes(randomIntegerBuffer);\n return BitConverter.ToInt32(randomIntegerBuffer, 0);\n };\n return from item in enumerable\n let rec = new {item, rnd = rand()}\n orderby rec.rnd\n select rec.item;\n }\n}\n</code></pre>\n\n<p>Shuffle() is an extension on any IEnumerable so getting, say, numbers from 0 to 1000 in random order in a list can be done with</p>\n\n<pre><code>Enumerable.Range(0,1000).Shuffle().ToList()\n</code></pre>\n\n<p>This method also wont give any surprises when it comes to sorting, since the sort value is generated and remembered exactly once per element in the sequence.</p>\n" }, { "answer_id": 29614719, "author": "bytecode77", "author_id": 1199684, "author_profile": "https://Stackoverflow.com/users/1199684", "pm_score": 0, "selected": false, "text": "<p>You don't need complicated algorithms.</p>\n\n<p><strong>Just one simple line:</strong></p>\n\n<pre><code>Random random = new Random();\narray.ToList().Sort((x, y) =&gt; random.Next(-1, 1)).ToArray();\n</code></pre>\n\n<p>Note that we need to convert the <code>Array</code> to a <code>List</code> first, if you don't use <code>List</code> in the first place.</p>\n\n<p>Also, mind that this is not efficient for very large arrays! Otherwise it's clean &amp; simple.</p>\n" }, { "answer_id": 36604736, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 0, "selected": false, "text": "<p>This is a complete working Console solution based on <a href=\"https://msdn.microsoft.com/en-us/library/dd537615%28v=vs.110%29.aspx\" rel=\"nofollow\">the example provided in here</a>:</p>\n\n<pre><code>class Program\n{\n static string[] words1 = new string[] { \"brown\", \"jumped\", \"the\", \"fox\", \"quick\" };\n\n static void Main()\n {\n var result = Shuffle(words1);\n foreach (var i in result)\n {\n Console.Write(i + \" \");\n }\n Console.ReadKey();\n }\n\n static string[] Shuffle(string[] wordArray) {\n Random random = new Random();\n for (int i = wordArray.Length - 1; i &gt; 0; i--)\n {\n int swapIndex = random.Next(i + 1);\n string temp = wordArray[i];\n wordArray[i] = wordArray[swapIndex];\n wordArray[swapIndex] = temp;\n }\n return wordArray;\n } \n}\n</code></pre>\n" }, { "answer_id": 42074323, "author": "Nitish Katare", "author_id": 486276, "author_profile": "https://Stackoverflow.com/users/486276", "pm_score": 0, "selected": false, "text": "<pre><code> int[] numbers = {0,1,2,3,4,5,6,7,8,9};\n List&lt;int&gt; numList = new List&lt;int&gt;();\n numList.AddRange(numbers);\n\n Console.WriteLine(\"Original Order\");\n for (int i = 0; i &lt; numList.Count; i++)\n {\n Console.Write(String.Format(\"{0} \",numList[i]));\n }\n\n Random random = new Random();\n Console.WriteLine(\"\\n\\nRandom Order\");\n for (int i = 0; i &lt; numList.Capacity; i++)\n {\n int randomIndex = random.Next(numList.Count);\n Console.Write(String.Format(\"{0} \", numList[randomIndex]));\n numList.RemoveAt(randomIndex);\n }\n Console.ReadLine();\n</code></pre>\n" }, { "answer_id": 70203369, "author": "Sith2021", "author_id": 1712913, "author_profile": "https://Stackoverflow.com/users/1712913", "pm_score": 0, "selected": false, "text": "<p>Could be:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Random random = new();\n\nstring RandomWord()\n{\n const string CHARS = &quot;abcdefghijklmnoprstuvwxyz&quot;;\n int n = random.Next(CHARS.Length);\n return string.Join(&quot;&quot;, CHARS.OrderBy(x =&gt; random.Next()).ToArray())[0..n];\n}\n</code></pre>\n" }, { "answer_id": 70973950, "author": "lev krinitsky", "author_id": 15795755, "author_profile": "https://Stackoverflow.com/users/15795755", "pm_score": 2, "selected": false, "text": "<pre><code> public static void Shuffle(object[] arr)\n {\n Random rand = new Random();\n for (int i = arr.Length - 1; i &gt;= 1; i--)\n {\n int j = rand.Next(i + 1);\n object tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n }\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new `Array` with the same strings but in a random order. Please include a C# example in your answer.
If you're on .NET 3.5, you can use the following IEnumerable coolness: ``` Random rnd=new Random(); string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray(); ``` Edit: and here's the corresponding VB.NET code: ``` Dim rnd As New System.Random Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray() ``` Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like `lock (MyRandomArray)` anyway in order not to corrupt your data, which will protect `rnd` as well. Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.random.aspx), you should use something derived from `System.Security.Cryptography.RandomNumberGenerator` if you're doing anything security-related. For example: ``` using System.Security.Cryptography; ``` ... ``` RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider(); string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray(); ``` ... ``` static int GetNextInt32(RNGCryptoServiceProvider rnd) { byte[] randomInt = new byte[4]; rnd.GetBytes(randomInt); return Convert.ToInt32(randomInt[0]); } ```
108,853
<p>I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.</p> <p>I.e., the same script is included on <code>/</code>, <code>/help</code>, <code>/whatever</code>, and so on, while it will always need to request from <code>/data.json</code>. Additionally, the same site is run on different servers, where the <code>/</code>-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.</p> <p>Are there small scripts that will work on all browsers made for this?</p>
[ { "answer_id": 108860, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<p><code>document.location.href</code> will give you the current URL, which you can then manipulate using JavaScript's string functions.</p>\n" }, { "answer_id": 108894, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<p>For this I like to put <code>&lt;link&gt;</code> elements in the page's <code>&lt;head&gt;</code>, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:</p>\n\n<pre><code>&lt;link id=\"link-action-1\" href=\"${reverse_url ('action_1')}\"/&gt;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>&lt;link id=\"link-action-1\" href=\"/my/web/root/action-1/\"/&gt;\n</code></pre>\n\n<p>and can be retrieved by Javascript with:</p>\n\n<pre><code>document.getElementById ('link-action-1').href;\n</code></pre>\n" }, { "answer_id": 108901, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 2, "selected": false, "text": "<p>There's no way that the client can determine the webapp root without being told by the server as it has no knowledge of the server's configuration. One option you can try is to use the base element inside the head element, getting the server to generate it dynamically rather than hardcoding it (so it shows the relevant URL for each server):</p>\n\n<pre><code>&lt;base href=\"http://path/to/webapp/root/\" /&gt;\n</code></pre>\n\n<p>All URLs will then be treated as relative to this. You would therefore simply make your request to /data.json. You do however need to ensure that all other links in the application bear this in mind.</p>\n" }, { "answer_id": 108949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I include the following code in my libraries main entry point (main.php):</p>\n\n<pre><code>/**\n * Build current url, depending on protocal (http/https),\n * port, server name and path suffix\n */\n$site_root = 'http';\nif (isset($_SERVER[\"HTTPS\"]) &amp;&amp; $_SERVER[\"HTTPS\"] == \"on\") \n $site_root .= \"s\";\n$site_root .= \"://\" . $_SERVER[\"SERVER_NAME\"];\nif ($_SERVER[\"SERVER_PORT\"] != \"80\")\n $site_root .= \":\" . $_SERVER[\"SERVER_PORT\"];\n$site_root .= $g_config[\"paths\"][\"site_suffix\"];\n\n$g_config[\"paths\"][\"site_root\"] = $site_root;\n</code></pre>\n\n<p>$g_config is a global array containing configuration options. So site_suffix might look like: \"/sites_working/thesite/public_html\" on your development box, and just \"/\" on a server with a virtual host (domain name).</p>\n\n<p>This method is also good, because if somebody types in the IP address of your development box, it will use that same IP address to build the path to the javascript folder instead of something like \"localhost,\" and if you use \"localhost\" it will use \"localhost\" to build the URL.</p>\n\n<p>And because it also detects SSL, you wont have to worry about weather your resources will be sent over HTTP or HTTPS if you ever add SSL support to your server.</p>\n\n<p>Then, in your template, either use</p>\n\n<pre><code>&lt;link id=\"site_root\" href=\"&lt;?php echo $g_config[\"paths\"][\"site_root\"] ?&gt;\"/&gt;\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>&lt;script type = \"text/javascript\"&gt;\nvar SiteRoot = \"&lt;?php echo $g_config[\"paths\"][\"site_root\"]; ?&gt;\";\n&lt;/script&gt;\n</code></pre>\n\n<p>I suppose the latter would be faster.</p>\n" }, { "answer_id": 7235971, "author": "Abc", "author_id": 369724, "author_profile": "https://Stackoverflow.com/users/369724", "pm_score": 2, "selected": false, "text": "<p>If the script knows its own filename, you can use document.<strong>getElementsByTagName</strong>(). Iterate through the list until you find the script that matches yours, and extract the full (or relative) url that way. </p>\n\n<p>Here's an example:</p>\n\n<pre><code>function getScriptUrl ( name ) {\n var scripts = document.getElementsByTagName('script');\n var re = RegExp(\"(\\/|^)\" + name + \"$\");\n var src;\n for( var i = 0; i &lt; scripts.length; i++){\n src = scripts[i].getAttribute('src');\n if( src.match(re) )\n return src;\n }\n return null;\n}\n\nconsole.log( 'found ' + getScriptUrl('demo.js') );\n</code></pre>\n\n<p>Take into consideration that this approach is subject to filename collisions.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax. I.e., the same script is included on `/`, `/help`, `/whatever`, and so on, while it will always need to request from `/data.json`. Additionally, the same site is run on different servers, where the `/`-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself. Are there small scripts that will work on all browsers made for this?
For this I like to put `<link>` elements in the page's `<head>`, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view: ``` <link id="link-action-1" href="${reverse_url ('action_1')}"/> ``` becomes ``` <link id="link-action-1" href="/my/web/root/action-1/"/> ``` and can be retrieved by Javascript with: ``` document.getElementById ('link-action-1').href; ```
108,866
<p>Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following:</p> <pre><code>int32_t array[10]; memset32(array, 0xDEADBEEF, sizeof(array)); </code></pre> <p>This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop.</p> <p>Specifically, I am interested in a 64 bit version of memset(). Know anything like that?</p>
[ { "answer_id": 108876, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 3, "selected": false, "text": "<p><code>wmemset(3)</code> is the wide (16-bit) version of memset. I think that's the closest you're going to get in C, without a loop.</p>\n" }, { "answer_id": 108884, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 6, "selected": true, "text": "<pre><code>void memset64( void * dest, uint64_t value, uintptr_t size )\n{\n uintptr_t i;\n for( i = 0; i &lt; (size &amp; (~7)); i+=8 )\n {\n memcpy( ((char*)dest) + i, &amp;value, 8 );\n } \n for( ; i &lt; size; i++ )\n {\n ((char*)dest)[i] = ((char*)&amp;value)[i&amp;7];\n } \n}\n</code></pre>\n\n<p>(Explanation, as requested in the comments: when you assign to a pointer, the compiler assumes that the pointer is aligned to the type's natural alignment; for uint64_t, that is 8 bytes. memcpy() makes no such assumption. On some hardware unaligned accesses are impossible, so assignment is not a suitable solution unless you know unaligned accesses work on the hardware with small or no penalty, or know that they will never occur, or both. The compiler will replace small memcpy()s and memset()s with more suitable code so it is not as horrible is it looks; but if you do know enough to guarantee assignment will always work and your profiler tells you it is faster, you can replace the memcpy with an assignment. The second for() loop is present in case the amount of memory to be filled is not a multiple of 64 bits. If you know it always will be, you can simply drop that loop.)</p>\n" }, { "answer_id": 108887, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": false, "text": "<p>Check your OS documentation for a local version, then consider just using the loop.</p>\n\n<p>The compiler probably knows more about optimizing memory access on any particular architecture than you do, so let it do the work.</p>\n\n<p>Wrap it up as a library and compile it with all the speed improving optimizations the compiler allows.</p>\n" }, { "answer_id": 108899, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": -1, "selected": false, "text": "<p>write your own; it's trivial even in asm. </p>\n" }, { "answer_id": 108908, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "<p>You should really let the compiler optimize this for you as someone else suggested. In most cases that loop will be negligible.</p>\n\n<p>But if this some special situation and you don't mind being platform specific, and really need to get rid of the loop, you can do this in an assembly block. </p>\n\n<pre><code>//pseudo code\nasm\n{\n rep stosq ...\n}\n</code></pre>\n\n<p>You can probably google stosq assembly command for the specifics. It shouldn't be more than a few lines of code.</p>\n" }, { "answer_id": 109853, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "<p>There's no standard library function afaik. So if you're writing portable code, you're looking at a loop.</p>\n\n<p>If you're writing non-portable code then check your compiler/platform documentation, but don't hold your breath because it's rare to get much help here. Maybe someone else will chip in with examples of platforms which do provide something.</p>\n\n<p>The way you'd write your own depends on whether you can define in the API that the caller guarantees the dst pointer will be sufficiently aligned for 64-bit writes on your platform (or platforms if portable). On any platform that has a 64-bit integer type at all, malloc at least will return suitably-aligned pointers.</p>\n\n<p>If you have to cope with non-alignment, then you need something like moonshadow's answer. The compiler may inline/unroll that memcpy with a size of 8 (and use 32- or 64-bit unaligned write ops if they exist), so the code should be pretty nippy, but my guess is it probably won't special-case the whole function for the destination being aligned. I'd love to be corrected, but fear I won't be.</p>\n\n<p>So if you know that the caller will always give you a dst with sufficient alignment for your architecture, and a length which is a multiple of 8 bytes, then do a simple loop writing a uint64_t (or whatever the 64-bit int is in your compiler) and you'll probably (no promises) end up with faster code. You'll certainly have shorter code.</p>\n\n<p>Whatever the case, if you do care about performance then profile it. If it's not fast enough try again with more optimisation. If it's still not fast enough, ask a question about an asm version for the CPU(s) on which it's not fast enough. memcpy/memset can get massive performance increases from per-platform optimisation.</p>\n" }, { "answer_id": 8820379, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 3, "selected": false, "text": "<p>Just for the record, the following uses <code>memcpy(..)</code> in the following pattern. Suppose we want to fill an array with 20 integers:</p>\n\n<pre><code>--------------------\n\nFirst copy one:\nN-------------------\n\nThen copy it to the neighbour:\nNN------------------\n\nThen copy them to make four:\nNNNN----------------\n\nAnd so on:\nNNNNNNNN------------\n\nNNNNNNNNNNNNNNNN----\n\nThen copy enough to fill the array:\nNNNNNNNNNNNNNNNNNNNN\n</code></pre>\n\n<p>This takes O(lg(num)) applications of <code>memcpy(..)</code>.</p>\n\n<pre><code>int *memset_int(int *ptr, int value, size_t num) {\n if (num &lt; 1) return ptr;\n memcpy(ptr, &amp;value, sizeof(int));\n size_t start = 1, step = 1;\n for ( ; start + step &lt;= num; start += step, step *= 2)\n memcpy(ptr + start, ptr, sizeof(int) * step);\n\n if (start &lt; num)\n memcpy(ptr + start, ptr, sizeof(int) * (num - start));\n return ptr;\n}\n</code></pre>\n\n<p>I thought it might be faster than a loop if <code>memcpy(..)</code> was optimised using some hardware block memory copy functionality, but it turns out that a simple loop is faster than the above with -O2 and -O3. (At least using MinGW GCC on Windows with my particular hardware.) Without the -O switch, on a 400 MB array the code above is about twice as fast as an equivalent loop, and takes 417 ms on my machine, while with optimisation they both go to about 300 ms. Which means that it takes approximately the same number of nanoseconds as bytes, and a clock cycle is about a nanosecond. So either there is no hardware block memory copy functionality on my machine, or the <code>memcpy(..)</code> implementation does not take advantage of it.</p>\n" }, { "answer_id": 15210350, "author": "Cosmin", "author_id": 1735438, "author_profile": "https://Stackoverflow.com/users/1735438", "pm_score": 2, "selected": false, "text": "<p>If you're just targeting an x86 compiler you could try something like (VC++ example):</p>\n\n<pre><code>inline void memset32(void *buf, uint32_t n, int32_t c)\n{\n __asm {\n mov ecx, n\n mov eax, c\n mov edi, buf\n rep stosd\n }\n}\n</code></pre>\n\n<p>Otherwise just make a simple loop and trust the optimizer to know what it's doing, just something like:</p>\n\n<pre><code>for(uint32_t i = 0;i &lt; n;i++)\n{\n ((int_32 *)buf)[i] = c;\n}\n</code></pre>\n\n<p>If you make it complicated chances are it will end up slower than simpler to optimize code, not to mention harder to maintain.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7748/" ]
Is there a version of memset() which sets a value that is larger than 1 byte (char)? For example, let's say we have a memset32() function, so using it we can do the following: ``` int32_t array[10]; memset32(array, 0xDEADBEEF, sizeof(array)); ``` This will set the value 0xDEADBEEF in all the elements of array. Currently it seems to me this can only be done with a loop. Specifically, I am interested in a 64 bit version of memset(). Know anything like that?
``` void memset64( void * dest, uint64_t value, uintptr_t size ) { uintptr_t i; for( i = 0; i < (size & (~7)); i+=8 ) { memcpy( ((char*)dest) + i, &value, 8 ); } for( ; i < size; i++ ) { ((char*)dest)[i] = ((char*)&value)[i&7]; } } ``` (Explanation, as requested in the comments: when you assign to a pointer, the compiler assumes that the pointer is aligned to the type's natural alignment; for uint64\_t, that is 8 bytes. memcpy() makes no such assumption. On some hardware unaligned accesses are impossible, so assignment is not a suitable solution unless you know unaligned accesses work on the hardware with small or no penalty, or know that they will never occur, or both. The compiler will replace small memcpy()s and memset()s with more suitable code so it is not as horrible is it looks; but if you do know enough to guarantee assignment will always work and your profiler tells you it is faster, you can replace the memcpy with an assignment. The second for() loop is present in case the amount of memory to be filled is not a multiple of 64 bits. If you know it always will be, you can simply drop that loop.)
108,892
<p>Basically, growl notifications (or other callbacks) when tests break or pass. <strong>Does anything like this exist?</strong></p> <p>If not, it should be pretty easy to write.. Easiest way would be to..</p> <ol> <li>run <code>python-autotest myfile1.py myfile2.py etc.py</code> <ul> <li>Check if files-to-be-monitored have been modified (possibly just if they've been saved).</li> <li>Run any tests in those files.</li> <li>If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass.</li> <li>Wait, and repeat steps 2-5.</li> </ul></li> </ol> <p>The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc..</p> <p>The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement?</p> <p>To summarise:</p> <ul> <li>Is there anything like the Ruby tool <code>autotest</code> (part of the <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" rel="noreferrer">ZenTest package</a>), but for Python code?</li> <li>How do you check which functions have changed between two revisions of a script?</li> <li>Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback)</li> </ul>
[ { "answer_id": 108911, "author": "macarthy", "author_id": 17232, "author_profile": "https://Stackoverflow.com/users/17232", "pm_score": 2, "selected": false, "text": "<p>Maybe buildbot would be useful <a href=\"http://buildbot.net/trac\" rel=\"nofollow noreferrer\">http://buildbot.net/trac</a> </p>\n" }, { "answer_id": 108934, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "<p>For your third question, maybe the <code>trace</code> module is what you need:</p>\n\n<pre><code>&gt;&gt;&gt; def y(a): return a*a\n&gt;&gt;&gt; def x(a): return y(a)\n&gt;&gt;&gt; import trace\n&gt;&gt;&gt; tracer = trace.Trace(countfuncs = 1)\n&gt;&gt;&gt; tracer.runfunc(x, 2)\n4\n&gt;&gt;&gt; res = tracer.results()\n&gt;&gt;&gt; res.calledfuncs\n{('&lt;stdin&gt;', '&lt;stdin&gt;', 'y'): 1, ('&lt;stdin&gt;', '&lt;stdin&gt;', 'x'): 1}\n</code></pre>\n\n<p><code>res.calledfuncs</code> contains the functions that were called. If you specify <code>countcallers = 1</code> when creating the tracer, you can get caller/callee relationships. See the <a href=\"http://docs.python.org/lib/trace-api.html\" rel=\"nofollow noreferrer\">docs of the <code>trace</code> module</a> for more information.</p>\n\n<p>You can also try to get the calls via static analysis, but this can be dangerous due to the dynamic nature of Python. </p>\n" }, { "answer_id": 109007, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>Django's development server has a file change monitor that watches for modifications and automatically reloads itself. You could re-use this code to launch unit tests on file modification.</p>\n" }, { "answer_id": 109011, "author": "GHZ", "author_id": 18138, "author_profile": "https://Stackoverflow.com/users/18138", "pm_score": 2, "selected": false, "text": "<p>Maybe Nose <a href=\"http://somethingaboutorange.com/mrl/projects/nose/\" rel=\"nofollow noreferrer\">http://somethingaboutorange.com/mrl/projects/nose/</a> has a plugin <a href=\"http://somethingaboutorange.com/mrl/projects/nose/doc/writing_plugins.html\" rel=\"nofollow noreferrer\">http://somethingaboutorange.com/mrl/projects/nose/doc/writing_plugins.html</a></p>\n\n<p>Found this: <a href=\"http://jeffwinkler.net/2006/04/27/keeping-your-nose-green/\" rel=\"nofollow noreferrer\">http://jeffwinkler.net/2006/04/27/keeping-your-nose-green/</a></p>\n" }, { "answer_id": 482668, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://github.com/gfxmonk/autonose/tree/master\" rel=\"noreferrer\">autonose</a> created by <a href=\"http://gfxmonk.net/\" rel=\"noreferrer\">gfxmonk</a>:</p>\n\n<blockquote>\n <p>Autonose is an autotest-like tool for python, using the excellent nosetest library.</p>\n \n <p>autotest tracks filesystem changes and automatically re-run any changed tests or dependencies whenever a file is added, removed or updated. A file counts as changed if it has iself been modified, or if any file it <code>import</code>s has changed.</p>\n \n <p>...</p>\n \n <p>Autonose currently has a native GUI for OSX and GTK. If neither of those are available to you, you can instead run the console version (with the --console option).</p>\n</blockquote>\n" }, { "answer_id": 1744498, "author": "mattorb", "author_id": 191200, "author_profile": "https://Stackoverflow.com/users/191200", "pm_score": 2, "selected": false, "text": "<p>I just found this: <a href=\"http://www.metareal.org/p/modipyd/\" rel=\"nofollow noreferrer\">http://www.metareal.org/p/modipyd/</a></p>\n\n<p>I'm currently using thumb.py, but as my current project transitions from a small project to a medium sized one, I've been looking for something that can do a bit more thorough dependency analysis, and with a few tweaks, I got modipyd up and running pretty quickly.</p>\n" }, { "answer_id": 9461979, "author": "jkp", "author_id": 912, "author_profile": "https://Stackoverflow.com/users/912", "pm_score": 6, "selected": true, "text": "<p>I found <a href=\"https://github.com/gfxmonk/autonose\">autonose</a> to be pretty unreliable but <a href=\"http://pypi.python.org/pypi/sniffer/0.2.3\">sniffer</a> seems to work very well.</p>\n\n<pre><code>$ pip install sniffer\n$ cd myproject\n</code></pre>\n\n<p>Then instead of running \"nosetests\", you run:</p>\n\n<pre><code>$ sniffer\n</code></pre>\n\n<p>Or instead of <code>nosetests --verbose --with-doctest</code>, you run:</p>\n\n<pre><code>$ sniffer -x--verbose -x--with-doctest\n</code></pre>\n\n<p>As described in the <a href=\"http://pypi.python.org/pypi/sniffer/0.2.3\">readme</a>, it's a good idea to install one of the platform-specific filesystem-watching libraries, <code>pyinotify</code>, <code>pywin32</code> or <code>MacFSEvents</code> (all installable via <code>pip</code> etc)</p>\n" }, { "answer_id": 17866537, "author": "Jim Stewart", "author_id": 719547, "author_profile": "https://Stackoverflow.com/users/719547", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/guard/guard\" rel=\"nofollow\">Guard</a> is an excellent tool that monitors for file changes and triggers tasks automatically. It's written in Ruby, but it can be used as a standalone tool for any task like this. There's a <a href=\"https://github.com/medihack/guard-nosetests\" rel=\"nofollow\">guard-nosetests</a> plugin to run Python tests via <a href=\"https://nose.readthedocs.org/en/latest/\" rel=\"nofollow\">nose</a>.</p>\n\n<p>Guard supports cross-platform notifications (Linux, OSX, Windows), including Growl, as well as many other great features. One of my can't-live-without dev tools.</p>\n" }, { "answer_id": 20275347, "author": "Paul", "author_id": 146171, "author_profile": "https://Stackoverflow.com/users/146171", "pm_score": 1, "selected": false, "text": "<p>Check out pytddmon. Here is a video demonstration of how to use it:\n<a href=\"http://pytddmon.org/?page_id=33\" rel=\"nofollow\">http://pytddmon.org/?page_id=33</a></p>\n" }, { "answer_id": 40910385, "author": "Oto Brglez", "author_id": 226622, "author_profile": "https://Stackoverflow.com/users/226622", "pm_score": 2, "selected": false, "text": "<p>One very useful tool that can make your life easier is <a href=\"http://entrproject.org/\" rel=\"nofollow noreferrer\">entr</a>. Written in C, and uses <a href=\"https://en.wikipedia.org/wiki/Kqueue\" rel=\"nofollow noreferrer\">kqueue</a> or <a href=\"http://man7.org/linux/man-pages/man7/inotify.7.html\" rel=\"nofollow noreferrer\">inotify</a> under the hood.</p>\n\n<p>Following command runs your test suite if any <code>*.py</code> file in your project is changed.</p>\n\n<pre><code>ls */**.py | entr python -m unittest discover -s test\n</code></pre>\n\n<p>Works for BSD, Mac OS, and Linux. You can get <a href=\"http://entrproject.org/\" rel=\"nofollow noreferrer\">entr</a> from Homebrew.</p>\n" }, { "answer_id": 52110595, "author": "Mark", "author_id": 3600510, "author_profile": "https://Stackoverflow.com/users/3600510", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"https://nodemon.io/\" rel=\"nofollow noreferrer\">nodemon</a> for the task, by watching .py files and execute <code>manage.py test</code>. The command will be: <code>nodemon --ext py --exec \"python manage.py test\"</code>.</p>\n\n<p><code>nodemon</code> is an npm package however, I assume you have node installed.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
Basically, growl notifications (or other callbacks) when tests break or pass. **Does anything like this exist?** If not, it should be pretty easy to write.. Easiest way would be to.. 1. run `python-autotest myfile1.py myfile2.py etc.py` * Check if files-to-be-monitored have been modified (possibly just if they've been saved). * Run any tests in those files. * If a test fails, but in the previous run it passed, generate a growl alert. Same with tests that fail then pass. * Wait, and repeat steps 2-5. The problem I can see there is if the tests are in a different file. The simple solution would be to run all the tests after each save.. but with slower tests, this might take longer than the time between saves, and/or could use a lot of CPU power etc.. The best way to do it would be to actually see what bits of code have changed, if function abc() has changed, only run tests that interact with this.. While this would be great, I think it'd be extremely complex to implement? To summarise: * Is there anything like the Ruby tool `autotest` (part of the [ZenTest package](http://www.zenspider.com/ZSS/Products/ZenTest/)), but for Python code? * How do you check which functions have changed between two revisions of a script? * Is it possible to determine which functions a command will call? (Somewhat like a reverse traceback)
I found [autonose](https://github.com/gfxmonk/autonose) to be pretty unreliable but [sniffer](http://pypi.python.org/pypi/sniffer/0.2.3) seems to work very well. ``` $ pip install sniffer $ cd myproject ``` Then instead of running "nosetests", you run: ``` $ sniffer ``` Or instead of `nosetests --verbose --with-doctest`, you run: ``` $ sniffer -x--verbose -x--with-doctest ``` As described in the [readme](http://pypi.python.org/pypi/sniffer/0.2.3), it's a good idea to install one of the platform-specific filesystem-watching libraries, `pyinotify`, `pywin32` or `MacFSEvents` (all installable via `pip` etc)
108,900
<p>How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <a href="http://www.compuphase.com/svnrev.htm" rel="nofollow noreferrer">http://www.compuphase.com/svnrev.htm</a> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info. </p> <p>What's the best way to proceed?</p>
[ { "answer_id": 108963, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>In your application.rc file there is a version block. This block controls the version info displayed in the filesystem.</p>\n\n<blockquote>\n <p>VS_VERSION_INFO VERSIONINFO<br>\n FILEVERSION 1,0,0,1<br>\n PRODUCTVERSION 1,0,0,1</p>\n</blockquote>\n\n<p>You can programmatically update this file. Make sure to open and save the file as binary. We have had issues where edits are done as text and the file gets corrupted.</p>\n" }, { "answer_id": 109026, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "<p>Changing <code>VS_VERSION_INFO</code> will reflect when you right click on the file in Explorer and see properties only.</p>\n\n<p>If you want to show the current SVN revision number in the Caption bar, i would suggest:</p>\n\n<ul>\n<li>Have a script get the version number and generate version.h file just with </li>\n</ul>\n\n<blockquote>\n<pre><code>#define SVN_VERSION_NO xxx\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Your project includes this version.h and uses that number to show in caption.</li>\n</ul>\n" }, { "answer_id": 109050, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": false, "text": "<p>An <code>.rc</code> file can <code>#include</code> header files just like <code>.c</code> files can. I have an auto-generated <code>version.h</code> file, which defines things like:</p>\n\n<pre><code>#define MY_PRODUCT_VERSION \"0.47\"\n#define MY_PRODUCT_VERSION_NUM 0,47,0,0\n</code></pre>\n\n<p>Then I just have my <code>.rc</code> file <code>#include \"version.h\"</code> and use those defines.</p>\n\n<pre><code>VS_VERSION_INFO VERSIONINFO\n FILEVERSION MY_PRODUCT_VERSION_NUM\n PRODUCTVERSION MY_PRODUCT_VERSION_NUM\n...\n VALUE \"FileVersion\", MY_PRODUCT_VERSION \"\\0\"\n VALUE \"ProductVersion\", MY_PRODUCT_VERSION \"\\0\"\n...\n</code></pre>\n\n<p>I haven't tried this technique with an MFC project. It might be necessary to move your <code>VS_VERSION_INFO</code> resource to your <code>.rc2</code> file (which won't get edited by Visual Studio).</p>\n" }, { "answer_id": 385722, "author": "mem64k", "author_id": 47418, "author_profile": "https://Stackoverflow.com/users/47418", "pm_score": 0, "selected": false, "text": "<p>Maybe this can be helpful: <a href=\"http://www.codeproject.com/KB/macros/versioningcontrolledbuild.aspx\" rel=\"nofollow noreferrer\">Versioning Controlled Build</a></p>\n" }, { "answer_id": 731297, "author": "Dan", "author_id": 54852, "author_profile": "https://Stackoverflow.com/users/54852", "pm_score": 2, "selected": false, "text": "<p>Don't have enough points to comment yet, but whatever solution you choose keep in mind that FILEVERSION fields can only support a short integer. In our situation, our SVN revision was already above this and resulted in an invalid revision number in our FILEVERSION.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17259/" ]
How do I go about programmatically updating the FILEVERSION string in an MFC app? I have a build process that I use to generate a header file which contains the SVN rev for a given release. I'm using SvnRev from <http://www.compuphase.com/svnrev.htm> to update a header file which I use to set the caption bar of my MFC app. Now I want to use this #define for my FILEVERION info. What's the best way to proceed?
An `.rc` file can `#include` header files just like `.c` files can. I have an auto-generated `version.h` file, which defines things like: ``` #define MY_PRODUCT_VERSION "0.47" #define MY_PRODUCT_VERSION_NUM 0,47,0,0 ``` Then I just have my `.rc` file `#include "version.h"` and use those defines. ``` VS_VERSION_INFO VERSIONINFO FILEVERSION MY_PRODUCT_VERSION_NUM PRODUCTVERSION MY_PRODUCT_VERSION_NUM ... VALUE "FileVersion", MY_PRODUCT_VERSION "\0" VALUE "ProductVersion", MY_PRODUCT_VERSION "\0" ... ``` I haven't tried this technique with an MFC project. It might be necessary to move your `VS_VERSION_INFO` resource to your `.rc2` file (which won't get edited by Visual Studio).
108,938
<p>Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session.</p> <p>I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible.</p> <p>So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts?</p>
[ { "answer_id": 108948, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 2, "selected": false, "text": "<p>You should have a look at memcached: <a href=\"http://wiki.rubyonrails.org/rails/pages/MemCached\" rel=\"nofollow noreferrer\">http://wiki.rubyonrails.org/rails/pages/MemCached</a></p>\n" }, { "answer_id": 108964, "author": "FlipFlop", "author_id": 19693, "author_profile": "https://Stackoverflow.com/users/19693", "pm_score": 2, "selected": false, "text": "<p>There is a helpful <a href=\"http://railscasts.com/episodes/115-caching-in-rails-2-1\" rel=\"nofollow noreferrer\">Railscast on Rails 2.1 caching</a>. It is very useful if you plan on using memcached with Rails.</p>\n" }, { "answer_id": 108975, "author": "bhollis", "author_id": 11284, "author_profile": "https://Stackoverflow.com/users/11284", "pm_score": 0, "selected": false, "text": "<p>@p3t0r- is right,MemCached is probably the best option, but you could also use the sqlite database that comes with Rails. That won't work over multiple machines though, where MemCached will. Also, sqlite will persist to disk, though I think you can set it up not to if you want. Rails itself has no application-scoped storage since it's being run as one-process-per-request-handler so it has no shared memory space like ASP.NET or a Java server would.</p>\n" }, { "answer_id": 108997, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 0, "selected": false, "text": "<p>So what you are asking is quite impossible in Rails because of the way it is designed. What you ask is a shared object and Rails is strictly single threaded. Memcached or similar tool for sharing data between distributed processes is the only way to go. </p>\n" }, { "answer_id": 109119, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 1, "selected": false, "text": "<p>Using the stock Rails cache is roughly equivalent to this. </p>\n" }, { "answer_id": 117610, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 4, "selected": true, "text": "<p><strong>Right answer</strong>: memcached . Fast, clean, supports multiple processes, integrates <strong>very</strong> cleanly with Rails these days. Not even that bad to set up, but it is one more thing to keep running.</p>\n\n<p><strong>90% Answer</strong>: There are probably multiple Rails processes running around -- one for each Mongrel you have, for example. Depending on the specifics of your caching needs, its quite possible that having one cache per Mongrel isn't the worst thing in the world. For example, supposing you were caching the results of a long-running query which </p>\n\n<ul>\n<li>gets fresh data every 8 hours</li>\n<li>is used every page load, 20,000 times a day</li>\n<li>needs to be accessed in 4 processes (Mongrels)</li>\n</ul>\n\n<p>then you can drop that 20,000 requests down to 12 with about a single line of code</p>\n\n<pre><code>@@arbitrary_name ||= Model.find_by_stupidly_long_query(param)\n</code></pre>\n\n<p>The double at-mark, a Ruby symbol you might not be familiar with, is a global variable. ||= is the commonly used Ruby idiom to execute the assignment if and only if the variable is currently nil or otherwise evaluates to false. It will stay good until you explicitly empty it OR until the process stops, for any reason -- server restart, explicitly killed, what have you. </p>\n\n<p>And after you go down from 20k calculations a day to 12 in about 15 seconds (OK, two minutes -- you need to wrap it in a trivial if block which stores the cache update time in a different global), you might find that there is no need to spend additional engineering assets on getting it down to 4 a day.</p>\n\n<p>I actually use this in one of my production sites, for caching a few expensive queries which literally only need to be evaluated once in the life of the process (i.e. they change only at deployment time -- I suppose I could precalculate the results and write them to disk or DB but why do that when SQL can do the work for me). </p>\n\n<p>You don't get any magic expiry syntax, reliability is pretty slim, and it can't be shared across processes -- but its 90% of what you need in a line of code.</p>\n" }, { "answer_id": 2733368, "author": "TraderJoeChicago", "author_id": 124708, "author_profile": "https://Stackoverflow.com/users/124708", "pm_score": 0, "selected": false, "text": "<p>The Rails.cache freezes the objects it stores. This kind of makes sense for a cache but NOT for an application context. I guess instead of doing a roundtrip to the moon to accomplish that simple task, all you have to do is create a constant inside config/environment.rb</p>\n\n<p><code>APP_CONTEXT = Hash.new</code></p>\n\n<p>Pretty simple, ah?</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041950/" ]
Rails comes with a handy session hash into which we can cram stuff to our heart's content. I would, however, like something like ASP's application context, which instead of sharing data only within a single session, will share it with all sessions in the same application. I'm writing a simple dashboard app, and would like to pull data every 5 minutes, rather than every 5 minutes for each session. I could, of course, store the cache update times in a database, but so far haven't needed to set up a database for this app, and would love to avoid that dependency if possible. So, is there any way to get (or simulate) this sort of thing? If there's no way to do it without a database, is there any kind of "fake" database engine that comes with Rails, runs in memory, but doesn't bother persisting data between restarts?
**Right answer**: memcached . Fast, clean, supports multiple processes, integrates **very** cleanly with Rails these days. Not even that bad to set up, but it is one more thing to keep running. **90% Answer**: There are probably multiple Rails processes running around -- one for each Mongrel you have, for example. Depending on the specifics of your caching needs, its quite possible that having one cache per Mongrel isn't the worst thing in the world. For example, supposing you were caching the results of a long-running query which * gets fresh data every 8 hours * is used every page load, 20,000 times a day * needs to be accessed in 4 processes (Mongrels) then you can drop that 20,000 requests down to 12 with about a single line of code ``` @@arbitrary_name ||= Model.find_by_stupidly_long_query(param) ``` The double at-mark, a Ruby symbol you might not be familiar with, is a global variable. ||= is the commonly used Ruby idiom to execute the assignment if and only if the variable is currently nil or otherwise evaluates to false. It will stay good until you explicitly empty it OR until the process stops, for any reason -- server restart, explicitly killed, what have you. And after you go down from 20k calculations a day to 12 in about 15 seconds (OK, two minutes -- you need to wrap it in a trivial if block which stores the cache update time in a different global), you might find that there is no need to spend additional engineering assets on getting it down to 4 a day. I actually use this in one of my production sites, for caching a few expensive queries which literally only need to be evaluated once in the life of the process (i.e. they change only at deployment time -- I suppose I could precalculate the results and write them to disk or DB but why do that when SQL can do the work for me). You don't get any magic expiry syntax, reliability is pretty slim, and it can't be shared across processes -- but its 90% of what you need in a line of code.
108,940
<p>I am trying to evaluate the answer <a href="https://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp">provided here</a>, and am getting the error: <code>"A file with name ASDF-INSTALL does not exist"</code> when using clisp:</p> <pre><code>dsm@localhost:~$ clisp -q [1]&gt; (require :asdf-install) *** - LOAD: A file with name ASDF-INSTALL does not exist The following restarts are available: ABORT :R1 ABORT Break 1 [2]&gt; :r1 [3]&gt; (quit) dsm@localhost:~$ </code></pre> <p>cmucl throws a similar error:</p> <pre><code>dsm@localhost:~$ cmucl -q Warning: #&lt;Command Line Switch "q"&gt; is an illegal switch CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile With core: /usr/lib/cmucl/lisp.core Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS. or to [email protected] type (help) for help, (quit) to exit, and (demo) to see the demos Loaded subsystems: Python 1.1, target Intel x86 CLOS based on Gerd's PCL 2004/04/14 03:32:47 * (require :asdf-install) Error in function REQUIRE: Don't know how to load ASDF-INSTALL [Condition of type SIMPLE-ERROR] Restarts: 0: [ABORT] Return to Top-Level. Debug (type H for help) (REQUIRE :ASDF-INSTALL NIL) Source: ; File: target:code/module.lisp (ERROR "Don't know how to load ~A" MODULE-NAME) 0] (quit) dsm@localhost:~$ </code></pre> <p>But sbcl works perfectly:</p> <pre><code>dsm@localhost:~$ sbcl -q This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp. More information about SBCL is available at &lt;http://www.sbcl.org/&gt;. SBCL is free software, provided as is, with absolutely no warranty. It is mostly in the public domain; some portions are provided under BSD-style licenses. See the CREDITS and COPYING files in the distribution for more information. * (require :asdf-install) ; loading system definition from ; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #&lt;PACKAGE "ASDF0"&gt; ; registering #&lt;SYSTEM SB-BSD-SOCKETS {AB01A89}&gt; as SB-BSD-SOCKETS ; registering #&lt;SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}&gt; as SB-BSD-SOCKETS-TESTS ("SB-BSD-SOCKETS" "ASDF-INSTALL") * (quit) </code></pre> <p>Any ideas on how to fix this? I found <a href="https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208" rel="nofollow noreferrer">this post</a> on the internet, but using that didn't work either.</p>
[ { "answer_id": 109028, "author": "Attila Lendvai", "author_id": 14464, "author_profile": "https://Stackoverflow.com/users/14464", "pm_score": 2, "selected": false, "text": "<p>try this before anything else:</p>\n\n<pre><code>(require :asdf)\n</code></pre>\n\n<p>you can steal some ideas from the environment we use. it's available at: <a href=\"http://dwim.hu/darcsweb/darcsweb.cgi?r=HEAD%20hu.dwim.environment;a=summary\" rel=\"nofollow noreferrer\">darcsweb</a></p>\n\n<p>see environment.lisp that loads and sets up asdf for us. (sbcl has asdf already loaded)</p>\n" }, { "answer_id": 109056, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 2, "selected": false, "text": "<p>The instructions you got mentioned SBCL explicitely, so it's expected that they'll work better using SBCL, I suppose. Some other Lisps don't come with ASDF or don't hook it up to CL:REQUIRE. In the former case, you'll have load ASDF yourself beforehand. In the latter case, you'll need to call (asdf:oos 'asdf:load-op ) instead of (require ).</p>\n" }, { "answer_id": 109253, "author": "FlinkmanSV", "author_id": 15054, "author_profile": "https://Stackoverflow.com/users/15054", "pm_score": 2, "selected": false, "text": "<p>wget <a href=\"http://cclan.cvs.sourceforge.net/\" rel=\"nofollow noreferrer\">http://cclan.cvs.sourceforge.net/</a><em>checkout</em>/cclan/asdf/asdf.lisp </p>\n\n<p>It worth checking out clbuild. <a href=\"http://common-lisp.net/project/clbuild/\" rel=\"nofollow noreferrer\">http://common-lisp.net/project/clbuild/</a></p>\n\n<p>To get a lisp webserver up and running. You only need:</p>\n\n<pre><code>darcs get http://common-lisp.net/project/clbuild/clbuild\ncd clbuild\nchmod +x ./clbuild\n./clbuild check\n./clbuild build slime hunchentoot\n./clbuild preloaded\n</code></pre>\n\n<p>Now a lisp repl will start. There you write:</p>\n\n<pre><code>* (hunchentoot:start-server :port 8080)\n</code></pre>\n\n<p>Testing that the server answer:</p>\n\n<pre><code>wget -O - http://localhost:8080/\n\n&lt;html&gt;&lt;head&gt;&lt;title&gt;Hunchentoot&lt;/title&gt;&lt;/head&gt;\n &lt;body&gt;&lt;h2&gt;Hunchentoot Default Page&lt;/h2&gt;\n &lt;p&gt;This is the Hunchentoot default page....\n</code></pre>\n" }, { "answer_id": 269758, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>use clc:clc-require in clisp. Refer to 'man common-lisp-controller'. I had the same error in clisp and resolved it by using clc:clc-require. sbcl works fine with just require though.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
I am trying to evaluate the answer [provided here](https://stackoverflow.com/questions/108081/are-there-any-high-level-easy-to-install-gui-libraries-for-common-lisp), and am getting the error: `"A file with name ASDF-INSTALL does not exist"` when using clisp: ``` dsm@localhost:~$ clisp -q [1]> (require :asdf-install) *** - LOAD: A file with name ASDF-INSTALL does not exist The following restarts are available: ABORT :R1 ABORT Break 1 [2]> :r1 [3]> (quit) dsm@localhost:~$ ``` cmucl throws a similar error: ``` dsm@localhost:~$ cmucl -q Warning: #<Command Line Switch "q"> is an illegal switch CMU Common Lisp CVS release-19a 19a-release-20040728 + minimal debian patches, running on crap-pile With core: /usr/lib/cmucl/lisp.core Dumped on: Sat, 2008-09-20 20:11:54+02:00 on localhost For support see http://www.cons.org/cmucl/support.html Send bug reports to the debian BTS. or to [email protected] type (help) for help, (quit) to exit, and (demo) to see the demos Loaded subsystems: Python 1.1, target Intel x86 CLOS based on Gerd's PCL 2004/04/14 03:32:47 * (require :asdf-install) Error in function REQUIRE: Don't know how to load ASDF-INSTALL [Condition of type SIMPLE-ERROR] Restarts: 0: [ABORT] Return to Top-Level. Debug (type H for help) (REQUIRE :ASDF-INSTALL NIL) Source: ; File: target:code/module.lisp (ERROR "Don't know how to load ~A" MODULE-NAME) 0] (quit) dsm@localhost:~$ ``` But sbcl works perfectly: ``` dsm@localhost:~$ sbcl -q This is SBCL 1.0.11.debian, an implementation of ANSI Common Lisp. More information about SBCL is available at <http://www.sbcl.org/>. SBCL is free software, provided as is, with absolutely no warranty. It is mostly in the public domain; some portions are provided under BSD-style licenses. See the CREDITS and COPYING files in the distribution for more information. * (require :asdf-install) ; loading system definition from ; /usr/lib/sbcl/sb-bsd-sockets/sb-bsd-sockets.asd into #<PACKAGE "ASDF0"> ; registering #<SYSTEM SB-BSD-SOCKETS {AB01A89}> as SB-BSD-SOCKETS ; registering #<SYSTEM SB-BSD-SOCKETS-TESTS {AC67181}> as SB-BSD-SOCKETS-TESTS ("SB-BSD-SOCKETS" "ASDF-INSTALL") * (quit) ``` Any ideas on how to fix this? I found [this post](https://bugs.launchpad.net/ubuntu/+source/common-lisp-controller/+bug/37208) on the internet, but using that didn't work either.
use clc:clc-require in clisp. Refer to 'man common-lisp-controller'. I had the same error in clisp and resolved it by using clc:clc-require. sbcl works fine with just require though.
108,971
<p>We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.</p> <p>Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?</p>
[ { "answer_id": 108998, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx\" rel=\"nofollow noreferrer\">corflags</a> utility to force an AnyCPU exe to load as an x86 or x64 executable, but that doesn't totally meet the file copy deployment requirement unless you choose which exe to copy based on the target.</p>\n" }, { "answer_id": 156024, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 7, "selected": true, "text": "<p>I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows:</p>\n\n<ol>\n<li>Make sure default .NET assembly loading mechanism (\"Fusion\" engine) can't find either x86 or x64 version of the platform-specific assembly</li>\n<li>Before the main application attempts loading the platform-specific assembly, install a custom assembly resolver in the current AppDomain</li>\n<li>Now when the main application needs the platform-specific assembly, Fusion engine will give up (because of step 1) and call our custom resolver (because of step 2); in the custom resolver we determine current platform and use directory-based lookup to load appropriate DLL.</li>\n</ol>\n\n<p>To demonstrate this technique, I am attaching a short, command-line based tutorial. I tested the resulting binaries on Windows XP x86 and then Vista SP1 x64 (by copying the binaries over, just like your deployment).</p>\n\n<p><strong>Note 1</strong>: \"csc.exe\" is a C-sharp compiler. This tutorial assumes it is in your path (my tests were using \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\csc.exe\")</p>\n\n<p><strong>Note 2</strong>: I recommend you create a temporary folder for the tests and run command line (or powershell) whose current working directory is set to this location, e.g.</p>\n\n<pre><code>(cmd.exe)\nC:\nmkdir \\TEMP\\CrossPlatformTest\ncd \\TEMP\\CrossPlatformTest\n</code></pre>\n\n<p><strong>Step 1</strong>: The platform-specific assembly is represented by a simple C# class library:</p>\n\n<pre><code>// file 'library.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Library\n{\n public static class Worker\n {\n public static void Run()\n {\n System.Console.WriteLine(\"Worker is running\");\n System.Console.WriteLine(\"(Enter to continue)\");\n System.Console.ReadLine();\n }\n }\n}\n</code></pre>\n\n<p><strong>Step 2</strong>: We compile platform-specific assemblies using simple command-line commands:</p>\n\n<pre><code>(cmd.exe from Note 2)\nmkdir platform\\x86\ncsc /out:platform\\x86\\library.dll /target:library /platform:x86 library.cs\nmkdir platform\\amd64\ncsc /out:platform\\amd64\\library.dll /target:library /platform:x64 library.cs\n</code></pre>\n\n<p><strong>Step 3</strong>: Main program is split into two parts. \"Bootstrapper\" contains main entry point for the executable and it registers a custom assembly resolver in current appdomain:</p>\n\n<pre><code>// file 'bootstrapper.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Program\n{\n public static class Bootstrapper\n {\n public static void Main()\n {\n System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve;\n App.Run();\n }\n\n private static System.Reflection.Assembly CustomResolve(\n object sender,\n System.ResolveEventArgs args)\n {\n if (args.Name.StartsWith(\"library\"))\n {\n string fileName = System.IO.Path.GetFullPath(\n \"platform\\\\\"\n + System.Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\")\n + \"\\\\library.dll\");\n System.Console.WriteLine(fileName);\n if (System.IO.File.Exists(fileName))\n {\n return System.Reflection.Assembly.LoadFile(fileName);\n }\n }\n return null;\n }\n }\n}\n</code></pre>\n\n<p>\"Program\" is the \"real\" implementation of the application (note that App.Run was invoked at the end of Bootstrapper.Main):</p>\n\n<pre><code>// file 'program.cs' in C:\\TEMP\\CrossPlatformTest\nnamespace Cross.Platform.Program\n{\n public static class App\n {\n public static void Run()\n {\n Cross.Platform.Library.Worker.Run();\n }\n }\n}\n</code></pre>\n\n<p><strong>Step 4</strong>: Compile the main application on command line:</p>\n\n<pre><code>(cmd.exe from Note 2)\ncsc /reference:platform\\x86\\library.dll /out:program.exe program.cs bootstrapper.cs\n</code></pre>\n\n<p><strong>Step 5</strong>: We're now finished. The structure of the directory we created should be as follows:</p>\n\n<pre><code>(C:\\TEMP\\CrossPlatformTest, root dir)\n platform (dir)\n amd64 (dir)\n library.dll\n x86 (dir)\n library.dll\n program.exe\n *.cs (source files)\n</code></pre>\n\n<p>If you now run program.exe on a 32bit platform, platform\\x86\\library.dll will be loaded; if you run program.exe on a 64bit platform, platform\\amd64\\library.dll will be loaded. Note that I added Console.ReadLine() at the end of the Worker.Run method so that you can use task manager/process explorer to investigate loaded DLLs, or you can use Visual Studio/Windows Debugger to attach to the process to see the call stack etc.</p>\n\n<p>When program.exe is run, our custom assembly resolver is attached to current appdomain. As soon as .NET starts loading the Program class, it sees a dependency on 'library' assembly, so it tries loading it. However, no such assembly is found (because we've hidden it in platform/* subdirectories). Luckily, our custom resolver knows our trickery and based on the current platform it tries loading the assembly from appropriate platform/* subdirectory.</p>\n" }, { "answer_id": 9951658, "author": "Yuri Astrakhan", "author_id": 177275, "author_profile": "https://Stackoverflow.com/users/177275", "pm_score": 5, "selected": false, "text": "<p>My version, similar to @Milan, but with several important changes:</p>\n\n<ul>\n<li>Works for ALL DLLs that were not found</li>\n<li>Can be turned on and off</li>\n<li><p><code>AppDomain.CurrentDomain.SetupInformation.ApplicationBase</code> is used instead of <code>Path.GetFullPath()</code> because the current directory might be different, e.g. in hosting scenarios, Excel might load your plugin but the current directory will not be set to your DLL.</p></li>\n<li><p><code>Environment.Is64BitProcess</code> is used instead of <code>PROCESSOR_ARCHITECTURE</code>, as we should not depend on what the OS is, rather how this process was started - it could have been x86 process on a x64 OS. Before .NET 4, use <code>IntPtr.Size == 8</code> instead.</p></li>\n</ul>\n\n<p>Call this code in a static constructor of some main class that is loaded before all else.</p>\n\n<pre><code>public static class MultiplatformDllLoader\n{\n private static bool _isEnabled;\n\n public static bool Enable\n {\n get { return _isEnabled; }\n set\n {\n lock (typeof (MultiplatformDllLoader))\n {\n if (_isEnabled != value)\n {\n if (value)\n AppDomain.CurrentDomain.AssemblyResolve += Resolver;\n else\n AppDomain.CurrentDomain.AssemblyResolve -= Resolver;\n _isEnabled = value;\n }\n }\n }\n }\n\n /// Will attempt to load missing assembly from either x86 or x64 subdir\n private static Assembly Resolver(object sender, ResolveEventArgs args)\n {\n string assemblyName = args.Name.Split(new[] {','}, 2)[0] + \".dll\";\n string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,\n Environment.Is64BitProcess ? \"x64\" : \"x86\",\n assemblyName);\n\n return File.Exists(archSpecificPath)\n ? Assembly.LoadFile(archSpecificPath)\n : null;\n }\n}\n</code></pre>\n" }, { "answer_id": 10881132, "author": "wvd_vegt", "author_id": 1034074, "author_profile": "https://Stackoverflow.com/users/1034074", "pm_score": 2, "selected": false, "text": "<p>Have a look at SetDllDirectory. I used it around the dynamically loading of an IBM spss assembly for both x64 and x86. It also solved paths for non assembly support dll's loaded by the assemblies in my case was the case with the spss dll's.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms686203%28VS.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms686203%28VS.85%29.aspx</a></p>\n" }, { "answer_id": 40727665, "author": "Kevin Marshall", "author_id": 5403550, "author_profile": "https://Stackoverflow.com/users/5403550", "pm_score": 1, "selected": false, "text": "<p>This solution can work for non managed assemblies as well. I have created a simple example similar to Milan Gardian's great example. The example I created dynamically loads a Managed C++ dll into a C# dll compiled for the Any CPU platform. The solution makes use of the InjectModuleInitializer nuget package to subscribe to the AssemblyResolve event before the dependencies of the assembly are loaded. </p>\n\n<p><a href=\"https://github.com/kevin-marshall/Managed.AnyCPU.git\" rel=\"nofollow noreferrer\">https://github.com/kevin-marshall/Managed.AnyCPU.git</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/108971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6156/" ]
We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so. Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?
I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows: 1. Make sure default .NET assembly loading mechanism ("Fusion" engine) can't find either x86 or x64 version of the platform-specific assembly 2. Before the main application attempts loading the platform-specific assembly, install a custom assembly resolver in the current AppDomain 3. Now when the main application needs the platform-specific assembly, Fusion engine will give up (because of step 1) and call our custom resolver (because of step 2); in the custom resolver we determine current platform and use directory-based lookup to load appropriate DLL. To demonstrate this technique, I am attaching a short, command-line based tutorial. I tested the resulting binaries on Windows XP x86 and then Vista SP1 x64 (by copying the binaries over, just like your deployment). **Note 1**: "csc.exe" is a C-sharp compiler. This tutorial assumes it is in your path (my tests were using "C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe") **Note 2**: I recommend you create a temporary folder for the tests and run command line (or powershell) whose current working directory is set to this location, e.g. ``` (cmd.exe) C: mkdir \TEMP\CrossPlatformTest cd \TEMP\CrossPlatformTest ``` **Step 1**: The platform-specific assembly is represented by a simple C# class library: ``` // file 'library.cs' in C:\TEMP\CrossPlatformTest namespace Cross.Platform.Library { public static class Worker { public static void Run() { System.Console.WriteLine("Worker is running"); System.Console.WriteLine("(Enter to continue)"); System.Console.ReadLine(); } } } ``` **Step 2**: We compile platform-specific assemblies using simple command-line commands: ``` (cmd.exe from Note 2) mkdir platform\x86 csc /out:platform\x86\library.dll /target:library /platform:x86 library.cs mkdir platform\amd64 csc /out:platform\amd64\library.dll /target:library /platform:x64 library.cs ``` **Step 3**: Main program is split into two parts. "Bootstrapper" contains main entry point for the executable and it registers a custom assembly resolver in current appdomain: ``` // file 'bootstrapper.cs' in C:\TEMP\CrossPlatformTest namespace Cross.Platform.Program { public static class Bootstrapper { public static void Main() { System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve; App.Run(); } private static System.Reflection.Assembly CustomResolve( object sender, System.ResolveEventArgs args) { if (args.Name.StartsWith("library")) { string fileName = System.IO.Path.GetFullPath( "platform\\" + System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") + "\\library.dll"); System.Console.WriteLine(fileName); if (System.IO.File.Exists(fileName)) { return System.Reflection.Assembly.LoadFile(fileName); } } return null; } } } ``` "Program" is the "real" implementation of the application (note that App.Run was invoked at the end of Bootstrapper.Main): ``` // file 'program.cs' in C:\TEMP\CrossPlatformTest namespace Cross.Platform.Program { public static class App { public static void Run() { Cross.Platform.Library.Worker.Run(); } } } ``` **Step 4**: Compile the main application on command line: ``` (cmd.exe from Note 2) csc /reference:platform\x86\library.dll /out:program.exe program.cs bootstrapper.cs ``` **Step 5**: We're now finished. The structure of the directory we created should be as follows: ``` (C:\TEMP\CrossPlatformTest, root dir) platform (dir) amd64 (dir) library.dll x86 (dir) library.dll program.exe *.cs (source files) ``` If you now run program.exe on a 32bit platform, platform\x86\library.dll will be loaded; if you run program.exe on a 64bit platform, platform\amd64\library.dll will be loaded. Note that I added Console.ReadLine() at the end of the Worker.Run method so that you can use task manager/process explorer to investigate loaded DLLs, or you can use Visual Studio/Windows Debugger to attach to the process to see the call stack etc. When program.exe is run, our custom assembly resolver is attached to current appdomain. As soon as .NET starts loading the Program class, it sees a dependency on 'library' assembly, so it tries loading it. However, no such assembly is found (because we've hidden it in platform/\* subdirectories). Luckily, our custom resolver knows our trickery and based on the current platform it tries loading the assembly from appropriate platform/\* subdirectory.
109,000
<p>My C application uses 3rd libraries, which do their own memory management. In order to be robust, my application has code to deal with failures of library functions due to lack of free memory.</p> <p>I would like to test this code, and for this, I need to simulate failures due to lack of memory.</p> <p>What tool/s are recommended for this? My environment is Linux/gcc.</p>
[ { "answer_id": 109004, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>Create your own malloc wrapper which will randomly return null instead of a valid pointer. Well, or which fails consistently if you want to unit test.</p>\n" }, { "answer_id": 109005, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 3, "selected": false, "text": "<p>You can write your own mock library with the same interface as your 3rd party library instead of it. You can also use LD_PRELOAD to override selected functions of the 3rd party library.</p>\n" }, { "answer_id": 109008, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 2, "selected": false, "text": "<p>I can give a Linux (maybe POSIX) specific version: __malloc_hook, __realloc_hook, __free_hook. These are declared in malloc.h.</p>\n\n<p>EDIT: A little elaboration: these are function pointers (see malloc.h and their man-page for the exact declaration), but beware: these are not exactly standards, just GNU extensions. So if portability is an issue, don't use this.</p>\n\n<p>A little less platform-dependent solution might be that you declare a malloc macro. If you're testing, this calls a hook and the real malloc.</p>\n\n<p>memhook.h:</p>\n\n<pre><code>#define malloc(s) (my_malloc(s))\n</code></pre>\n\n<p>memhook.c:</p>\n\n<pre><code>#include \"memhook.h\"\n#undef malloc\n#include &lt;stdlib.h&gt;\n</code></pre>\n\n<p>etc.</p>\n\n<p>You can use this to detect leaks, randomly fail the allocation, etc.</p>\n" }, { "answer_id": 109012, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": false, "text": "<p>You can use <code>ulimit</code> to limit the amount of resources a user can use, including memory. So you create a test user, limit their memory use to something just enough to launch your program, and watch it die :)</p>\n\n<p>Example:</p>\n\n<pre><code>ulimit -m 64\n</code></pre>\n\n<p>Sets a memory limit of 64kb.</p>\n" }, { "answer_id": 109017, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 0, "selected": false, "text": "<p>You want the ulimit command in bash. Try \n<pre>help ulimit</pre> at a bash shell prompt.</p>\n" }, { "answer_id": 109037, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>In addition, you should use <a href=\"http://valgrind.org\" rel=\"nofollow noreferrer\">Valgrind</a> to test it all and get real useful reports about memory behavior of your program</p>\n" }, { "answer_id": 116119, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 0, "selected": false, "text": "<p>(As a complement to some of the previous answers)</p>\n\n<p>Checkout \"Electric Fence\" for an example of a malloc-intercepting library that you can use with your executable (using the LD_PRELOAD trick, for instance). </p>\n\n<p>Once you've intercepted malloc, you can use whatever you want to trigger failures. A randomly triggered failure would be a good stress test for the various parts of the system. You could also modify the failure probability based on the amount of memory requested.</p>\n\n<p>Yours is an interesting idea, by the way, clearly something I'd like to do on some of my code...</p>\n" }, { "answer_id": 122369, "author": "ChrisInEdmonton", "author_id": 16266, "author_profile": "https://Stackoverflow.com/users/16266", "pm_score": 3, "selected": false, "text": "<p>On operating systems that overcommit memory (for example, Linux or Windows), it is simply not possible to handle out-of-memory errors. malloc may return a valid pointer and later, when you try to dereference it, your operating system may determine that you are out of memory and kill the process.</p>\n\n<p><a href=\"http://www.reddit.com/comments/60vys/how_not_to_write_a_shared_library/\" rel=\"noreferrer\">http://www.reddit.com/comments/60vys/how_not_to_write_a_shared_library/</a> is a good write-up on this.</p>\n" }, { "answer_id": 215895, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 0, "selected": false, "text": "<p>You might want to look at some of the recovery oriented computing sites, such as the <a href=\"http://roc.cs.berkeley.edu/\" rel=\"nofollow noreferrer\">Berkeley/Stanford ROC group</a>. I've heard some of these folks talk before, and they use code to randomly inject errors in the C runtime. There's a link to their FIT tool at the bottom of their page.</p>\n" }, { "answer_id": 2910583, "author": "a_m0d", "author_id": 106762, "author_profile": "https://Stackoverflow.com/users/106762", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"http://sqlite.org/testing.html#oomtesting\" rel=\"nofollow noreferrer\">the way sqlite3 does this</a>. They perform extensive unit testing, including out of memory testing.</p>\n\n<p>You may also want to look at <a href=\"http://sqlite.org/malloc.html\" rel=\"nofollow noreferrer\">their page on malloc</a>, particularly <a href=\"http://sqlite.org/malloc.html#nofrag\" rel=\"nofollow noreferrer\">Section 4.0</a>.</p>\n" }, { "answer_id": 53161379, "author": "Antonin GAVREL", "author_id": 3161139, "author_profile": "https://Stackoverflow.com/users/3161139", "pm_score": 1, "selected": false, "text": "<p>You can setup a define in the header file to return NULL whenever malloc is used:</p>\n\n<p>Usually malloc will be protected the following way:</p>\n\n<pre><code>if ((int *x = malloc(sizeof(int))) == NULL)\n{\n return NULL;\n}\n</code></pre>\n\n<p>So you use a define to force a NULL return; pseudocode example:</p>\n\n<pre><code># define malloc(X) NULL\n</code></pre>\n\n<p>And check if you get a segfault</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11886/" ]
My C application uses 3rd libraries, which do their own memory management. In order to be robust, my application has code to deal with failures of library functions due to lack of free memory. I would like to test this code, and for this, I need to simulate failures due to lack of memory. What tool/s are recommended for this? My environment is Linux/gcc.
You can use `ulimit` to limit the amount of resources a user can use, including memory. So you create a test user, limit their memory use to something just enough to launch your program, and watch it die :) Example: ``` ulimit -m 64 ``` Sets a memory limit of 64kb.
109,023
<p>8 bits representing the number 7 look like this:</p> <pre><code>00000111 </code></pre> <p>Three bits are set.</p> <p>What are the algorithms to determine the number of set bits in a 32-bit integer?</p>
[ { "answer_id": 109025, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 11, "selected": true, "text": "<p>This is known as the '<a href=\"https://en.wikipedia.org/wiki/Hamming_weight\" rel=\"nofollow noreferrer\">Hamming Weight</a>', 'popcount' or 'sideways addition'.</p>\n<p>Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. Instructions like x86's <a href=\"https://www.felixcloutier.com/x86/popcnt\" rel=\"nofollow noreferrer\"><code>popcnt</code></a> (on CPUs where it's supported) will almost certainly be fastest for a single integer. Some other architectures may have a slow instruction implemented with a microcoded loop that tests a bit per cycle (<em>citation needed</em> - hardware popcount is normally fast if it exists at all.).</p>\n<p>The 'best' algorithm really depends on which CPU you are on and what your usage pattern is.</p>\n<p>Your compiler may know how to do something that's good for the specific CPU you're compiling for, e.g. <a href=\"https://en.cppreference.com/w/cpp/numeric/popcount\" rel=\"nofollow noreferrer\">C++20 <code>std::popcount()</code></a>, or C++ <a href=\"https://en.cppreference.com/w/cpp/utility/bitset/count\" rel=\"nofollow noreferrer\"><code>std::bitset&lt;32&gt;::count()</code></a>, as a portable way to access builtin / intrinsic functions (see <a href=\"https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109069#109069\">another answer</a> on this question). But your compiler's choice of fallback for target CPUs that don't have hardware popcnt might not be optimal for your use-case. Or your language (e.g. C) might not expose any portable function that could use a CPU-specific popcount when there is one.</p>\n<hr />\n<h3>Portable algorithms that don't need (or benefit from) any HW support</h3>\n<p>A pre-populated table lookup method can be very fast if your CPU has a large cache and you are doing lots of these operations in a tight loop. However it can suffer because of the expense of a 'cache miss', where the CPU has to fetch some of the table from main memory. (Look up each byte separately to keep the table small.) If you want popcount for a contiguous range of numbers, only the low byte is changing for groups of 256 numbers, <a href=\"https://stackoverflow.com/questions/66520106/count-integers-in-1-n-with-k-zero-bits-below-the-leading-1-popcount-for-a-c/66532113#66532113\">making this very good</a>.</p>\n<p>If you know that your bytes will be mostly 0's or mostly 1's then there are efficient algorithms for these scenarios, e.g. clearing the lowest set with a bithack in a loop until it becomes zero.</p>\n<p>I believe a very good general purpose algorithm is the following, known as 'parallel' or 'variable-precision SWAR algorithm'. I have expressed this in a C-like pseudo language, you may need to adjust it to work for a particular language (e.g. using uint32_t for C++ and &gt;&gt;&gt; in Java):</p>\n<p>GCC10 and clang 10.0 can recognize this pattern / idiom and compile it to a hardware popcnt or equivalent instruction when available, giving you the best of both worlds. (<a href=\"https://godbolt.org/z/qGdh1dvKK\" rel=\"nofollow noreferrer\">https://godbolt.org/z/qGdh1dvKK</a>)</p>\n<pre class=\"lang-c prettyprint-override\"><code>int numberOfSetBits(uint32_t i)\n{\n // Java: use int, and use &gt;&gt;&gt; instead of &gt;&gt;. Or use Integer.bitCount()\n // C or C++: use uint32_t\n i = i - ((i &gt;&gt; 1) &amp; 0x55555555); // add pairs of bits\n i = (i &amp; 0x33333333) + ((i &gt;&gt; 2) &amp; 0x33333333); // quads\n i = (i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F; // groups of 8\n return (i * 0x01010101) &gt;&gt; 24; // horizontal sum of bytes\n}\n</code></pre>\n<p>For JavaScript: <a href=\"https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#comment103845611_109025\">coerce to integer</a> with <code>|0</code> for performance: change the first line to <code>i = (i|0) - ((i &gt;&gt; 1) &amp; 0x55555555);</code></p>\n<p>This has the best worst-case behaviour of any of the algorithms discussed, so will efficiently deal with any usage pattern or values you throw at it. (Its performance is not data-dependent on normal CPUs where all integer operations including multiply are constant-time. It doesn't get any faster with &quot;simple&quot; inputs, but it's still pretty decent.)</p>\n<p>References:</p>\n<ul>\n<li><a href=\"https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel\" rel=\"nofollow noreferrer\">https://graphics.stanford.edu/~seander/bithacks.html</a></li>\n<li><a href=\"https://catonmat.net/low-level-bit-hacks\" rel=\"nofollow noreferrer\">https://catonmat.net/low-level-bit-hacks</a> for bithack basics, like how subtracting 1 flips contiguous zeros.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Hamming_weight\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Hamming_weight</a></li>\n<li><a href=\"http://gurmeet.net/puzzles/fast-bit-counting-routines/\" rel=\"nofollow noreferrer\">http://gurmeet.net/puzzles/fast-bit-counting-routines/</a></li>\n<li><a href=\"http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)\" rel=\"nofollow noreferrer\">http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)</a></li>\n</ul>\n<hr />\n<h3>How this SWAR bithack works:</h3>\n<pre><code>i = i - ((i &gt;&gt; 1) &amp; 0x55555555);\n</code></pre>\n<p>The first step is an optimized version of masking to isolate the odd / even bits, shifting to line them up, and adding. This effectively does 16 separate additions in 2-bit accumulators (<a href=\"https://en.wikipedia.org/wiki/SWAR\" rel=\"nofollow noreferrer\">SWAR = SIMD Within A Register</a>). Like <code>(i &amp; 0x55555555) + ((i&gt;&gt;1) &amp; 0x55555555)</code>.</p>\n<p>The next step takes the odd/even eight of those 16x 2-bit accumulators and adds again, producing 8x 4-bit sums. The <code>i - ...</code> optimization isn't possible this time so it does just mask before / after shifting. Using the same <code>0x33...</code> constant both times instead of <code>0xccc...</code> before shifting is a good thing when compiling for ISAs that need to construct 32-bit constants in registers separately.</p>\n<p>The final shift-and-add step of <code>(i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F</code> widens to 4x 8-bit accumulators. It masks <em>after</em> adding instead of before, because the maximum value in any 4-bit accumulator is <code>4</code>, if all 4 bits of the corresponding input bits were set. 4+4 = 8 which still fits in 4 bits, so carry between nibble elements is impossible in <code>i + (i &gt;&gt; 4)</code>.</p>\n<p>So far this is just fairly normal SIMD using SWAR techniques with a few clever optimizations. Continuing on with the same pattern for 2 more steps can widen to 2x 16-bit then 1x 32-bit counts. But there is a more efficient way on machines with fast hardware multiply:</p>\n<p>Once we have few enough &quot;elements&quot;, <strong>a multiply with a magic constant can sum all the elements into the top element</strong>. In this case byte elements. Multiply is done by left-shifting and adding, so <strong>a multiply of <code>x * 0x01010101</code> results in <code>x + (x&lt;&lt;8) + (x&lt;&lt;16) + (x&lt;&lt;24)</code>.</strong> Our 8-bit elements are wide enough (and holding small enough counts) that this doesn't produce carry <em>into</em> that top 8 bits.</p>\n<p><strong>A 64-bit version of this</strong> can do 8x 8-bit elements in a 64-bit integer with a 0x0101010101010101 multiplier, and extract the high byte with <code>&gt;&gt;56</code>. So it doesn't take any extra steps, just wider constants. This is what GCC uses for <code>__builtin_popcountll</code> on x86 systems when the hardware <code>popcnt</code> instruction isn't enabled. If you can use builtins or intrinsics for this, do so to give the compiler a chance to do target-specific optimizations.</p>\n<hr />\n<h3>With full SIMD for wider vectors (e.g. counting a whole array)</h3>\n<p>This bitwise-SWAR algorithm could parallelize to be done in multiple vector elements at once, instead of in a single integer register, for a speedup on CPUs with SIMD but no usable popcount instruction. (e.g. x86-64 code that has to run on any CPU, not just Nehalem or later.)</p>\n<p>However, the best way to use vector instructions for popcount is usually by using a variable-shuffle to do a table-lookup for 4 bits at a time of each byte in parallel. (The 4 bits index a 16 entry table held in a vector register).</p>\n<p>On Intel CPUs, the hardware 64bit popcnt instruction can outperform an <a href=\"http://wm.ite.pl/articles/sse-popcount.html\" rel=\"nofollow noreferrer\">SSSE3 <code>PSHUFB</code> bit-parallel implementation</a> by about a factor of 2, but only <a href=\"http://danluu.com/assembly-intrinsics/\" rel=\"nofollow noreferrer\">if your compiler gets it just right</a>. Otherwise SSE can come out significantly ahead. Newer compiler versions are aware of the <a href=\"https://stackoverflow.com/a/25089720/224132\">popcnt false dependency</a> <a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011\" rel=\"nofollow noreferrer\">problem on Intel</a>.</p>\n<ul>\n<li><a href=\"https://github.com/WojciechMula/sse-popcount\" rel=\"nofollow noreferrer\">https://github.com/WojciechMula/sse-popcount</a> state-of-the-art x86 SIMD popcount for SSSE3, AVX2, AVX512BW, AVX512VBMI, or AVX512 VPOPCNT. Using Harley-Seal across vectors to defer popcount within an element. (Also ARM NEON)</li>\n<li><a href=\"https://stackoverflow.com/questions/50081465/counting-1-bits-population-count-on-large-data-using-avx-512-or-avx-2\">Counting 1 bits (population count) on large data using AVX-512 or AVX-2</a></li>\n<li>related: <a href=\"https://github.com/mklarqvist/positional-popcount\" rel=\"nofollow noreferrer\">https://github.com/mklarqvist/positional-popcount</a> - separate counts for each bit-position of multiple 8, 16, 32, or 64-bit integers. (Again, x86 SIMD including AVX-512 which is really good at this, with <code>vpternlogd</code> making Harley-Seal <em>very</em> good.)</li>\n</ul>\n" }, { "answer_id": 109045, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 5, "selected": false, "text": "<p>Why not iteratively divide by 2?</p>\n\n<pre>\ncount = 0\nwhile n > 0\n if (n % 2) == 1\n count += 1\n n /= 2 \n</pre>\n\n<p>I agree that this isn't the fastest, but \"best\" is somewhat ambiguous. I'd argue though that \"best\" should have an element of clarity</p>\n" }, { "answer_id": 109054, "author": "Noether", "author_id": 12210, "author_profile": "https://Stackoverflow.com/users/12210", "pm_score": 6, "selected": false, "text": "<p>If you happen to be using Java, the built-in method <code>Integer.bitCount</code> will do that.</p>\n" }, { "answer_id": 109069, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 8, "selected": false, "text": "<p>Some languages portably expose the operation in a way that <em>can</em> use efficient hardware support if available, otherwise some library fallback that's hopefully decent.</p>\n<p>For example (from <a href=\"https://en.wikichip.org/wiki/population_count#Software_support\" rel=\"noreferrer\">a table by language</a>):</p>\n<ul>\n<li>C++ has <code>std::bitset&lt;&gt;::count()</code>, or <a href=\"https://en.cppreference.com/w/cpp/numeric/popcount\" rel=\"noreferrer\">C++20 <code>std::popcount(T x)</code></a></li>\n<li>Java has <code>java.lang.Integer.bitCount()</code> (also for Long or BigInteger)</li>\n<li>C# has <code>System.Numerics.BitOperations.PopCount()</code></li>\n<li>Python has <code>int.bit_count()</code> (since 3.10)</li>\n</ul>\n<p>Not all compilers / libraries actually manage to use HW support when it's available, though. (Notably MSVC, even with options that make std::popcount inline as x86 popcnt, its std::bitset::count still always uses a lookup table. This will hopefully change in future versions.)</p>\n<p>Also consider the built-in functions of your compiler when the portable language doesn't have this basic bit operation. In GNU C for example:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>int __builtin_popcount (unsigned int x);\nint __builtin_popcountll (unsigned long long x);\n</code></pre>\n<p>In the worst case (no single-instruction HW support) the compiler will generate a call to a function (which in current GCC uses a shift/and bit-hack <a href=\"https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#109025\">like this answer</a>, at least for x86). In the best case the compiler will emit a cpu instruction to do the job. (Just like a <code>*</code> or <code>/</code> operator - GCC will use a hardware multiply or divide instruction if available, otherwise will call a libgcc helper function.) Or even better, if the operand is a compile-time constant after inlining, it can do constant-propagation to get a compile-time-constant popcount result.</p>\n<p>The GCC builtins even work across multiple platforms. Popcount has almost become mainstream in the x86 architecture, so it makes sense to start using the builtin now so you can recompile to let it inline a hardware instruction when you compile with <code>-mpopcnt</code> or something that includes that (e.g. <a href=\"https://godbolt.org/z/Ma5e5a\" rel=\"noreferrer\">https://godbolt.org/z/Ma5e5a</a>). Other architectures have had popcount for years, but in the x86 world there are still some ancient Core 2 and similar vintage AMD CPUs in use.</p>\n<hr />\n<p>On x86, you can tell the compiler that it can assume support for <code>popcnt</code> instruction with <code>-mpopcnt</code> (also implied by <code>-msse4.2</code>). See <a href=\"https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html\" rel=\"noreferrer\">GCC x86 options</a>. <code>-march=nehalem -mtune=skylake</code> (or <code>-march=</code> whatever CPU you want your code to assume and to tune for) could be a good choice. Running the resulting binary on an older CPU will result in an illegal-instruction fault.</p>\n<p>To make binaries optimized for the machine you build them on, <strong>use <code>-march=native</code></strong> (with gcc, clang, or ICC).</p>\n<p><a href=\"https://stackoverflow.com/questions/3849337/msvc-equivalent-to-builtin-popcount\">MSVC provides an intrinsic for the x86 <code>popcnt</code> instruction</a>, but unlike gcc it's really an intrinsic for the hardware instruction and requires hardware support.</p>\n<hr />\n<h2>Using <code>std::bitset&lt;&gt;::count()</code> instead of a built-in</h2>\n<p>In theory, any compiler that knows how to popcount efficiently for the target CPU should expose that functionality through ISO C++ <a href=\"http://en.cppreference.com/w/cpp/utility/bitset/count\" rel=\"noreferrer\"><code>std::bitset&lt;&gt;</code></a>. In practice, you might be better off with the bit-hack AND/shift/ADD in some cases for some target CPUs.</p>\n<p>For target architectures where hardware popcount is an optional extension (like x86), not all compilers have a <code>std::bitset</code> that takes advantage of it when available. For example, MSVC has no way to enable <code>popcnt</code> support at compile time, and it's <code>std::bitset&lt;&gt;::count</code> always uses <a href=\"https://stackoverflow.com/questions/12324081/how-does-this-implementation-of-bitsetcount-work\">a table lookup</a>, even with <code>/Ox /arch:AVX</code> (which implies SSE4.2, which in turn implies the popcnt feature.) (Update: see below; that <em>does</em> get MSVC's C++20 <code>std::popcount</code> to use x86 <code>popcnt</code>, but still not its bitset&lt;&gt;::count. MSVC could fix that by updating their standard library headers to use std::popcount when available.)</p>\n<p>But at least you get something portable that works everywhere, and with gcc/clang with the right target options, you get hardware popcount for architectures that support it.</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;bitset&gt;\n#include &lt;limits&gt;\n#include &lt;type_traits&gt;\n\ntemplate&lt;typename T&gt;\n//static inline // static if you want to compile with -mpopcnt in one compilation unit but not others\ntypename std::enable_if&lt;std::is_integral&lt;T&gt;::value, unsigned &gt;::type \npopcount(T x)\n{\n static_assert(std::numeric_limits&lt;T&gt;::radix == 2, &quot;non-binary type&quot;);\n\n // sizeof(x)*CHAR_BIT\n constexpr int bitwidth = std::numeric_limits&lt;T&gt;::digits + std::numeric_limits&lt;T&gt;::is_signed;\n // std::bitset constructor was only unsigned long before C++11. Beware if porting to C++03\n static_assert(bitwidth &lt;= std::numeric_limits&lt;unsigned long long&gt;::digits, &quot;arg too wide for std::bitset() constructor&quot;);\n\n typedef typename std::make_unsigned&lt;T&gt;::type UT; // probably not needed, bitset width chops after sign-extension\n\n std::bitset&lt;bitwidth&gt; bs( static_cast&lt;UT&gt;(x) );\n return bs.count();\n}\n</code></pre>\n<p>See <a href=\"https://gcc.godbolt.org/#z:OYLghAFBqd5TKALEBjA9gEwKYFFMCWALugE4A0BIEAViAIzkDO6ArqatiAOQCkATAGYCAO1QAbVjgDUvQQGEARsSbYic3LwAMAQQHCxkmXPniCAWxUbteoaIlTsshUQCeAB2wB9IqQCGVoKaugD0IdIAqqrSREhOSOieAGas4uKuALTA6FjSTESYICDKRKpERRisIkQQAJTSFu7i2ObY1X5EBOgi0klk0n6kJf6krg3V2MDYpDEe2Ew2YdI6AG7oBJhMeQTAIhnYAB5EbYQiwNu72Jizngu6i%2BEA8j3AqKgDItcSfmfk0tgAR1YBBWfma1Ri6GkXi8imB4k6Ii87kSlWqaTqD2kmHQAHcREwNlwBuJcX5XFtWKotgA2AAsGRK0kS0x%2BmAyhIAXk4IN1pPTGcRpPIAApRWpYgBiZE4W25pHQ%2ByObUJfJI/IZJQAdFidOIWHlxHjptJccQEqwiNIkINMGTSE4Ue40UQ/vNPKgCGD0qbzQMYn5FM0Mkb0ABrVjuaSh9w60JPHoHAAcNL%2BuLI0ViCtYwCQ7ktzJ6OgAsgARaQAIVS4hx8oyST8lh9sR%2B0kE/EFVqdqGquv1ULJ%2BXm/oASrgABrSdwOpIEA5xvS6Y7mJodbAmNyeESNpwAFWs8fyHQI71EZhETmkSyPnVPSWkrjYpp%2BVvVGBXBGavti0gyK9REKiIWTjvu4n7HnyVRCnCVoiOgVrwXEpB3Dom5tDueQFEU6FBt4BBJCY%2BSFCABBMF4ojHMA/jiCY%2B5BEUoKSNgfzSFUhKXNcGhFGhsi6N2bDVBAu7SAcEr3AA7BWNjaAAnDeJ5eH4TCqKQNREUUIisK0pAKWYlilLRXEgP4hAHM4pZyOW/B/AI/BwXsyjbqMNzrvw/ASoIUn3N5MnXgQ3LoEkECiQAVPIAASOgjl4FYAJL7j5GAEscBzTuMVolGamA/pZmHEZp2m6RYgTyHRuBFIQwAqLI/AVnlGladMRX6QsChlUUpFeOxF6YHIXmLr54TqcUKhqNISX5KQrCoCQMyDoWPpsTsPXRt05yKNgfQOsKAhSbV9D0Fq0iVtg9pOPhU5kIi5zqvIu27Vogg2Mdx3yaginKdMNSZRsOUKLlw0FU1716SVS0catZyQ8ARmVSoNluYMN05L6MhbfVI2lGodTjd0k3TbNtkef10laDJaE4PeaHbq0GPmH4YbeODPWGfRIA8REdF1S9PNLNO6CKIGPpwbB2BXFcfwlGUqM/qgCTuFsfhJMcMzdUqxwEl0Iik3JWGY2UJg/dlSAaNIihMBAmHHu9qBKeoCicxowX1MTOsOkQ7A9ObWoupinnSeJFneYuOjM1cMTzEQyKogJUdMAkqkQPHV0DPUvCSdI7ue5dzqxxAfjE7Igc2GH1zHPk0e51UUcURAFGp0XdVZ6QPT8dX%2BeF%2BnQc6GEpcRxXbfVF4pcQH3BeN5najZ4PNQF31Rfd335dRzP9IQEaUMb%2Bc4/p03U8tznvtz55C9YjhzTkfe%2BSJFssSkb0CrmLjH7nsj/o4qwuEZBofdJSs0yqm1vGJekdK7vQ/rhCAECvw7wzs3VuMd27Hzql3UmId659HQEnBOVo/B/C3tDM2adJJu33j0HWh8847x8rtSh7dFCu10C9PqAdu5oKWDCCi9B%2BBJgaFsLKJoWw9D7gQre0k7D3noDVGkAgaTYk2qIK4EAYQAGVYoAC1cCPElF4WKAA5Xc3CkwwjEj3cIsQnBvQ%2BipK018FYxCQPfJIj9n5gVftICA6pug%2BhdA4pwRpcTWjBEkUxvdNYQ2XmA2ORjlHkWqEYhuu9J4ewPjPDu89UHByWLuRxWwbSoDDKaMgYYth8leKgEI3wzggAGMpRqZtRpWnvmCMkFJejiA6NIVo5gyCuBAM9F6SxYrRk2q%2BXJzICyBT8RHFcHTjhm2wLbKk50iBgG4FsEWl1VJC3XD5MI%2BEk7%2BWwIFZ2zhcDbACkFERa1oa1DTns8IL1umoHcK4CAsjzYIxpAcP4XJjlBXNnclhwd9D2CME4EwqBJqiBhkEEu4SVr5LDFE6uMTOHxJ4YkkhPlhpSzUCYIxptzbpP9j5Z5rz3n8BpJ86ReCLn/IgICwuV5wj2hEDCmpGBXkwo%2BMyRQNBFkIXvPZDIvgQRenEC5DxZofww1qrtUxsl4FmyYD7POjC9DF3uEIE4%2BEbDcFqOQcQPAACs3ByAiB4Foc16AeB3XlbVPIbAOAQqEPQc15RuDWrueQMMIBBBJi1FoGk4lxL0BkgGmkSYkxaC0HSI1PA6TmvMCAcSWgtT0BpDSdsWhM3Zv4Lm1MlqvU2p4OapgIAtDkE9d68gcBYAoFAp%2BaYlBqBNuaKQEA7hnT0maMAbNVbZwIgAdQRQVrzXvlaNUZ46Rx3kEIA6GaIJ5hzootgY1JbDVmHNvAQ1iROh4x4BkAA6t6X8jxBC/iIpZXYrB7r7XdcwZ1nAGBbtNea4t1ryC2u4CKY0pARTyA1PyLUggg0ePwMQfo%2BhGDCnQC/E0MHagevHT6uIfgcCdrqAm7gSbyApv4DJLUSZBCCBDTJEjZHxIUYDRaudP7y2Vurahw1fqA1BpDWGiNKZo2xvjRuwQH76NluY5uutiB63IDQPBtxLaqAQHbdMNAHSzhkZ%2BUOlWFbGVzsnW0IgM6%2BklvnQQRdnR/4VqM2ujdtbt0VsgHu9wB6CRHuvYIUst770VgOlego27LLbtQJ538p60jnsvX%2BbsEI/yDDlpZG0TBcTrvEOW59XBGBkmnY52KIg%2Bg8HdW%2B7gZq6NGZ/cmGkGR6TjRU%2BcMDciICQdmjVQQsH5AyebTMfQghkOie9Ya9DmHqCsf9YGmSdIkwmpkuJJMdITUxqozhvDKbSPEfoLm3NMkZLcJNVNmSxWv0MeYExmtBrxPwAgI2trHbW0Kcu0p4AdJRvkA0yO2JXgtCDfIGOozunp0iFnUZhdgrl0Wa/VZudNAgTTEM2B/gGbzXgmALEBg5BpzYBWI8flgrqAwje9QLknJmj0BNcG4Nm2TV0jG4IagVRKaKMKOvSYJx4D0HEoINNu2q3cHy3crdbREcoEYKj9HmOZrY5hO92gABFVgUP2yrZI4RmSNJHoza0MTjbJr6DUEIEwVchmTv48J8T5XNIycU5I9Tz4CierUD7UzyALO2dk3IJz7nPqEdI/oDzo1BAd32e/Y5rWFmT1noyBenzvU3MeYdV5qREWAJWmixwE2bn4uJbSCl9gL6vc4aK5%2B0t3AysVbpNIcp0g6RaiIyX%2BrhBGswb%2BK1hDHWhAmu68d93ibk3%2BpNcRmkE2c1K7I3SAtJq9sF8Y1W9vp2G3Sab9dxTnaTyoBZ09z8mmxe4%2Bw19r9P39N/cM1%2BwHS7zOromNZ81EOZejB4DDuHRq%2Bee5Rw6YXArRevYl4b7AROSem6J%2Bbqno8Vus4NuDOUwnwzO4kBaq2Lu5AXOBq3uHuAuT%2BaOGOr%2B5Q7%2B1ANA0usu/A8u7YG2yuggqu6uMkmu2upEeuZahqn%2B3%2BJuZulOlutOIBdu4BDukBa2MBcBPOvOZwnuCBvudm2G%2B6QeR6IWkqYe4Wrm7mmknm3m8ezoUW9Myelk24Zm2AmeLqr6ueQmJWPARelWS%2B0gLOEGte0GbqDet2zeRBbeLG5A/WSm2GG6i2/q6a7YggSuE23CbO1GY%2B36ImFak%2BthbGYGY2fej0SYrO/AkBYaOGgmvhB2U%2Bkm52s%2BsmFA8mC%2Bym4aXg9Iq%2Bw6yEo6Om8GU6e%2B/2h%2BJmQOJ%2BlmZ%2BqGPufuQhgeh63AIQjwZkIQMWKAOgAAauOBodnuQBlvplljlj%2BvltofEXoSmMXsKAADJGEyTSBQHiTSAji7jHomFQZWEtaWFNbuQoabpDY8JagU7bbiQhruHTaQF94LY6H7b%2BFHa2Ebr8Bd6rZVr55%2BHcB7G9bkD/zIRawgB0hAA%3D\" rel=\"noreferrer\">asm from gcc, clang, icc, and MSVC</a> on the Godbolt compiler explorer.</p>\n<p>x86-64 <code>gcc -O3 -std=gnu++11 -mpopcnt</code> emits this:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>unsigned test_short(short a) { return popcount(a); }\n movzx eax, di # note zero-extension, not sign-extension\n popcnt rax, rax\n ret\n\nunsigned test_int(int a) { return popcount(a); }\n mov eax, edi\n popcnt rax, rax # unnecessary 64-bit operand size\n ret\n\nunsigned test_u64(unsigned long long a) { return popcount(a); }\n xor eax, eax # gcc avoids false dependencies for Intel CPUs\n popcnt rax, rdi\n ret\n</code></pre>\n<p>PowerPC64 <code>gcc -O3 -std=gnu++11</code> emits (for the <code>int</code> arg version):</p>\n<pre class=\"lang-c++ prettyprint-override\"><code> rldicl 3,3,0,32 # zero-extend from 32 to 64-bit\n popcntd 3,3 # popcount\n blr\n</code></pre>\n<p>This source isn't x86-specific or GNU-specific at all, but only compiles well with gcc/clang/icc, at least when targeting x86 (including x86-64).</p>\n<p>Also note that gcc's fallback for architectures without single-instruction popcount is a byte-at-a-time table lookup. This isn't wonderful <a href=\"https://stackoverflow.com/questions/15736602/fastest-way-to-count-number-of-1s-in-a-register-arm-assembly\">for ARM, for example</a>.</p>\n<h2><a href=\"https://en.cppreference.com/w/cpp/numeric/popcount\" rel=\"noreferrer\">C++20 has <code>std::popcount(T)</code></a></h2>\n<p>Current libstdc++ headers unfortunately define it with a special case <code>if(x==0) return 0;</code> at the start, which clang doesn't optimize away when compiling for x86:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>#include &lt;bit&gt;\nint bar(unsigned x) {\n return std::popcount(x);\n}\n</code></pre>\n<p>clang 11.0.1 <code>-O3 -std=gnu++20 -march=nehalem</code> (<a href=\"https://godbolt.org/z/arMe5a\" rel=\"noreferrer\">https://godbolt.org/z/arMe5a</a>)</p>\n<pre class=\"lang-c++ prettyprint-override\"><code># clang 11\n bar(unsigned int): # @bar(unsigned int)\n popcnt eax, edi\n cmove eax, edi # redundant: if popcnt result is 0, return the original 0 instead of the popcnt-generated 0...\n ret\n</code></pre>\n<p>But GCC compiles nicely:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code># gcc 10\n xor eax, eax # break false dependency on Intel SnB-family before Ice Lake.\n popcnt eax, edi\n ret\n</code></pre>\n<p>Even MSVC does well with it, as long as you use <code>-arch:AVX</code> or later (and enable C++20 with <code>-std:c++latest</code>). <a href=\"https://godbolt.org/z/7K4Gef\" rel=\"noreferrer\">https://godbolt.org/z/7K4Gef</a></p>\n<pre class=\"lang-c++ prettyprint-override\"><code>int bar(unsigned int) PROC ; bar, COMDAT\n popcnt eax, ecx\n ret 0\nint bar(unsigned int) ENDP ; bar\n</code></pre>\n" }, { "answer_id": 109093, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 3, "selected": false, "text": "<p>What do you means with \"Best algorithm\"? The shorted code or the fasted code? Your code look very elegant and it has a constant execution time. The code is also very short.</p>\n\n<p>But if the speed is the major factor and not the code size then I think the follow can be faster:</p>\n\n<pre><code> static final int[] BIT_COUNT = { 0, 1, 1, ... 256 values with a bitsize of a byte ... };\n static int bitCountOfByte( int value ){\n return BIT_COUNT[ value &amp; 0xFF ];\n }\n\n static int bitCountOfInt( int value ){\n return bitCountOfByte( value ) \n + bitCountOfByte( value &gt;&gt; 8 ) \n + bitCountOfByte( value &gt;&gt; 16 ) \n + bitCountOfByte( value &gt;&gt; 24 );\n }\n</code></pre>\n\n<p>I think that this will not more faster for a 64 bit value but a 32 bit value can be faster.</p>\n" }, { "answer_id": 109117, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://books.google.com/books?id=iBNKMspIlqEC&amp;pg=PA66\" rel=\"noreferrer\">From Hacker's Delight, p. 66, Figure 5-2</a></p>\n\n<pre><code>int pop(unsigned x)\n{\n x = x - ((x &gt;&gt; 1) &amp; 0x55555555);\n x = (x &amp; 0x33333333) + ((x &gt;&gt; 2) &amp; 0x33333333);\n x = (x + (x &gt;&gt; 4)) &amp; 0x0F0F0F0F;\n x = x + (x &gt;&gt; 8);\n x = x + (x &gt;&gt; 16);\n return x &amp; 0x0000003F;\n}\n</code></pre>\n\n<p>Executes in ~20-ish instructions (arch dependent), no branching.<br><br><a href=\"http://books.google.com/books?id=iBNKMspIlqEC\" rel=\"noreferrer\">Hacker's Delight</a> <em>is</em> delightful! Highly recommended.</p>\n" }, { "answer_id": 109915, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 8, "selected": false, "text": "<p>In my opinion, the &quot;best&quot; solution is the one that can be read by another programmer (or the original programmer two years later) without copious comments. You may well want the fastest or cleverest solution which some have already provided but I prefer readability over cleverness any time.</p>\n<pre><code>unsigned int bitCount (unsigned int value) {\n unsigned int count = 0;\n while (value &gt; 0) { // until all bits are zero\n if ((value &amp; 1) == 1) // check lower bit\n count++;\n value &gt;&gt;= 1; // shift bits, removing lower bit\n }\n return count;\n}\n</code></pre>\n<p>If you want more speed (and assuming you document it well to help out your successors), you could use a table lookup:</p>\n<pre><code>// Lookup table for fast calculation of bits set in 8-bit unsigned char.\n\nstatic unsigned char oneBitsInUChar[] = {\n// 0 1 2 3 4 5 6 7 8 9 A B C D E F (&lt;- n)\n// =====================================================\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 0n\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1n\n : : :\n 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, // Fn\n};\n\n// Function for fast calculation of bits set in 16-bit unsigned short.\n\nunsigned char oneBitsInUShort (unsigned short x) {\n return oneBitsInUChar [x &gt;&gt; 8]\n + oneBitsInUChar [x &amp; 0xff];\n}\n\n// Function for fast calculation of bits set in 32-bit unsigned int.\n\nunsigned char oneBitsInUInt (unsigned int x) {\n return oneBitsInUShort (x &gt;&gt; 16)\n + oneBitsInUShort (x &amp; 0xffff);\n}\n</code></pre>\n<p>These rely on specific data type sizes so they're not that portable. But, since many performance optimisations aren't portable anyway, that may not be an issue. If you want portability, I'd stick to the readable solution.</p>\n" }, { "answer_id": 113098, "author": "PhirePhly", "author_id": 20082, "author_profile": "https://Stackoverflow.com/users/20082", "pm_score": 5, "selected": false, "text": "<p>For a happy medium between a 2<sup>32</sup> lookup table and iterating through each bit individually:</p>\n\n<pre><code>int bitcount(unsigned int num){\n int count = 0;\n static int nibblebits[] =\n {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};\n for(; num != 0; num &gt;&gt;= 4)\n count += nibblebits[num &amp; 0x0f];\n return count;\n}\n</code></pre>\n\n<p>From <a href=\"http://ctips.pbwiki.com/CountBits\" rel=\"noreferrer\">http://ctips.pbwiki.com/CountBits</a></p>\n" }, { "answer_id": 118631, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I'm particularly fond of this example from the fortune file:</p>\n\n<pre>\n#define BITCOUNT(x) (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)\n#define BX_(x) ((x) - (((x)>>1)&0x77777777)\n - (((x)>>2)&0x33333333)\n - (((x)>>3)&0x11111111))\n</pre>\n\n<p>I like it best because it's so pretty!</p>\n" }, { "answer_id": 120019, "author": "Michael Dorfman", "author_id": 6741, "author_profile": "https://Stackoverflow.com/users/6741", "pm_score": 3, "selected": false, "text": "<p>The function you are looking for is often called the \"sideways sum\" or \"population count\" of a binary number. Knuth discusses it in pre-Fascicle 1A, pp11-12 (although there was a brief reference in Volume 2, 4.6.3-(7).)</p>\n\n<p>The <em>locus classicus</em> is Peter Wegner's article \"A Technique for Counting Ones in a Binary Computer\", from the <a href=\"http://cacm.acm.org/magazines/1960/5/14709-a-technique-for-counting-ones-in-a-binary-computer/abstract\" rel=\"nofollow noreferrer\"><em>Communications of the ACM</em>, Volume 3 (1960) Number 5, page 322</a>. He gives two different algorithms there, one optimized for numbers expected to be \"sparse\" (i.e., have a small number of ones) and one for the opposite case.</p>\n" }, { "answer_id": 131212, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>I got bored, and timed a billion iterations of three approaches. Compiler is gcc -O3. CPU is whatever they put in the 1st gen Macbook Pro.</p>\n\n<p>Fastest is the following, at 3.7 seconds:</p>\n\n<pre><code>static unsigned char wordbits[65536] = { bitcounts of ints between 0 and 65535 };\nstatic int popcount( unsigned int i )\n{\n return( wordbits[i&amp;0xFFFF] + wordbits[i&gt;&gt;16] );\n}\n</code></pre>\n\n<p>Second place goes to the same code but looking up 4 bytes instead of 2 halfwords. That took around 5.5 seconds.</p>\n\n<p>Third place goes to the bit-twiddling 'sideways addition' approach, which took 8.6 seconds.</p>\n\n<p>Fourth place goes to GCC's __builtin_popcount(), at a shameful 11 seconds.</p>\n\n<p>The counting one-bit-at-a-time approach was waaaay slower, and I got bored of waiting for it to complete.</p>\n\n<p>So if you care about performance above all else then use the first approach. If you care, but not enough to spend 64Kb of RAM on it, use the second approach. Otherwise use the readable (but slow) one-bit-at-a-time approach.</p>\n\n<p>It's hard to think of a situation where you'd want to use the bit-twiddling approach.</p>\n\n<p>Edit: Similar results <a href=\"http://www.dalkescientific.com/writings/diary/archive/2008/07/03/hakmem_and_other_popcounts.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 1511920, "author": "user183351", "author_id": 183351, "author_profile": "https://Stackoverflow.com/users/183351", "pm_score": 5, "selected": false, "text": "<p>This is one of those questions where it helps to know your micro-architecture. I just timed two variants under gcc 4.3.3 compiled with -O3 using C++ inlines to eliminate function call overhead, one billion iterations, keeping the running sum of all counts to ensure the compiler doesn't remove anything important, using rdtsc for timing (clock cycle precise). </p>\n\n<pre>\ninline int pop2(unsigned x, unsigned y)\n{\n x = x - ((x >> 1) & 0x55555555);\n y = y - ((y >> 1) & 0x55555555);\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333);\n y = (y & 0x33333333) + ((y >> 2) & 0x33333333);\n x = (x + (x >> 4)) & 0x0F0F0F0F;\n y = (y + (y >> 4)) & 0x0F0F0F0F;\n x = x + (x >> 8);\n y = y + (y >> 8);\n x = x + (x >> 16);\n y = y + (y >> 16);\n return (x+y) & 0x000000FF;\n}\n</pre> \n\n<p>The unmodified Hacker's Delight took 12.2 gigacycles. My parallel version (counting twice as many bits) runs in 13.0 gigacycles. 10.5s total elapsed for both together on a 2.4GHz Core Duo. 25 gigacycles = just over 10 seconds at this clock frequency, so I'm confident my timings are right. </p>\n\n<p>This has to do with instruction dependency chains, which are very bad for this algorithm. I could nearly double the speed again by using a pair of 64-bit registers. In fact, if I was clever and added x+y a little sooner I could shave off some shifts. The 64-bit version with some small tweaks would come out about even, but count twice as many bits again. </p>\n\n<p>With 128 bit SIMD registers, yet another factor of two, and the SSE instruction sets often have clever short-cuts, too. </p>\n\n<p>There's no reason for the code to be especially transparent. The interface is simple, the algorithm can be referenced on-line in many places, and it's amenable to comprehensive unit test. The programmer who stumbles upon it might even learn something. These bit operations are extremely natural at the machine level. </p>\n\n<p>OK, I decided to bench the tweaked 64-bit version. For this one sizeof(unsigned long) == 8 </p>\n\n<pre>\ninline int pop2(unsigned long x, unsigned long y)\n{\n x = x - ((x >> 1) & 0x5555555555555555);\n y = y - ((y >> 1) & 0x5555555555555555);\n x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);\n y = (y & 0x3333333333333333) + ((y >> 2) & 0x3333333333333333);\n x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F;\n y = (y + (y >> 4)) & 0x0F0F0F0F0F0F0F0F;\n x = x + y; \n x = x + (x >> 8);\n x = x + (x >> 16);\n x = x + (x >> 32); \n return x & 0xFF;\n}\n</pre> \n\n<p>That looks about right (I'm not testing carefully, though). Now the timings come out at 10.70 gigacycles / 14.1 gigacycles. That later number summed 128 billion bits and corresponds to 5.9s elapsed on this machine. The non-parallel version speeds up a tiny bit because I'm running in 64-bit mode and it likes 64-bit registers slightly better than 32-bit registers. </p>\n\n<p>Let's see if there's a bit more OOO pipelining to be had here. This was a bit more involved, so I actually tested a bit. Each term alone sums to 64, all combined sum to 256. </p>\n\n<pre>\ninline int pop4(unsigned long x, unsigned long y, \n unsigned long u, unsigned long v)\n{\n enum { m1 = 0x5555555555555555, \n m2 = 0x3333333333333333, \n m3 = 0x0F0F0F0F0F0F0F0F, \n m4 = 0x000000FF000000FF };\n\n x = x - ((x >> 1) & m1);\n y = y - ((y >> 1) & m1);\n u = u - ((u >> 1) & m1);\n v = v - ((v >> 1) & m1);\n x = (x & m2) + ((x >> 2) & m2);\n y = (y & m2) + ((y >> 2) & m2);\n u = (u & m2) + ((u >> 2) & m2);\n v = (v & m2) + ((v >> 2) & m2);\n x = x + y; \n u = u + v; \n x = (x & m3) + ((x >> 4) & m3);\n u = (u & m3) + ((u >> 4) & m3);\n x = x + u; \n x = x + (x >> 8);\n x = x + (x >> 16);\n x = x & m4; \n x = x + (x >> 32);\n return x & 0x000001FF;\n}\n</pre>\n\n<p>I was excited for a moment, but it turns out gcc is playing inline tricks with -O3 even though I'm not using the inline keyword in some tests. When I let gcc play tricks, a billion calls to pop4() takes 12.56 gigacycles, but I determined it was folding arguments as constant expressions. A more realistic number appears to be 19.6gc for another 30% speed-up. My test loop now looks like this, making sure each argument is different enough to stop gcc from playing tricks. </p>\n\n<pre>\n hitime b4 = rdtsc(); \n for (unsigned long i = 10L * 1000*1000*1000; i &lt; 11L * 1000*1000*1000; ++i) \n sum += pop4 (i, i^1, ~i, i|1); \n hitime e4 = rdtsc(); \n</pre>\n\n<p>256 billion bits summed in 8.17s elapsed. Works out to 1.02s for 32 million bits as benchmarked in the 16-bit table lookup. Can't compare directly, because the other bench doesn't give a clock speed, but looks like I've slapped the snot out of the 64KB table edition, which is a tragic use of L1 cache in the first place. </p>\n\n<p>Update: decided to do the obvious and create pop6() by adding four more duplicated lines. Came out to 22.8gc, 384 billion bits summed in 9.5s elapsed. So there's another 20% Now at 800ms for 32 billion bits. </p>\n" }, { "answer_id": 2786288, "author": "Baban", "author_id": 335085, "author_profile": "https://Stackoverflow.com/users/335085", "pm_score": 3, "selected": false, "text": "<p>Few open questions:-</p>\n\n<ol>\n<li>If the number is negative then?</li>\n<li>If the number is 1024 , then the \"iteratively divide by 2\" method will iterate 10 times.</li>\n</ol>\n\n<p>we can modify the algo to support the negative number as follows:-</p>\n\n<pre><code>count = 0\nwhile n != 0\nif ((n % 2) == 1 || (n % 2) == -1\n count += 1\n n /= 2 \nreturn count\n</code></pre>\n\n<p>now to overcome the second problem we can write the algo like:-</p>\n\n<pre><code>int bit_count(int num)\n{\n int count=0;\n while(num)\n {\n num=(num)&amp;(num-1);\n count++;\n }\n return count;\n}\n</code></pre>\n\n<p>for complete reference see :</p>\n\n<p><a href=\"http://goursaha.freeoda.com/Miscellaneous/IntegerBitCount.html\" rel=\"noreferrer\">http://goursaha.freeoda.com/Miscellaneous/IntegerBitCount.html</a></p>\n" }, { "answer_id": 2953644, "author": "Matthew Mitchell", "author_id": 238411, "author_profile": "https://Stackoverflow.com/users/238411", "pm_score": 0, "selected": false, "text": "<p>A simple way which should work nicely for a small amount of bits it something like this (For 4 bits in this example):</p>\n\n<p>(i &amp; 1) + (i &amp; 2)/2 + (i &amp; 4)/4 + (i &amp; 8)/8</p>\n\n<p>Would others recommend this for a small number of bits as a simple solution?</p>\n" }, { "answer_id": 3026418, "author": "systemBuilder", "author_id": 364891, "author_profile": "https://Stackoverflow.com/users/364891", "pm_score": 3, "selected": false, "text": "<p>I wrote a fast bitcount macro for RISC machines in about 1990. It does not use advanced arithmetic (multiplication, division, %), memory fetches (way too slow), branches (way too slow), but it does assume the CPU has a 32-bit barrel shifter (in other words, >> 1 and >> 32 take the same amount of cycles.) It assumes that small constants (such as 6, 12, 24) cost nothing to load into the registers, or are stored in temporaries and reused over and over again.</p>\n\n<p>With these assumptions, it counts 32 bits in about 16 cycles/instructions on most RISC machines. Note that 15 instructions/cycles is close to a lower bound on the number of cycles or instructions, because it seems to take at least 3 instructions (mask, shift, operator) to cut the number of addends in half, so log_2(32) = 5, 5 x 3 = 15 instructions is a quasi-lowerbound.</p>\n\n<pre><code>#define BitCount(X,Y) \\\n Y = X - ((X &gt;&gt; 1) &amp; 033333333333) - ((X &gt;&gt; 2) &amp; 011111111111); \\\n Y = ((Y + (Y &gt;&gt; 3)) &amp; 030707070707); \\\n Y = (Y + (Y &gt;&gt; 6)); \\\n Y = (Y + (Y &gt;&gt; 12) + (Y &gt;&gt; 24)) &amp; 077;\n</code></pre>\n\n<p>Here is a secret to the first and most complex step:</p>\n\n<pre><code>input output\nAB CD Note\n00 00 = AB\n01 01 = AB\n10 01 = AB - (A &gt;&gt; 1) &amp; 0x1\n11 10 = AB - (A &gt;&gt; 1) &amp; 0x1\n</code></pre>\n\n<p>so if I take the 1st column (A) above, shift it right 1 bit, and subtract it from AB, I get the output (CD). The extension to 3 bits is similar; you can check it with an 8-row boolean table like mine above if you wish.</p>\n\n<ul>\n<li>Don Gillies</li>\n</ul>\n" }, { "answer_id": 4413115, "author": "Rahul", "author_id": 538356, "author_profile": "https://Stackoverflow.com/users/538356", "pm_score": 3, "selected": false, "text": "<p>Java JDK1.5</p>\n\n<p>Integer.bitCount(n);</p>\n\n<p>where n is the number whose 1's are to be counted.</p>\n\n<p>check also,</p>\n\n<pre><code>Integer.highestOneBit(n);\nInteger.lowestOneBit(n);\nInteger.numberOfLeadingZeros(n);\nInteger.numberOfTrailingZeros(n);\n\n//Beginning with the value 1, rotate left 16 times\n n = 1;\n for (int i = 0; i &lt; 16; i++) {\n n = Integer.rotateLeft(n, 1);\n System.out.println(n);\n }\n</code></pre>\n" }, { "answer_id": 5469563, "author": "Robert S. Barnes", "author_id": 71074, "author_profile": "https://Stackoverflow.com/users/71074", "pm_score": 3, "selected": false, "text": "<p>Here is a portable module ( ANSI-C ) which can benchmark each of your algorithms on any architecture. </p>\n\n<p>Your CPU has 9 bit bytes? No problem :-) At the moment it implements 2 algorithms, the K&amp;R algorithm and a byte wise lookup table. The lookup table is on average 3 times faster than the K&amp;R algorithm. If someone can figure a way to make the \"Hacker's Delight\" algorithm portable feel free to add it in.</p>\n\n<pre><code>#ifndef _BITCOUNT_H_\n#define _BITCOUNT_H_\n\n/* Return the Hamming Wieght of val, i.e. the number of 'on' bits. */\nint bitcount( unsigned int );\n\n/* List of available bitcount algorithms. \n * onTheFly: Calculate the bitcount on demand.\n *\n * lookupTalbe: Uses a small lookup table to determine the bitcount. This\n * method is on average 3 times as fast as onTheFly, but incurs a small\n * upfront cost to initialize the lookup table on the first call.\n *\n * strategyCount is just a placeholder. \n */\nenum strategy { onTheFly, lookupTable, strategyCount };\n\n/* String represenations of the algorithm names */\nextern const char *strategyNames[];\n\n/* Choose which bitcount algorithm to use. */\nvoid setStrategy( enum strategy );\n\n#endif\n</code></pre>\n\n<p>.</p>\n\n<pre><code>#include &lt;limits.h&gt;\n\n#include \"bitcount.h\"\n\n/* The number of entries needed in the table is equal to the number of unique\n * values a char can represent which is always UCHAR_MAX + 1*/\nstatic unsigned char _bitCountTable[UCHAR_MAX + 1];\nstatic unsigned int _lookupTableInitialized = 0;\n\nstatic int _defaultBitCount( unsigned int val ) {\n int count;\n\n /* Starting with:\n * 1100 - 1 == 1011, 1100 &amp; 1011 == 1000\n * 1000 - 1 == 0111, 1000 &amp; 0111 == 0000\n */\n for ( count = 0; val; ++count )\n val &amp;= val - 1;\n\n return count;\n}\n\n/* Looks up each byte of the integer in a lookup table.\n *\n * The first time the function is called it initializes the lookup table.\n */\nstatic int _tableBitCount( unsigned int val ) {\n int bCount = 0;\n\n if ( !_lookupTableInitialized ) {\n unsigned int i;\n for ( i = 0; i != UCHAR_MAX + 1; ++i )\n _bitCountTable[i] =\n ( unsigned char )_defaultBitCount( i );\n\n _lookupTableInitialized = 1;\n }\n\n for ( ; val; val &gt;&gt;= CHAR_BIT )\n bCount += _bitCountTable[val &amp; UCHAR_MAX];\n\n return bCount;\n}\n\nstatic int ( *_bitcount ) ( unsigned int ) = _defaultBitCount;\n\nconst char *strategyNames[] = { \"onTheFly\", \"lookupTable\" };\n\nvoid setStrategy( enum strategy s ) {\n switch ( s ) {\n case onTheFly:\n _bitcount = _defaultBitCount;\n break;\n case lookupTable:\n _bitcount = _tableBitCount;\n break;\n case strategyCount:\n break;\n }\n}\n\n/* Just a forwarding function which will call whichever version of the\n * algorithm has been selected by the client \n */\nint bitcount( unsigned int val ) {\n return _bitcount( val );\n}\n\n#ifdef _BITCOUNT_EXE_\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\n/* Use the same sequence of pseudo random numbers to benmark each Hamming\n * Weight algorithm.\n */\nvoid benchmark( int reps ) {\n clock_t start, stop;\n int i, j;\n static const int iterations = 1000000;\n\n for ( j = 0; j != strategyCount; ++j ) {\n setStrategy( j );\n\n srand( 257 );\n\n start = clock( );\n\n for ( i = 0; i != reps * iterations; ++i )\n bitcount( rand( ) );\n\n stop = clock( );\n\n printf\n ( \"\\n\\t%d psudoe-random integers using %s: %f seconds\\n\\n\",\n reps * iterations, strategyNames[j],\n ( double )( stop - start ) / CLOCKS_PER_SEC );\n }\n}\n\nint main( void ) {\n int option;\n\n while ( 1 ) {\n printf( \"Menu Options\\n\"\n \"\\t1.\\tPrint the Hamming Weight of an Integer\\n\"\n \"\\t2.\\tBenchmark Hamming Weight implementations\\n\"\n \"\\t3.\\tExit ( or cntl-d )\\n\\n\\t\" );\n\n if ( scanf( \"%d\", &amp;option ) == EOF )\n break;\n\n switch ( option ) {\n case 1:\n printf( \"Please enter the integer: \" );\n if ( scanf( \"%d\", &amp;option ) != EOF )\n printf\n ( \"The Hamming Weight of %d ( 0x%X ) is %d\\n\\n\",\n option, option, bitcount( option ) );\n break;\n case 2:\n printf\n ( \"Please select number of reps ( in millions ): \" );\n if ( scanf( \"%d\", &amp;option ) != EOF )\n benchmark( option );\n break;\n case 3:\n goto EXIT;\n break;\n default:\n printf( \"Invalid option\\n\" );\n }\n\n }\n\n EXIT:\n printf( \"\\n\" );\n\n return 0;\n}\n\n#endif\n</code></pre>\n" }, { "answer_id": 5646017, "author": "Mostafa", "author_id": 593387, "author_profile": "https://Stackoverflow.com/users/593387", "pm_score": 3, "selected": false, "text": "<p>There are many algorithm to count the set bits; but i think the best one is the faster one!\nYou can see the detailed on this page:</p>\n\n<p><a href=\"http://graphics.stanford.edu/~seander/bithacks.html\">Bit Twiddling Hacks</a> </p>\n\n<p>I suggest this one:</p>\n\n<p><strong>Counting bits set in 14, 24, or 32-bit words using 64-bit instructions</strong></p>\n\n<pre><code>unsigned int v; // count the number of bits set in v\nunsigned int c; // c accumulates the total bits set in v\n\n// option 1, for at most 14-bit values in v:\nc = (v * 0x200040008001ULL &amp; 0x111111111111111ULL) % 0xf;\n\n// option 2, for at most 24-bit values in v:\nc = ((v &amp; 0xfff) * 0x1001001001001ULL &amp; 0x84210842108421ULL) % 0x1f;\nc += (((v &amp; 0xfff000) &gt;&gt; 12) * 0x1001001001001ULL &amp; 0x84210842108421ULL) \n % 0x1f;\n\n// option 3, for at most 32-bit values in v:\nc = ((v &amp; 0xfff) * 0x1001001001001ULL &amp; 0x84210842108421ULL) % 0x1f;\nc += (((v &amp; 0xfff000) &gt;&gt; 12) * 0x1001001001001ULL &amp; 0x84210842108421ULL) % \n 0x1f;\nc += ((v &gt;&gt; 24) * 0x1001001001001ULL &amp; 0x84210842108421ULL) % 0x1f;\n</code></pre>\n\n<p>This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15. </p>\n" }, { "answer_id": 8144833, "author": "Raymond Chenon", "author_id": 311420, "author_profile": "https://Stackoverflow.com/users/311420", "pm_score": 2, "selected": false, "text": "<p>32-bit or not ? I just came with this method in Java after reading \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/145157827X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">cracking the coding interview</a>\" 4th edition exercice 5.5 ( chap 5: Bit Manipulation). If the least significant bit is 1 increment <code>count</code>, then right-shift the integer.</p>\n\n<pre><code>public static int bitCount( int n){\n int count = 0;\n for (int i=n; i!=0; i = i &gt;&gt; 1){\n count += i &amp; 1;\n }\n return count;\n}\n</code></pre>\n\n<p>I think this one is more intuitive than the solutions with constant 0x33333333 no matter how fast they are. It depends on your definition of \"best algorithm\" .</p>\n" }, { "answer_id": 9426462, "author": "sanjay gopalakrishnan", "author_id": 1230114, "author_profile": "https://Stackoverflow.com/users/1230114", "pm_score": 0, "selected": false, "text": "<p>Here is the sample code, which might be useful.</p>\n\n<pre><code>private static final int[] bitCountArr = new int[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};\nprivate static final int firstByteFF = 255;\npublic static final int getCountOfSetBits(int value){\n int count = 0;\n for(int i=0;i&lt;4;i++){\n if(value == 0) break;\n count += bitCountArr[value &amp; firstByteFF];\n value &gt;&gt;&gt;= 8;\n }\n return count;\n}\n</code></pre>\n" }, { "answer_id": 9432202, "author": "oxygen", "author_id": 584490, "author_profile": "https://Stackoverflow.com/users/584490", "pm_score": 0, "selected": false, "text": "<p>Here's something that works in PHP (all PHP intergers are 32 bit signed, thus 31 bit):</p>\n\n<pre><code>function bits_population($nInteger)\n{\n\n $nPop=0;\n while($nInteger)\n {\n $nInteger^=(1&lt;&lt;(floor(1+log($nInteger)/log(2))-1));\n $nPop++;\n }\n return $nPop;\n}\n</code></pre>\n" }, { "answer_id": 10004919, "author": "pentaphobe", "author_id": 679950, "author_profile": "https://Stackoverflow.com/users/679950", "pm_score": 3, "selected": false, "text": "<p>if you're using C++ another option is to use template metaprogramming:</p>\n\n<pre><code>// recursive template to sum bits in an int\ntemplate &lt;int BITS&gt;\nint countBits(int val) {\n // return the least significant bit plus the result of calling ourselves with\n // .. the shifted value\n return (val &amp; 0x1) + countBits&lt;BITS-1&gt;(val &gt;&gt; 1);\n}\n\n// template specialisation to terminate the recursion when there's only one bit left\ntemplate&lt;&gt;\nint countBits&lt;1&gt;(int val) {\n return val &amp; 0x1;\n}\n</code></pre>\n\n<p>usage would be:</p>\n\n<pre><code>// to count bits in a byte/char (this returns 8)\ncountBits&lt;8&gt;( 255 )\n\n// another byte (this returns 7)\ncountBits&lt;8&gt;( 254 )\n\n// counting bits in a word/short (this returns 1)\ncountBits&lt;16&gt;( 256 )\n</code></pre>\n\n<p>you could of course further expand this template to use different types (even auto-detecting bit size) but I've kept it simple for clarity.</p>\n\n<p><strong>edit: forgot to mention this is good because it <em>should</em> work in any C++ compiler and it basically just unrolls your loop for you if a constant value is used for the bit count</strong> (in other words, I'm pretty sure it's the fastest general method you'll find)</p>\n" }, { "answer_id": 10049437, "author": "Jim McCurdy", "author_id": 227695, "author_profile": "https://Stackoverflow.com/users/227695", "pm_score": -1, "selected": false, "text": "<pre><code>// How about the following:\npublic int CountBits(int value)\n{\n int count = 0;\n while (value &gt; 0)\n {\n if (value &amp; 1)\n count++;\n value &lt;&lt;= 1;\n }\n return count;\n}\n</code></pre>\n" }, { "answer_id": 10326415, "author": "SteveR", "author_id": 1291368, "author_profile": "https://Stackoverflow.com/users/1291368", "pm_score": 2, "selected": false, "text": "<p>Personally I use this :</p>\n\n<pre><code> public static int myBitCount(long L){\n int count = 0;\n while (L != 0) {\n count++;\n L ^= L &amp; -L; \n }\n return count;\n }\n</code></pre>\n" }, { "answer_id": 10459753, "author": "Manish Mulani", "author_id": 316419, "author_profile": "https://Stackoverflow.com/users/316419", "pm_score": 3, "selected": false, "text": "<p>I use the below code which is more intuitive.</p>\n\n<pre><code>int countSetBits(int n) {\n return !n ? 0 : 1 + countSetBits(n &amp; (n-1));\n}\n</code></pre>\n\n<p>Logic : n &amp; (n-1) resets the last set bit of n.</p>\n\n<p>P.S : I know this is not O(1) solution, albeit an interesting solution.</p>\n" }, { "answer_id": 10921350, "author": "dhpant28", "author_id": 1440678, "author_profile": "https://Stackoverflow.com/users/1440678", "pm_score": 0, "selected": false, "text": "<pre><code>#!/user/local/bin/perl\n\n\n $c=0x11BBBBAB;\n $count=0;\n $m=0x00000001;\n for($i=0;$i&lt;32;$i++)\n {\n $f=$c &amp; $m;\n if($f == 1)\n {\n $count++;\n }\n $c=$c &gt;&gt; 1;\n }\n printf(\"%d\",$count);\n\nive done it through a perl script. the number taken is $c=0x11BBBBAB \nB=3 1s \nA=2 1s \nso in total \n1+1+3+3+3+2+3+3=19\n</code></pre>\n" }, { "answer_id": 11139377, "author": "Green goblin", "author_id": 1347366, "author_profile": "https://Stackoverflow.com/users/1347366", "pm_score": -1, "selected": false, "text": "<p>You can do something like:</p>\n\n<pre><code>int countSetBits(int n)\n{\n n=((n&amp;0xAAAAAAAA)&gt;&gt;1) + (n&amp;0x55555555);\n n=((n&amp;0xCCCCCCCC)&gt;&gt;2) + (n&amp;0x33333333);\n n=((n&amp;0xF0F0F0F0)&gt;&gt;4) + (n&amp;0x0F0F0F0F);\n n=((n&amp;0xFF00FF00)&gt;&gt;8) + (n&amp;0x00FF00FF);\n return n;\n}\n\nint main()\n{\n int n=10;\n printf(\"Number of set bits: %d\",countSetBits(n));\n return 0;\n}\n</code></pre>\n\n<p>See heer: <a href=\"http://ideone.com/JhwcX\" rel=\"nofollow\">http://ideone.com/JhwcX</a></p>\n\n<p>The working can be explained as follows:</p>\n\n<p>First, all the even bits are shifted towards right &amp; added with the odd bits to count the number of bits in group of two.\nThen we work in group of two, then four &amp; so on.. </p>\n" }, { "answer_id": 11816547, "author": "abcdabcd987", "author_id": 1332817, "author_profile": "https://Stackoverflow.com/users/1332817", "pm_score": 5, "selected": false, "text": "<pre><code>unsigned int count_bit(unsigned int x)\n{\n x = (x &amp; 0x55555555) + ((x &gt;&gt; 1) &amp; 0x55555555);\n x = (x &amp; 0x33333333) + ((x &gt;&gt; 2) &amp; 0x33333333);\n x = (x &amp; 0x0F0F0F0F) + ((x &gt;&gt; 4) &amp; 0x0F0F0F0F);\n x = (x &amp; 0x00FF00FF) + ((x &gt;&gt; 8) &amp; 0x00FF00FF);\n x = (x &amp; 0x0000FFFF) + ((x &gt;&gt; 16)&amp; 0x0000FFFF);\n return x;\n}\n</code></pre>\n\n<p>Let me explain this algorithm.</p>\n\n<p>This algorithm is based on Divide and Conquer Algorithm. Suppose there is a 8bit integer 213(11010101 in binary), the algorithm works like this(each time merge two neighbor blocks):</p>\n\n<pre><code>+-------------------------------+\n| 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | &lt;- x\n| 1 0 | 0 1 | 0 1 | 0 1 | &lt;- first time merge\n| 0 0 1 1 | 0 0 1 0 | &lt;- second time merge\n| 0 0 0 0 0 1 0 1 | &lt;- third time ( answer = 00000101 = 5)\n+-------------------------------+\n</code></pre>\n" }, { "answer_id": 12974349, "author": "Peter", "author_id": 1759303, "author_profile": "https://Stackoverflow.com/users/1759303", "pm_score": 4, "selected": false, "text": "<p>It's not the fastest or best solution, but I found the same question in my way, and I started to think and think. finally I realized that it can be done like this if you get the problem from mathematical side, and draw a graph, then you find that it's a function which has some periodic part, and then you realize the difference between the periods... so here you go:</p>\n\n<pre><code>unsigned int f(unsigned int x)\n{\n switch (x) {\n case 0:\n return 0;\n case 1:\n return 1;\n case 2:\n return 1;\n case 3:\n return 2;\n default:\n return f(x/4) + f(x%4);\n }\n}\n</code></pre>\n" }, { "answer_id": 15979139, "author": "vidit", "author_id": 962111, "author_profile": "https://Stackoverflow.com/users/962111", "pm_score": 6, "selected": false, "text": "<p>I think the fastest way—without using lookup tables and <em>popcount</em>—is the following. It counts the set bits with just 12 operations.</p>\n<pre><code>int popcount(int v) {\n v = v - ((v &gt;&gt; 1) &amp; 0x55555555); // put count of each 2 bits into those 2 bits\n v = (v &amp; 0x33333333) + ((v &gt;&gt; 2) &amp; 0x33333333); // put count of each 4 bits into those 4 bits \n return ((v + (v &gt;&gt; 4) &amp; 0xF0F0F0F) * 0x1010101) &gt;&gt; 24;\n}\n</code></pre>\n<p>It works because you can count the total number of set bits by dividing in two halves, counting the number of set bits in both halves and then adding them up. Also know as <code>Divide and Conquer</code> paradigm. Let's get into detail..</p>\n<pre><code>v = v - ((v &gt;&gt; 1) &amp; 0x55555555); \n</code></pre>\n<p>The number of bits in two bits can be <code>0b00</code>, <code>0b01</code> or <code>0b10</code>. Lets try to work this out on 2 bits..</p>\n<pre><code> ---------------------------------------------\n | v | (v &gt;&gt; 1) &amp; 0b0101 | v - x |\n ---------------------------------------------\n 0b00 0b00 0b00 \n 0b01 0b00 0b01 \n 0b10 0b01 0b01\n 0b11 0b01 0b10\n</code></pre>\n<p>This is what was required: the last column shows the count of set bits in every two bit pair. If the two bit number is <code>&gt;= 2 (0b10)</code> then <code>and</code> produces <code>0b01</code>, else it produces <code>0b00</code>.</p>\n<pre><code>v = (v &amp; 0x33333333) + ((v &gt;&gt; 2) &amp; 0x33333333); \n</code></pre>\n<p>This statement should be easy to understand. After the first operation we have the count of set bits in every two bits, now we sum up that count in every 4 bits.</p>\n<pre><code>v &amp; 0b00110011 //masks out even two bits\n(v &gt;&gt; 2) &amp; 0b00110011 // masks out odd two bits\n</code></pre>\n<p>We then sum up the above result, giving us the total count of set bits in 4 bits. The last statement is the most tricky.</p>\n<pre><code>c = ((v + (v &gt;&gt; 4) &amp; 0xF0F0F0F) * 0x1010101) &gt;&gt; 24;\n</code></pre>\n<p>Let's break it down further...</p>\n<pre><code>v + (v &gt;&gt; 4)\n</code></pre>\n<p>It's similar to the second statement; we are counting the set bits in groups of 4 instead. We know—because of our previous operations—that every nibble has the count of set bits in it. Let's look an example. Suppose we have the byte <code>0b01000010</code>. It means the first nibble has its 4bits set and the second one has its 2bits set. Now we add those nibbles together.</p>\n<pre><code>v = 0b01000010\n(v &gt;&gt; 4) = 0b00000100\nv + (v &gt;&gt; 4) = 0b01000010 + 0b00000100\n</code></pre>\n<p>It gives us the count of set bits in a byte, in the second nibble <code>0b01000110</code> and therefore we mask the first four bytes of all the bytes in the number (discarding them).</p>\n<pre><code>0b01000110 &amp; 0x0F = 0b00000110\n</code></pre>\n<p>Now every byte has the count of set bits in it. We need to add them up all together. The trick is to multiply the result by <code>0b10101010</code> which has an interesting property. If our number has four bytes, <code>A B C D</code>, it will result in a new number with these bytes <code>A+B+C+D B+C+D C+D D</code>. A 4 byte number can have maximum of 32 bits set, which can be represented as <code>0b00100000</code>.</p>\n<p>All we need now is the first byte which has the sum of all set bits in all the bytes, and we get it by <code>&gt;&gt; 24</code>. This algorithm was designed for <code>32 bit</code> words but can be easily modified for <code>64 bit</code> words.</p>\n" }, { "answer_id": 16809972, "author": "prongs", "author_id": 459384, "author_profile": "https://Stackoverflow.com/users/459384", "pm_score": -1, "selected": false, "text": "<p>I use the following function. I haven't checked benchmarks, but it works.</p>\n<pre><code>int msb(int num)\n{\n int m = 0;\n for (int i = 16; i &gt; 0; i = i&gt;&gt;1)\n {\n // debug(i, num, m);\n if(num&gt;&gt;i)\n {\n m += i;\n num&gt;&gt;=i;\n }\n }\n return m;\n}\n</code></pre>\n" }, { "answer_id": 20230136, "author": "Stefan", "author_id": 1209253, "author_profile": "https://Stackoverflow.com/users/1209253", "pm_score": 1, "selected": false, "text": "<p>Here is a solution that has not been mentioned so far, using bitfields. The following program counts the set bits in an array of 100000000 16-bit integers using 4 different methods. Timing results are given in parentheses (on MacOSX, with <code>gcc -O3</code>):</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define LENGTH 100000000\n\ntypedef struct {\n unsigned char bit0 : 1;\n unsigned char bit1 : 1;\n unsigned char bit2 : 1;\n unsigned char bit3 : 1;\n unsigned char bit4 : 1;\n unsigned char bit5 : 1;\n unsigned char bit6 : 1;\n unsigned char bit7 : 1;\n} bits;\n\nunsigned char sum_bits(const unsigned char x) {\n const bits *b = (const bits*) &amp;x;\n return b-&gt;bit0 + b-&gt;bit1 + b-&gt;bit2 + b-&gt;bit3 \\\n + b-&gt;bit4 + b-&gt;bit5 + b-&gt;bit6 + b-&gt;bit7;\n}\n\nint NumberOfSetBits(int i) {\n i = i - ((i &gt;&gt; 1) &amp; 0x55555555);\n i = (i &amp; 0x33333333) + ((i &gt;&gt; 2) &amp; 0x33333333);\n return (((i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F) * 0x01010101) &gt;&gt; 24;\n}\n\n#define out(s) \\\n printf(\"bits set: %lu\\nbits counted: %lu\\n\", 8*LENGTH*sizeof(short)*3/4, s);\n\nint main(int argc, char **argv) {\n unsigned long i, s;\n unsigned short *x = malloc(LENGTH*sizeof(short));\n unsigned char lut[65536], *p;\n unsigned short *ps;\n int *pi;\n\n /* set 3/4 of the bits */\n for (i=0; i&lt;LENGTH; ++i)\n x[i] = 0xFFF0;\n\n /* sum_bits (1.772s) */\n for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=sum_bits(*p++));\n out(s);\n\n /* NumberOfSetBits (0.404s) */\n for (i=LENGTH*sizeof(short)/sizeof(int), pi=(int*)x, s=0; i--; s+=NumberOfSetBits(*pi++));\n out(s);\n\n /* populate lookup table */\n for (i=0, p=(unsigned char*) &amp;i; i&lt;sizeof(lut); ++i)\n lut[i] = sum_bits(p[0]) + sum_bits(p[1]);\n\n /* 256-bytes lookup table (0.317s) */\n for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=lut[*p++]);\n out(s);\n\n /* 65536-bytes lookup table (0.250s) */\n for (i=LENGTH, ps=x, s=0; i--; s+=lut[*ps++]);\n out(s);\n\n free(x);\n return 0;\n}\n</code></pre>\n\n<p>While the bitfield version is very readable, the timing results show that it is over 4x slower than <code>NumberOfSetBits()</code>. The lookup-table based implementations are still quite a bit faster, in particular with a 65 kB table.</p>\n" }, { "answer_id": 20697993, "author": "John Dimm", "author_id": 1976377, "author_profile": "https://Stackoverflow.com/users/1976377", "pm_score": 5, "selected": false, "text": "<p>The Hacker's Delight bit-twiddling becomes so much clearer when you write out the bit patterns. </p>\n\n<pre><code>unsigned int bitCount(unsigned int x)\n{\n x = ((x &gt;&gt; 1) &amp; 0b01010101010101010101010101010101)\n + (x &amp; 0b01010101010101010101010101010101);\n x = ((x &gt;&gt; 2) &amp; 0b00110011001100110011001100110011)\n + (x &amp; 0b00110011001100110011001100110011); \n x = ((x &gt;&gt; 4) &amp; 0b00001111000011110000111100001111)\n + (x &amp; 0b00001111000011110000111100001111); \n x = ((x &gt;&gt; 8) &amp; 0b00000000111111110000000011111111)\n + (x &amp; 0b00000000111111110000000011111111); \n x = ((x &gt;&gt; 16)&amp; 0b00000000000000001111111111111111)\n + (x &amp; 0b00000000000000001111111111111111); \n return x;\n}\n</code></pre>\n\n<p>The first step adds the even bits to the odd bits, producing a sum of bits in each two. The other steps add high-order chunks to low-order chunks, doubling the chunk size all the way up, until we have the final count taking up the entire int.</p>\n" }, { "answer_id": 21114060, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 4, "selected": false, "text": "<p>This can be done in <code>O(k)</code>, where <code>k</code> is the number of bits set.</p>\n\n<pre><code>int NumberOfSetBits(int n)\n{\n int count = 0;\n\n while (n){\n ++ count;\n n = (n - 1) &amp; n;\n }\n\n return count;\n}\n</code></pre>\n" }, { "answer_id": 21455308, "author": "dadhi", "author_id": 2492669, "author_profile": "https://Stackoverflow.com/users/2492669", "pm_score": 3, "selected": false, "text": "<p>A fast C# solution using a pre-calculated table of Byte bit counts with branching on the input size.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public static class BitCount\n{\n public static uint GetSetBitsCount(uint n)\n {\n var counts = BYTE_BIT_COUNTS;\n return n &lt;= 0xff ? counts[n]\n : n &lt;= 0xffff ? counts[n &amp; 0xff] + counts[n &gt;&gt; 8]\n : n &lt;= 0xffffff ? counts[n &amp; 0xff] + counts[(n &gt;&gt; 8) &amp; 0xff] + counts[(n &gt;&gt; 16) &amp; 0xff]\n : counts[n &amp; 0xff] + counts[(n &gt;&gt; 8) &amp; 0xff] + counts[(n &gt;&gt; 16) &amp; 0xff] + counts[(n &gt;&gt; 24) &amp; 0xff];\n }\n\n public static readonly uint[] BYTE_BIT_COUNTS =\n {\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,\n 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8\n };\n}\n</code></pre>\n" }, { "answer_id": 24099386, "author": "Mufaddal Kagda", "author_id": 1925185, "author_profile": "https://Stackoverflow.com/users/1925185", "pm_score": 1, "selected": false, "text": "<pre><code>int bitcount(unsigned int n)\n{ \n int count=0;\n while(n)\n {\n count += n &amp; 0x1u;\n n &gt;&gt;= 1;\n }\n return count;\n }\n</code></pre>\n\n<p>Iterated 'count' runs in time proportional to the total number of bits. It simply loops through all the bits, terminating slightly earlier because of the while condition. Useful, if 1'S or the set bits are <strong>sparse</strong> and among the <strong>least significant bits</strong>.</p>\n" }, { "answer_id": 27853048, "author": "Nikhil Katre", "author_id": 3030376, "author_profile": "https://Stackoverflow.com/users/3030376", "pm_score": -1, "selected": false, "text": "<p>I am giving two algorithms to answer the question,</p>\n<pre class=\"lang-java prettyprint-override\"><code>package countSetBitsInAnInteger;\n\nimport java.util.Scanner;\n\npublic class UsingLoop {\n\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n try {\n System.out.println(&quot;Enter a integer number to check for set bits in it&quot;);\n int n = in.nextInt();\n System.out.println(&quot;Using while loop, we get the number of set bits as: &quot; + usingLoop(n));\n System.out.println(&quot;Using Brain Kernighan's Algorithm, we get the number of set bits as: &quot; + usingBrainKernighan(n));\n System.out.println(&quot;Using &quot;);\n }\n finally {\n in.close();\n }\n }\n\n private static int usingBrainKernighan(int n) {\n int count = 0;\n while(n &gt; 0) {\n n&amp; = (n-1);\n count++;\n }\n return count;\n }\n\n /*\n Analysis:\n Time complexity = O(lgn)\n Space complexity = O(1)\n */\n\n private static int usingLoop(int n) {\n int count = 0;\n for(int i=0; i&lt;32; i++) {\n if((n&amp;(1 &lt;&lt; i)) != 0)\n count++;\n }\n return count;\n }\n\n /*\n Analysis:\n Time Complexity = O(32) // Maybe the complexity is O(lgn)\n Space Complexity = O(1)\n */\n}\n</code></pre>\n" }, { "answer_id": 28469209, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 2, "selected": false, "text": "<pre><code>int countBits(int x)\n{\n int n = 0;\n if (x) do n++;\n while(x=x&amp;(x-1));\n return n;\n} \n</code></pre>\n<p>Or also:</p>\n<pre><code>int countBits(int x) { return (x)? 1+countBits(x&amp;(x-1)): 0; }\n</code></pre>\n<hr>\n<p>7 1/2 years after my original answer, @PeterMortensen questioned if this was even valid C syntax. I posted a link to an online compiler showing that it is in fact perfectly valid syntax (code below).</p>\n<pre><code>#include &lt;stdio.h&gt;\nint countBits(int x)\n{\n int n = 0;\n if (x) do n++; /* Totally Normal Valid code. */\n while(x=x&amp;(x-1)); /* Nothing to see here. */\n return n;\n} \n \nint main(void) {\n printf(&quot;%d\\n&quot;, countBits(25));\n return 0;\n}\n \n</code></pre>\n<h2>Output:</h2>\n<pre><code>3\n</code></pre>\n<p>If you want to re-write it for clarity, it would look like:</p>\n<pre><code>if (x)\n{\n do\n {\n n++;\n } while(x=x&amp;(x-1));\n}\n</code></pre>\n<p>But that seems excessive to my eye.</p>\n<p>However, I've also realized the function can be made shorter, but perhaps more cryptic, written as:</p>\n<pre><code>int countBits(int x)\n{\n int n = 0;\n while (x) x=(n++,x&amp;(x-1));\n return n;\n} \n</code></pre>\n" }, { "answer_id": 32787654, "author": "Burhan ARAS", "author_id": 1149401, "author_profile": "https://Stackoverflow.com/users/1149401", "pm_score": -1, "selected": false, "text": "<pre><code>public class BinaryCounter {\n\nprivate int N;\n\npublic BinaryCounter(int N) {\n this.N = N;\n}\n\npublic static void main(String[] args) {\n\n BinaryCounter counter=new BinaryCounter(7); \n System.out.println(\"Number of ones is \"+ counter.count());\n\n}\n\npublic int count(){\n if(N&lt;=0) return 0;\n int counter=0;\n int K = 0;\n do{\n K = biggestPowerOfTwoSmallerThan(N);\n N = N-K;\n counter++;\n }while (N != 0);\n return counter;\n\n}\n\nprivate int biggestPowerOfTwoSmallerThan(int N) {\n if(N==1) return 1;\n for(int i=0;i&lt;N;i++){\n if(Math.pow(2, i) &gt; N){\n int power = i-1;\n return (int) Math.pow(2, power);\n }\n }\n return 0;\n}\n}\n</code></pre>\n" }, { "answer_id": 33791923, "author": "Anders Cedronius", "author_id": 2353816, "author_profile": "https://Stackoverflow.com/users/2353816", "pm_score": 1, "selected": false, "text": "<p>Another <a href=\"https://en.wikipedia.org/wiki/Hamming_weight\" rel=\"nofollow noreferrer\">Hamming weight</a> algorithm if you're on a <a href=\"https://en.wikipedia.org/wiki/X86_Bit_manipulation_instruction_set#BMI2_(Bit_Manipulation_Instruction_Set_2)\" rel=\"nofollow noreferrer\">BMI2</a> capable CPU:</p>\n<pre><code>the_weight = __tzcnt_u64(~_pext_u64(data[i], data[i]));\n</code></pre>\n" }, { "answer_id": 35200163, "author": "KeineKaefer", "author_id": 1684019, "author_profile": "https://Stackoverflow.com/users/1684019", "pm_score": 0, "selected": false, "text": "<p>Convert the integer to a binary string and count the ones.</p>\n<p>PHP solution:</p>\n<pre><code>substr_count(decbin($integer), '1');\n</code></pre>\n" }, { "answer_id": 35412017, "author": "ErmIg", "author_id": 2831104, "author_profile": "https://Stackoverflow.com/users/2831104", "pm_score": 3, "selected": false, "text": "<p>I found an implementation of bit counting in an array with using of SIMD instruction (SSSE3 and AVX2). It has in 2-2.5 times better performance than if it will use __popcnt64 intrinsic function.</p>\n\n<p>SSSE3 version:</p>\n\n<pre><code>#include &lt;smmintrin.h&gt;\n#include &lt;stdint.h&gt;\n\nconst __m128i Z = _mm_set1_epi8(0x0);\nconst __m128i F = _mm_set1_epi8(0xF);\n//Vector with pre-calculated bit count:\nconst __m128i T = _mm_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);\n\nuint64_t BitCount(const uint8_t * src, size_t size)\n{\n __m128i _sum = _mm128_setzero_si128();\n for (size_t i = 0; i &lt; size; i += 16)\n {\n //load 16-byte vector\n __m128i _src = _mm_loadu_si128((__m128i*)(src + i));\n //get low 4 bit for every byte in vector\n __m128i lo = _mm_and_si128(_src, F);\n //sum precalculated value from T\n _sum = _mm_add_epi64(_sum, _mm_sad_epu8(Z, _mm_shuffle_epi8(T, lo)));\n //get high 4 bit for every byte in vector\n __m128i hi = _mm_and_si128(_mm_srli_epi16(_src, 4), F);\n //sum precalculated value from T\n _sum = _mm_add_epi64(_sum, _mm_sad_epu8(Z, _mm_shuffle_epi8(T, hi)));\n }\n uint64_t sum[2];\n _mm_storeu_si128((__m128i*)sum, _sum);\n return sum[0] + sum[1];\n}\n</code></pre>\n\n<p>AVX2 version:</p>\n\n<pre><code>#include &lt;immintrin.h&gt;\n#include &lt;stdint.h&gt;\n\nconst __m256i Z = _mm256_set1_epi8(0x0);\nconst __m256i F = _mm256_set1_epi8(0xF);\n//Vector with pre-calculated bit count:\nconst __m256i T = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, \n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4);\n\nuint64_t BitCount(const uint8_t * src, size_t size)\n{\n __m256i _sum = _mm256_setzero_si256();\n for (size_t i = 0; i &lt; size; i += 32)\n {\n //load 32-byte vector\n __m256i _src = _mm256_loadu_si256((__m256i*)(src + i));\n //get low 4 bit for every byte in vector\n __m256i lo = _mm256_and_si256(_src, F);\n //sum precalculated value from T\n _sum = _mm256_add_epi64(_sum, _mm256_sad_epu8(Z, _mm256_shuffle_epi8(T, lo)));\n //get high 4 bit for every byte in vector\n __m256i hi = _mm256_and_si256(_mm256_srli_epi16(_src, 4), F);\n //sum precalculated value from T\n _sum = _mm256_add_epi64(_sum, _mm256_sad_epu8(Z, _mm256_shuffle_epi8(T, hi)));\n }\n uint64_t sum[4];\n _mm256_storeu_si256((__m256i*)sum, _sum);\n return sum[0] + sum[1] + sum[2] + sum[3];\n}\n</code></pre>\n" }, { "answer_id": 37558380, "author": "Erorr", "author_id": 4686763, "author_profile": "https://Stackoverflow.com/users/4686763", "pm_score": 4, "selected": false, "text": "<p>I think the <a href=\"https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan\" rel=\"noreferrer\">Brian Kernighan's</a> method will be useful too...\nIt goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop. </p>\n\n<pre><code>int countSetBits(unsigned int n) { \n unsigned int n; // count the number of bits set in n\n unsigned int c; // c accumulates the total bits set in n\n for (c=0;n&gt;0;n=n&amp;(n-1)) c++; \n return c; \n}\n</code></pre>\n\n<blockquote>\n <p>Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method \"was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)\"</p>\n</blockquote>\n" }, { "answer_id": 39861725, "author": "Jonatan Kaźmierczak", "author_id": 1131188, "author_profile": "https://Stackoverflow.com/users/1131188", "pm_score": 1, "selected": false, "text": "<p>In Java 8 or 9 just invoke <code>Integer.bitCount</code> .</p>\n" }, { "answer_id": 40411172, "author": "iamdeit", "author_id": 4830460, "author_profile": "https://Stackoverflow.com/users/4830460", "pm_score": 3, "selected": false, "text": "<p>I always use this in <a href=\"https://en.wikipedia.org/wiki/Competitive_programming\" rel=\"nofollow noreferrer\">competitive programming</a>, and it's easy to write and is efficient:</p>\n<pre><code>#include &lt;bits/stdc++.h&gt;\n\nusing namespace std;\n\nint countOnes(int n) {\n bitset&lt;32&gt; b(n);\n return b.count();\n}\n</code></pre>\n" }, { "answer_id": 44566978, "author": "rashedcs", "author_id": 6714430, "author_profile": "https://Stackoverflow.com/users/6714430", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>You can use built in function named __builtin_popcount(). There is no__builtin_popcount in C++ but it is a built in function of GCC compiler. This function return the number of set bit in an integer.</p>\n</blockquote>\n\n<pre><code>int __builtin_popcount (unsigned int x);\n</code></pre>\n\n<p>Reference : <a href=\"http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable\" rel=\"nofollow noreferrer\">Bit Twiddling Hacks</a></p>\n" }, { "answer_id": 44981129, "author": "cipilo", "author_id": 8272794, "author_profile": "https://Stackoverflow.com/users/8272794", "pm_score": 0, "selected": false, "text": "<p>I have not seen this approach anywhere:</p>\n<pre><code>int nbits(unsigned char v) {\n return ((((v - ((v &gt;&gt; 1) &amp; 0x55)) * 0x1010101) &amp; 0x30c00c03) * 0x10040041) &gt;&gt; 0x1c;\n}\n</code></pre>\n<p>It works per byte, so it would have to be called four times for a 32-bit integer. It is derived from the sideways addition, but it uses two 32-bit multiplications to reduce the number of instructions to only seven.</p>\n<p>Most current C compilers will optimize this function using <a href=\"https://en.wikipedia.org/wiki/SIMD\" rel=\"nofollow noreferrer\">SIMD</a> (<a href=\"https://en.wikipedia.org/wiki/SSE2\" rel=\"nofollow noreferrer\">SSE2</a>) instructions when it is clear that the number of requests is a multiple of 4, and it becomes quite competitive. It is portable, can be defined as a macro or inline function and does not need data tables.</p>\n<p>This approach can be extended to work on 16 bits at a time, using 64-bit multiplications. However, it fails when all 16 bits are set, returning zero, so it can be used only when the 0xFFFF input value is not present. It is also slower due to the 64-bit operations and does not optimize well.</p>\n" }, { "answer_id": 45846017, "author": "Varun Gusain", "author_id": 7113494, "author_profile": "https://Stackoverflow.com/users/7113494", "pm_score": 3, "selected": false, "text": "<p>You can do:</p>\n<pre><code>while(n){\n n = n &amp; (n-1);\n count++;\n}\n</code></pre>\n<p>The logic behind this is the bits of n-1 is inverted from rightmost set bit of n.</p>\n<p>If n=6, i.e., 110 then 5 is 101 the bits are inverted from rightmost set bit of n.</p>\n<p>So if we <code>&amp;</code> these two we will make the rightmost bit 0 in every iteration and always go to the next rightmost set bit. Hence, counting the set bit. The worst time complexity will be O(log n) when every bit is set.</p>\n" }, { "answer_id": 47182710, "author": "stacktay", "author_id": 6858149, "author_profile": "https://Stackoverflow.com/users/6858149", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>private int get_bits_set(int v)\n{\n int c; // 'c' accumulates the total bits set in 'v'\n for (c = 0; v&gt;0; c++)\n {\n v &amp;= v - 1; // Clear the least significant bit set\n }\n return c;\n}\n</code></pre>\n" }, { "answer_id": 48731845, "author": "decrypto", "author_id": 7488288, "author_profile": "https://Stackoverflow.com/users/7488288", "pm_score": -1, "selected": false, "text": "<p>This will also work fine:</p>\n<pre><code>int ans = 0;\nwhile(num) {\n ans += (num &amp; 1);\n num = num &gt;&gt; 1;\n} \nreturn ans;\n</code></pre>\n" }, { "answer_id": 56481445, "author": "Arjun Singh", "author_id": 10389478, "author_profile": "https://Stackoverflow.com/users/10389478", "pm_score": 0, "selected": false, "text": "<p>A simple algorithm to count the number of set bits:</p>\n<pre><code>int countbits(n) {\n int count = 0;\n while(n != 0) {\n n = n &amp; (n-1);\n count++;\n }\n return count;\n}\n</code></pre>\n<p>Take the example of 11 (1011) and try manually running through the algorithm. It should help you a lot!</p>\n" }, { "answer_id": 57285674, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "<p><strong>C++20 <code>std::popcount</code></strong></p>\n\n<p>The following proposal has been merged <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0553r4.html\" rel=\"noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0553r4.html</a> and should add it to a the <code>&lt;bit&gt;</code> header.</p>\n\n<p>I expect the usage to be like:</p>\n\n<pre><code>#include &lt;bit&gt;\n#include &lt;iostream&gt;\n\nint main() {\n std::cout &lt;&lt; std::popcount(0x55) &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>I'll give it a try when support arrives to GCC, GCC 9.1.0 with <code>g++-9 -std=c++2a</code> still doesn't support it.</p>\n\n<p>The proposal says:</p>\n\n<blockquote>\n <p>Header: <code>&lt;bit&gt;</code></p>\n\n<pre><code>namespace std {\n\n // 25.5.6, counting\n template&lt;class T&gt;\n constexpr int popcount(T x) noexcept;\n</code></pre>\n</blockquote>\n\n<p>and:</p>\n\n<blockquote>\n<pre><code>template&lt;class T&gt;\n constexpr int popcount(T x) noexcept;\n</code></pre>\n \n <p>Constraints: T is an unsigned integer type (3.9.1 [basic.fundamental]).</p>\n \n <p>Returns: The number of 1 bits in the value of x.</p>\n</blockquote>\n\n<p><code>std::rotl</code> and <code>std::rotr</code> were also added to do circular bit rotations: <a href=\"https://stackoverflow.com/questions/776508/best-practices-for-circular-shift-rotate-operations-in-c/57285854#57285854\">Best practices for circular shift (rotate) operations in C++</a></p>\n" }, { "answer_id": 57650036, "author": "Bamidele Alegbe", "author_id": 4934096, "author_profile": "https://Stackoverflow.com/users/4934096", "pm_score": -1, "selected": false, "text": "<p>This is the implementation in golang</p>\n\n<pre><code>func CountBitSet(n int) int {\n\n\n count := 0\n for n &gt; 0 {\n count += n &amp; 1\n n &gt;&gt;= 1\n\n }\n return count\n}\n</code></pre>\n" }, { "answer_id": 60796828, "author": "Shyambeer Singh", "author_id": 1442015, "author_profile": "https://Stackoverflow.com/users/1442015", "pm_score": 0, "selected": false, "text": "<pre><code>def hammingWeight(n):\n count = 0\n while n:\n if n&amp;1:\n count += 1\n n &gt;&gt;= 1\n return count\n</code></pre>\n" }, { "answer_id": 63889264, "author": "Boštjan Mejak", "author_id": 7771315, "author_profile": "https://Stackoverflow.com/users/7771315", "pm_score": 1, "selected": false, "text": "<p>From Python 3.10 onwards, you will be able to use the <code>int.bit_count()</code> function, but for the time being, you can define this function yourself.</p>\n<pre><code>def bit_count(integer):\n return bin(integer).count(&quot;1&quot;)\n</code></pre>\n" }, { "answer_id": 64391462, "author": "monoceres", "author_id": 242348, "author_profile": "https://Stackoverflow.com/users/242348", "pm_score": 0, "selected": false, "text": "<p>Here is the functional master race recursive solution, and it is by far the purest one (and can be used with any bit length!):</p>\n<pre><code>template&lt;typename T&gt;\nint popcnt(T n)\n{\n if (n&gt;0)\n return n&amp;1 + popcnt(n&gt;&gt;1);\n return 0; \n}\n</code></pre>\n" }, { "answer_id": 65121086, "author": "Steven Chou", "author_id": 2971851, "author_profile": "https://Stackoverflow.com/users/2971851", "pm_score": 0, "selected": false, "text": "<p>For Java, there is a <code>java.util.BitSet</code>.\n<a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html</a></p>\n<blockquote>\n<p>cardinality(): Returns the number of bits set to true in this BitSet.</p>\n</blockquote>\n<p>The BitSet is memory efficient since it's stored as a Long.</p>\n" }, { "answer_id": 66086390, "author": "Jerry An", "author_id": 10153574, "author_profile": "https://Stackoverflow.com/users/10153574", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://leetcode.com/problems/number-of-1-bits/solution/\" rel=\"nofollow noreferrer\">Python solution:</a></p>\n<pre class=\"lang-python prettyprint-override\"><code>def hammingWeight(n: int) -&gt; int:\n sums = 0\n while (n!=0):\n sums+=1\n n = n &amp;(n-1)\n\n return sums\n</code></pre>\n<p>In the binary representation, the least significant 1-bit in n always corresponds to a 0-bit in n - 1. Therefore, anding the two numbers n and n - 1 always flips the least significant 1-bit in n to 0, and keeps all other bits the same.</p>\n<p><a href=\"https://i.stack.imgur.com/zRjbD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zRjbD.png\" alt=\"Enter image description here\" /></a></p>\n" }, { "answer_id": 67185779, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 1, "selected": false, "text": "<p>I am providing one more unmentioned algorithm, called Parallel, taken <a href=\"http://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel\" rel=\"nofollow noreferrer\">from here</a>. The nice point about it that it is generic, meaning that the code is the same for bit sizes 8, 16, 32, 64, and 128.</p>\n<p>I checked the correctness of its values and timings on an amount of 2^26 numbers for bits sizes 8, 16, 32, and 64. See the timings below.</p>\n<p>This algorithm is a first code snippet. The other two are mentioned here just for reference, because I tested and compared to them.</p>\n<p>Algorithms are coded in C++, to be generic, but it can be easily adopted to old C.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;type_traits&gt;\n#include &lt;cstdint&gt;\n\ntemplate &lt;typename IntT&gt;\ninline size_t PopCntParallel(IntT n) {\n // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n using T = std::make_unsigned_t&lt;IntT&gt;;\n\n T v = T(n);\n v = v - ((v &gt;&gt; 1) &amp; (T)~(T)0/3); // temp\n v = (v &amp; (T)~(T)0/15*3) + ((v &gt;&gt; 2) &amp; (T)~(T)0/15*3); // temp\n v = (v + (v &gt;&gt; 4)) &amp; (T)~(T)0/255*15; // temp\n return size_t((T)(v * ((T)~(T)0/255)) &gt;&gt; (sizeof(T) - 1) * 8); // count\n}\n</code></pre>\n<p>Below are two algorithms that I compared with. One is the Kernighan simple method with a loop, taken from <a href=\"http://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetKernighan\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;typename IntT&gt;\ninline size_t PopCntKernighan(IntT n) {\n // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan\n using T = std::make_unsigned_t&lt;IntT&gt;;\n T v = T(n);\n size_t c;\n for (c = 0; v; ++c)\n v &amp;= v - 1; // Clear the least significant bit set\n return c;\n}\n</code></pre>\n<p>Another one is using built-in <code>__popcnt16()</code>/<code>__popcnt()</code>/<code>__popcnt64()</code> MSVC's intrinsic (<a href=\"https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-160\" rel=\"nofollow noreferrer\">doc here</a>). Or <code>__builtin_popcount</code> of CLang/GCC (<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\" rel=\"nofollow noreferrer\">doc here</a>). This intrinsic should provide a very optimized version, possibly hardware:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifdef _MSC_VER\n // https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-160\n #include &lt;intrin.h&gt;\n #define popcnt16 __popcnt16\n #define popcnt32 __popcnt\n #define popcnt64 __popcnt64\n#else\n // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\n #define popcnt16 __builtin_popcount\n #define popcnt32 __builtin_popcount\n #define popcnt64 __builtin_popcountll\n#endif\n\ntemplate &lt;typename IntT&gt;\ninline size_t PopCntBuiltin(IntT n) {\n using T = std::make_unsigned_t&lt;IntT&gt;;\n T v = T(n);\n if constexpr(sizeof(IntT) &lt;= 2)\n return popcnt16(uint16_t(v));\n else if constexpr(sizeof(IntT) &lt;= 4)\n return popcnt32(uint32_t(v));\n else if constexpr(sizeof(IntT) &lt;= 8)\n return popcnt64(uint64_t(v));\n else\n static_assert([]{ return false; }());\n}\n</code></pre>\n<p>Below are the timings, in nanoseconds per one number. All timings are done for 2^26 random numbers. Timings are compared for all three algorithms and all bit sizes among 8, 16, 32, and 64. In sum, all tests took 16 seconds on my machine. The high-resolution clock was used.</p>\n<pre><code>08 bit Builtin 8.2 ns\n08 bit Parallel 8.2 ns\n08 bit Kernighan 26.7 ns\n\n16 bit Builtin 7.7 ns\n16 bit Parallel 7.7 ns\n16 bit Kernighan 39.7 ns\n\n32 bit Builtin 7.0 ns\n32 bit Parallel 7.0 ns\n32 bit Kernighan 47.9 ns\n\n64 bit Builtin 7.5 ns\n64 bit Parallel 7.5 ns\n64 bit Kernighan 59.4 ns\n\n128 bit Builtin 7.8 ns\n128 bit Parallel 13.8 ns\n128 bit Kernighan 127.6 ns\n</code></pre>\n<p>As one can see, the provided Parallel algorithm (first among three) is as good as <a href=\"https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B\" rel=\"nofollow noreferrer\">MSVC</a>'s/CLang's intrinsic.</p>\n<hr />\n<p>For reference, below is full code that I used to test speed/time/correctness of all functions.</p>\n<p>As a bonus this code (unlike short code snippets above) also tests 128 bit size, but only under CLang/GCC (not MSVC), as they have <code>unsigned __int128</code>.</p>\n<p><a href=\"https://godbolt.org/z/c398nTvaM\" rel=\"nofollow noreferrer\">Try it online!</a></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;type_traits&gt;\n#include &lt;cstdint&gt;\n\nusing std::size_t;\n\n#if defined(_MSC_VER) &amp;&amp; !defined(__clang__)\n #define IS_MSVC 1\n#else\n #define IS_MSVC 0\n#endif\n\n#if IS_MSVC\n #define HAS128 false\n#else\n using int128_t = __int128;\n using uint128_t = unsigned __int128;\n #define HAS128 true\n#endif\n\ntemplate &lt;typename T&gt; struct UnSignedT { using type = std::make_unsigned_t&lt;T&gt;; };\n#if HAS128\n template &lt;&gt; struct UnSignedT&lt;int128_t&gt; { using type = uint128_t; };\n template &lt;&gt; struct UnSignedT&lt;uint128_t&gt; { using type = uint128_t; };\n#endif\ntemplate &lt;typename T&gt; using UnSigned = typename UnSignedT&lt;T&gt;::type;\n\ntemplate &lt;typename IntT&gt;\ninline size_t PopCntParallel(IntT n) {\n // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n using T = UnSigned&lt;IntT&gt;;\n\n T v = T(n);\n v = v - ((v &gt;&gt; 1) &amp; (T)~(T)0/3); // temp\n v = (v &amp; (T)~(T)0/15*3) + ((v &gt;&gt; 2) &amp; (T)~(T)0/15*3); // temp\n v = (v + (v &gt;&gt; 4)) &amp; (T)~(T)0/255*15; // temp\n return size_t((T)(v * ((T)~(T)0/255)) &gt;&gt; (sizeof(T) - 1) * 8); // count\n}\n\ntemplate &lt;typename IntT&gt;\ninline size_t PopCntKernighan(IntT n) {\n // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan\n using T = UnSigned&lt;IntT&gt;;\n T v = T(n);\n size_t c;\n for (c = 0; v; ++c)\n v &amp;= v - 1; // Clear the least significant bit set\n return c;\n}\n\n#if IS_MSVC\n // https://learn.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-160\n #include &lt;intrin.h&gt;\n #define popcnt16 __popcnt16\n #define popcnt32 __popcnt\n #define popcnt64 __popcnt64\n#else\n // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\n #define popcnt16 __builtin_popcount\n #define popcnt32 __builtin_popcount\n #define popcnt64 __builtin_popcountll\n#endif\n\n#define popcnt128(x) (popcnt64(uint64_t(x)) + popcnt64(uint64_t(x &gt;&gt; 64)))\n\ntemplate &lt;typename IntT&gt;\ninline size_t PopCntBuiltin(IntT n) {\n using T = UnSigned&lt;IntT&gt;;\n T v = T(n);\n if constexpr(sizeof(IntT) &lt;= 2)\n return popcnt16(uint16_t(v));\n else if constexpr(sizeof(IntT) &lt;= 4)\n return popcnt32(uint32_t(v));\n else if constexpr(sizeof(IntT) &lt;= 8)\n return popcnt64(uint64_t(v));\n else if constexpr(sizeof(IntT) &lt;= 16)\n return popcnt128(uint128_t(v));\n else\n static_assert([]{ return false; }());\n}\n\n#include &lt;random&gt;\n#include &lt;vector&gt;\n#include &lt;chrono&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n#include &lt;map&gt;\n\ninline double Time() {\n static auto const gtb = std::chrono::high_resolution_clock::now();\n return std::chrono::duration_cast&lt;std::chrono::duration&lt;double&gt;&gt;(\n std::chrono::high_resolution_clock::now() - gtb).count();\n}\n\ntemplate &lt;typename T, typename F&gt;\nvoid Test(std::string const &amp; name, F f) {\n std::mt19937_64 rng{123};\n size_t constexpr bit_size = sizeof(T) * 8, ntests = 1 &lt;&lt; 6, nnums = 1 &lt;&lt; 14;\n std::vector&lt;T&gt; nums(nnums);\n for (size_t i = 0; i &lt; nnums; ++i)\n nums[i] = T(rng() % ~T(0));\n static std::map&lt;size_t, size_t&gt; times;\n double min_time = 1000;\n for (size_t i = 0; i &lt; ntests; ++i) {\n double timer = Time();\n size_t sum = 0;\n for (size_t j = 0; j &lt; nnums; j += 4)\n sum += f(nums[j + 0]) + f(nums[j + 1]) + f(nums[j + 2]) + f(nums[j + 3]);\n auto volatile vsum = sum;\n min_time = std::min(min_time, (Time() - timer) / nnums);\n if (times.count(bit_size) &amp;&amp; times.at(bit_size) != sum)\n std::cout &lt;&lt; &quot;Wrong bit cnt checksum!&quot; &lt;&lt; std::endl;\n times[bit_size] = sum;\n }\n std::cout &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; bit_size\n &lt;&lt; &quot; bit &quot; &lt;&lt; name &lt;&lt; &quot; &quot; &lt;&lt; std::fixed &lt;&lt; std::setprecision(1)\n &lt;&lt; min_time * 1000000000 &lt;&lt; &quot; ns&quot; &lt;&lt; std::endl;\n}\n\nint main() {\n #define TEST(T) \\\n Test&lt;T&gt;(&quot;Builtin&quot;, PopCntBuiltin&lt;T&gt;); \\\n Test&lt;T&gt;(&quot;Parallel&quot;, PopCntParallel&lt;T&gt;); \\\n Test&lt;T&gt;(&quot;Kernighan&quot;, PopCntKernighan&lt;T&gt;); \\\n std::cout &lt;&lt; std::endl;\n \n TEST(uint8_t); TEST(uint16_t); TEST(uint32_t); TEST(uint64_t);\n #if HAS128\n TEST(uint128_t);\n #endif\n \n #undef TEST\n}\n</code></pre>\n" }, { "answer_id": 67410903, "author": "Jfm Meyers", "author_id": 6499953, "author_profile": "https://Stackoverflow.com/users/6499953", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://en.wikipedia.org/wiki/Kotlin_(programming_language)\" rel=\"nofollow noreferrer\">Kotlin</a> pre 1.4</p>\n<pre><code> fun NumberOfSetBits(i: Int): Int {\n var i = i\n i -= (i ushr 1 and 0x55555555)\n i = (i and 0x33333333) + (i ushr 2 and 0x33333333)\n return (i + (i ushr 4) and 0x0F0F0F0F) * 0x01010101 ushr 24\n }\n</code></pre>\n<p>This is more or less a copy of the answer seen in <a href=\"https://stackoverflow.com/questions/109023/count-the-number-of-set-bits-in-a-32-bit-integer/109025#109025\">the top answer</a>.</p>\n<p>It is with the Java fixes and is then converted using the converter in the <a href=\"https://en.wikipedia.org/wiki/IntelliJ_IDEA\" rel=\"nofollow noreferrer\">IntelliJ IDEA</a> Community Edition</p>\n<p>1.4 and beyond (as of 2021-05-05 - it could change in the future).</p>\n<pre><code> fun NumberOfSetBits(i: Int): Int {\n return i.countOneBits()\n }\n</code></pre>\n<p>Under the hood it uses <code>Integer.bitCount</code> as seen here:</p>\n<pre><code>@SinceKotlin(&quot;1.4&quot;)\n@WasExperimental(ExperimentalStdlibApi::class)\[email protected]\npublic actual inline fun Int.countOneBits(): Int = Integer.bitCount(this)\n\n</code></pre>\n" }, { "answer_id": 67619076, "author": "Amisha Sahu", "author_id": 14651946, "author_profile": "https://Stackoverflow.com/users/14651946", "pm_score": 2, "selected": false, "text": "<p><strong>Naive Solution</strong></p>\n<p>Time Complexity is O(no. of bits in n)</p>\n<pre><code>int countSet(unsigned int n)\n{\n int res=0;\n while(n!=0){\n res += (n&amp;1);\n n &gt;&gt;= 1; // logical right shift, like C unsigned or Java &gt;&gt;&gt;\n }\n return res;\n}\n</code></pre>\n<p><strong>Brian Kerningam's algorithm</strong></p>\n<p>Time Complexity is O(no of set bits in n)</p>\n<pre><code>int countSet(unsigned int n)\n{\n int res=0;\n while(n != 0)\n {\n n = (n &amp; (n-1));\n res++;\n }\n return res;\n} \n</code></pre>\n<p><strong>Lookup table method for 32-bit number-</strong> In this method we break the 32-bit number into chunks of four, 8-bit numbers</p>\n<p>Time Complexity is O(1)</p>\n<pre><code>static unsigned char table[256]; /* the table size is 256,\n the number of values i&amp;0xFF (8 bits) can have */\n\nvoid initialize() //holds the number of set bits from 0 to 255\n{\n table[0]=0;\n for(unsigned int i=1;i&lt;256;i++)\n table[i]=(i&amp;1)+table[i&gt;&gt;1];\n}\n\nint countSet(unsigned int n)\n{\n // 0xff is hexadecimal representation of 8 set bits.\n int res=table[n &amp; 0xff];\n n=n&gt;&gt;8;\n res=res+ table[n &amp; 0xff];\n n=n&gt;&gt;8;\n res=res+ table[n &amp; 0xff];\n n=n&gt;&gt;8;\n res=res+ table[n &amp; 0xff];\n return res;\n}\n</code></pre>\n" }, { "answer_id": 70767495, "author": "Andry", "author_id": 2672125, "author_profile": "https://Stackoverflow.com/users/2672125", "pm_score": 0, "selected": false, "text": "<p>For those who want it in <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11\" rel=\"nofollow noreferrer\">C++11</a> for any unsigned integer type as a consexpr function (<em><a href=\"https://github.com/andry81/tacklelib/blob/trunk/include/tacklelib/utility/math.hpp\" rel=\"nofollow noreferrer\">tacklelib/include/tacklelib/utility/math.hpp</a></em>):</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;stdint.h&gt;\n#include &lt;limits&gt;\n#include &lt;type_traits&gt;\n\nconst constexpr uint32_t uint32_max = (std::numeric_limits&lt;uint32_t&gt;::max)();\n\nnamespace detail\n{\n template &lt;typename T&gt;\n inline constexpr T _count_bits_0(const T &amp; v)\n {\n return v - ((v &gt;&gt; 1) &amp; 0x55555555);\n }\n\n template &lt;typename T&gt;\n inline constexpr T _count_bits_1(const T &amp; v)\n {\n return (v &amp; 0x33333333) + ((v &gt;&gt; 2) &amp; 0x33333333);\n }\n\n template &lt;typename T&gt;\n inline constexpr T _count_bits_2(const T &amp; v)\n {\n return (v + (v &gt;&gt; 4)) &amp; 0x0F0F0F0F;\n }\n\n template &lt;typename T&gt;\n inline constexpr T _count_bits_3(const T &amp; v)\n {\n return v + (v &gt;&gt; 8);\n }\n\n template &lt;typename T&gt;\n inline constexpr T _count_bits_4(const T &amp; v)\n {\n return v + (v &gt;&gt; 16);\n }\n\n template &lt;typename T&gt;\n inline constexpr T _count_bits_5(const T &amp; v)\n {\n return v &amp; 0x0000003F;\n }\n\n template &lt;typename T, bool greater_than_uint32&gt;\n struct _impl\n {\n static inline constexpr T _count_bits_with_shift(const T &amp; v)\n {\n return\n detail::_count_bits_5(\n detail::_count_bits_4(\n detail::_count_bits_3(\n detail::_count_bits_2(\n detail::_count_bits_1(\n detail::_count_bits_0(v)))))) + count_bits(v &gt;&gt; 32);\n }\n };\n\n template &lt;typename T&gt;\n struct _impl&lt;T, false&gt;\n {\n static inline constexpr T _count_bits_with_shift(const T &amp; v)\n {\n return 0;\n }\n };\n}\n\ntemplate &lt;typename T&gt;\ninline constexpr T count_bits(const T &amp; v)\n{\n static_assert(std::is_integral&lt;T&gt;::value, &quot;type T must be an integer&quot;);\n static_assert(!std::is_signed&lt;T&gt;::value, &quot;type T must be not signed&quot;);\n\n return uint32_max &gt;= v ?\n detail::_count_bits_5(\n detail::_count_bits_4(\n detail::_count_bits_3(\n detail::_count_bits_2(\n detail::_count_bits_1(\n detail::_count_bits_0(v)))))) :\n detail::_impl&lt;T, sizeof(uint32_t) &lt; sizeof(v)&gt;::_count_bits_with_shift(v);\n}\n</code></pre>\n<p>Plus tests in google test library:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\nnamespace {\n template &lt;typename T&gt;\n inline uint32_t _test_count_bits(const T &amp; v)\n {\n uint32_t count = 0;\n T n = v;\n while (n &gt; 0) {\n if (n % 2) {\n count += 1;\n }\n n /= 2;\n }\n return count;\n }\n}\n\nTEST(FunctionsTest, random_count_bits_uint32_100K)\n{\n srand(uint_t(time(NULL)));\n for (uint32_t i = 0; i &lt; 100000; i++) {\n const uint32_t r = uint32_t(rand()) + (uint32_t(rand()) &lt;&lt; 16);\n ASSERT_EQ(_test_count_bits(r), count_bits(r));\n }\n}\n\nTEST(FunctionsTest, random_count_bits_uint64_100K)\n{\n srand(uint_t(time(NULL)));\n for (uint32_t i = 0; i &lt; 100000; i++) {\n const uint64_t r = uint64_t(rand()) + (uint64_t(rand()) &lt;&lt; 16) + (uint64_t(rand()) &lt;&lt; 32) + (uint64_t(rand()) &lt;&lt; 48);\n ASSERT_EQ(_test_count_bits(r), count_bits(r));\n }\n}\n</code></pre>\n" }, { "answer_id": 70898893, "author": "Mayukh Pankaj", "author_id": 16168153, "author_profile": "https://Stackoverflow.com/users/16168153", "pm_score": 0, "selected": false, "text": "<h2>Counting set bits in binary representation (N):</h2>\n<h4>Pseudocode -</h4>\n<ol>\n<li><p>set counter = 0.</p>\n</li>\n<li><p>repeat counting till N is not zero.</p>\n</li>\n<li><p>check last bit.\nif last bit = 1 , increment counter</p>\n</li>\n<li><p>Discard last digit of N.</p>\n</li>\n</ol>\n<h4>Now let's code this in C++</h4>\n<pre><code>int countSetBits(unsigned int n){\n\nint count = 0;\n\nwhile(n!=0){\n\n count += n&amp;1;\n\n n = n &gt;&gt;1;\n}\n\n return count;\n\n}\n</code></pre>\n<p>Let's use this function.</p>\n<pre><code>int main(){\n\n int x = 5;\n cout&lt;&lt;countSetBits(x);\n\n return 0;\n}\n</code></pre>\n<p><em>Output:</em> 2</p>\n<p>Because 5 has 2 bits set in binary representation (101).</p>\n<p>You can run the code <a href=\"https://replit.com/@mayukhpankaj/countsetbits#main.cpp\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 71935909, "author": "Lance", "author_id": 169992, "author_profile": "https://Stackoverflow.com/users/169992", "pm_score": -1, "selected": false, "text": "<p>For JavaScript, you can count the number of set bits on a 32-bit value using a lookup table (and this code can be easily translated to C). In addition, added 8-bit and 16-bit versions for completeness for people who find this through web search.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const COUNT_BITS_TABLE = makeLookupTable()\n\nfunction makeLookupTable() {\n const table = new Uint8Array(256)\n for (let i = 0; i &lt; 256; i++) {\n table[i] = (i &amp; 1) + table[(i / 2) | 0];\n }\n return table\n}\n\nfunction countOneBits32(n) {\n return COUNT_BITS_TABLE[n &amp; 0xff] +\n COUNT_BITS_TABLE[(n &gt;&gt; 8) &amp; 0xff] +\n COUNT_BITS_TABLE[(n &gt;&gt; 16) &amp; 0xff] +\n COUNT_BITS_TABLE[(n &gt;&gt; 24) &amp; 0xff];\n}\n\nfunction countOneBits16(n) {\n return COUNT_BITS_TABLE[n &amp; 0xff] +\n COUNT_BITS_TABLE[(n &gt;&gt; 8) &amp; 0xff]\n}\n\nfunction countOneBits8(n) {\n return COUNT_BITS_TABLE[n &amp; 0xff]\n}\n\nconsole.log('countOneBits32', countOneBits32(0b10101010000000001010101000000000))\nconsole.log('countOneBits32', countOneBits32(0b10101011110000001010101000000000))\nconsole.log('countOneBits16', countOneBits16(0b1010101000000000))\nconsole.log('countOneBits8', countOneBits8(0b10000010))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
8 bits representing the number 7 look like this: ``` 00000111 ``` Three bits are set. What are the algorithms to determine the number of set bits in a 32-bit integer?
This is known as the '[Hamming Weight](https://en.wikipedia.org/wiki/Hamming_weight)', 'popcount' or 'sideways addition'. Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. Instructions like x86's [`popcnt`](https://www.felixcloutier.com/x86/popcnt) (on CPUs where it's supported) will almost certainly be fastest for a single integer. Some other architectures may have a slow instruction implemented with a microcoded loop that tests a bit per cycle (*citation needed* - hardware popcount is normally fast if it exists at all.). The 'best' algorithm really depends on which CPU you are on and what your usage pattern is. Your compiler may know how to do something that's good for the specific CPU you're compiling for, e.g. [C++20 `std::popcount()`](https://en.cppreference.com/w/cpp/numeric/popcount), or C++ [`std::bitset<32>::count()`](https://en.cppreference.com/w/cpp/utility/bitset/count), as a portable way to access builtin / intrinsic functions (see [another answer](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109069#109069) on this question). But your compiler's choice of fallback for target CPUs that don't have hardware popcnt might not be optimal for your use-case. Or your language (e.g. C) might not expose any portable function that could use a CPU-specific popcount when there is one. --- ### Portable algorithms that don't need (or benefit from) any HW support A pre-populated table lookup method can be very fast if your CPU has a large cache and you are doing lots of these operations in a tight loop. However it can suffer because of the expense of a 'cache miss', where the CPU has to fetch some of the table from main memory. (Look up each byte separately to keep the table small.) If you want popcount for a contiguous range of numbers, only the low byte is changing for groups of 256 numbers, [making this very good](https://stackoverflow.com/questions/66520106/count-integers-in-1-n-with-k-zero-bits-below-the-leading-1-popcount-for-a-c/66532113#66532113). If you know that your bytes will be mostly 0's or mostly 1's then there are efficient algorithms for these scenarios, e.g. clearing the lowest set with a bithack in a loop until it becomes zero. I believe a very good general purpose algorithm is the following, known as 'parallel' or 'variable-precision SWAR algorithm'. I have expressed this in a C-like pseudo language, you may need to adjust it to work for a particular language (e.g. using uint32\_t for C++ and >>> in Java): GCC10 and clang 10.0 can recognize this pattern / idiom and compile it to a hardware popcnt or equivalent instruction when available, giving you the best of both worlds. (<https://godbolt.org/z/qGdh1dvKK>) ```c int numberOfSetBits(uint32_t i) { // Java: use int, and use >>> instead of >>. Or use Integer.bitCount() // C or C++: use uint32_t i = i - ((i >> 1) & 0x55555555); // add pairs of bits i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8 return (i * 0x01010101) >> 24; // horizontal sum of bytes } ``` For JavaScript: [coerce to integer](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#comment103845611_109025) with `|0` for performance: change the first line to `i = (i|0) - ((i >> 1) & 0x55555555);` This has the best worst-case behaviour of any of the algorithms discussed, so will efficiently deal with any usage pattern or values you throw at it. (Its performance is not data-dependent on normal CPUs where all integer operations including multiply are constant-time. It doesn't get any faster with "simple" inputs, but it's still pretty decent.) References: * [https://graphics.stanford.edu/~seander/bithacks.html](https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel) * <https://catonmat.net/low-level-bit-hacks> for bithack basics, like how subtracting 1 flips contiguous zeros. * <https://en.wikipedia.org/wiki/Hamming_weight> * <http://gurmeet.net/puzzles/fast-bit-counting-routines/> * <http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)> --- ### How this SWAR bithack works: ``` i = i - ((i >> 1) & 0x55555555); ``` The first step is an optimized version of masking to isolate the odd / even bits, shifting to line them up, and adding. This effectively does 16 separate additions in 2-bit accumulators ([SWAR = SIMD Within A Register](https://en.wikipedia.org/wiki/SWAR)). Like `(i & 0x55555555) + ((i>>1) & 0x55555555)`. The next step takes the odd/even eight of those 16x 2-bit accumulators and adds again, producing 8x 4-bit sums. The `i - ...` optimization isn't possible this time so it does just mask before / after shifting. Using the same `0x33...` constant both times instead of `0xccc...` before shifting is a good thing when compiling for ISAs that need to construct 32-bit constants in registers separately. The final shift-and-add step of `(i + (i >> 4)) & 0x0F0F0F0F` widens to 4x 8-bit accumulators. It masks *after* adding instead of before, because the maximum value in any 4-bit accumulator is `4`, if all 4 bits of the corresponding input bits were set. 4+4 = 8 which still fits in 4 bits, so carry between nibble elements is impossible in `i + (i >> 4)`. So far this is just fairly normal SIMD using SWAR techniques with a few clever optimizations. Continuing on with the same pattern for 2 more steps can widen to 2x 16-bit then 1x 32-bit counts. But there is a more efficient way on machines with fast hardware multiply: Once we have few enough "elements", **a multiply with a magic constant can sum all the elements into the top element**. In this case byte elements. Multiply is done by left-shifting and adding, so **a multiply of `x * 0x01010101` results in `x + (x<<8) + (x<<16) + (x<<24)`.** Our 8-bit elements are wide enough (and holding small enough counts) that this doesn't produce carry *into* that top 8 bits. **A 64-bit version of this** can do 8x 8-bit elements in a 64-bit integer with a 0x0101010101010101 multiplier, and extract the high byte with `>>56`. So it doesn't take any extra steps, just wider constants. This is what GCC uses for `__builtin_popcountll` on x86 systems when the hardware `popcnt` instruction isn't enabled. If you can use builtins or intrinsics for this, do so to give the compiler a chance to do target-specific optimizations. --- ### With full SIMD for wider vectors (e.g. counting a whole array) This bitwise-SWAR algorithm could parallelize to be done in multiple vector elements at once, instead of in a single integer register, for a speedup on CPUs with SIMD but no usable popcount instruction. (e.g. x86-64 code that has to run on any CPU, not just Nehalem or later.) However, the best way to use vector instructions for popcount is usually by using a variable-shuffle to do a table-lookup for 4 bits at a time of each byte in parallel. (The 4 bits index a 16 entry table held in a vector register). On Intel CPUs, the hardware 64bit popcnt instruction can outperform an [SSSE3 `PSHUFB` bit-parallel implementation](http://wm.ite.pl/articles/sse-popcount.html) by about a factor of 2, but only [if your compiler gets it just right](http://danluu.com/assembly-intrinsics/). Otherwise SSE can come out significantly ahead. Newer compiler versions are aware of the [popcnt false dependency](https://stackoverflow.com/a/25089720/224132) [problem on Intel](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011). * <https://github.com/WojciechMula/sse-popcount> state-of-the-art x86 SIMD popcount for SSSE3, AVX2, AVX512BW, AVX512VBMI, or AVX512 VPOPCNT. Using Harley-Seal across vectors to defer popcount within an element. (Also ARM NEON) * [Counting 1 bits (population count) on large data using AVX-512 or AVX-2](https://stackoverflow.com/questions/50081465/counting-1-bits-population-count-on-large-data-using-avx-512-or-avx-2) * related: <https://github.com/mklarqvist/positional-popcount> - separate counts for each bit-position of multiple 8, 16, 32, or 64-bit integers. (Again, x86 SIMD including AVX-512 which is really good at this, with `vpternlogd` making Harley-Seal *very* good.)
109,044
<p>I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL.</p> <p>Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions.</p> <pre><code>bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline; routes.MapRoute( "Default", usingIntegratedPipeline ? "{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre> <p><strong>Update</strong>: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server.</p>
[ { "answer_id": 109103, "author": "alex", "author_id": 19268, "author_profile": "https://Stackoverflow.com/users/19268", "pm_score": 0, "selected": false, "text": "<p>You can use an ISAPI filter to rewrite URLs which will allow you to have the nice URLs while still on IIS 6. </p>\n\n<p>Look, for example, <a href=\"http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 109115, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 3, "selected": true, "text": "<p>That should fix the .mvc problem since the integrated pipeline is IIS7 strictly.\nBut remember to change settings on the IIS7 website to use \"2.0 Integrated Pipeline\" otherwhise it will return false aswell.\nAlso ofcouse setup the mapping of .mvc to the asp.net isapi dll, but Im guessing that you already know this.</p>\n\n<p>Some small suggestions on other things you might need to remember when deploying MVC applications on IIS6 that I found useful:\n<a href=\"http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx\" rel=\"nofollow noreferrer\">http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL. Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions. ``` bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline; routes.MapRoute( "Default", usingIntegratedPipeline ? "{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); ``` **Update**: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server.
That should fix the .mvc problem since the integrated pipeline is IIS7 strictly. But remember to change settings on the IIS7 website to use "2.0 Integrated Pipeline" otherwhise it will return false aswell. Also ofcouse setup the mapping of .mvc to the asp.net isapi dll, but Im guessing that you already know this. Some small suggestions on other things you might need to remember when deploying MVC applications on IIS6 that I found useful: <http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx>
109,064
<p>Could you recommend me a way to place a coundown timer on ASP.NET page?</p> <p>Now I use this code:</p> <p><strong>Default.aspx</strong></p> <pre><code>&lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:Label ID="Label1" runat="server"&gt;60&lt;/asp:Label&gt; &lt;asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"&gt; &lt;/asp:Timer&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p><strong>Default.aspx.cs</strong></p> <pre><code>protected void Timer1_Tick(object sender, EventArgs e) { int seconds = int.Parse(Label1.Text); if (seconds &gt; 0) Label1.Text = (seconds - 1).ToString(); else Timer1.Enabled = false; } </code></pre> <p>But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET? </p>
[ { "answer_id": 109096, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>You might add something like this in your .aspx page</p>\n\n<pre><code>&lt;form name=\"counter\"&gt;&lt;input type=\"text\" size=\"8\" \nname=\"d2\"&gt;&lt;/form&gt; \n\n&lt;script&gt; \n&lt;!-- \n// \n var milisec=0 \n var seconds=30 \n document.counter.d2.value='30' \n\nfunction display(){ \n if (milisec&lt;=0){ \n milisec=9 \n seconds-=1 \n } \n if (seconds&lt;=-1){ \n milisec=0 \n seconds+=1 \n } \n else \n milisec-=1 \n document.counter.d2.value=seconds+\".\"+milisec \n setTimeout(\"display()\",100) \n} \ndisplay() \n--&gt; \n&lt;/script&gt; \n</code></pre>\n\n<p>Found <a href=\"http://www.java-scripts.net/javascripts/Countdown-Timer.phtml\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 111002, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": true, "text": "<p>OK, finally I ended with</p>\n\n<pre><code>&lt;span id=\"timerLabel\" runat=\"server\"&gt;&lt;/span&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n\n function countdown() \n {\n seconds = document.getElementById(\"timerLabel\").innerHTML;\n if (seconds &gt; 0) \n {\n document.getElementById(\"timerLabel\").innerHTML = seconds - 1;\n setTimeout(\"countdown()\", 1000);\n }\n }\n\n setTimeout(\"countdown()\", 1000);\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Really simple. Like old good plain HTML with JavaScript.</p>\n" }, { "answer_id": 3492283, "author": "rakesh", "author_id": 421610, "author_profile": "https://Stackoverflow.com/users/421610", "pm_score": 1, "selected": false, "text": "<p>use this javascript code----</p>\n\n<pre><code>var sec=0 ;\n var min=0;\nvar hour=0;\nvar t;\n\nfunction display(){ \n if (sec&lt;=0){ \n sec+=1;\n } \nif(sec==60)\n{\nsec=0;\nmin+=1;\n}\nif(min==60){\nhour+=1;\nmin=0;\n}\n\n if (min&lt;=-1){ \n sec=0; \n min+=1;\n } \n\n else \n sec+=1 ;\ndocument.getElementById(\"&lt;%=TextBox1.ClientID%&gt;\").value=hour+\":\"+min+\":\"+sec;\n t=setTimeout(\"display()\",1000);\n }\nwindow.onload=display; \n</code></pre>\n" }, { "answer_id": 5014096, "author": "user554151", "author_id": 554151, "author_profile": "https://Stackoverflow.com/users/554151", "pm_score": 2, "selected": false, "text": "<pre><code>time1 = (DateTime)ViewState[\"time\"] - DateTime.Now;\n\nif (time1.TotalSeconds &lt;= 0)\n{\n Label1.Text = Label2.Text = \"TimeOut!\"; \n}\nelse\n{\n if (time1.TotalMinutes &gt; 59)\n {\n Label1.Text = Label2.Text = string.Format(\"{0}:{1:D2}:{2:D2}\",\n time1.Hours,\n time1.Minutes,\n time1.Seconds);\n }\n else\n {\n Label1.Text = Label2.Text = string.Format(\"{0:D2}:{1:D2}\", \n time1.Minutes,\n time1.Seconds);\n }\n}\n</code></pre>\n" }, { "answer_id": 8153199, "author": "Casselj", "author_id": 1049861, "author_profile": "https://Stackoverflow.com/users/1049861", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\"&gt;\n var sec = 10;\n var min = 0\n var hour = 0;\n var t;\n\n function display() {\n sec -= 1\n if ((sec == 0) &amp;&amp; (min == 0) &amp;&amp; (hour == 0)) {\n //if a popup window is used:\n setTimeout(\"self.close()\", 1000);\n return;\n }\n if (sec &lt; 0) {\n sec = 59;\n min -= 1;\n }\n if (min &lt; 0) {\n min = 59;\n hour -= 1;\n }\n else\n document.getElementById(\"&lt;%=TextBox1.ClientID%&gt;\").value = hour + \":\" + min + \":\" + sec;\n t = setTimeout(\"display()\", 1000);\n }\n window.onload = display; \n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
Could you recommend me a way to place a coundown timer on ASP.NET page? Now I use this code: **Default.aspx** ``` <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server">60</asp:Label> <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"> </asp:Timer> </ContentTemplate> </asp:UpdatePanel> ``` **Default.aspx.cs** ``` protected void Timer1_Tick(object sender, EventArgs e) { int seconds = int.Parse(Label1.Text); if (seconds > 0) Label1.Text = (seconds - 1).ToString(); else Timer1.Enabled = false; } ``` But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET?
OK, finally I ended with ``` <span id="timerLabel" runat="server"></span> <script type="text/javascript"> function countdown() { seconds = document.getElementById("timerLabel").innerHTML; if (seconds > 0) { document.getElementById("timerLabel").innerHTML = seconds - 1; setTimeout("countdown()", 1000); } } setTimeout("countdown()", 1000); </script> ``` Really simple. Like old good plain HTML with JavaScript.
109,066
<p>I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.</p> <p>See answers for the link</p>
[ { "answer_id": 109067, "author": "Eliram", "author_id": 18790, "author_profile": "https://Stackoverflow.com/users/18790", "pm_score": 1, "selected": false, "text": "<pre><code>var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;\n</code></pre>\n\n<p>The entire article is at:</p>\n\n<p><a href=\"http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html\" rel=\"nofollow noreferrer\">http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html</a></p>\n\n<p>Important note! This will only work in the main class. If you'll try to load the parameters in a subclass you'll get nothing.</p>\n" }, { "answer_id": 132047, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 3, "selected": true, "text": "<p>Not sure why <a href=\"http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html\" rel=\"nofollow noreferrer\">his example</a> calls LoaderInfo. The <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html\" rel=\"nofollow noreferrer\">DisplayObject</a> class has its own (readonly) <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html#loaderInfo\" rel=\"nofollow noreferrer\">loaderinfo</a> property. As long as your main class extends a DisplayObject, you can call the property directly</p>\n\n<pre><code>package {\n import flash.display.Sprite;\n\n public class Main extends Sprite {\n\n public function Main() {\n var test1:String = '';\n\n if (this.loaderInfo.parameters.test1 !== undefined) {\n test1 = this.loaderInfo.parameters.test1;\n }\n }\n }\n}\n</code></pre>\n\n<p>From the doc:</p>\n\n<blockquote>\n <p>Returns a LoaderInfo object containing\n information about loading the file to\n which this display object belongs. The\n loaderInfo property is defined only\n for the root display object of a SWF\n file or for a loaded Bitmap (not for a\n Bitmap that is drawn with\n ActionScript). To find the loaderInfo\n object associated with the SWF file\n that contains a display object named\n myDisplayObject, use\n myDisplayObject.root.loaderInfo.</p>\n</blockquote>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18790/" ]
I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters. See answers for the link
Not sure why [his example](http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html) calls LoaderInfo. The [DisplayObject](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html) class has its own (readonly) [loaderinfo](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html#loaderInfo) property. As long as your main class extends a DisplayObject, you can call the property directly ``` package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var test1:String = ''; if (this.loaderInfo.parameters.test1 !== undefined) { test1 = this.loaderInfo.parameters.test1; } } } } ``` From the doc: > > Returns a LoaderInfo object containing > information about loading the file to > which this display object belongs. The > loaderInfo property is defined only > for the root display object of a SWF > file or for a loaded Bitmap (not for a > Bitmap that is drawn with > ActionScript). To find the loaderInfo > object associated with the SWF file > that contains a display object named > myDisplayObject, use > myDisplayObject.root.loaderInfo. > > >
109,086
<p>I am using <code>setInterval(fname, 10000);</code> to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? </p> <p>I want the user to be able to stop the repeated refresh of data.</p>
[ { "answer_id": 109091, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 12, "selected": true, "text": "<p><code>setInterval()</code> returns an interval ID, which you can pass to <code>clearInterval()</code>:</p>\n<pre><code>var refreshIntervalId = setInterval(fname, 10000);\n\n/* later */\nclearInterval(refreshIntervalId);\n</code></pre>\n<p>See the docs for <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"noreferrer\"><code>setInterval()</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval\" rel=\"noreferrer\"><code>clearInterval()</code></a>.</p>\n" }, { "answer_id": 109098, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 7, "selected": false, "text": "<p>If you set the return value of <code>setInterval</code> to a variable, you can use <code>clearInterval</code> to stop it.</p>\n\n<pre><code>var myTimer = setInterval(...);\nclearInterval(myTimer);\n</code></pre>\n" }, { "answer_id": 2844027, "author": "OMGrant", "author_id": 342388, "author_profile": "https://Stackoverflow.com/users/342388", "pm_score": 6, "selected": false, "text": "<p>You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:</p>\n\n<pre><code>var intervalId = null;\nvar varCounter = 0;\nvar varName = function(){\n if(varCounter &lt;= 10) {\n varCounter++;\n /* your code goes here */\n } else {\n clearInterval(intervalId);\n }\n};\n\n$(document).ready(function(){\n intervalId = setInterval(varName, 10000);\n});\n</code></pre>\n\n<p>I hope that it helps and it is right.</p>\n" }, { "answer_id": 29902905, "author": "Aart den Braber", "author_id": 1056159, "author_profile": "https://Stackoverflow.com/users/1056159", "pm_score": -1, "selected": false, "text": "<h2>Why not use a simpler approach? Add a class!</h2>\n\n<p>Simply add a class that tells the interval not to do anything. For example: on hover.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var i = 0;\r\nthis.setInterval(function() {\r\n if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'\r\n console.log('Counting...');\r\n $('#counter').html(i++); //just for explaining and showing\r\n } else {\r\n console.log('Stopped counting');\r\n }\r\n}, 500);\r\n\r\n/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */\r\n$('#counter').hover(function() { //mouse enter\r\n $(this).addClass('pauseInterval');\r\n },function() { //mouse leave\r\n $(this).removeClass('pauseInterval');\r\n }\r\n);\r\n\r\n/* Other example */\r\n$('#pauseInterval').click(function() {\r\n $('#counter').toggleClass('pauseInterval');\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n background-color: #eee;\r\n font-family: Calibri, Arial, sans-serif;\r\n}\r\n#counter {\r\n width: 50%;\r\n background: #ddd;\r\n border: 2px solid #009afd;\r\n border-radius: 5px;\r\n padding: 5px;\r\n text-align: center;\r\n transition: .3s;\r\n margin: 0 auto;\r\n}\r\n#counter.pauseInterval {\r\n border-color: red; \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!-- you'll need jQuery for this. If you really want a vanilla version, ask --&gt;\r\n&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\n\r\n&lt;p id=\"counter\"&gt;&amp;nbsp;&lt;/p&gt;\r\n&lt;button id=\"pauseInterval\"&gt;Pause&lt;/button&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.</p>\n" }, { "answer_id": 39104954, "author": "Onur Yıldırım", "author_id": 112731, "author_profile": "https://Stackoverflow.com/users/112731", "pm_score": 4, "selected": false, "text": "<p>Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my <a href=\"https://github.com/onury/tasktimer\" rel=\"noreferrer\">TaskTimer</a> (for Node and browser). </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// Timer with 1000ms (1 second) base interval resolution.\nconst timer = new TaskTimer(1000);\n\n// Add task(s) based on tick intervals.\ntimer.add({\n id: 'job1', // unique id of the task\n tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)\n totalRuns: 10, // run 10 times only. (omit for unlimited times)\n callback(task) {\n // code to be executed on each run\n console.log(task.name + ' task has run ' + task.currentRuns + ' times.');\n // stop the timer anytime you like\n if (someCondition()) timer.stop();\n // or simply remove this task if you have others\n if (someCondition()) timer.remove(task.id);\n }\n});\n\n// Start the timer\ntimer.start();\n</code></pre>\n\n<p>In your case, when users click for disturbing the data-refresh; you can also call <code>timer.pause()</code> then <code>timer.resume()</code> if they need to re-enable.</p>\n\n<p>See <a href=\"https://onury.io/tasktimer/api\" rel=\"noreferrer\">more here</a>.</p>\n" }, { "answer_id": 63892625, "author": "assayag.org", "author_id": 2244093, "author_profile": "https://Stackoverflow.com/users/2244093", "pm_score": 3, "selected": false, "text": "<p>In nodeJS you can you use the &quot;<strong>this</strong>&quot; special keyword within the setInterval function.</p>\n<p>You can use this <strong>this</strong> keyword to clearInterval, and here is an example:</p>\n<pre><code>setInterval(\n function clear() {\n clearInterval(this) \n return clear;\n }()\n, 1000)\n</code></pre>\n<p>When you print the value of <strong>this</strong> special keyword within the function you output a Timeout object <code>Timeout {...}</code></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
I am using `setInterval(fname, 10000);` to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? I want the user to be able to stop the repeated refresh of data.
`setInterval()` returns an interval ID, which you can pass to `clearInterval()`: ``` var refreshIntervalId = setInterval(fname, 10000); /* later */ clearInterval(refreshIntervalId); ``` See the docs for [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) and [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval).
109,087
<p>Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:</p> <pre><code>class hi: def __init__(self): self.ii = "foo" self.kk = "bar" </code></pre> <p>Is there a way for me to do this:</p> <pre><code>&gt;&gt;&gt; mystery_method(hi) ["ii", "kk"] </code></pre> <p>Edit: I originally had asked for class variables erroneously.</p>
[ { "answer_id": 109106, "author": "cnu", "author_id": 1448, "author_profile": "https://Stackoverflow.com/users/1448", "pm_score": 9, "selected": true, "text": "<p>Every object has a <code>__dict__</code> variable containing all the variables and its values in it.</p>\n<p>Try this</p>\n<pre><code>&gt;&gt;&gt; hi_obj = hi()\n&gt;&gt;&gt; hi_obj.__dict__.keys()\n</code></pre>\n<p>Output</p>\n<pre><code>dict_keys(['ii', 'kk'])\n</code></pre>\n" }, { "answer_id": 109118, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "<p>You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the __init__ method.</p>\n\n<p>An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in <a href=\"http://www.python.org/2.2.3/descrintro.html\" rel=\"noreferrer\">http://www.python.org/2.2.3/descrintro.html</a>, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.</p>\n" }, { "answer_id": 109122, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 4, "selected": false, "text": "<p>You can also test if an object has a specific variable with:</p>\n<pre><code>&gt;&gt;&gt; hi_obj = hi()\n&gt;&gt;&gt; hasattr(hi_obj, &quot;some attribute&quot;)\nFalse\n&gt;&gt;&gt; hasattr(hi_obj, &quot;ii&quot;)\nTrue\n&gt;&gt;&gt; hasattr(hi_obj, &quot;kk&quot;)\nTrue\n</code></pre>\n" }, { "answer_id": 109127, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>Your example shows \"instance variables\", not really class variables.</p>\n\n<p>Look in <code>hi_obj.__class__.__dict__.items()</code> for the class variables, along with other other class members like member functions and the containing module.</p>\n\n<pre><code>class Hi( object ):\n class_var = ( 23, 'skidoo' ) # class variable\n def __init__( self ):\n self.ii = \"foo\" # instance variable\n self.jj = \"bar\"\n</code></pre>\n\n<p>Class variables are shared by all instances of the class.</p>\n" }, { "answer_id": 109173, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 7, "selected": false, "text": "<p>Use vars()</p>\n\n<pre><code>class Foo(object):\n def __init__(self):\n self.a = 1\n self.b = 2\n\nvars(Foo()) #==&gt; {'a': 1, 'b': 2}\nvars(Foo()).keys() #==&gt; ['a', 'b']\n</code></pre>\n" }, { "answer_id": 109207, "author": "daniel", "author_id": 19741, "author_profile": "https://Stackoverflow.com/users/19741", "pm_score": 3, "selected": false, "text": "<p>Suggest</p>\n\n<pre><code>&gt;&gt;&gt; print vars.__doc__\nvars([object]) -&gt; dictionary\n\nWithout arguments, equivalent to locals().\nWith an argument, equivalent to object.__dict__.\n</code></pre>\n\n<p>In otherwords, it essentially just wraps __dict__ </p>\n" }, { "answer_id": 111876, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 3, "selected": false, "text": "<p>Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:</p>\n\n<pre><code>&gt;&gt;&gt; def f(x, y):\n z = x**2 + y**2\n sqrt_z = z**.5\n return sqrt_z\n\n&gt;&gt;&gt; f.func_code.co_varnames\n('x', 'y', 'z', 'sqrt_z')\n&gt;&gt;&gt; \n</code></pre>\n\n<p>The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:</p>\n\n<pre><code>def exec_command(self, cmd, msg, sig):\n\n def message(msg):\n a = self.link.process(self.link.recieved_message(msg))\n self.exec_command(*a)\n\n def error(msg):\n self.printer.printInfo(msg)\n\n def set_usrlist(msg):\n self.client.connected_users = msg\n\n def chatmessage(msg):\n self.printer.printInfo(msg)\n\n if not locals().has_key(cmd): return\n cmd = locals()[cmd]\n\n try:\n if 'sig' in cmd.func_code.co_varnames and \\\n 'msg' in cmd.func_code.co_varnames: \n cmd(msg, sig)\n elif 'msg' in cmd.func_code.co_varnames: \n cmd(msg)\n else:\n cmd()\n except Exception, e:\n print '\\n-----------ERROR-----------'\n print 'error: ', e\n print 'Error proccessing: ', cmd.__name__\n print 'Message: ', msg\n print 'Sig: ', sig\n print '-----------ERROR-----------\\n'\n</code></pre>\n" }, { "answer_id": 4522706, "author": "dmark", "author_id": 552829, "author_profile": "https://Stackoverflow.com/users/552829", "pm_score": 4, "selected": false, "text": "<p>Both the Vars() and dict methods will work for the example the OP posted, but they won't work for \"loosely\" defined objects like:</p>\n\n<pre><code>class foo:\n a = 'foo'\n b = 'bar'\n</code></pre>\n\n<p>To print all non-callable attributes, you can use the following function:</p>\n\n<pre><code>def printVars(object):\n for i in [v for v in dir(object) if not callable(getattr(object,v))]:\n print '\\n%s:' % i\n exec('print object.%s\\n\\n') % i\n</code></pre>\n" }, { "answer_id": 56897819, "author": "Ethan Joffe", "author_id": 1516256, "author_profile": "https://Stackoverflow.com/users/1516256", "pm_score": 2, "selected": false, "text": "<p>built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...</p>\n\n<pre><code>def sprint(object):\n result = ''\n for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:\n result += '\\n%s:' % i + str(getattr(object, i, ''))\n return result\n</code></pre>\n" }, { "answer_id": 61438322, "author": "hi2meuk", "author_id": 9638474, "author_profile": "https://Stackoverflow.com/users/9638474", "pm_score": 2, "selected": false, "text": "<p>Sometimes you want to filter the list based on public/private vars. E.g.</p>\n\n<pre><code>def pub_vars(self):\n \"\"\"Gives the variable names of our instance we want to expose\n \"\"\"\n return [k for k in vars(self) if not k.startswith('_')]\n</code></pre>\n" }, { "answer_id": 65427547, "author": "Eric Silveira", "author_id": 13430089, "author_profile": "https://Stackoverflow.com/users/13430089", "pm_score": 0, "selected": false, "text": "<p>You will need to first, <strong>examine the class</strong>, next, <strong>examine the bytecode for functions</strong>, then, <strong>copy the bytecode</strong>, and finally, <strong>use the <code>__code__.co_varnames</code></strong>. <strong>This is tricky</strong> because <strong>some classes create their methods using constructors like those in the <code>types</code> module</strong>. I will provide code for it on <a href=\"https://github.com/g7a20/class-inst-vars\" rel=\"nofollow noreferrer\">GitHub</a>.</p>\n" }, { "answer_id": 71689332, "author": "Valentin", "author_id": 11221432, "author_profile": "https://Stackoverflow.com/users/11221432", "pm_score": 0, "selected": false, "text": "<p>Based on answer of Ethan Joffe</p>\n<pre><code>def print_inspect(obj):\n print(f&quot;{type(obj)}\\n&quot;)\n var_names = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith(&quot;__&quot;)]\n for v in var_names: \n print(f&quot;\\tself.{v} = {getattr(obj, v)}\\n&quot;)\n\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Edit: I originally had asked for class variables erroneously.
Every object has a `__dict__` variable containing all the variables and its values in it. Try this ``` >>> hi_obj = hi() >>> hi_obj.__dict__.keys() ``` Output ``` dict_keys(['ii', 'kk']) ```
109,134
<p>How do I change the style (color) of a div such as the following? </p> <pre><code>"&lt;div id=foo class="ed" style="display: &lt;%= ((foo.isTrue) ? string.Empty : "none") %&gt;"&gt; &lt;%= ((foo.isTrue) ? foo.Name: "false foo") %&gt;"` </code></pre>
[ { "answer_id": 109140, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 0, "selected": false, "text": "<p>That code fragment doesn't say much - if the code is server-side why don't you change e.g. the class of the HTML element there?</p>\n" }, { "answer_id": 109142, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "<p>It looks like you are writing ASP, or maybe JSP. I'm not too familiar with either language, but the principles are the same no matter what language you are working in.</p>\n\n<p>If you are working with a limited number of colours, then the usual option is to create a number of classes and write rule-sets for them in your stylesheet:</p>\n\n<pre><code>\n.important { background: red; }\n.todo { background: blue; }\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Then have your server side script generate the HTML to make the CSS match:</p>\n\n<pre><code>\n&lt;div class=\"important\">\n</code></pre>\n\n<p>You should, of course, <a href=\"http://www.w3.org/TR/WCAG10-CSS-TECHS/#style-info-not-in-color-alone\" rel=\"nofollow noreferrer\">ensure that the information is available through means other than colour</a> as well.</p>\n\n<p>If the colours are determined at run time, then you can generate style attributes:</p>\n\n<pre><code>\n&lt;div style=\"background-color: red;\">\n</code></pre>\n" }, { "answer_id": 109145, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "<p>You should set your colors in CSS, and then change the CSS class programatically. For example:</p>\n\n<p>(CSS)</p>\n\n<pre><code>div.Error {\n color:red;\n}\n</code></pre>\n\n<p>(ASP.NET/VB)</p>\n\n<pre><code>&lt;div class='&lt;%=Iif(HasError, \"Error\", \"\")%&gt;'&gt; .... &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 109152, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 2, "selected": false, "text": "<p>Generally, you can do it directly</p>\n\n<p>document.getElementById(\"myDiv\").style.color = \"red\";</p>\n\n<p>There's a reference <a href=\"http://w3schools.com/htmldom/dom_obj_style.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 109159, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 4, "selected": true, "text": "<p>If you want to alter the color of the div with client side code (javascript) running in the browser, you do something like the following:</p>\n\n<pre><code>&lt;script&gt;\n var fooElement = document.getElementById(\"foo\");\n fooElement.style.color = \"red\"; //to change the font color\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 109160, "author": "starec", "author_id": 19727, "author_profile": "https://Stackoverflow.com/users/19727", "pm_score": 3, "selected": false, "text": "<p>Try this:\nin the .aspx file put thees lines</p>\n\n<pre><code>&lt;div id=\"myDiv\" runat=\"server\"&gt;\n Some text\n&lt;/div&gt;\n</code></pre>\n\n<p>then you can use for example</p>\n\n<pre><code>myDiv.Style[\"color\"] = \"red\";\n</code></pre>\n" }, { "answer_id": 3213603, "author": "Ben Call", "author_id": 328042, "author_profile": "https://Stackoverflow.com/users/328042", "pm_score": 3, "selected": false, "text": "<p>If you wanted to change the class instead of the style directly:\nie.. create another class with the styling you want...</p>\n\n<pre><code>myDiv.Attributes[\"class\"] = \"otherClassName\"\n</code></pre>\n" }, { "answer_id": 61762611, "author": "Deathstalker", "author_id": 773704, "author_profile": "https://Stackoverflow.com/users/773704", "pm_score": 0, "selected": false, "text": "<p>IMO this is the better way to do it. I found some of this in other posts but this one comes up first in google search. </p>\n\n<p>This part works for standard JavaScript. I am pretty sure you can use it to remove all styles as well as add/overwite. </p>\n\n<pre><code>var div = document.createElement('div');\ndiv.style.cssText = \"border-radius: 6px 6px 6px 6px; height: 250px; width: 600px\";\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>var div = document.getElementById('foo');\ndiv.style.cssText = \"background-color: red;\";\n</code></pre>\n\n<p>This works for jQuery only</p>\n\n<pre><code>$(\"#\" + TDDeviceTicketID).attr(\"style\", \"padding: 10px;\");\n$(\"#\" + TDDeviceTicketID).attr(\"class\", \"roundbox1\");\n\nThis works for removing it JQUERY\n$(\"#\" + TDDeviceTicketID).removeAttr(\"style\");\n$(\"#\" + TDDeviceTicketID).removeAttr(\"class\");\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
How do I change the style (color) of a div such as the following? ``` "<div id=foo class="ed" style="display: <%= ((foo.isTrue) ? string.Empty : "none") %>"> <%= ((foo.isTrue) ? foo.Name: "false foo") %>"` ```
If you want to alter the color of the div with client side code (javascript) running in the browser, you do something like the following: ``` <script> var fooElement = document.getElementById("foo"); fooElement.style.color = "red"; //to change the font color </script> ```
109,232
<p>What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?</p>
[ { "answer_id": 109258, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": -1, "selected": false, "text": "<p>You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.</p>\n\n<ul>\n<li>Create a scrollable resultset / dataset. This required a primary on the table(s)</li>\n<li>jump to the end</li>\n<li>request the row count </li>\n<li>jump to the start of the page</li>\n<li>scroll through the rows until the end of the page</li>\n</ul>\n" }, { "answer_id": 109290, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 10, "selected": true, "text": "<p>Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is</p>\n\n<pre><code>SELECT * FROM Orders WHERE OrderDate &gt;= '1980-01-01' ORDER BY OrderDate\n</code></pre>\n\n<p>In this case, you would determine the total number of results using:</p>\n\n<pre><code>SELECT COUNT(*) FROM Orders WHERE OrderDate &gt;= '1980-01-01'\n</code></pre>\n\n<p>...which may seem inefficient, but is actually pretty performant, assuming all indexes etc. are properly set up.</p>\n\n<p>Next, to get actual results back in a paged fashion, the following query would be most efficient:</p>\n\n<pre><code>SELECT *\nFROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *\n FROM Orders\n WHERE OrderDate &gt;= '1980-01-01'\n ) AS RowConstrainedResult\nWHERE RowNum &gt;= 1\n AND RowNum &lt; 20\nORDER BY RowNum\n</code></pre>\n\n<p>This will return rows 1-19 of the original query. The cool thing here, especially for web apps, is that you don't have to keep any state, except the row numbers to be returned.</p>\n" }, { "answer_id": 109338, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 4, "selected": false, "text": "<p>There is a good overview of different paging techniques at <a href=\"http://www.codeproject.com/KB/aspnet/PagingLarge.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/PagingLarge.aspx</a></p>\n\n<p>I've used ROWCOUNT method quite often mostly with SQL Server 2000 (will work with 2005 &amp; 2008 too, just measure performance compared to ROW_NUMBER), it's lightning fast, but you need to make sure that the sorted column(s) have (mostly) unique values.</p>\n" }, { "answer_id": 980555, "author": "Jalal El-Shaer", "author_id": 95380, "author_profile": "https://Stackoverflow.com/users/95380", "pm_score": 0, "selected": false, "text": "<p>Well I have used the following sample query in my SQL 2000 database, it works well for SQL 2005 too. The power it gives you is dynamically order by using multiple columns. \nI tell you ... this is powerful :) </p>\n\n<pre><code> ALTER PROCEDURE [dbo].[RE_ListingReports_SelectSummary] \n\n@CompanyID int,\n@pageNumber int,\n@pageSize int, \n@sort varchar(200)\nAS\n\nDECLARE @sql nvarchar(4000)\nDECLARE @strPageSize nvarchar(20)\nDECLARE @strSkippedRows nvarchar(20)\nDECLARE @strFields nvarchar(4000)\nDECLARE @strFilter nvarchar(4000)\nDECLARE @sortBy nvarchar(4000)\nDECLARE @strFrom nvarchar(4000)\nDECLARE @strID nvarchar(100)\n\nIf(@pageNumber &lt; 0)\n SET @pageNumber = 1\nSET @strPageSize = CAST(@pageSize AS varchar(20)) \nSET @strSkippedRows = CAST(((@pageNumber - 1) * @pageSize) AS varchar(20))-- For example if pageNumber is 5 pageSize is 10, then SkippedRows = 40.\nSET @strID = 'ListingDbID'\nSET @strFields = 'ListingDbID,\nListingID, \n[ExtraRoom]\n'\nSET @strFrom = ' vwListingSummary '\n\nSET @strFilter = ' WHERE\n CompanyID = ' + CAST(@CompanyID As varchar(20)) \nEnd\nSET @sortBy = ''\nif(len(ltrim(rtrim(@sort))) &gt; 0)\nSET @sortBy = ' Order By ' + @sort\n\n-- Total Rows Count\n\nSET @sql = 'SELECT Count(' + @strID + ') FROM ' + @strFROM + @strFilter\nEXEC sp_executesql @sql\n\n--// This technique is used in a Single Table pagination\nSET @sql = 'SELECT ' + @strFields + ' FROM ' + @strFROM +\n ' WHERE ' + @strID + ' IN ' + \n ' (SELECT TOP ' + @strPageSize + ' ' + @strID + ' FROM ' + @strFROM + @strFilter + \n ' AND ' + @strID + ' NOT IN ' + '\n (SELECT TOP ' + @strSkippedRows + ' ' + @strID + ' FROM ' + @strFROM + @strFilter + @SortBy + ') ' \n + @SortBy + ') ' + @SortBy\nPrint @sql \nEXEC sp_executesql @sql\n</code></pre>\n\n<p>The best part is sp_executesql caches later calls, provided you pass same parameters i.e generate same sql text.</p>\n" }, { "answer_id": 9895345, "author": "Thomas S. Trias", "author_id": 189048, "author_profile": "https://Stackoverflow.com/users/189048", "pm_score": 3, "selected": false, "text": "<p>For SQL Server 2000 you can simulate ROW_NUMBER() using a table variable with an IDENTITY column:</p>\n\n<pre><code>DECLARE @pageNo int -- 1 based\nDECLARE @pageSize int\nSET @pageNo = 51\nSET @pageSize = 20\n\nDECLARE @firstRecord int\nDECLARE @lastRecord int\nSET @firstRecord = (@pageNo - 1) * @pageSize + 1 -- 1001\nSET @lastRecord = @firstRecord + @pageSize - 1 -- 1020\n\nDECLARE @orderedKeys TABLE (\n rownum int IDENTITY NOT NULL PRIMARY KEY CLUSTERED,\n TableKey int NOT NULL\n)\n\nSET ROWCOUNT @lastRecord\nINSERT INTO @orderedKeys (TableKey) SELECT ID FROM Orders WHERE OrderDate &gt;= '1980-01-01' ORDER BY OrderDate\n\nSET ROWCOUNT 0\n\nSELECT t.*\nFROM Orders t\n INNER JOIN @orderedKeys o ON o.TableKey = t.ID\nWHERE o.rownum &gt;= @firstRecord\nORDER BY o.rownum\n</code></pre>\n\n<p>This approach can be extended to tables with multi-column keys, and it doesn't incur the performance overhead of using OR (which skips index usage). The downside is the amount of temporary space used up if the data set is very large and one is near the last page. I did not test cursor performance in that case, but it might be better.</p>\n\n<p>Note that this approach could be optimized for the first page of data. Also, ROWCOUNT was used since TOP does not accept a variable in SQL Server 2000.</p>\n" }, { "answer_id": 10639172, "author": "Jama A.", "author_id": 416996, "author_profile": "https://Stackoverflow.com/users/416996", "pm_score": 9, "selected": false, "text": "<p>Finally, <strong>Microsoft SQL Server 2012</strong> was released, I really like its simplicity for a pagination, you don't have to use complex queries like answered here. </p>\n\n<p>For getting the next 10 rows just run this query:</p>\n\n<pre><code>SELECT * FROM TableName ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql#using-offset-and-fetch-to-limit-the-rows-returned\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql#using-offset-and-fetch-to-limit-the-rows-returned</a></p>\n\n<p>Key points to consider when using it:</p>\n\n<ul>\n<li><code>ORDER BY</code> is mandatory to use <code>OFFSET ... FETCH</code> clause.</li>\n<li><code>OFFSET</code> clause is mandatory with <code>FETCH</code>. You cannot use <code>ORDER BY ...\nFETCH</code>.</li>\n<li><code>TOP</code> cannot be combined with <code>OFFSET</code> and <code>FETCH</code> in the same query\nexpression.</li>\n</ul>\n" }, { "answer_id": 13153631, "author": "Dinesh Rabara", "author_id": 797241, "author_profile": "https://Stackoverflow.com/users/797241", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/ms186734%28v=sql.105%29.aspx\" rel=\"noreferrer\">MSDN: ROW_NUMBER (Transact-SQL)</a></p>\n\n<blockquote>\n <p>Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.</p>\n \n <p>The following example returns rows with numbers 50 to 60 inclusive in the order of the OrderDate.</p>\n</blockquote>\n\n<pre class=\"lang-sql prettyprint-override\"><code>WITH OrderedOrders AS\n(\n SELECT\n ROW_NUMBER() OVER(ORDER BY FirstName DESC) AS RowNumber, \n FirstName, LastName, ROUND(SalesYTD,2,1) AS \"Sales YTD\"\n FROM [dbo].[vSalesPerson]\n) \nSELECT RowNumber, \n FirstName, LastName, Sales YTD \nFROM OrderedOrders \nWHERE RowNumber &gt; 50 AND RowNumber &lt; 60;\n</code></pre>\n\n\n\n<pre><code> RowNumber FirstName LastName SalesYTD\n --- ----------- ---------------------- -----------------\n 1 Linda Mitchell 4251368.54\n 2 Jae Pak 4116871.22\n 3 Michael Blythe 3763178.17\n 4 Jillian Carson 3189418.36\n 5 Ranjit Varkey Chudukatil 3121616.32\n 6 José Saraiva 2604540.71\n 7 Shu Ito 2458535.61\n 8 Tsvi Reiter 2315185.61\n 9 Rachel Valdez 1827066.71\n 10 Tete Mensa-Annan 1576562.19\n 11 David Campbell 1573012.93\n 12 Garrett Vargas 1453719.46\n 13 Lynn Tsoflias 1421810.92\n 14 Pamela Ansman-Wolfe 1352577.13\n</code></pre>\n" }, { "answer_id": 19609938, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 7, "selected": false, "text": "<p>Incredibly, no other answer has mentioned the <em>fastest</em> way to do pagination in all SQL Server versions. Offsets can be terribly slow for large page numbers as is <a href=\"https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml\" rel=\"noreferrer\">benchmarked here</a>. There is an entirely different, much faster way to perform pagination in SQL. This is often called the \"seek method\" or \"keyset pagination\" as described in <a href=\"http://blog.jooq.org/2013/10/26/faster-sql-paging-with-jooq-using-the-seek-method/\" rel=\"noreferrer\">this blog post here</a>.</p>\n\n<pre><code>SELECT TOP 10 first_name, last_name, score, COUNT(*) OVER()\nFROM players\nWHERE (score &lt; @previousScore)\n OR (score = @previousScore AND player_id &lt; @previousPlayerId)\nORDER BY score DESC, player_id DESC\n</code></pre>\n\n<h3>The \"seek predicate\"</h3>\n\n<p>The <code>@previousScore</code> and <code>@previousPlayerId</code> values are the respective values of the last record from the previous page. This allows you to fetch the \"next\" page. If the <code>ORDER BY</code> direction is <code>ASC</code>, simply use <code>&gt;</code> instead.</p>\n\n<p>With the above method, you cannot immediately jump to page 4 without having first fetched the previous 40 records. But often, you do not want to jump that far anyway. Instead, you get a much faster query that might be able to fetch data in constant time, depending on your indexing. Plus, your pages remain \"stable\", no matter if the underlying data changes (e.g. on page 1, while you're on page 4).</p>\n\n<p>This is the best way to implement pagination when lazy loading more data in web applications, for instance.</p>\n\n<p>Note, the \"seek method\" is also called <a href=\"https://stackoverflow.com/a/3215973/521799\">keyset pagination</a>.</p>\n\n<h3>Total records before pagination</h3>\n\n<p>The <code>COUNT(*) OVER()</code> window function will help you count the number of total records \"before pagination\". If you're using SQL Server 2000, you will have to resort to two queries for the <code>COUNT(*)</code>.</p>\n" }, { "answer_id": 22368100, "author": "aden", "author_id": 3282216, "author_profile": "https://Stackoverflow.com/users/3282216", "pm_score": 0, "selected": false, "text": "<pre><code> CREATE view vw_sppb_part_listsource as \n select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (\n select \n part.SPPB_PART_ID\n , 0 as is_rev\n , part.part_number \n , part.init_id \n from t_sppb_init_part part \n left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )\n where prev.SPPB_PART_ID is null \n union \n select \n part.SPPB_PART_ID\n , 1 as is_rev\n , prev.part_number \n , part.init_id \n from t_sppb_init_part part \n inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )\n ) sppb_part\n</code></pre>\n\n<p>will restart idx when it comes to different init_id</p>\n" }, { "answer_id": 23935681, "author": "fatlion", "author_id": 3687935, "author_profile": "https://Stackoverflow.com/users/3687935", "pm_score": 2, "selected": false, "text": "<p>Try this approach:</p>\n\n<pre><code>SELECT TOP @offset a.*\nFROM (select top @limit b.*, COUNT(*) OVER() totalrows \n from TABLENAME b order by id asc) a\nORDER BY id desc;\n</code></pre>\n" }, { "answer_id": 27182167, "author": "Thunder", "author_id": 232687, "author_profile": "https://Stackoverflow.com/users/232687", "pm_score": 2, "selected": false, "text": "<p>Use case wise the following seem to be easy to use and fast. Just set the page number.</p>\n\n<pre><code>use AdventureWorks\nDECLARE @RowsPerPage INT = 10, @PageNumber INT = 6;\nwith result as(\nSELECT SalesOrderDetailID, SalesOrderID, ProductID,\nROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum\nFROM Sales.SalesOrderDetail\nwhere 1=1\n)\nselect SalesOrderDetailID, SalesOrderID, ProductID from result\nWHERE result.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1\nAND @RowsPerPage*(@PageNumber)\n</code></pre>\n\n<p>also without CTE</p>\n\n<pre><code>use AdventureWorks\nDECLARE @RowsPerPage INT = 10, @PageNumber INT = 6\nSELECT SalesOrderDetailID, SalesOrderID, ProductID\nFROM (\nSELECT SalesOrderDetailID, SalesOrderID, ProductID,\nROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum\nFROM Sales.SalesOrderDetail\nwhere 1=1\n ) AS SOD\nWHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1\nAND @RowsPerPage*(@PageNumber)\n</code></pre>\n" }, { "answer_id": 34792367, "author": "Mohan", "author_id": 2189263, "author_profile": "https://Stackoverflow.com/users/2189263", "pm_score": 6, "selected": false, "text": "<p>From SQL Server 2012, we can use <code>OFFSET</code> and <code>FETCH NEXT</code> Clause to achieve the pagination. </p>\n\n<p>Try this, for SQL Server:</p>\n\n<blockquote>\n <p>In the SQL Server 2012 a new feature was added in the ORDER BY clause,\n to query optimization of a set data, making work easier with data\n paging for anyone who writes in T-SQL as well for the entire Execution\n Plan in SQL Server.</p>\n \n <p>Below the T-SQL script with the same logic used in the previous\n example.</p>\n\n<pre><code>--CREATING A PAGING WITH OFFSET and FETCH clauses IN \"SQL SERVER 2012\"\nDECLARE @PageNumber AS INT, @RowspPage AS INT\nSET @PageNumber = 2\nSET @RowspPage = 10 \nSELECT ID_EXAMPLE, NM_EXAMPLE, DT_CREATE\nFROM TB_EXAMPLE\nORDER BY ID_EXAMPLE\nOFFSET ((@PageNumber - 1) * @RowspPage) ROWS\nFETCH NEXT @RowspPage ROWS ONLY;\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://social.technet.microsoft.com/wiki/contents/articles/23811.paging-a-query-with-sql-server.aspx\" rel=\"noreferrer\">TechNet: Paging a Query with SQL Server</a></p>\n" }, { "answer_id": 35355293, "author": "tinonetic", "author_id": 919426, "author_profile": "https://Stackoverflow.com/users/919426", "pm_score": 0, "selected": false, "text": "<p>For the <code>ROW_NUMBER</code> technique, if you do not have a sorting column to use, you can use the <a href=\"https://msdn.microsoft.com/en-us/library/ms188751.aspx\" rel=\"nofollow noreferrer\"><code>CURRENT_TIMESTAMP</code></a> as follows:</p>\n\n<pre><code>SELECT TOP 20 \n col1,\n col2,\n col3,\n col4\nFROM (\n SELECT \n tbl.col1 AS col1\n ,tbl.col2 AS col2\n ,tbl.col3 AS col3\n ,tbl.col4 AS col4\n ,ROW_NUMBER() OVER (\n ORDER BY CURRENT_TIMESTAMP\n ) AS sort_row\n FROM dbo.MyTable tbl\n ) AS query\nWHERE query.sort_row &gt; 10\nORDER BY query.sort_row\n</code></pre>\n\n<p>This has worked well for me for searches over table sizes of even up to 700,000. </p>\n\n<p><strong>This fetches records 11 to 30.</strong></p>\n" }, { "answer_id": 40142567, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 2, "selected": false, "text": "<p>These are my solutions for paging the result of query in SQL server side.\nthese approaches are different between SQL Server 2008 and 2012.\nAlso, I have added the concept of filtering and order by with one column. It is very efficient when you are paging and filtering and ordering in your Gridview.</p>\n\n<p>Before testing, you have to create one sample table and insert some row in this table : (In real world you have to change Where clause considering your table fields and maybe you have some join and subquery in main part of select)</p>\n\n<pre><code>Create Table VLT\n(\n ID int IDentity(1,1),\n Name nvarchar(50),\n Tel Varchar(20)\n)\nGO\n\n\nInsert INTO VLT\nVALUES\n ('NAME' + Convert(varchar(10),@@identity),'FAMIL' + Convert(varchar(10),@@identity))\nGO 500000\n</code></pre>\n\n<p>In all of these sample, I want to query 200 rows per page and I am fetching the row for page number 1200.</p>\n\n<p>In SQL server 2008, you can use the CTE concept. Because of that, I have written two type of query for SQL server 2008+</p>\n\n<p>-- SQL Server 2008+</p>\n\n<pre><code>DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM\n ( \n SELECT \n ROW_NUMBER() \n OVER( ORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN VLT.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN VLT.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN VLT.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN VLT.Tel END ASC\n ) AS RowNum\n ,* \n FROM VLT \n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID &lt;&gt; @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name &lt;&gt; @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel &lt;&gt; @FilterValue THEN 1 \n\n END\n ) = 1 \n ) AS Data\nWHERE Data.RowNum &gt; @PageSize * (@PageNumber - 1)\n AND Data.RowNum &lt;= @PageSize * @PageNumber\nORDER BY Data.RowNum\n\nGO\n</code></pre>\n\n<p>And second solution with CTE in SQL server 2008+</p>\n\n<pre><code>DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\n;WITH\n Data_CTE\n AS\n ( \n SELECT \n ROW_NUMBER() \n OVER( ORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN VLT.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN VLT.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN VLT.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN VLT.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN VLT.Tel END ASC\n ) AS RowNum\n ,* \n FROM VLT\n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID &lt;&gt; @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name &lt;&gt; @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel &lt;&gt; @FilterValue THEN 1 \n\n END\n ) = 1 \n )\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM Data_CTE AS Data\nWHERE Data.RowNum &gt; @PageSize * (@PageNumber - 1)\n AND Data.RowNum &lt;= @PageSize * @PageNumber\nORDER BY Data.RowNum\n</code></pre>\n\n<p>-- SQL Server 2012+</p>\n\n<pre><code>DECLARE @PageNumber Int = 1200\nDECLARE @PageSize INT = 200\nDECLARE @SortByField int = 1 --The field used for sort by\nDECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC\nDECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)\nDECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter\nDECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.\n\n;WITH\n Data_CTE\n AS\n ( \n SELECT \n * \n FROM VLT\n WHERE\n ( -- We apply the filter logic here\n CASE\n WHEN @FilterType = 'None' THEN 1\n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 1\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.ID NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 1\n AND VLT.ID = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1\n AND VLT.ID &lt;&gt; @FilterValue THEN 1 \n\n -- Name column filter\n WHEN @FilterType = 'Contain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 2\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Name NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 2\n AND VLT.Name = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2\n AND VLT.Name &lt;&gt; @FilterValue THEN 1 \n\n -- Tel column filter \n WHEN @FilterType = 'Contain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'NotContain' AND @FilterColumn = 3\n AND ( -- In this case, when the filter value is empty, we want to show everything.\n VLT.Tel NOT LIKE '%' + @FilterValue + '%'\n OR\n @FilterValue = ''\n ) THEN 1\n WHEN @FilterType = 'Match' AND @FilterColumn = 3\n AND VLT.Tel = @FilterValue THEN 1\n WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3\n AND VLT.Tel &lt;&gt; @FilterValue THEN 1 \n\n END\n ) = 1 \n )\n\nSELECT \n Data.ID,\n Data.Name,\n Data.Tel\nFROM Data_CTE AS Data\nORDER BY \n CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'\n THEN Data.ID END ASC,\n CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'\n THEN Data.ID END DESC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'\n THEN Data.Name END ASC,\n CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'\n THEN Data.Name END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'\n THEN Data.Tel END ASC,\n CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'\n THEN Data.Tel END ASC\nOFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;\n</code></pre>\n" }, { "answer_id": 48257328, "author": "Debendra Dash", "author_id": 5418530, "author_profile": "https://Stackoverflow.com/users/5418530", "pm_score": 2, "selected": false, "text": "<p>The best way for paging in sql server 2012 is by using offset and fetch next in a stored procedure.\n<strong>OFFSET Keyword</strong> - If we use offset with the order by clause then the query will skip the number of records we specified in OFFSET n Rows.</p>\n\n<p><strong>FETCH NEXT Keywords</strong> - When we use Fetch Next with an order by clause only it will returns the no of rows you want to display in paging, without Offset then SQL will generate an error.\nhere is the example given below.</p>\n\n<pre><code>create procedure sp_paging\n(\n @pageno as int,\n @records as int\n)\nas\nbegin\ndeclare @offsetcount as int\nset @offsetcount=(@pageno-1)*@records\nselect id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only\nend\n</code></pre>\n\n<p>you can execute it as follow.</p>\n\n<pre><code>exec sp_paging 2,3\n</code></pre>\n" }, { "answer_id": 50900663, "author": "salem albadawi", "author_id": 7325608, "author_profile": "https://Stackoverflow.com/users/7325608", "pm_score": 0, "selected": false, "text": "<blockquote>\n<pre><code>create PROCEDURE SP_Company_List (@pagesize int = -1 ,@pageindex int= 0 ) &gt; AS BEGIN SET NOCOUNT ON;\n\n\n select Id , NameEn from Company ORDER by Id ASC \nOFFSET (@pageindex-1 )* @pagesize ROWS FETCH NEXt @pagesize ROWS ONLY END GO\n</code></pre>\n \n <hr>\n\n<pre><code>DECLARE @return_value int\n\nEXEC @return_value = [dbo].[SP_Company_List] @pagesize = 1 , &gt; @pageindex = 2\n\nSELECT 'Return Value' = @return_value\n\nGO\n</code></pre>\n</blockquote>\n" }, { "answer_id": 55382053, "author": "Alex M", "author_id": 5705766, "author_profile": "https://Stackoverflow.com/users/5705766", "pm_score": 0, "selected": false, "text": "<p>This bit gives you ability to paginate using SQL Server, and newer versions of MySQL and carries the total number of rows in every row.\nUses your pimary key to count number of unique rows.</p>\n\n<pre><code>WITH T AS\n( \n SELECT TABLE_ID, ROW_NUMBER() OVER (ORDER BY TABLE_ID) AS RN\n , (SELECT COUNT(TABLE_ID) FROM TABLE) AS TOTAL \n FROM TABLE (NOLOCK)\n)\n\nSELECT T2.FIELD1, T2.FIELD2, T2.FIELD3, T.TOTAL \nFROM TABLE T2 (NOLOCK)\nINNER JOIN T ON T2.TABLE_ID=T.TABLE_ID\nWHERE T.RN &gt;= 100\nAND T.RN &lt; 200\n</code></pre>\n" }, { "answer_id": 59156960, "author": "d.popov", "author_id": 1407302, "author_profile": "https://Stackoverflow.com/users/1407302", "pm_score": 1, "selected": false, "text": "<p>This is a duplicate of the 2012 old SO question:\n<a href=\"https://stackoverflow.com/questions/548475/efficient-way-to-implement-paging/13991192#13991192\">efficient way to implement paging</a></p>\n\n<blockquote>\n <p>FROM [TableX]\n ORDER BY [FieldX]\n OFFSET 500 ROWS\n FETCH NEXT 100 ROWS ONLY</p>\n</blockquote>\n\n<p><a href=\"https://sqlperformance.com/2015/01/t-sql-queries/pagination-with-offset-fetch\" rel=\"nofollow noreferrer\">Here</a> the topic is discussed in greater details, and with alternate approaches. </p>\n" }, { "answer_id": 59785217, "author": "Damitha", "author_id": 2074778, "author_profile": "https://Stackoverflow.com/users/2074778", "pm_score": 2, "selected": false, "text": "<p>From 2012 onward we can use \n<code>OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY</code></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331/" ]
What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?
Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is ``` SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate ``` In this case, you would determine the total number of results using: ``` SELECT COUNT(*) FROM Orders WHERE OrderDate >= '1980-01-01' ``` ...which may seem inefficient, but is actually pretty performant, assuming all indexes etc. are properly set up. Next, to get actual results back in a paged fashion, the following query would be most efficient: ``` SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, * FROM Orders WHERE OrderDate >= '1980-01-01' ) AS RowConstrainedResult WHERE RowNum >= 1 AND RowNum < 20 ORDER BY RowNum ``` This will return rows 1-19 of the original query. The cool thing here, especially for web apps, is that you don't have to keep any state, except the row numbers to be returned.
109,249
<p>Why doesn't have the c standard a memswap function, which would probably look like:</p> <pre><code>int memswap(void *ptr1, void *ptr2, size_t nbytes)? </code></pre> <p>I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.</p>
[ { "answer_id": 109259, "author": "Colen", "author_id": 13500, "author_profile": "https://Stackoverflow.com/users/13500", "pm_score": 2, "selected": false, "text": "<p>Probably because it's not needed very often - I memset and memcpy reasonably often, but I don't know that I'd ever have used memswap if it was available.</p>\n" }, { "answer_id": 109302, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 4, "selected": false, "text": "<p>I think because it's not needed very often. However, there is an easy way to do this in C++:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n\nswap_ranges(ptr1, ptr1 + nbytes, ptr2)\n</code></pre>\n\n<p>It's it may not be quite as optimized as a compiler built in, but it has the potential of being faster than a loop you write for yourself, since it may have platform specific optimization that you would not implement.</p>\n\n<p>You do need to be careful with the above, because it assumes that ptr1 and ptr2 are char pointers. The more canonical way to do this is:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n\nswap_ranges(ptr1, ptr1 + num_items, ptr2)\n</code></pre>\n" }, { "answer_id": 109308, "author": "Alaric", "author_id": 19744, "author_profile": "https://Stackoverflow.com/users/19744", "pm_score": 2, "selected": false, "text": "<p>It probably isn't required very often in C programming, in C++ where swap is a regular thing to do on class members there's the <a href=\"http://www.sgi.com/tech/stl/swap.html\" rel=\"nofollow noreferrer\">std::swap</a> algorithm which is highly optimized for different types.</p>\n" }, { "answer_id": 111215, "author": "itj", "author_id": 888, "author_profile": "https://Stackoverflow.com/users/888", "pm_score": 4, "selected": true, "text": "<p>This isn't something that is routinely required.</p>\n\n<p>The ideas may have been considered and discarded because it is quite difficult to come up with an algorithm that is general purpose. Don't forget that C is an old language and extensions need to be generally useful.</p>\n\n<p>Possible error conditions :-</p>\n\n<ul>\n<li>behaviour when the ranges being swapped overlap</li>\n<li>length of zero</li>\n<li>running out of memory (an optimal implementation might allocate memory to do this)</li>\n<li>null pointer</li>\n</ul>\n\n<p>The <strong>best</strong> algorithm might also depend upon what you are doing, and so <em>could</em> be better coded directly by you.</p>\n\n<ul>\n<li>swapping structures likely to be quicker using a temp structure and assignment</li>\n<li>small lengths - may be better allocating temporary memory</li>\n<li>long lengths - 'section' by section swap (where section is some optimal length)</li>\n<li>use of hardware copy functions</li>\n</ul>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18687/" ]
Why doesn't have the c standard a memswap function, which would probably look like: ``` int memswap(void *ptr1, void *ptr2, size_t nbytes)? ``` I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.
This isn't something that is routinely required. The ideas may have been considered and discarded because it is quite difficult to come up with an algorithm that is general purpose. Don't forget that C is an old language and extensions need to be generally useful. Possible error conditions :- * behaviour when the ranges being swapped overlap * length of zero * running out of memory (an optimal implementation might allocate memory to do this) * null pointer The **best** algorithm might also depend upon what you are doing, and so *could* be better coded directly by you. * swapping structures likely to be quicker using a temp structure and assignment * small lengths - may be better allocating temporary memory * long lengths - 'section' by section swap (where section is some optimal length) * use of hardware copy functions
109,284
<p>Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following:</p> <pre><code>response.should use_layout('my_layout_name') </code></pre> <p>I found a use_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.</p>
[ { "answer_id": 110301, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 4, "selected": true, "text": "<p>I found an example of <a href=\"http://rubyforge.org/pipermail/rspec-users/2007-May/001816.html\" rel=\"noreferrer\">how to write a <code>use_layout</code> matcher</a> that will do just that. Here's the code in case that link goes away:</p>\n\n<pre><code># in spec_helper.rb\n\nclass UseLayout\n def initialize(expected)\n @expected = 'layouts/' + expected\n end\n def matches?(controller)\n @actual = controller.layout\n #@actual.equal?(@expected)\n @actual == @expected\n end\n def failure_message\n return \"use_layout expected #{@expected.inspect}, got # \n{@actual.inspect}\", @expected, @actual\n end\n def negeative_failure_message\n return \"use_layout expected #{@expected.inspect} not to equal # \n{@actual.inspect}\", @expected, @actual\n end\nend\n\n\ndef use_layout(expected)\n UseLayout.new(expected)\nend\n\n# in controller spec\n response.should use_layout(\"application\")\n</code></pre>\n" }, { "answer_id": 143967, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 4, "selected": false, "text": "<p>This works for me with edge Rails and edge RSpec on Rails:</p>\n\n<pre><code>response.layout.should == 'layouts/application'\n</code></pre>\n\n<p>Shouldn't be hard to turn this into a matcher suitable for you.</p>\n" }, { "answer_id": 1316482, "author": "dmcnally", "author_id": 32777, "author_profile": "https://Stackoverflow.com/users/32777", "pm_score": 2, "selected": false, "text": "<p>Here is an updated version of the matcher. I've updated it to conform to the latest version of RSpec. I've added the relevant read only attributes and remove old return format. </p>\n\n<pre><code># in spec_helper.rb\n\nclass UseLayout\n attr_reader :expected\n attr_reader :actual\n\n def initialize(expected)\n @expected = 'layouts/' + expected\n end\n\n def matches?(controller)\n if controller.is_a?(ActionController::Base)\n @actual = 'layouts/' + controller.class.read_inheritable_attribute(:layout)\n else\n @actual = controller.layout\n end\n @actual ||= \"layouts/application\"\n @actual == @expected\n end\n\n def description\n \"Determines if a controller uses a layout\"\n end\n\n def failure_message\n return \"use_layout expected #{@expected.inspect}, got #{@actual.inspect}\"\n end\n\n def negeative_failure_message\n return \"use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}\"\n end\nend\n\ndef use_layout(expected)\n UseLayout.new(expected)\nend\n</code></pre>\n\n<p>Additionally the matcher now also works with layouts specified at the controller class level and can be used as follows:</p>\n\n<pre><code>class PostsController &lt; ApplicationController\n layout \"posts\"\nend\n</code></pre>\n\n<p>And in the controller spec you can simply use:</p>\n\n<pre><code>it { should use_layout(\"posts\") }\n</code></pre>\n" }, { "answer_id": 1319506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><code>controller.active_layout.name</code> works for me.</p>\n" }, { "answer_id": 2484251, "author": "Martin Pain", "author_id": 1216210, "author_profile": "https://Stackoverflow.com/users/1216210", "pm_score": 0, "selected": false, "text": "<p>Here's a version of dmcnally's code that allows no arguments to be passed, making \"should use_layout\" and \"should_not use_layout\" work (to assert that the controller is using any layout, or no layout, respectively - of which I would expect only the second to be useful as you should be more specific if it is using a layout):</p>\n\n<pre><code>class UseLayout\n def initialize(expected = nil)\n if expected.nil?\n @expected = nil\n else\n @expected = 'layouts/' + expected\n end\n end\n def matches?(controller)\n @actual = controller.layout\n #@actual.equal?(@expected)\n if @expected.nil?\n @actual\n else\n @actual == @expected\n end\n end\n def failure_message\n if @expected.nil?\n return 'use_layout expected a layout to be used, but none was', 'any', @actual\n else\n return \"use_layout expected #{@expected.inspect}, got #{@actual.inspect}\", @expected, @actual\n end\n end\n def negative_failure_message\n if @expected.nil?\n return \"use_layout expected no layout to be used, but #{@actual.inspect} found\", 'any', @actual\n else\n return \"use_layout expected #{@expected.inspect} not to equal #{@actual.inspect}\", @expected, @actual\n end\n end\nend\n\n\ndef use_layout(expected = nil)\n UseLayout.new(expected)\nend\n</code></pre>\n" }, { "answer_id": 3813372, "author": "Kevin Ansfield", "author_id": 1163866, "author_profile": "https://Stackoverflow.com/users/1163866", "pm_score": 6, "selected": false, "text": "<p>David Chelimsky posted a good answer over on the <a href=\"http://www.ruby-forum.com/topic/216851\" rel=\"noreferrer\">Ruby Forum</a>:</p>\n\n<pre><code>response.should render_template(\"layouts/some_layout\")\n</code></pre>\n" }, { "answer_id": 6012622, "author": "jacklin", "author_id": 215708, "author_profile": "https://Stackoverflow.com/users/215708", "pm_score": 2, "selected": false, "text": "<p>Here's the solution I ended up going with. Its for rpsec 2 and rails 3.<br>\nI just added this file in the spec/support directory.\nThe link is: <a href=\"https://gist.github.com/971342\" rel=\"nofollow\">https://gist.github.com/971342</a>\n <p><pre><code># spec/support/matchers/render_layout.rb</p>\n\n<p>ActionView::Base.class_eval do\n unless instance_methods.include?('_render_layout_with_tracking')\n def _render_layout_with_tracking(layout, locals, &amp;block)\n controller.instance_variable_set(:@_rendered_layout, layout)\n _render_layout_without_tracking(layout, locals, &amp;block)\n end\n alias_method_chain :_render_layout, :tracking\n end\nend</p>\n\n<p># You can use this matcher anywhere that you have access to the controller instance,\n# like in controller or integration specs.\n#\n# == Example Usage\n#\n# Expects no layout to be rendered:\n# controller.should_not render_layout\n# Expects any layout to be rendered:\n# controller.should render_layout\n# Expects app/views/layouts/application.html.erb to be rendered:\n# controller.should render_layout('application')\n# Expects app/views/layouts/application.html.erb not to be rendered:\n# controller.should_not render_layout('application')\n# Expects app/views/layouts/mobile/application.html.erb to be rendered:\n# controller.should_not render_layout('mobile/application')\nRSpec::Matchers.define :render_layout do |*args|\n expected = args.first\n match do |c|\n actual = get_layout(c)\n if expected.nil?\n !actual.nil? # actual must be nil for the test to pass. Usage: should_not render_layout\n elsif actual\n actual == expected.to_s\n else\n false\n end\n end</p>\n\n<p>failure_message_for_should do |c|\n actual = get_layout(c)\n if actual.nil? &amp;&amp; expected.nil?\n \"expected a layout to be rendered but none was\"\n elsif actual.nil?\n \"expected layout #{expected.inspect} but no layout was rendered\"\n else\n \"expected layout #{expected.inspect} but #{actual.inspect} was rendered\"\n end\n end</p>\n\n<p>failure_message_for_should_not do |c|\n actual = get_layout(c)\n if expected.nil?\n \"expected no layout but #{actual.inspect} was rendered\"\n else\n \"expected #{expected.inspect} not to be rendered but it was\"\n end\n end</p>\n\n<p>def get_layout(controller)\n if template = controller.instance_variable_get(:@_rendered_layout)\n template.virtual_path.sub(/layouts\\//, '')\n end\n end\nend\n</code></pre></p></p>\n" }, { "answer_id": 8790824, "author": "nathanvda", "author_id": 216513, "author_profile": "https://Stackoverflow.com/users/216513", "pm_score": 3, "selected": false, "text": "<p>I had to write the following to make this work:</p>\n\n<pre><code>response.should render_template(\"layouts/some_folder/some_layout\", \"template-name\")\n</code></pre>\n" }, { "answer_id": 10646477, "author": "lidaobing", "author_id": 156285, "author_profile": "https://Stackoverflow.com/users/156285", "pm_score": 1, "selected": false, "text": "<p><code>\nresponse.should render_template(\"layouts/some_folder/some_layout\")\nresponse.should render_template(\"template-name\")\n</code></p>\n" }, { "answer_id": 10786526, "author": "Will Tomlins", "author_id": 690904, "author_profile": "https://Stackoverflow.com/users/690904", "pm_score": 4, "selected": false, "text": "<p>There's already a perfectly functional matcher for this:</p>\n\n<pre><code>response.should render_template(:layout =&gt; 'fooo')\n</code></pre>\n\n<p>(Rspec 2.6.4)</p>\n" }, { "answer_id": 31754355, "author": "tgf", "author_id": 1760776, "author_profile": "https://Stackoverflow.com/users/1760776", "pm_score": 1, "selected": false, "text": "<p><strong>Shoulda Matchers</strong> provides a matcher for this scenario. (<a href=\"http://www.rubydoc.info/github/thoughtbot/shoulda-matchers/Shoulda%2FMatchers%2FActionController%3Arender_with_layout\" rel=\"nofollow noreferrer\">Documentation</a>) \nThis seems to work:</p>\n\n<pre><code> expect(response).to render_with_layout('my_layout')\n</code></pre>\n\n<p>it produces appropriate failure messages like:</p>\n\n<p><em>Expected to render with the \"calendar_layout\" layout, but rendered with \"application\", \"application\"</em></p>\n\n<p>Tested with <code>rails 4.2</code>, <code>rspec 3.3</code> and <code>shoulda-matchers 2.8.0</code></p>\n\n<p><em>Edit: shoulda-matchers provides this method. Shoulda::Matchers::ActionController::RenderWithLayoutMatcher</em></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
Is it possible to test the use of a given layout using RSpec with Rails, for example I'd like a matcher that does the following: ``` response.should use_layout('my_layout_name') ``` I found a use\_layout matcher when Googling but it doesn't work as neither the response or controller seem to have a layout property that matcher was looking for.
I found an example of [how to write a `use_layout` matcher](http://rubyforge.org/pipermail/rspec-users/2007-May/001816.html) that will do just that. Here's the code in case that link goes away: ``` # in spec_helper.rb class UseLayout def initialize(expected) @expected = 'layouts/' + expected end def matches?(controller) @actual = controller.layout #@actual.equal?(@expected) @actual == @expected end def failure_message return "use_layout expected #{@expected.inspect}, got # {@actual.inspect}", @expected, @actual end def negeative_failure_message return "use_layout expected #{@expected.inspect} not to equal # {@actual.inspect}", @expected, @actual end end def use_layout(expected) UseLayout.new(expected) end # in controller spec response.should use_layout("application") ```
109,305
<p>I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or <em>n</em> records in the grid. The header and the footer should remain in the same position regardless of the amount of data in the grid. Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView? Ideally I would like this to be a reusable control.</p>
[ { "answer_id": 109496, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 1, "selected": false, "text": "<p>You may have to drop the headers and footers from the GridView altogether and add them to the page as separate table elements. You will need to make sure each table cell in the header and footer tables have fixed widths that correspond to the widths of the cells in your GridView. </p>\n\n<p>The GridView itself would probably be nested in a DIV tag of a fixed height. Something like as follows. </p>\n\n<pre><code>&lt;table&gt;&lt;tr&gt;&lt;td style=\"width:100px\"&gt;Header 1&lt;/td&gt;&lt;td style=\"width:200px\"&gt;Header 2&lt;/td&gt;&lt;/table&gt;\n&lt;div style=\"width:300px;height:400px\"&gt;\n&lt;asp:GridView&gt;.....&lt;/asp:GridView&gt;\n&lt;/div&gt;\n&lt;table&gt;&lt;tr&gt;&lt;td style=\"width:100px\"&gt;Footer 1&lt;/td&gt;&lt;td style=\"width:200px\"&gt;Footer 2&lt;/td&gt;&lt;/table&gt;\n</code></pre>\n\n<p>You will probably have to tweak the margin and padding value to get it all to line up exactly though.</p>\n" }, { "answer_id": 13683625, "author": "sreejithsdev", "author_id": 905389, "author_profile": "https://Stackoverflow.com/users/905389", "pm_score": 0, "selected": false, "text": "<p>Put grid inside div set div style as follows</p>\n\n<pre><code>&lt;div style=\"width:100px; height:100px; overflow:scroll;\"&gt;\n &lt;asp:GridView ID=\"GridView1\" runat=\"server\"&gt;\n &lt;/asp:GridView&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
I have an ASP.Net GridView control that I need to remain a fixed size whether there are 0 records or *n* records in the grid. The header and the footer should remain in the same position regardless of the amount of data in the grid. Obviously, I need to implement paging for larger datasets but how would I achieve this fixed sized GridView? Ideally I would like this to be a reusable control.
You may have to drop the headers and footers from the GridView altogether and add them to the page as separate table elements. You will need to make sure each table cell in the header and footer tables have fixed widths that correspond to the widths of the cells in your GridView. The GridView itself would probably be nested in a DIV tag of a fixed height. Something like as follows. ``` <table><tr><td style="width:100px">Header 1</td><td style="width:200px">Header 2</td></table> <div style="width:300px;height:400px"> <asp:GridView>.....</asp:GridView> </div> <table><tr><td style="width:100px">Footer 1</td><td style="width:200px">Footer 2</td></table> ``` You will probably have to tweak the margin and padding value to get it all to line up exactly though.
109,325
<p>How do you perform the equivalent of Oracle's <code>DESCRIBE TABLE</code> in PostgreSQL (using the psql command)?</p>
[ { "answer_id": 109329, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 5, "selected": false, "text": "<p>The psql equivalent of <code>DESCRIBE TABLE</code> is <code>\\d table</code>.</p>\n\n<p>See the psql portion of the PostgreSQL manual for more details.</p>\n" }, { "answer_id": 109331, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 6, "selected": false, "text": "<p>You can do that with a psql slash command:</p>\n\n<pre><code> \\d myTable describe table\n</code></pre>\n\n<p>It also works for other objects:</p>\n\n<pre><code> \\d myView describe view\n \\d myIndex describe index\n \\d mySequence describe sequence\n</code></pre>\n\n<p>Source: <a href=\"http://www.faqs.org/docs/ppbook/c4890.htm\" rel=\"noreferrer\">faqs.org</a></p>\n" }, { "answer_id": 109334, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 13, "selected": true, "text": "<p>Try this (in the <code>psql</code> command-line tool):</p>\n\n<pre><code>\\d+ tablename\n</code></pre>\n\n<p>See <a href=\"http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS\" rel=\"noreferrer\">the manual</a> for more info.</p>\n" }, { "answer_id": 109337, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": false, "text": "<p>In addition to the PostgreSQL way (\\d 'something' or \\dt 'table' or \\ds 'sequence' and so on)</p>\n<p>The SQL standard way, as shown <a href=\"https://stackoverflow.com/questions/100504/what-is-the-sql-command-to-return-the-field-names-of-a-table#100513\">here</a>:</p>\n<pre><code>select column_name, data_type, character_maximum_length, column_default, is_nullable\nfrom INFORMATION_SCHEMA.COLUMNS where table_name = '&lt;name of table&gt;';\n</code></pre>\n<p>It's supported by many db engines.</p>\n" }, { "answer_id": 118245, "author": "Gavin M. Roy", "author_id": 13203, "author_profile": "https://Stackoverflow.com/users/13203", "pm_score": 6, "selected": false, "text": "<p>If you want to obtain it from query instead of psql, you can query the catalog schema. Here's a complex query that does that:</p>\n\n<pre><code>SELECT \n f.attnum AS number, \n f.attname AS name, \n f.attnum, \n f.attnotnull AS notnull, \n pg_catalog.format_type(f.atttypid,f.atttypmod) AS type, \n CASE \n WHEN p.contype = 'p' THEN 't' \n ELSE 'f' \n END AS primarykey, \n CASE \n WHEN p.contype = 'u' THEN 't' \n ELSE 'f'\n END AS uniquekey,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreignkey,\n CASE\n WHEN p.contype = 'f' THEN p.confkey\n END AS foreignkey_fieldnum,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreignkey,\n CASE\n WHEN p.contype = 'f' THEN p.conkey\n END AS foreignkey_connnum,\n CASE\n WHEN f.atthasdef = 't' THEN d.adsrc\n END AS default\nFROM pg_attribute f \n JOIN pg_class c ON c.oid = f.attrelid \n JOIN pg_type t ON t.oid = f.atttypid \n LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum \n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace \n LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) \n LEFT JOIN pg_class AS g ON p.confrelid = g.oid \nWHERE c.relkind = 'r'::char \n AND n.nspname = '%s' -- Replace with Schema name \n AND c.relname = '%s' -- Replace with table name \n AND f.attnum > 0 ORDER BY number\n;\n</code></pre>\n\n<p>It's pretty complex but it does show you the power and flexibility of the PostgreSQL system catalog and should get you on your way to pg_catalog mastery ;-). Be sure to change out the %s's in the query. The first is Schema and the second is the table name.</p>\n" }, { "answer_id": 16841210, "author": "Ryan", "author_id": 2437411, "author_profile": "https://Stackoverflow.com/users/2437411", "pm_score": 5, "selected": false, "text": "<p>You may do a <code>\\d *search pattern *</code> <strong>with asterisks</strong> to find tables that match the search pattern you're interested in.</p>\n" }, { "answer_id": 20408274, "author": "YATK", "author_id": 1911345, "author_profile": "https://Stackoverflow.com/users/1911345", "pm_score": 4, "selected": false, "text": "<p>You can use this : </p>\n\n<pre><code>SELECT attname \nFROM pg_attribute,pg_class \nWHERE attrelid=pg_class.oid \nAND relname='TableName' \nAND attstattarget &lt;&gt;0; \n</code></pre>\n" }, { "answer_id": 35621545, "author": "Mushahid Khan", "author_id": 4636600, "author_profile": "https://Stackoverflow.com/users/4636600", "pm_score": 4, "selected": false, "text": "<p>In addition to the command line <code>\\d+ &lt;table_name&gt;</code> you already found, you could also use the <a href=\"http://www.postgresql.org/docs/current/static/information-schema.html\">information-schema</a> to look up the column data, using <a href=\"http://www.postgresql.org/docs/current/static/infoschema-columns.html\">info_schema.columns</a> </p>\n\n<pre><code>SELECT *\nFROM info_schema.columns\nWHERE table_schema = 'your_schema'\nAND table_name = 'your_table'\n</code></pre>\n" }, { "answer_id": 37045464, "author": "Mr.Tananki", "author_id": 3541955, "author_profile": "https://Stackoverflow.com/users/3541955", "pm_score": 4, "selected": false, "text": "<p>Use the following SQL statement </p>\n\n<pre><code>SELECT DATA_TYPE \nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE table_name = 'tbl_name' \nAND COLUMN_NAME = 'col_name'\n</code></pre>\n\n<p>If you replace tbl_name and col_name, it displays data type of the particular coloumn that you looking for.</p>\n" }, { "answer_id": 41100953, "author": "Riya Bansal", "author_id": 6721338, "author_profile": "https://Stackoverflow.com/users/6721338", "pm_score": 3, "selected": false, "text": "<p>You can also check using below query</p>\n\n<pre><code>Select * from schema_name.table_name limit 0;\n</code></pre>\n\n<p>Expmple : My table has 2 columns name and pwd. Giving screenshot below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/QokcT.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QokcT.png\" alt=\"Adding image\"></a></p>\n\n<p>*Using PG admin3</p>\n" }, { "answer_id": 45216067, "author": "Usman Yaqoob", "author_id": 2196607, "author_profile": "https://Stackoverflow.com/users/2196607", "pm_score": 2, "selected": false, "text": "<pre><code>Use this command \n\n\\d table name\n\nlike \n\n\\d queuerecords\n\n Table \"public.queuerecords\"\n Column | Type | Modifiers\n-----------+-----------------------------+-----------\n id | uuid | not null\n endtime | timestamp without time zone |\n payload | text |\n queueid | text |\n starttime | timestamp without time zone |\n status | text |\n</code></pre>\n" }, { "answer_id": 45533525, "author": "Guardian", "author_id": 8241603, "author_profile": "https://Stackoverflow.com/users/8241603", "pm_score": 2, "selected": false, "text": "<p>The best way to describe a table such as a column, type, modifiers of columns, etc.</p>\n\n<pre><code>\\d+ tablename or \\d tablename\n</code></pre>\n" }, { "answer_id": 45582724, "author": "Pavan Teja", "author_id": 7132961, "author_profile": "https://Stackoverflow.com/users/7132961", "pm_score": 0, "selected": false, "text": "<p>/dt is the commad which lists you all the tables present in a database. using<br>\n/d command and /d+ we can get the details of a table. The sysntax will be like<br>\n* /d table_name (or) \\d+ table_name </p>\n" }, { "answer_id": 48788746, "author": "anurag2090", "author_id": 1591945, "author_profile": "https://Stackoverflow.com/users/1591945", "pm_score": 3, "selected": false, "text": "<p>This variation of the query (as explained in other answers) worked for me.</p>\n\n<pre><code>SELECT\n COLUMN_NAME\nFROM\n information_schema.COLUMNS\nWHERE\n TABLE_NAME = 'city';\n</code></pre>\n\n<p>It's described here in details:\n<a href=\"http://www.postgresqltutorial.com/postgresql-describe-table/\" rel=\"noreferrer\">http://www.postgresqltutorial.com/postgresql-describe-table/</a></p>\n" }, { "answer_id": 49440385, "author": "paulg", "author_id": 7899140, "author_profile": "https://Stackoverflow.com/users/7899140", "pm_score": -1, "selected": false, "text": "<p>I worked out the following script for get table schema.</p>\n\n<pre><code>'CREATE TABLE ' || 'yourschema.yourtable' || E'\\n(\\n' ||\narray_to_string(\narray_agg(\n' ' || column_expr\n)\n, E',\\n'\n) || E'\\n);\\n'\nfrom\n(\nSELECT ' ' || column_name || ' ' || data_type || \ncoalesce('(' || character_maximum_length || ')', '') || \ncase when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr\nFROM information_schema.columns\nWHERE table_schema || '.' || table_name = 'yourschema.yourtable'\nORDER BY ordinal_position\n) column_list;\n</code></pre>\n" }, { "answer_id": 49749357, "author": "MisterJoyson", "author_id": 7519321, "author_profile": "https://Stackoverflow.com/users/7519321", "pm_score": 3, "selected": false, "text": "<p>In <strong>MySQL</strong> , DESCRIBE table_name</p>\n\n<hr>\n\n<p>In <strong>PostgreSQL</strong> , \\d table_name</p>\n\n<hr>\n\n<p>Or , you can use this long command:</p>\n\n<pre><code>SELECT\n a.attname AS Field,\n t.typname || '(' || a.atttypmod || ')' AS Type,\n CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,\n CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,\n (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\\'(.*)\\'')\n FROM\n pg_catalog.pg_attrdef d\n WHERE\n d.adrelid = a.attrelid\n AND d.adnum = a.attnum\n AND a.atthasdef) AS Default,\n '' as Extras\nFROM\n pg_class c \n JOIN pg_attribute a ON a.attrelid = c.oid\n JOIN pg_type t ON a.atttypid = t.oid\n LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid \n AND r.conname = a.attname\nWHERE\n c.relname = 'tablename'\n AND a.attnum &gt; 0\n\nORDER BY a.attnum\n</code></pre>\n" }, { "answer_id": 50906124, "author": "meenal", "author_id": 8142051, "author_profile": "https://Stackoverflow.com/users/8142051", "pm_score": 2, "selected": false, "text": "<p>In postgres \\d is used to describe the table structure.</p>\n<p>e.g. <code>\\d schema_name.table_name</code></p>\n<p>this command will provide you the basic info of table such as, columns, type and modifiers.</p>\n<p>If you want more info about table use</p>\n<pre><code>\\d+ schema_name.table_name\n</code></pre>\n<p>this will give you extra info such as, storage, stats target and description</p>\n" }, { "answer_id": 52614714, "author": "Howard Elton", "author_id": 7588326, "author_profile": "https://Stackoverflow.com/users/7588326", "pm_score": 3, "selected": false, "text": "<p>To improve on the other answer's SQL query (which is great!), here is a revised query. It also includes constraint names, inheritance information, and a data types broken into it's constituent parts (type, length, precision, scale). It also filters out columns that have been dropped (which still exist in the database).</p>\n\n<pre><code>SELECT\n n.nspname as schema,\n c.relname as table,\n f.attname as column, \n f.attnum as column_id, \n f.attnotnull as not_null,\n f.attislocal not_inherited,\n f.attinhcount inheritance_count,\n pg_catalog.format_type(f.atttypid,f.atttypmod) AS data_type_full,\n t.typname AS data_type_name,\n CASE \n WHEN f.atttypmod &gt;= 0 AND t.typname &lt;&gt; 'numeric'THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data\n END AS data_type_length, \n CASE \n WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) &gt;&gt; 16) &amp; 65535)\n END AS numeric_precision, \n CASE \n WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)&amp; 65535 )\n END AS numeric_scale, \n CASE \n WHEN p.contype = 'p' THEN 't' \n ELSE 'f' \n END AS is_primary_key, \n CASE\n WHEN p.contype = 'p' THEN p.conname\n END AS primary_key_name,\n CASE \n WHEN p.contype = 'u' THEN 't' \n ELSE 'f'\n END AS is_unique_key,\n CASE\n WHEN p.contype = 'u' THEN p.conname\n END AS unique_key_name,\n CASE\n WHEN p.contype = 'f' THEN 't'\n ELSE 'f'\n END AS is_foreign_key,\n CASE\n WHEN p.contype = 'f' THEN p.conname\n END AS foreignkey_name,\n CASE\n WHEN p.contype = 'f' THEN p.confkey\n END AS foreign_key_columnid,\n CASE\n WHEN p.contype = 'f' THEN g.relname\n END AS foreign_key_table,\n CASE\n WHEN p.contype = 'f' THEN p.conkey\n END AS foreign_key_local_column_id,\n CASE\n WHEN f.atthasdef = 't' THEN d.adsrc\n END AS default_value\nFROM pg_attribute f \n JOIN pg_class c ON c.oid = f.attrelid \n JOIN pg_type t ON t.oid = f.atttypid \n LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum \n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace \n LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) \n LEFT JOIN pg_class AS g ON p.confrelid = g.oid \nWHERE c.relkind = 'r'::char \n AND f.attisdropped = false\n AND n.nspname = '%s' -- Replace with Schema name \n AND c.relname = '%s' -- Replace with table name \n AND f.attnum &gt; 0 \nORDER BY f.attnum\n;\n</code></pre>\n" }, { "answer_id": 54107940, "author": "LeYAUable", "author_id": 9210263, "author_profile": "https://Stackoverflow.com/users/9210263", "pm_score": 5, "selected": false, "text": "<p>This should be the solution:</p>\n\n<pre><code>SELECT * FROM information_schema.columns\nWHERE table_schema = 'your_schema'\n AND table_name = 'your_table'\n</code></pre>\n" }, { "answer_id": 60523298, "author": "SumiSujith", "author_id": 9348676, "author_profile": "https://Stackoverflow.com/users/9348676", "pm_score": 1, "selected": false, "text": "<p><strong>1) PostgreSQL DESCRIBE TABLE using psql</strong></p>\n<p>In psql command line tool, <strong>\\d table_name</strong> or <strong>\\d+ table_name</strong> to find the information on columns of a table</p>\n<p><strong>2) PostgreSQL DESCRIBE TABLE using information_schema</strong></p>\n<p>SELECT statement to query the column_names,datatype,character maximum length of the columns table in the information_schema database;</p>\n<p><strong>SELECT\nCOLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH\nfrom INFORMATION_SCHEMA.COLUMNS where table_name = 'tablename';</strong></p>\n<p>For more information <a href=\"https://www.postgresqltutorial.com/postgresql-describe-table/\" rel=\"nofollow noreferrer\">https://www.postgresqltutorial.com/postgresql-describe-table/</a></p>\n" }, { "answer_id": 63752212, "author": "zmerr", "author_id": 4621188, "author_profile": "https://Stackoverflow.com/users/4621188", "pm_score": 2, "selected": false, "text": "<p>When your table is not part of the default schema, you should write:</p>\n<pre><code>\\d+ schema_name.table_name\n\n</code></pre>\n<p>Otherwise, you would get the error saying that &quot;the relation doesn not exist.&quot;</p>\n" }, { "answer_id": 69942312, "author": "Daywalker", "author_id": 2617354, "author_profile": "https://Stackoverflow.com/users/2617354", "pm_score": 1, "selected": false, "text": "<p>I'll add the pg_dump command even thou the psql command was requested. because it generate an output more common to previous MySQl users.</p>\n<p><code># sudo -u postgres pg_dump --table=my_table_name --schema-only mydb</code></p>\n" }, { "answer_id": 72168740, "author": "Mistico", "author_id": 11670863, "author_profile": "https://Stackoverflow.com/users/11670863", "pm_score": 2, "selected": false, "text": "<p>When your table name starts with a capital letter you should put your table name in the quotation.</p>\n<p>Example: <code>\\d &quot;Users&quot;</code></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657951/" ]
How do you perform the equivalent of Oracle's `DESCRIBE TABLE` in PostgreSQL (using the psql command)?
Try this (in the `psql` command-line tool): ``` \d+ tablename ``` See [the manual](http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS) for more info.
109,343
<p>With web services it is considered a good practice to batch several service calls into one message to reduce a number of remote calls. Is there any way to do this with RESTful services?</p>
[ { "answer_id": 109479, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": -1, "selected": false, "text": "<p>Of course there is a way but it would require server-side support. There is no magical one size fits all methodology that I know of.</p>\n" }, { "answer_id": 115026, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 3, "selected": true, "text": "<p>I don't see how batching requests makes any sense in REST. Since the URL in a REST-based service represents the operation to perform and the data on which to perform it, making batch requests would seriously break the conceptual model.</p>\n\n<p>An exception would be if you were performing the same operation on the same data multiple times. In this case you can either pass in multiple values for a request parameter or encode this repetition in the body (however this would only really work for PUT or POST). The Gliffy REST API supports adding multiple users to the same folder via</p>\n\n<pre><code>POST /folders/ROOT/the/folder/name/users?userId=56&amp;userId=87&amp;userId=45\n</code></pre>\n\n<p>which is essentially:</p>\n\n<pre><code>PUT /folders/ROOT/the/folder/name/users/56\nPUT /folders/ROOT/the/folder/name/users/87\nPUT /folders/ROOT/the/folder/name/users/45\n</code></pre>\n\n<p>As the other commenter pointed out, paging results from a GET can be done via request parameters:</p>\n\n<pre><code>GET /some/list/of/resources?startIndex=10&amp;pageSize=50\n</code></pre>\n\n<p><strong>if</strong> the REST service supports it.</p>\n" }, { "answer_id": 127034, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 3, "selected": false, "text": "<p>If you really need to batch, Http 1.1 supports a concept called HTTP Pipelining that allows you to send multiple requests before receiving a response. Check it out <a href=\"http://en.wikipedia.org/wiki/HTTP_pipelining\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 148158, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 2, "selected": false, "text": "<p>I agree with Darrel Miller. HTTP already supports HTTP Pipelining, plus HTTP supports keep alive letting you stream multiple HTTP operations concurrently down the same socket to avoid having to wait for the responses before streaming new requests to the server etc.</p>\n\n<p>So with HTTP pipelining and keep alive you get the effect of batching while using the same underlying REST API - so there's usually no need for another REST API to your service</p>\n" }, { "answer_id": 438035, "author": "Brian Adams", "author_id": 32992, "author_profile": "https://Stackoverflow.com/users/32992", "pm_score": 2, "selected": false, "text": "<p>The team with Astoria made good use of multi-part mime to send a batch of calls. Different from pipelining as the multi-part message can infer the intent of an atomic operation. Seems rather elegant.</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/astoriateam/archive/2008/04/06/batching-data-service-requests.aspx\" rel=\"nofollow noreferrer\">Original blog post explaining\nrational</a> </li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/cc668802.aspx\" rel=\"nofollow noreferrer\">MSDN Documentation</a></li>\n</ul>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ]
With web services it is considered a good practice to batch several service calls into one message to reduce a number of remote calls. Is there any way to do this with RESTful services?
I don't see how batching requests makes any sense in REST. Since the URL in a REST-based service represents the operation to perform and the data on which to perform it, making batch requests would seriously break the conceptual model. An exception would be if you were performing the same operation on the same data multiple times. In this case you can either pass in multiple values for a request parameter or encode this repetition in the body (however this would only really work for PUT or POST). The Gliffy REST API supports adding multiple users to the same folder via ``` POST /folders/ROOT/the/folder/name/users?userId=56&userId=87&userId=45 ``` which is essentially: ``` PUT /folders/ROOT/the/folder/name/users/56 PUT /folders/ROOT/the/folder/name/users/87 PUT /folders/ROOT/the/folder/name/users/45 ``` As the other commenter pointed out, paging results from a GET can be done via request parameters: ``` GET /some/list/of/resources?startIndex=10&pageSize=50 ``` **if** the REST service supports it.
109,383
<p>I am relatively new to Java, and often find that I need to sort a <code>Map&lt;Key, Value&gt;</code> on the values.</p> <p>Since the values are not unique, I find myself converting the <code>keySet</code> into an <code>array</code>, and sorting that array through <strong>array sort</strong> with a <strong>custom comparator</strong> that sorts on the value associated with the key.</p> <p>Is there an easier way?</p>
[ { "answer_id": 109389, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 8, "selected": false, "text": "<p>From <a href=\"http://www.programmersheaven.com/download/49349/download.aspx\" rel=\"noreferrer\">http://www.programmersheaven.com/download/49349/download.aspx</a></p>\n\n<pre><code>private static &lt;K, V&gt; Map&lt;K, V&gt; sortByValue(Map&lt;K, V&gt; map) {\n List&lt;Entry&lt;K, V&gt;&gt; list = new LinkedList&lt;&gt;(map.entrySet());\n Collections.sort(list, new Comparator&lt;Object&gt;() {\n @SuppressWarnings(\"unchecked\")\n public int compare(Object o1, Object o2) {\n return ((Comparable&lt;V&gt;) ((Map.Entry&lt;K, V&gt;) (o1)).getValue()).compareTo(((Map.Entry&lt;K, V&gt;) (o2)).getValue());\n }\n });\n\n Map&lt;K, V&gt; result = new LinkedHashMap&lt;&gt;();\n for (Iterator&lt;Entry&lt;K, V&gt;&gt; it = list.iterator(); it.hasNext();) {\n Map.Entry&lt;K, V&gt; entry = (Map.Entry&lt;K, V&gt;) it.next();\n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 109396, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 3, "selected": false, "text": "<p>Depending on the context, using <code>java.util.LinkedHashMap&lt;T&gt;</code> which rememebers the order in which items are placed into the map. Otherwise, if you need to sort values based on their natural ordering, I would recommend maintaining a separate List which can be sorted via <code>Collections.sort()</code>.</p>\n" }, { "answer_id": 109406, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 5, "selected": false, "text": "<p>The commons-collections library contains a solution called <a href=\"http://commons.apache.org/collections/api-release/org/apache/commons/collections/bidimap/TreeBidiMap.html\" rel=\"noreferrer\">TreeBidiMap</a>. Or, you could have a look at the Google Collections API. It has <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/TreeMultimap.html\" rel=\"noreferrer\">TreeMultimap</a> which you could use.</p>\n\n<p>And if you don't want to use these framework... they come with source code.</p>\n" }, { "answer_id": 109407, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": -1, "selected": false, "text": "<p>If your Map values implement Comparable (e.g. String), this should work</p>\n\n<pre><code>Map&lt;Object, String&gt; map = new HashMap&lt;Object, String&gt;();\n// Populate the Map\nList&lt;String&gt; mapValues = new ArrayList&lt;String&gt;(map.values());\nCollections.sort(mapValues);\n</code></pre>\n\n<p>If the map values themselves don't implement Comparable, but you have an instance of Comparable that can sort them, replace the last line with this:</p>\n\n<pre><code>Collections.sort(mapValues, comparable);\n</code></pre>\n" }, { "answer_id": 109495, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": -1, "selected": false, "text": "<p>For sorting upon the keys I found a better solution with a TreeMap (I will try to get a solution for value based sorting ready too):</p>\n\n<pre><code>public static void main(String[] args) {\n Map&lt;String, String&gt; unsorted = new HashMap&lt;String, String&gt;();\n unsorted.put(\"Cde\", \"Cde_Value\");\n unsorted.put(\"Abc\", \"Abc_Value\");\n unsorted.put(\"Bcd\", \"Bcd_Value\");\n\n Comparator&lt;String&gt; comparer = new Comparator&lt;String&gt;() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }};\n\n Map&lt;String, String&gt; sorted = new TreeMap&lt;String, String&gt;(comparer);\n sorted.putAll(unsorted);\n System.out.println(sorted);\n}\n</code></pre>\n\n<p>Output would be:</p>\n\n<p>{Abc=Abc_Value, Bcd=Bcd_Value, Cde=Cde_Value}</p>\n" }, { "answer_id": 109667, "author": "yoliho", "author_id": 237, "author_profile": "https://Stackoverflow.com/users/237", "pm_score": -1, "selected": false, "text": "<p>Use <strong><a href=\"http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\">java.util.TreeMap</a></strong>.</p>\n\n<p>\"The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.\"</p>\n" }, { "answer_id": 109787, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 5, "selected": false, "text": "<p>Sorting the keys requires the Comparator to look up each value for each comparison. A more scalable solution would use the entrySet directly, since then the value would be immediately available for each comparison (although I haven't backed this up by numbers).</p>\n\n<p>Here's a generic version of such a thing:</p>\n\n<pre><code>public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; List&lt;K&gt; getKeysSortedByValue(Map&lt;K, V&gt; map) {\n final int size = map.size();\n final List&lt;Map.Entry&lt;K, V&gt;&gt; list = new ArrayList&lt;Map.Entry&lt;K, V&gt;&gt;(size);\n list.addAll(map.entrySet());\n final ValueComparator&lt;V&gt; cmp = new ValueComparator&lt;V&gt;();\n Collections.sort(list, cmp);\n final List&lt;K&gt; keys = new ArrayList&lt;K&gt;(size);\n for (int i = 0; i &lt; size; i++) {\n keys.set(i, list.get(i).getKey());\n }\n return keys;\n}\n\nprivate static final class ValueComparator&lt;V extends Comparable&lt;? super V&gt;&gt;\n implements Comparator&lt;Map.Entry&lt;?, V&gt;&gt; {\n public int compare(Map.Entry&lt;?, V&gt; o1, Map.Entry&lt;?, V&gt; o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n}\n</code></pre>\n\n<p>There are ways to lessen memory rotation for the above solution. The first ArrayList created could for instance be re-used as a return value; this would require suppression of some generics warnings, but it might be worth it for re-usable library code. Also, the Comparator does not have to be re-allocated at every invocation.</p>\n\n<p>Here's a more efficient albeit less appealing version:</p>\n\n<pre><code>public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; List&lt;K&gt; getKeysSortedByValue2(Map&lt;K, V&gt; map) {\n final int size = map.size();\n final List reusedList = new ArrayList(size);\n final List&lt;Map.Entry&lt;K, V&gt;&gt; meView = reusedList;\n meView.addAll(map.entrySet());\n Collections.sort(meView, SINGLE);\n final List&lt;K&gt; keyView = reusedList;\n for (int i = 0; i &lt; size; i++) {\n keyView.set(i, meView.get(i).getKey());\n }\n return keyView;\n}\n\nprivate static final Comparator SINGLE = new ValueComparator();\n</code></pre>\n\n<p>Finally, if you need to continously access the sorted information (rather than just sorting it once in a while), you can use an additional multi map. Let me know if you need more details...</p>\n" }, { "answer_id": 109958, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": -1, "selected": false, "text": "<p>Okay, this version works with two new Map objects and two iterations and sorts on values. Hope, the performs well although the map entries must be looped twice:</p>\n\n<pre><code>public static void main(String[] args) {\n Map&lt;String, String&gt; unsorted = new HashMap&lt;String, String&gt;();\n unsorted.put(\"Cde\", \"Cde_Value\");\n unsorted.put(\"Abc\", \"Abc_Value\");\n unsorted.put(\"Bcd\", \"Bcd_Value\");\n\n Comparator&lt;String&gt; comparer = new Comparator&lt;String&gt;() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }};\n\n System.out.println(sortByValue(unsorted, comparer));\n\n}\n\npublic static &lt;K, V&gt; Map&lt;K,V&gt; sortByValue(Map&lt;K, V&gt; in, Comparator&lt;? super V&gt; compare) {\n Map&lt;V, K&gt; swapped = new TreeMap&lt;V, K&gt;(compare);\n for(Entry&lt;K,V&gt; entry: in.entrySet()) {\n if (entry.getValue() != null) {\n swapped.put(entry.getValue(), entry.getKey());\n }\n }\n LinkedHashMap&lt;K, V&gt; result = new LinkedHashMap&lt;K, V&gt;();\n for(Entry&lt;V,K&gt; entry: swapped.entrySet()) {\n if (entry.getValue() != null) {\n result.put(entry.getValue(), entry.getKey());\n }\n }\n return result;\n}\n</code></pre>\n\n<p>The solution uses a TreeMap with a Comparator and sorts out all null keys and values. First, the ordering functionality from the TreeMap is used to sort upon the values, next the sorted Map is used to create a result as a LinkedHashMap that retains has the same order of values.</p>\n\n<p>Greetz, GHad</p>\n" }, { "answer_id": 111183, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": false, "text": "<p>When I'm faced with this, I just create a list on the side. If you put them together in a custom Map implementation, it'll have a nice feel to it... You can use something like the following, performing the sort only when needed. (Note: I haven't really tested this, but it compiles... might be a silly little bug in there somewhere)</p>\n\n<p>(If you want it sorted by both keys and values, have the class extend TreeMap, don't define the accessor methods, and have the mutators call super.xxxxx instead of map_.xxxx)</p>\n\n<pre><code>package com.javadude.sample;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class SortedValueHashMap&lt;K, V&gt; implements Map&lt;K, V&gt; {\n private Map&lt;K, V&gt; map_ = new HashMap&lt;K, V&gt;();\n private List&lt;V&gt; valueList_ = new ArrayList&lt;V&gt;();\n private boolean needsSort_ = false;\n private Comparator&lt;V&gt; comparator_;\n\n public SortedValueHashMap() {\n }\n public SortedValueHashMap(List&lt;V&gt; valueList) {\n valueList_ = valueList;\n }\n\n public List&lt;V&gt; sortedValues() {\n if (needsSort_) {\n needsSort_ = false;\n Collections.sort(valueList_, comparator_);\n }\n return valueList_;\n }\n\n // mutators\n public void clear() {\n map_.clear();\n valueList_.clear();\n needsSort_ = false;\n }\n\n public V put(K key, V value) {\n valueList_.add(value);\n needsSort_ = true;\n return map_.put(key, value);\n }\n\n public void putAll(Map&lt;? extends K, ? extends V&gt; m) {\n map_.putAll(m);\n valueList_.addAll(m.values());\n needsSort_ = true;\n }\n\n public V remove(Object key) {\n V value = map_.remove(key);\n valueList_.remove(value);\n return value;\n }\n\n // accessors\n public boolean containsKey(Object key) { return map_.containsKey(key); }\n public boolean containsValue(Object value) { return map_.containsValue(value); }\n public Set&lt;java.util.Map.Entry&lt;K, V&gt;&gt; entrySet() { return map_.entrySet(); }\n public boolean equals(Object o) { return map_.equals(o); }\n public V get(Object key) { return map_.get(key); }\n public int hashCode() { return map_.hashCode(); }\n public boolean isEmpty() { return map_.isEmpty(); }\n public Set&lt;K&gt; keySet() { return map_.keySet(); }\n public int size() { return map_.size(); }\n public Collection&lt;V&gt; values() { return map_.values(); }\n}\n</code></pre>\n" }, { "answer_id": 119143, "author": "Lyudmil", "author_id": 13121, "author_profile": "https://Stackoverflow.com/users/13121", "pm_score": 4, "selected": false, "text": "<p>While I agree that the constant need to sort a map is probably a smell, I think the following code is the easiest way to do it without using a different data structure.</p>\n\n<pre><code>public class MapUtilities {\n\npublic static &lt;K, V extends Comparable&lt;V&gt;&gt; List&lt;Entry&lt;K, V&gt;&gt; sortByValue(Map&lt;K, V&gt; map) {\n List&lt;Entry&lt;K, V&gt;&gt; entries = new ArrayList&lt;Entry&lt;K, V&gt;&gt;(map.entrySet());\n Collections.sort(entries, new ByValue&lt;K, V&gt;());\n return entries;\n}\n\nprivate static class ByValue&lt;K, V extends Comparable&lt;V&gt;&gt; implements Comparator&lt;Entry&lt;K, V&gt;&gt; {\n public int compare(Entry&lt;K, V&gt; o1, Entry&lt;K, V&gt; o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>And here is an embarrassingly incomplete unit test:</p>\n\n<pre><code>public class MapUtilitiesTest extends TestCase {\npublic void testSorting() {\n HashMap&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;();\n map.put(\"One\", 1);\n map.put(\"Two\", 2);\n map.put(\"Three\", 3);\n\n List&lt;Map.Entry&lt;String, Integer&gt;&gt; sorted = MapUtilities.sortByValue(map);\n assertEquals(\"First\", \"One\", sorted.get(0).getKey());\n assertEquals(\"Second\", \"Two\", sorted.get(1).getKey());\n assertEquals(\"Third\", \"Three\", sorted.get(2).getKey());\n}\n</code></pre>\n\n<p>}</p>\n\n<p>The result is a sorted list of Map.Entry objects, from which you can obtain the keys and values.</p>\n" }, { "answer_id": 747627, "author": "Maxim Veksler", "author_id": 48062, "author_profile": "https://Stackoverflow.com/users/48062", "pm_score": 2, "selected": false, "text": "<p>Based on @devinmoore code, a map sorting methods using generics and supporting both ascending and descending ordering.</p>\n\n<pre><code>/**\n * Sort a map by it's keys in ascending order. \n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static &lt;K, V&gt; LinkedHashMap&lt;K, V&gt; sortMapByKey(final Map&lt;K, V&gt; map) {\n return sortMapByKey(map, SortingOrder.ASCENDING);\n}\n\n/**\n * Sort a map by it's values in ascending order.\n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static &lt;K, V&gt; LinkedHashMap&lt;K, V&gt; sortMapByValue(final Map&lt;K, V&gt; map) {\n return sortMapByValue(map, SortingOrder.ASCENDING);\n}\n\n/**\n * Sort a map by it's keys.\n * \n * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order. \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static &lt;K, V&gt; LinkedHashMap&lt;K, V&gt; sortMapByKey(final Map&lt;K, V&gt; map, final SortingOrder sortingOrder) {\n Comparator&lt;Map.Entry&lt;K, V&gt;&gt; comparator = new Comparator&lt;Entry&lt;K,V&gt;&gt;() {\n public int compare(Entry&lt;K, V&gt; o1, Entry&lt;K, V&gt; o2) {\n return comparableCompare(o1.getKey(), o2.getKey(), sortingOrder);\n }\n };\n\n return sortMap(map, comparator);\n}\n\n/**\n * Sort a map by it's values.\n * \n * @param sortingOrder {@link SortingOrder} enum specifying requested sorting order. \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static &lt;K, V&gt; LinkedHashMap&lt;K, V&gt; sortMapByValue(final Map&lt;K, V&gt; map, final SortingOrder sortingOrder) {\n Comparator&lt;Map.Entry&lt;K, V&gt;&gt; comparator = new Comparator&lt;Entry&lt;K,V&gt;&gt;() {\n public int compare(Entry&lt;K, V&gt; o1, Entry&lt;K, V&gt; o2) {\n return comparableCompare(o1.getValue(), o2.getValue(), sortingOrder);\n }\n };\n\n return sortMap(map, comparator);\n}\n\n@SuppressWarnings(\"unchecked\")\nprivate static &lt;T&gt; int comparableCompare(T o1, T o2, SortingOrder sortingOrder) {\n int compare = ((Comparable&lt;T&gt;)o1).compareTo(o2);\n\n switch (sortingOrder) {\n case ASCENDING:\n return compare;\n case DESCENDING:\n return (-1) * compare;\n }\n\n return 0;\n}\n\n/**\n * Sort a map by supplied comparator logic.\n * \n * @return new instance of {@link LinkedHashMap} contained sorted entries of supplied map.\n * @author Maxim Veksler\n */\npublic static &lt;K, V&gt; LinkedHashMap&lt;K, V&gt; sortMap(final Map&lt;K, V&gt; map, final Comparator&lt;Map.Entry&lt;K, V&gt;&gt; comparator) {\n // Convert the map into a list of key,value pairs.\n List&lt;Map.Entry&lt;K, V&gt;&gt; mapEntries = new LinkedList&lt;Map.Entry&lt;K, V&gt;&gt;(map.entrySet());\n\n // Sort the converted list according to supplied comparator.\n Collections.sort(mapEntries, comparator);\n\n // Build a new ordered map, containing the same entries as the old map. \n LinkedHashMap&lt;K, V&gt; result = new LinkedHashMap&lt;K, V&gt;(map.size() + (map.size() / 20));\n for(Map.Entry&lt;K, V&gt; entry : mapEntries) {\n // We iterate on the mapEntries list which is sorted by the comparator putting new entries into \n // the targeted result which is a sorted map. \n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n}\n\n/**\n * Sorting order enum, specifying request result sort behavior.\n * @author Maxim Veksler\n *\n */\npublic static enum SortingOrder {\n /**\n * Resulting sort will be from smaller to biggest.\n */\n ASCENDING,\n /**\n * Resulting sort will be from biggest to smallest.\n */\n DESCENDING\n}\n</code></pre>\n" }, { "answer_id": 1283722, "author": "user157196", "author_id": 157196, "author_profile": "https://Stackoverflow.com/users/157196", "pm_score": 9, "selected": false, "text": "<h3>Important note:</h3>\n<p><strong>This code can break in multiple ways.</strong> If you intend to use the code provided, be sure to read the comments as well to be aware of the implications. For example, values can no longer be retrieved by their key. (<code>get</code> always returns <code>null</code>.)</p>\n<hr />\n<p>It seems much easier than all of the foregoing. Use a TreeMap as follows:</p>\n<pre><code>public class Testing {\n public static void main(String[] args) {\n HashMap&lt;String, Double&gt; map = new HashMap&lt;String, Double&gt;();\n ValueComparator bvc = new ValueComparator(map);\n TreeMap&lt;String, Double&gt; sorted_map = new TreeMap&lt;String, Double&gt;(bvc);\n\n map.put(&quot;A&quot;, 99.5);\n map.put(&quot;B&quot;, 67.4);\n map.put(&quot;C&quot;, 67.4);\n map.put(&quot;D&quot;, 67.3);\n\n System.out.println(&quot;unsorted map: &quot; + map);\n sorted_map.putAll(map);\n System.out.println(&quot;results: &quot; + sorted_map);\n }\n}\n\nclass ValueComparator implements Comparator&lt;String&gt; {\n Map&lt;String, Double&gt; base;\n\n public ValueComparator(Map&lt;String, Double&gt; base) {\n this.base = base;\n }\n\n // Note: this comparator imposes orderings that are inconsistent with\n // equals.\n public int compare(String a, String b) {\n if (base.get(a) &gt;= base.get(b)) {\n return -1;\n } else {\n return 1;\n } // returning 0 would merge keys\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4}\nresults: {D=67.3, B=67.4, C=67.4, A=99.5}\n</code></pre>\n" }, { "answer_id": 2112659, "author": "Anthony", "author_id": 236152, "author_profile": "https://Stackoverflow.com/users/236152", "pm_score": 5, "selected": false, "text": "<p>I've looked at the given answers, but a lot of them are more complicated than needed or remove map elements when several keys have same value.</p>\n\n<p>Here is a solution that I think fits better:</p>\n\n<pre><code>public static &lt;K, V extends Comparable&lt;V&gt;&gt; Map&lt;K, V&gt; sortByValues(final Map&lt;K, V&gt; map) {\n Comparator&lt;K&gt; valueComparator = new Comparator&lt;K&gt;() {\n public int compare(K k1, K k2) {\n int compare = map.get(k2).compareTo(map.get(k1));\n if (compare == 0) return 1;\n else return compare;\n }\n };\n Map&lt;K, V&gt; sortedByValues = new TreeMap&lt;K, V&gt;(valueComparator);\n sortedByValues.putAll(map);\n return sortedByValues;\n}\n</code></pre>\n\n<p>Note that the map is sorted from the highest value to the lowest.</p>\n" }, { "answer_id": 2581754, "author": "Carter Page", "author_id": 309596, "author_profile": "https://Stackoverflow.com/users/309596", "pm_score": 10, "selected": false, "text": "<p>Here's a generic-friendly version:</p>\n\n<pre><code>public class MapUtil {\n public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; Map&lt;K, V&gt; sortByValue(Map&lt;K, V&gt; map) {\n List&lt;Entry&lt;K, V&gt;&gt; list = new ArrayList&lt;&gt;(map.entrySet());\n list.sort(Entry.comparingByValue());\n\n Map&lt;K, V&gt; result = new LinkedHashMap&lt;&gt;();\n for (Entry&lt;K, V&gt; entry : list) {\n result.put(entry.getKey(), entry.getValue());\n }\n\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 2797784, "author": "Darkless", "author_id": 336642, "author_profile": "https://Stackoverflow.com/users/336642", "pm_score": 3, "selected": false, "text": "<p>This is just too complicated. Maps were not supposed to do such job as sorting them by Value. The easiest way is to create your own Class so it fits your requirement.</p>\n\n<p>In example lower you are supposed to add TreeMap a comparator at place where * is. But by java API it gives comparator only keys, not values. All of examples stated here is based on 2 Maps. One Hash and one new Tree. Which is odd.</p>\n\n<p>The example:</p>\n\n<pre><code>Map&lt;Driver driver, Float time&gt; map = new TreeMap&lt;Driver driver, Float time&gt;(*);\n</code></pre>\n\n<p>So change the map into a set this way:</p>\n\n<pre><code>ResultComparator rc = new ResultComparator();\nSet&lt;Results&gt; set = new TreeSet&lt;Results&gt;(rc);\n</code></pre>\n\n<p>You will create class <code>Results</code>,</p>\n\n<pre><code>public class Results {\n private Driver driver;\n private Float time;\n\n public Results(Driver driver, Float time) {\n this.driver = driver;\n this.time = time;\n }\n\n public Float getTime() {\n return time;\n }\n\n public void setTime(Float time) {\n this.time = time;\n }\n\n public Driver getDriver() {\n return driver;\n }\n\n public void setDriver (Driver driver) {\n this.driver = driver;\n }\n}\n</code></pre>\n\n<p>and the Comparator class:</p>\n\n<pre><code>public class ResultsComparator implements Comparator&lt;Results&gt; {\n public int compare(Results t, Results t1) {\n if (t.getTime() &lt; t1.getTime()) {\n return 1;\n } else if (t.getTime() == t1.getTime()) {\n return 0;\n } else {\n return -1;\n }\n }\n}\n</code></pre>\n\n<p>This way you can easily add more dependencies.</p>\n\n<p>And as the last point I'll add simple iterator:</p>\n\n<pre><code>Iterator it = set.iterator();\nwhile (it.hasNext()) {\n Results r = (Results)it.next();\n System.out.println( r.getDriver().toString\n //or whatever that is related to Driver class -getName() getSurname()\n + \" \"\n + r.getTime()\n );\n}\n</code></pre>\n" }, { "answer_id": 3420912, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": 8, "selected": false, "text": "<p><strong>Three 1-line answers...</strong></p>\n\n<p>I would use <s>Google Collections</s> <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"noreferrer\"><strong>Guava</strong></a> to do this - if your values are <code>Comparable</code> then you can use</p>\n\n<pre><code>valueComparator = Ordering.natural().onResultOf(Functions.forMap(map))\n</code></pre>\n\n<p>Which will create a function (object) for the map [that takes any of the keys as input, returning the respective value], and then apply natural (comparable) ordering to them [the values].</p>\n\n<p>If they're not comparable, then you'll need to do something along the lines of</p>\n\n<pre><code>valueComparator = Ordering.from(comparator).onResultOf(Functions.forMap(map)) \n</code></pre>\n\n<p>These may be applied to a TreeMap (as <code>Ordering</code> extends <code>Comparator</code>), or a <a href=\"https://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java/109389#109389\">LinkedHashMap after some sorting</a></p>\n\n<p><em>NB</em>: If you are going to use a TreeMap, remember that if a comparison == 0, then the item is already in the list (which will happen if you have multiple values that compare the same). To alleviate this, you could add your key to the comparator like so (presuming that your keys and values are <code>Comparable</code>):</p>\n\n<pre><code>valueComparator = Ordering.natural().onResultOf(Functions.forMap(map)).compound(Ordering.natural())\n</code></pre>\n\n<p>= <em>Apply natural ordering to the value mapped by the key, and compound that with the natural ordering of the key</em></p>\n\n<p>Note that this will still not work if your keys compare to 0, but this should be sufficient for most <code>comparable</code> items (as <code>hashCode</code>, <code>equals</code> and <code>compareTo</code> are often in sync...)</p>\n\n<p>See <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Ordering.html#onResultOf(com.google.common.base.Function)\" rel=\"noreferrer\">Ordering.onResultOf()</a> and <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Functions.html#forMap(java.util.Map)\" rel=\"noreferrer\">Functions.forMap()</a>.</p>\n\n<h2>Implementation</h2>\n\n<p>So now that we've got a comparator that does what we want, we need to get a result from it. </p>\n\n<pre><code>map = ImmutableSortedMap.copyOf(myOriginalMap, valueComparator);\n</code></pre>\n\n<p>Now this will most likely work work, but:</p>\n\n<ol>\n<li>needs to be done given a complete finished map</li>\n<li>Don't try the comparators above on a <code>TreeMap</code>; there's no point trying to compare an inserted key when it doesn't have a value until after the put, i.e., it will break really fast</li>\n</ol>\n\n<p>Point 1 is a bit of a deal-breaker for me; google collections is incredibly lazy (which is good: you can do pretty much every operation in an instant; the real work is done when you start using the result), and this requires copying a <em>whole</em> map!</p>\n\n<h2>\"Full\" answer/Live sorted map by values</h2>\n\n<p>Don't worry though; if you were obsessed enough with having a \"live\" map sorted in this manner, you could solve not one but both(!) of the above issues with something crazy like the following:</p>\n\n<p><strong>Note: This has changed significantly in June 2012 - the previous code could never work: an internal HashMap is required to lookup the values without creating an infinite loop between the <code>TreeMap.get()</code> -> <code>compare()</code> and <code>compare()</code> -> <code>get()</code></strong></p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.TreeMap;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.Ordering;\n\nclass ValueComparableMap&lt;K extends Comparable&lt;K&gt;,V&gt; extends TreeMap&lt;K,V&gt; {\n //A map for doing lookups on the keys for comparison so we don't get infinite loops\n private final Map&lt;K, V&gt; valueMap;\n\n ValueComparableMap(final Ordering&lt;? super V&gt; partialValueOrdering) {\n this(partialValueOrdering, new HashMap&lt;K,V&gt;());\n }\n\n private ValueComparableMap(Ordering&lt;? super V&gt; partialValueOrdering,\n HashMap&lt;K, V&gt; valueMap) {\n super(partialValueOrdering //Apply the value ordering\n .onResultOf(Functions.forMap(valueMap)) //On the result of getting the value for the key from the map\n .compound(Ordering.natural())); //as well as ensuring that the keys don't get clobbered\n this.valueMap = valueMap;\n }\n\n public V put(K k, V v) {\n if (valueMap.containsKey(k)){\n //remove the key in the sorted set before adding the key again\n remove(k);\n }\n valueMap.put(k,v); //To get \"real\" unsorted values for the comparator\n return super.put(k, v); //Put it in value order\n }\n\n public static void main(String[] args){\n TreeMap&lt;String, Integer&gt; map = new ValueComparableMap&lt;String, Integer&gt;(Ordering.natural());\n map.put(\"a\", 5);\n map.put(\"b\", 1);\n map.put(\"c\", 3);\n assertEquals(\"b\",map.firstKey());\n assertEquals(\"a\",map.lastKey());\n map.put(\"d\",0);\n assertEquals(\"d\",map.firstKey());\n //ensure it's still a map (by overwriting a key, but with a new value) \n map.put(\"d\", 2);\n assertEquals(\"b\", map.firstKey());\n //Ensure multiple values do not clobber keys\n map.put(\"e\", 2);\n assertEquals(5, map.size());\n assertEquals(2, (int) map.get(\"e\"));\n assertEquals(2, (int) map.get(\"d\"));\n }\n }\n</code></pre>\n\n<p>When we put, we ensure that the hash map has the value for the comparator, and then put to the TreeSet for sorting. But before that we check the hash map to see that the key is not actually a duplicate. Also, the comparator that we create will also include the key so that duplicate values don't delete the non-duplicate keys (due to == comparison).\nThese 2 items are <em>vital</em> for ensuring the map contract is kept; if you think you don't want that, then you're almost at the point of reversing the map entirely (to <code>Map&lt;V,K&gt;</code>).</p>\n\n<p>The constructor would need to be called as </p>\n\n<pre><code> new ValueComparableMap(Ordering.natural());\n //or\n new ValueComparableMap(Ordering.from(comparator));\n</code></pre>\n" }, { "answer_id": 4577336, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 2, "selected": false, "text": "<p>Here is an OO solution (i.e., doesn't use <code>static</code> methods):</p>\n\n<pre><code>import java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class SortableValueMap&lt;K, V extends Comparable&lt;V&gt;&gt;\n extends LinkedHashMap&lt;K, V&gt; {\n public SortableValueMap() { }\n\n public SortableValueMap( Map&lt;K, V&gt; map ) {\n super( map );\n }\n\n public void sortByValue() {\n List&lt;Map.Entry&lt;K, V&gt;&gt; list = new LinkedList&lt;Map.Entry&lt;K, V&gt;&gt;( entrySet() );\n\n Collections.sort( list, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {\n public int compare( Map.Entry&lt;K, V&gt; entry1, Map.Entry&lt;K, V&gt; entry2 ) {\n return entry1.getValue().compareTo( entry2.getValue() );\n }\n });\n\n clear();\n\n for( Map.Entry&lt;K, V&gt; entry : list ) {\n put( entry.getKey(), entry.getValue() );\n }\n }\n\n private static void print( String text, Map&lt;String, Double&gt; map ) {\n System.out.println( text );\n\n for( String key : map.keySet() ) {\n System.out.println( \"key/value: \" + key + \"/\" + map.get( key ) );\n }\n }\n\n public static void main( String[] args ) {\n SortableValueMap&lt;String, Double&gt; map =\n new SortableValueMap&lt;String, Double&gt;();\n\n map.put( \"A\", 67.5 );\n map.put( \"B\", 99.5 );\n map.put( \"C\", 82.4 );\n map.put( \"D\", 42.0 );\n\n print( \"Unsorted map\", map );\n map.sortByValue();\n print( \"Sorted map\", map );\n }\n}\n</code></pre>\n\n<p>Hereby donated to the public domain.</p>\n" }, { "answer_id": 4943507, "author": "Roger", "author_id": 558193, "author_profile": "https://Stackoverflow.com/users/558193", "pm_score": 3, "selected": false, "text": "<p>This is a variation of Anthony's answer, which doesn't work if there are duplicate values:</p>\n\n<pre><code>public static &lt;K, V extends Comparable&lt;V&gt;&gt; Map&lt;K, V&gt; sortMapByValues(final Map&lt;K, V&gt; map) {\n Comparator&lt;K&gt; valueComparator = new Comparator&lt;K&gt;() {\n public int compare(K k1, K k2) {\n final V v1 = map.get(k1);\n final V v2 = map.get(k2);\n\n /* Not sure how to handle nulls ... */\n if (v1 == null) {\n return (v2 == null) ? 0 : 1;\n }\n\n int compare = v2.compareTo(v1);\n if (compare != 0)\n {\n return compare;\n }\n else\n {\n Integer h1 = k1.hashCode();\n Integer h2 = k2.hashCode();\n return h2.compareTo(h1);\n }\n }\n };\n Map&lt;K, V&gt; sortedByValues = new TreeMap&lt;K, V&gt;(valueComparator);\n sortedByValues.putAll(map);\n return sortedByValues;\n}\n</code></pre>\n\n<p>Note that it's rather up in the air how to handle nulls. </p>\n\n<p>One important advantage of this approach is that it actually returns a Map, unlike some of the other solutions offered here.</p>\n" }, { "answer_id": 5041615, "author": "Sunil Kumar Sahoo", "author_id": 111988, "author_profile": "https://Stackoverflow.com/users/111988", "pm_score": -1, "selected": false, "text": "<pre><code>public class SortedMapExample {\n\n public static void main(String[] args) {\n Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n\n map.put(\"Cde\", \"C\");\n map.put(\"Abc\", \"A\");\n map.put(\"Cbc\", \"Z\");\n map.put(\"Dbc\", \"D\");\n map.put(\"Bcd\", \"B\");\n map.put(\"sfd\", \"Bqw\");\n map.put(\"DDD\", \"Bas\");\n map.put(\"BGG\", \"Basd\");\n\n System.out.println(sort(map, new Comparator&lt;String&gt;() {\n @Override\n public int compare(String o1, String o2) {\n return o1.compareTo(o2);\n }}));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static &lt;K, V&gt; Map&lt;K,V&gt; sort(Map&lt;K, V&gt; in, Comparator&lt;? super V&gt; compare) {\n Map&lt;K, V&gt; result = new LinkedHashMap&lt;K, V&gt;();\n V[] array = (V[])in.values().toArray();\n for(int i=0;i&lt;array.length;i++)\n {\n\n }\n Arrays.sort(array, compare);\n for (V item : array) {\n K key= (K) getKey(in, item);\n result.put(key, item);\n }\n return result;\n }\n\n public static &lt;K, V&gt; Object getKey(Map&lt;K, V&gt; in,V value)\n {\n Set&lt;K&gt; key= in.keySet();\n Iterator&lt;K&gt; keyIterator=key.iterator();\n while (keyIterator.hasNext()) {\n K valueObject = (K) keyIterator.next();\n if(in.get(valueObject).equals(value))\n {\n return valueObject;\n }\n }\n return null;\n }\n</code></pre>\n\n<p>}</p>\n\n<p>// Please try here. I am modifing the code for value sort.</p>\n" }, { "answer_id": 6281263, "author": "lisak", "author_id": 306488, "author_profile": "https://Stackoverflow.com/users/306488", "pm_score": 3, "selected": false, "text": "<p>Afaik the most cleaner way is utilizing collections to sort map on value:</p>\n\n<pre><code>Map&lt;String, Long&gt; map = new HashMap&lt;String, Long&gt;();\n// populate with data to sort on Value\n// use datastructure designed for sorting\n\nQueue queue = new PriorityQueue( map.size(), new MapComparable() );\nqueue.addAll( map.entrySet() );\n\n// get a sorted map\nLinkedHashMap&lt;String, Long&gt; linkedMap = new LinkedHashMap&lt;String, Long&gt;();\n\nfor (Map.Entry&lt;String, Long&gt; entry; (entry = queue.poll())!=null;) {\n linkedMap.put(entry.getKey(), entry.getValue());\n}\n\npublic static class MapComparable implements Comparator&lt;Map.Entry&lt;String, Long&gt;&gt;{\n\n public int compare(Entry&lt;String, Long&gt; e1, Entry&lt;String, Long&gt; e2) {\n return e1.getValue().compareTo(e2.getValue());\n }\n}\n</code></pre>\n" }, { "answer_id": 6584631, "author": "RoyalBigorno", "author_id": 829939, "author_profile": "https://Stackoverflow.com/users/829939", "pm_score": 4, "selected": false, "text": "<p>Use a generic comparator such as:</p>\n<pre class=\"lang-java prettyprint-override\"><code>final class MapValueComparator&lt;K,V extends Comparable&lt;V&gt;&gt; implements Comparator&lt;K&gt; {\n private final Map&lt;K,V&gt; map;\n \n private MapValueComparator() {\n super();\n }\n \n public MapValueComparator(Map&lt;K,V&gt; map) {\n this();\n this.map = map;\n }\n \n public int compare(K o1, K o2) {\n return map.get(o1).compareTo(map.get(o2));\n }\n}\n</code></pre>\n" }, { "answer_id": 6705027, "author": "michel.iamit", "author_id": 369060, "author_profile": "https://Stackoverflow.com/users/369060", "pm_score": 4, "selected": false, "text": "<p>The answer voted for the most does not work when you have 2 items that equals.\nthe TreeMap leaves equal values out.</p>\n\n<p>the exmaple:\nunsorted map</p>\n\n<pre>\nkey/value: D/67.3\nkey/value: A/99.5\nkey/value: B/67.4\nkey/value: C/67.5\nkey/value: E/99.5\n</pre>\n\n<p>results</p>\n\n<pre>\nkey/value: A/99.5\nkey/value: C/67.5\nkey/value: B/67.4\nkey/value: D/67.3\n</pre>\n\n<p>So leaves out E!!</p>\n\n<p>For me it worked fine to adjust the comparator, if it equals do not return 0 but -1.</p>\n\n<p>in the example:</p>\n\n<blockquote>\n <blockquote>\n <p>class ValueComparator implements Comparator {</p>\n \n <p>Map base;\n public ValueComparator(Map base) {\n this.base = base;\n }</p>\n \n <p>public int compare(Object a, Object b) {</p>\n\n<pre><code>if((Double)base.get(a) &lt; (Double)base.get(b)) {\n return 1;\n} else if((Double)base.get(a) == (Double)base.get(b)) {\n return -1;\n} else {\n return -1;\n}\n</code></pre>\n \n <p>}\n }</p>\n </blockquote>\n</blockquote>\n\n<p>now it returns:</p>\n\n<p>unsorted map:</p>\n\n<pre>\nkey/value: D/67.3\nkey/value: A/99.5\nkey/value: B/67.4\nkey/value: C/67.5\nkey/value: E/99.5\n</pre>\n\n<p>results:</p>\n\n<pre>\nkey/value: A/99.5\nkey/value: E/99.5\nkey/value: C/67.5\nkey/value: B/67.4\nkey/value: D/67.3\n</pre>\n\n<p>as a response to Aliens (2011 nov. 22):\nI Am using this solution for a map of Integer Id's and names, but the idea is the same, so might be the code above is not correct (I will write it in a test and give you the correct code), this is the code for a Map sorting, based on the solution above:</p>\n\n<pre><code>package nl.iamit.util;\n\nimport java.util.Comparator;\nimport java.util.Map;\n\npublic class Comparators {\n\n\n public static class MapIntegerStringComparator implements Comparator {\n\n Map&lt;Integer, String&gt; base;\n\n public MapIntegerStringComparator(Map&lt;Integer, String&gt; base) {\n this.base = base;\n }\n\n public int compare(Object a, Object b) {\n\n int compare = ((String) base.get(a))\n .compareTo((String) base.get(b));\n if (compare == 0) {\n return -1;\n }\n return compare;\n }\n }\n\n\n}\n</code></pre>\n\n<p>and this is the test class (I just tested it, and this works for the Integer, String Map:</p>\n\n<pre><code>package test.nl.iamit.util;\n\nimport java.util.HashMap;\nimport java.util.TreeMap;\nimport nl.iamit.util.Comparators;\nimport org.junit.Test;\nimport static org.junit.Assert.assertArrayEquals;\n\npublic class TestComparators {\n\n\n @Test\n public void testMapIntegerStringComparator(){\n HashMap&lt;Integer, String&gt; unSoretedMap = new HashMap&lt;Integer, String&gt;();\n Comparators.MapIntegerStringComparator bvc = new Comparators.MapIntegerStringComparator(\n unSoretedMap);\n TreeMap&lt;Integer, String&gt; sorted_map = new TreeMap&lt;Integer, String&gt;(bvc);\n //the testdata:\n unSoretedMap.put(new Integer(1), \"E\");\n unSoretedMap.put(new Integer(2), \"A\");\n unSoretedMap.put(new Integer(3), \"E\");\n unSoretedMap.put(new Integer(4), \"B\");\n unSoretedMap.put(new Integer(5), \"F\");\n\n sorted_map.putAll(unSoretedMap);\n\n Object[] targetKeys={new Integer(2),new Integer(4),new Integer(3),new Integer(1),new Integer(5) };\n Object[] currecntKeys=sorted_map.keySet().toArray();\n\n assertArrayEquals(targetKeys,currecntKeys);\n }\n}\n</code></pre>\n\n<p>here is the code for the Comparator of a Map:</p>\n\n<pre><code>public static class MapStringDoubleComparator implements Comparator {\n\n Map&lt;String, Double&gt; base;\n\n public MapStringDoubleComparator(Map&lt;String, Double&gt; base) {\n this.base = base;\n }\n\n //note if you want decending in stead of ascending, turn around 1 and -1\n public int compare(Object a, Object b) {\n if ((Double) base.get(a) == (Double) base.get(b)) {\n return 0;\n } else if((Double) base.get(a) &lt; (Double) base.get(b)) {\n return -1;\n }else{\n return 1;\n }\n }\n}\n</code></pre>\n\n<p>and this is the testcase for this:</p>\n\n<pre><code>@Test\npublic void testMapStringDoubleComparator(){\n HashMap&lt;String, Double&gt; unSoretedMap = new HashMap&lt;String, Double&gt;();\n Comparators.MapStringDoubleComparator bvc = new Comparators.MapStringDoubleComparator(\n unSoretedMap);\n TreeMap&lt;String, Double&gt; sorted_map = new TreeMap&lt;String, Double&gt;(bvc);\n //the testdata:\n unSoretedMap.put(\"D\",new Double(67.3));\n unSoretedMap.put(\"A\",new Double(99.5));\n unSoretedMap.put(\"B\",new Double(67.4));\n unSoretedMap.put(\"C\",new Double(67.5));\n unSoretedMap.put(\"E\",new Double(99.5));\n\n sorted_map.putAll(unSoretedMap);\n\n Object[] targetKeys={\"D\",\"B\",\"C\",\"E\",\"A\"};\n Object[] currecntKeys=sorted_map.keySet().toArray();\n\n assertArrayEquals(targetKeys,currecntKeys);\n}\n</code></pre>\n\n<p>of cource you can make this a lot more generic, but I just needed it for 1 case (the Map)</p>\n" }, { "answer_id": 7166058, "author": "didxga", "author_id": 231010, "author_profile": "https://Stackoverflow.com/users/231010", "pm_score": 2, "selected": false, "text": "<p>This method will just serve the purpose. (the 'setback' is that the Values <strong>must implement the java.util.Comparable interface</strong>)</p>\n\n<pre><code> /**\n\n * Sort a map according to values.\n\n * @param &lt;K&gt; the key of the map.\n * @param &lt;V&gt; the value to sort according to.\n * @param mapToSort the map to sort.\n\n * @return a map sorted on the values.\n\n */ \npublic static &lt;K, V extends Comparable&lt; ? super V&gt;&gt; Map&lt;K, V&gt;\nsortMapByValues(final Map &lt;K, V&gt; mapToSort)\n{\n List&lt;Map.Entry&lt;K, V&gt;&gt; entries =\n new ArrayList&lt;Map.Entry&lt;K, V&gt;&gt;(mapToSort.size()); \n\n entries.addAll(mapToSort.entrySet());\n\n Collections.sort(entries,\n new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;()\n {\n @Override\n public int compare(\n final Map.Entry&lt;K, V&gt; entry1,\n final Map.Entry&lt;K, V&gt; entry2)\n {\n return entry1.getValue().compareTo(entry2.getValue());\n }\n }); \n\n Map&lt;K, V&gt; sortedMap = new LinkedHashMap&lt;K, V&gt;(); \n\n for (Map.Entry&lt;K, V&gt; entry : entries)\n {\n sortedMap.put(entry.getKey(), entry.getValue());\n\n } \n\n return sortedMap;\n\n}\n</code></pre>\n\n<p><a href=\"http://javawithswaranga.blogspot.com/2011/06/generic-method-to-sort-hashmap.html\" rel=\"nofollow\">http://javawithswaranga.blogspot.com/2011/06/generic-method-to-sort-hashmap.html</a></p>\n" }, { "answer_id": 7263116, "author": "malix", "author_id": 856468, "author_profile": "https://Stackoverflow.com/users/856468", "pm_score": 3, "selected": false, "text": "<p>Since <strong><em>TreeMap&lt;> does not work</em></strong> for values that can be equal, I used this:</p>\n\n<pre><code>private &lt;K, V extends Comparable&lt;? super V&gt;&gt; List&lt;Entry&lt;K, V&gt;&gt; sort(Map&lt;K, V&gt; map) {\n List&lt;Map.Entry&lt;K, V&gt;&gt; list = new LinkedList&lt;Map.Entry&lt;K, V&gt;&gt;(map.entrySet());\n Collections.sort(list, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() {\n public int compare(Map.Entry&lt;K, V&gt; o1, Map.Entry&lt;K, V&gt; o2) {\n return o1.getValue().compareTo(o2.getValue());\n }\n });\n\n return list;\n}\n</code></pre>\n\n<p>You might want to put <strong><em>list</em></strong> in a <strong><em>LinkedHashMap</em></strong>, but if you're only going to iterate over it right away, that's superfluous...</p>\n" }, { "answer_id": 7268690, "author": "dimkar", "author_id": 923190, "author_profile": "https://Stackoverflow.com/users/923190", "pm_score": 2, "selected": false, "text": "<p>Some simple changes in order to have a sorted map with pairs that have duplicate values. In the compare method (class ValueComparator) when values are equal do not return 0 but return the result of comparing the 2 keys. Keys are distinct in a map so you succeed to keep duplicate values (which are sorted by keys by the way). So the above example could be modified like this:</p>\n\n<pre><code> public int compare(Object a, Object b) {\n\n if((Double)base.get(a) &lt; (Double)base.get(b)) {\n return 1;\n } else if((Double)base.get(a) == (Double)base.get(b)) {\n return ((String)a).compareTo((String)b);\n } else {\n return -1;\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 7561661, "author": "nibor", "author_id": 965886, "author_profile": "https://Stackoverflow.com/users/965886", "pm_score": 2, "selected": false, "text": "<p>If you have duplicate keys and only a small set of data (&lt;1000) and your code is not performance critical you can just do the following:</p>\n\n<pre><code>Map&lt;String,Integer&gt; tempMap=new HashMap&lt;String,Integer&gt;(inputUnsortedMap);\nLinkedHashMap&lt;String,Integer&gt; sortedOutputMap=new LinkedHashMap&lt;String,Integer&gt;();\n\nfor(int i=0;i&lt;inputUnsortedMap.size();i++){\n Map.Entry&lt;String,Integer&gt; maxEntry=null;\n Integer maxValue=-1;\n for(Map.Entry&lt;String,Integer&gt; entry:tempMap.entrySet()){\n if(entry.getValue()&gt;maxValue){\n maxValue=entry.getValue();\n maxEntry=entry;\n }\n }\n tempMap.remove(maxEntry.getKey());\n sortedOutputMap.put(maxEntry.getKey(),maxEntry.getValue());\n}\n</code></pre>\n\n<p><strong>inputUnsortedMap</strong> is the input to the code.</p>\n\n<p>The variable <strong>sortedOutputMap</strong> will contain the data in decending order when iterated over. To change order just change > to a &lt; in the if statement.</p>\n\n<p>Is not the fastest sort but does the job without any additional dependencies.</p>\n" }, { "answer_id": 8647597, "author": "Sebastien Lorber", "author_id": 82609, "author_profile": "https://Stackoverflow.com/users/82609", "pm_score": 2, "selected": false, "text": "<p>For sure the solution of Stephen is really great, but for those who can't use Guava:</p>\n\n<p>Here's my solution for sorting by value a map.\nThis solution handle the case where there are twice the same value etc...</p>\n\n<pre><code>// If you want to sort a map by value, and if there can be twice the same value:\n\n// here is your original map\nMap&lt;String,Integer&gt; mapToSortByValue = new HashMap&lt;String, Integer&gt;();\nmapToSortByValue.put(\"A\", 3);\nmapToSortByValue.put(\"B\", 1);\nmapToSortByValue.put(\"C\", 3);\nmapToSortByValue.put(\"D\", 5);\nmapToSortByValue.put(\"E\", -1);\nmapToSortByValue.put(\"F\", 1000);\nmapToSortByValue.put(\"G\", 79);\nmapToSortByValue.put(\"H\", 15);\n\n// Sort all the map entries by value\nSet&lt;Map.Entry&lt;String,Integer&gt;&gt; set = new TreeSet&lt;Map.Entry&lt;String,Integer&gt;&gt;(\n new Comparator&lt;Map.Entry&lt;String,Integer&gt;&gt;(){\n @Override\n public int compare(Map.Entry&lt;String,Integer&gt; obj1, Map.Entry&lt;String,Integer&gt; obj2) {\n Integer val1 = obj1.getValue();\n Integer val2 = obj2.getValue();\n // DUPLICATE VALUE CASE\n // If the values are equals, we can't return 0 because the 2 entries would be considered\n // as equals and one of them would be deleted (because we use a set, no duplicate, remember!)\n int compareValues = val1.compareTo(val2);\n if ( compareValues == 0 ) {\n String key1 = obj1.getKey();\n String key2 = obj2.getKey();\n int compareKeys = key1.compareTo(key2);\n if ( compareKeys == 0 ) {\n // what you return here will tell us if you keep REAL KEY-VALUE duplicates in your set\n // if you want to, do whatever you want but do not return 0 (but don't break the comparator contract!)\n return 0;\n }\n return compareKeys;\n }\n return compareValues;\n }\n }\n);\nset.addAll(mapToSortByValue.entrySet());\n\n\n// OK NOW OUR SET IS SORTED COOL!!!!\n\n// And there's nothing more to do: the entries are sorted by value!\nfor ( Map.Entry&lt;String,Integer&gt; entry : set ) {\n System.out.println(\"Set entries: \" + entry.getKey() + \" -&gt; \" + entry.getValue());\n}\n\n\n\n\n// But if you add them to an hashmap\nMap&lt;String,Integer&gt; myMap = new HashMap&lt;String,Integer&gt;();\n// When iterating over the set the order is still good in the println...\nfor ( Map.Entry&lt;String,Integer&gt; entry : set ) {\n System.out.println(\"Added to result map entries: \" + entry.getKey() + \" \" + entry.getValue());\n myMap.put(entry.getKey(), entry.getValue());\n}\n\n// But once they are in the hashmap, the order is not kept!\nfor ( Integer value : myMap.values() ) {\n System.out.println(\"Result map values: \" + value);\n}\n// Also this way doesn't work:\n// Logic because the entryset is a hashset for hashmaps and not a treeset\n// (and even if it was a treeset, it would be on the keys only)\nfor ( Map.Entry&lt;String,Integer&gt; entry : myMap.entrySet() ) {\n System.out.println(\"Result map entries: \" + entry.getKey() + \" -&gt; \" + entry.getValue());\n}\n\n\n// CONCLUSION:\n// If you want to iterate on a map ordered by value, you need to remember:\n// 1) Maps are only sorted by keys, so you can't sort them directly by value\n// 2) So you simply CAN'T return a map to a sortMapByValue function\n// 3) You can't reverse the keys and the values because you have duplicate values\n// This also means you can't neither use Guava/Commons bidirectionnal treemaps or stuff like that\n\n// SOLUTIONS\n// So you can:\n// 1) only sort the values which is easy, but you loose the key/value link (since you have duplicate values)\n// 2) sort the map entries, but don't forget to handle the duplicate value case (like i did)\n// 3) if you really need to return a map, use a LinkedHashMap which keep the insertion order\n</code></pre>\n\n<p>The exec:\n<a href=\"http://www.ideone.com/dq3Lu\" rel=\"nofollow\">http://www.ideone.com/dq3Lu</a></p>\n\n<p>The output:</p>\n\n<pre><code>Set entries: E -&gt; -1\nSet entries: B -&gt; 1\nSet entries: A -&gt; 3\nSet entries: C -&gt; 3\nSet entries: D -&gt; 5\nSet entries: H -&gt; 15\nSet entries: G -&gt; 79\nSet entries: F -&gt; 1000\nAdded to result map entries: E -1\nAdded to result map entries: B 1\nAdded to result map entries: A 3\nAdded to result map entries: C 3\nAdded to result map entries: D 5\nAdded to result map entries: H 15\nAdded to result map entries: G 79\nAdded to result map entries: F 1000\nResult map values: 5\nResult map values: -1\nResult map values: 1000\nResult map values: 79\nResult map values: 3\nResult map values: 1\nResult map values: 3\nResult map values: 15\nResult map entries: D -&gt; 5\nResult map entries: E -&gt; -1\nResult map entries: F -&gt; 1000\nResult map entries: G -&gt; 79\nResult map entries: A -&gt; 3\nResult map entries: B -&gt; 1\nResult map entries: C -&gt; 3\nResult map entries: H -&gt; 15\n</code></pre>\n\n<p>Hope it will help some folks</p>\n" }, { "answer_id": 10808650, "author": "ciamej", "author_id": 821497, "author_profile": "https://Stackoverflow.com/users/821497", "pm_score": 3, "selected": false, "text": "<p>Instead of using <code>Collections.sort</code> as some do I'd suggest using <code>Arrays.sort</code>. Actually what <code>Collections.sort</code> does is something like this:</p>\n\n<pre><code>public static &lt;T extends Comparable&lt;? super T&gt;&gt; void sort(List&lt;T&gt; list) {\n Object[] a = list.toArray();\n Arrays.sort(a);\n ListIterator&lt;T&gt; i = list.listIterator();\n for (int j=0; j&lt;a.length; j++) {\n i.next();\n i.set((T)a[j]);\n }\n}\n</code></pre>\n\n<p>It just calls <code>toArray</code> on the list and then uses <code>Arrays.sort</code>. This way all the map entries will be copied three times: once from the map to the temporary list (be it a LinkedList or ArrayList), then to the temporary array and finally to the new map.</p>\n\n<p>My solution ommits this one step as it does not create unnecessary LinkedList. Here is the code, generic-friendly and performance-optimal:</p>\n\n<pre><code>public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; Map&lt;K, V&gt; sortByValue(Map&lt;K, V&gt; map) \n{\n @SuppressWarnings(\"unchecked\")\n Map.Entry&lt;K,V&gt;[] array = map.entrySet().toArray(new Map.Entry[map.size()]);\n\n Arrays.sort(array, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() \n {\n public int compare(Map.Entry&lt;K, V&gt; e1, Map.Entry&lt;K, V&gt; e2) \n {\n return e1.getValue().compareTo(e2.getValue());\n }\n });\n\n Map&lt;K, V&gt; result = new LinkedHashMap&lt;K, V&gt;();\n for (Map.Entry&lt;K, V&gt; entry : array)\n result.put(entry.getKey(), entry.getValue());\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 12172924, "author": "Rashid C Y", "author_id": 1619400, "author_profile": "https://Stackoverflow.com/users/1619400", "pm_score": -1, "selected": false, "text": "<p>We simply sort a map just like this</p>\n\n<pre><code> Map&lt;String, String&gt; unsortedMap = new HashMap&lt;String, String&gt;();\n\n unsortedMap.put(\"E\", \"E Val\");\n unsortedMap.put(\"F\", \"F Val\");\n unsortedMap.put(\"H\", \"H Val\");\n unsortedMap.put(\"B\", \"B Val\");\n unsortedMap.put(\"C\", \"C Val\");\n unsortedMap.put(\"A\", \"A Val\");\n unsortedMap.put(\"G\", \"G Val\");\n unsortedMap.put(\"D\", \"D Val\");\n\n Map&lt;String, String&gt; sortedMap = new TreeMap&lt;String, String&gt;(unsortedMap);\n\n System.out.println(\"\\nAfter sorting..\");\n for (Map.Entry &lt;String, String&gt; mapEntry : sortedMap.entrySet()) {\n System.out.println(mapEntry.getKey() + \" \\t\" + mapEntry.getValue());\n</code></pre>\n" }, { "answer_id": 13438052, "author": "cuneyt", "author_id": 1833089, "author_profile": "https://Stackoverflow.com/users/1833089", "pm_score": 3, "selected": false, "text": "<p>Major problem. If you use the first answer (Google takes you here), change the comparator to add an equal clause, otherwise you cannot get values from the sorted_map by keys:</p>\n\n<pre><code>public int compare(String a, String b) {\n if (base.get(a) &gt; base.get(b)) {\n return 1;\n } else if (base.get(a) &lt; base.get(b)){\n return -1;\n } \n\n return 0;\n // returning 0 would merge keys\n }\n</code></pre>\n" }, { "answer_id": 14795215, "author": "Sujan Reddy A", "author_id": 2056362, "author_profile": "https://Stackoverflow.com/users/2056362", "pm_score": 4, "selected": false, "text": "<p>Create customized comparator and use it while creating new TreeMap object.</p>\n\n<pre><code>class MyComparator implements Comparator&lt;Object&gt; {\n\n Map&lt;String, Integer&gt; map;\n\n public MyComparator(Map&lt;String, Integer&gt; map) {\n this.map = map;\n }\n\n public int compare(Object o1, Object o2) {\n\n if (map.get(o2) == map.get(o1))\n return 1;\n else\n return ((Integer) map.get(o2)).compareTo((Integer) \n map.get(o1));\n\n }\n}\n</code></pre>\n\n<p>Use the below code in your main func</p>\n\n<pre><code> Map&lt;String, Integer&gt; lMap = new HashMap&lt;String, Integer&gt;();\n lMap.put(\"A\", 35);\n lMap.put(\"B\", 75);\n lMap.put(\"C\", 50);\n lMap.put(\"D\", 50);\n\n MyComparator comparator = new MyComparator(lMap);\n\n Map&lt;String, Integer&gt; newMap = new TreeMap&lt;String, Integer&gt;(comparator);\n newMap.putAll(lMap);\n System.out.println(newMap);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>{B=75, D=50, C=50, A=35}\n</code></pre>\n" }, { "answer_id": 17904414, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 2, "selected": false, "text": "<p>You can try Guava's multimaps:</p>\n\n<pre><code>TreeMap&lt;Integer, Collection&lt;String&gt;&gt; sortedMap = new TreeMap&lt;&gt;(\n Multimaps.invertFrom(Multimaps.forMap(originalMap), \n ArrayListMultimap.&lt;Integer, String&gt;create()).asMap());\n</code></pre>\n\n<p>As a result you get a map from original values to collections of keys that correspond to them. This approach can be used even if there are multiple keys for the same value.</p>\n" }, { "answer_id": 19563077, "author": "rohan kamat", "author_id": 2335562, "author_profile": "https://Stackoverflow.com/users/2335562", "pm_score": -1, "selected": false, "text": "<p>as map is unordered \nto sort it ,we can do following </p>\n\n<pre><code>Map&lt;String, String&gt; map= new TreeMap&lt;String, String&gt;(unsortMap);\n</code></pre>\n\n<p>You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.</p>\n" }, { "answer_id": 20089342, "author": "gdejohn", "author_id": 464306, "author_profile": "https://Stackoverflow.com/users/464306", "pm_score": 4, "selected": false, "text": "<p>To accomplish this with the new features in Java 8:</p>\n\n<pre><code>import static java.util.Map.Entry.comparingByValue;\nimport static java.util.stream.Collectors.toList;\n\n&lt;K, V&gt; List&lt;Entry&lt;K, V&gt;&gt; sort(Map&lt;K, V&gt; map, Comparator&lt;? super V&gt; comparator) {\n return map.entrySet().stream().sorted(comparingByValue(comparator)).collect(toList());\n}\n</code></pre>\n\n<p>The entries are ordered by their values using the given comparator. Alternatively, if your values are mutually comparable, no explicit comparator is needed:</p>\n\n<pre><code>&lt;K, V extends Comparable&lt;? super V&gt;&gt; List&lt;Entry&lt;K, V&gt;&gt; sort(Map&lt;K, V&gt; map) {\n return map.entrySet().stream().sorted(comparingByValue()).collect(toList());\n}\n</code></pre>\n\n<p>The returned list is a snapshot of the given map at the time this method is called, so neither will reflect subsequent changes to the other. For a live iterable view of the map:</p>\n\n<pre><code>&lt;K, V extends Comparable&lt;? super V&gt;&gt; Iterable&lt;Entry&lt;K, V&gt;&gt; sort(Map&lt;K, V&gt; map) {\n return () -&gt; map.entrySet().stream().sorted(comparingByValue()).iterator();\n}\n</code></pre>\n\n<p>The returned iterable creates a fresh snapshot of the given map each time it's iterated, so barring concurrent modification, it will always reflect the current state of the map.</p>\n" }, { "answer_id": 22132422, "author": "assylias", "author_id": 829571, "author_profile": "https://Stackoverflow.com/users/829571", "pm_score": 7, "selected": false, "text": "<p>With Java 8, you can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html\" rel=\"noreferrer\">streams api</a> to do it in a significantly less verbose way:</p>\n\n<pre><code>Map&lt;K, V&gt; sortedMap = map.entrySet().stream()\n .sorted(Entry.comparingByValue())\n .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -&gt; e1, LinkedHashMap::new));\n</code></pre>\n" }, { "answer_id": 23215184, "author": "RobotMan", "author_id": 2491301, "author_profile": "https://Stackoverflow.com/users/2491301", "pm_score": 2, "selected": false, "text": "<p>I've merged the solutions of user157196 and Carter Page:</p>\n\n<pre><code>class MapUtil {\n\n public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; Map&lt;K, V&gt; sortByValue( Map&lt;K, V&gt; map ){\n ValueComparator&lt;K,V&gt; bvc = new ValueComparator&lt;K,V&gt;(map);\n TreeMap&lt;K,V&gt; sorted_map = new TreeMap&lt;K,V&gt;(bvc);\n sorted_map.putAll(map);\n return sorted_map;\n }\n\n}\n\nclass ValueComparator&lt;K, V extends Comparable&lt;? super V&gt;&gt; implements Comparator&lt;K&gt; {\n\n Map&lt;K, V&gt; base;\n public ValueComparator(Map&lt;K, V&gt; base) {\n this.base = base;\n }\n\n public int compare(K a, K b) {\n int result = (base.get(a).compareTo(base.get(b)));\n if (result == 0) result=1;\n // returning 0 would merge keys\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 23846961, "author": "Brian Goetz", "author_id": 3553087, "author_profile": "https://Stackoverflow.com/users/3553087", "pm_score": 9, "selected": false, "text": "<p>Java 8 offers a new answer: convert the entries into a stream, and use the comparator combinators from Map.Entry:</p>\n<pre><code>Stream&lt;Map.Entry&lt;K,V&gt;&gt; sorted =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue());\n</code></pre>\n<p>This will let you consume the entries sorted in ascending order of value. If you want descending value, simply reverse the comparator:</p>\n<pre><code>Stream&lt;Map.Entry&lt;K,V&gt;&gt; sorted =\n map.entrySet().stream()\n .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));\n</code></pre>\n<p>If the values are not comparable, you can pass an explicit comparator:</p>\n<pre><code>Stream&lt;Map.Entry&lt;K,V&gt;&gt; sorted =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue(comparator));\n</code></pre>\n<p>You can then proceed to use other stream operations to consume the data. For example, if you want the top 10 in a new map:</p>\n<pre><code>Map&lt;K,V&gt; topTen =\n map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n .limit(10)\n .collect(Collectors.toMap(\n Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -&gt; e1, LinkedHashMap::new));\n</code></pre>\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/LinkedHashMap.html\" rel=\"noreferrer\"><code>LinkedHashMap</code></a> seen above iterates entries in the order in which they were inserted.</p>\n<p>Or print to <code>System.out</code>:</p>\n<pre><code>map.entrySet().stream()\n .sorted(Map.Entry.comparingByValue())\n .forEach(System.out::println);\n</code></pre>\n" }, { "answer_id": 33801276, "author": "Nilesh Jadav", "author_id": 3966892, "author_profile": "https://Stackoverflow.com/users/3966892", "pm_score": 3, "selected": false, "text": "<p><strong>Best Approach</strong></p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry; \n\npublic class OrderByValue {\n\n public static void main(String a[]){\n Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;();\n map.put(\"java\", 20);\n map.put(\"C++\", 45);\n map.put(\"Unix\", 67);\n map.put(\"MAC\", 26);\n map.put(\"Why this kolavari\", 93);\n Set&lt;Entry&lt;String, Integer&gt;&gt; set = map.entrySet();\n List&lt;Entry&lt;String, Integer&gt;&gt; list = new ArrayList&lt;Entry&lt;String, Integer&gt;&gt;(set);\n Collections.sort( list, new Comparator&lt;Map.Entry&lt;String, Integer&gt;&gt;()\n {\n public int compare( Map.Entry&lt;String, Integer&gt; o1, Map.Entry&lt;String, Integer&gt; o2 )\n {\n return (o1.getValue()).compareTo( o2.getValue() );//Ascending order\n //return (o2.getValue()).compareTo( o1.getValue() );//Descending order\n }\n } );\n for(Map.Entry&lt;String, Integer&gt; entry:list){\n System.out.println(entry.getKey()+\" ==== \"+entry.getValue());\n }\n }}\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>java ==== 20\n\nMAC ==== 26\n\nC++ ==== 45\n\nUnix ==== 67\n\nWhy this kolavari ==== 93\n</code></pre>\n" }, { "answer_id": 34295647, "author": "Uxío", "author_id": 724991, "author_profile": "https://Stackoverflow.com/users/724991", "pm_score": -1, "selected": false, "text": "<p>If there's not any value bigger than the size of the map, you could use arrays, this should be the fastest approach:</p>\n\n<pre><code>public List&lt;String&gt; getList(Map&lt;String, Integer&gt; myMap) {\n String[] copyArray = new String[myMap.size()];\n for (Entry&lt;String, Integer&gt; entry : myMap.entrySet()) {\n copyArray[entry.getValue()] = entry.getKey();\n }\n return Arrays.asList(copyArray);\n}\n</code></pre>\n" }, { "answer_id": 34802755, "author": "Bruce Zu", "author_id": 913717, "author_profile": "https://Stackoverflow.com/users/913717", "pm_score": -1, "selected": false, "text": "<pre><code> static &lt;K extends Comparable&lt;? super K&gt;, V extends Comparable&lt;? super V&gt;&gt;\n Map sortByValueInDescendingOrder(final Map&lt;K, V&gt; map) {\n Map re = new TreeMap(new Comparator&lt;K&gt;() {\n @Override\n public int compare(K o1, K o2) {\n if (map.get(o1) == null || map.get(o2) == null) {\n return -o1.compareTo(o2);\n }\n int result = -map.get(o1).compareTo(map.get(o2));\n if (result != 0) {\n return result;\n }\n return -o1.compareTo(o2);\n }\n });\n re.putAll(map);\n return re;\n }\n @Test(timeout = 3000l, expected = Test.None.class)\n public void testSortByValueInDescendingOrder() {\n char[] arr = \"googler\".toCharArray();\n Map&lt;Character, Integer&gt; charToTimes = new HashMap();\n for (int i = 0; i &lt; arr.length; i++) {\n Integer times = charToTimes.get(arr[i]);\n charToTimes.put(arr[i], times == null ? 1 : times + 1);\n }\n Map sortedByTimes = sortByValueInDescendingOrder(charToTimes);\n Assert.assertEquals(charToTimes.toString(), \"{g=2, e=1, r=1, o=2, l=1}\");\n Assert.assertEquals(sortedByTimes.toString(), \"{o=2, g=2, r=1, l=1, e=1}\");\n Assert.assertEquals(sortedByTimes.containsKey('a'), false);\n Assert.assertEquals(sortedByTimes.get('a'), null);\n Assert.assertEquals(sortedByTimes.get('g'), 2);\n Assert.assertEquals(sortedByTimes.equals(charToTimes), true);\n }\n</code></pre>\n" }, { "answer_id": 36819520, "author": "David Bleckmann", "author_id": 1760575, "author_profile": "https://Stackoverflow.com/users/1760575", "pm_score": 3, "selected": false, "text": "<p>There are a lot of answers for this question already, but none provided me what I was looking for, a map implementation that returns keys and entries sorted by the associated value, and maintains this property as keys and values are modified in the map. Two <a href=\"https://stackoverflow.com/q/13108887/1760575\">other</a> <a href=\"https://stackoverflow.com/q/7465369/1760575\">questions</a> ask for this specifically. </p>\n\n<p>I cooked up a generic friendly example that solves this use case. This implementation does not honor all of the contracts of the Map interface, such as reflecting value changes and removals in the sets return from keySet() and entrySet() in the original object. I felt such a solution would be too large to include in a Stack Overflow answer. If I manage to create a more complete implementation, perhaps I will post it to Github and then to it link in an updated version of this answer.</p>\n\n<pre><code>import java.util.*;\n\n/**\n * A map where {@link #keySet()} and {@link #entrySet()} return sets ordered\n * by associated values based on the the comparator provided at construction\n * time. The order of two or more keys with identical values is not defined.\n * &lt;p&gt;\n * Several contracts of the Map interface are not satisfied by this minimal\n * implementation.\n */\npublic class ValueSortedMap&lt;K, V&gt; extends HashMap&lt;K, V&gt; {\n protected Map&lt;V, Collection&lt;K&gt;&gt; valueToKeysMap;\n\n // uses natural order of value object, if any\n public ValueSortedMap() {\n this((Comparator&lt;? super V&gt;) null);\n }\n\n public ValueSortedMap(Comparator&lt;? super V&gt; valueComparator) {\n this.valueToKeysMap = new TreeMap&lt;V, Collection&lt;K&gt;&gt;(valueComparator);\n }\n\n public boolean containsValue(Object o) {\n return valueToKeysMap.containsKey(o);\n }\n\n public V put(K k, V v) {\n V oldV = null;\n if (containsKey(k)) {\n oldV = get(k);\n valueToKeysMap.get(oldV).remove(k);\n }\n super.put(k, v);\n if (!valueToKeysMap.containsKey(v)) {\n Collection&lt;K&gt; keys = new ArrayList&lt;K&gt;();\n keys.add(k);\n valueToKeysMap.put(v, keys);\n } else {\n valueToKeysMap.get(v).add(k);\n }\n return oldV;\n }\n\n public void putAll(Map&lt;? extends K, ? extends V&gt; m) {\n for (Map.Entry&lt;? extends K, ? extends V&gt; e : m.entrySet())\n put(e.getKey(), e.getValue());\n }\n\n public V remove(Object k) {\n V oldV = null;\n if (containsKey(k)) {\n oldV = get(k);\n super.remove(k);\n valueToKeysMap.get(oldV).remove(k);\n }\n return oldV;\n }\n\n public void clear() {\n super.clear();\n valueToKeysMap.clear();\n }\n\n public Set&lt;K&gt; keySet() {\n LinkedHashSet&lt;K&gt; ret = new LinkedHashSet&lt;K&gt;(size());\n for (V v : valueToKeysMap.keySet()) {\n Collection&lt;K&gt; keys = valueToKeysMap.get(v);\n ret.addAll(keys);\n }\n return ret;\n }\n\n public Set&lt;Map.Entry&lt;K, V&gt;&gt; entrySet() {\n LinkedHashSet&lt;Map.Entry&lt;K, V&gt;&gt; ret = new LinkedHashSet&lt;Map.Entry&lt;K, V&gt;&gt;(size());\n for (Collection&lt;K&gt; keys : valueToKeysMap.values()) {\n for (final K k : keys) {\n final V v = get(k);\n ret.add(new Map.Entry&lt;K,V&gt;() {\n public K getKey() {\n return k;\n }\n\n public V getValue() {\n return v;\n }\n\n public V setValue(V v) {\n throw new UnsupportedOperationException();\n }\n });\n }\n }\n return ret;\n }\n}\n</code></pre>\n" }, { "answer_id": 39659333, "author": "Alexander", "author_id": 4525620, "author_profile": "https://Stackoverflow.com/users/4525620", "pm_score": 1, "selected": false, "text": "<p>My solution is a quite simple approach in the way of using mostly given APIs.\nWe use the feature of <strong>Map</strong> to export its content as <strong>Set</strong> via <strong>entrySet()</strong> method. We now have a <strong>Set</strong> containing <strong>Map.Entry</strong> objects. </p>\n\n<p>Okay, a Set does not carry an order, but we can take the content an put it into an <strong>ArrayList</strong>. It now has an <em>random</em> order, but we will sort it anyway.</p>\n\n<p>As <strong>ArrayList</strong> is a <strong>Collection</strong>, we now use the <strong>Collections.sort()</strong> method to bring order to chaos. Because our <strong>Map.Entry</strong> objects do not realize the kind of comparison we need, we provide a custom <strong>Comparator</strong>.</p>\n\n<pre><code>public static void main(String[] args) {\n HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();\n map.put(\"Z\", \"E\");\n map.put(\"G\", \"A\");\n map.put(\"D\", \"C\");\n map.put(\"E\", null);\n map.put(\"O\", \"C\");\n map.put(\"L\", \"D\");\n map.put(\"Q\", \"B\");\n map.put(\"A\", \"F\");\n map.put(null, \"X\");\n MapEntryComparator mapEntryComparator = new MapEntryComparator();\n\n List&lt;Entry&lt;String,String&gt;&gt; entryList = new ArrayList&lt;&gt;(map.entrySet());\n Collections.sort(entryList, mapEntryComparator);\n\n for (Entry&lt;String, String&gt; entry : entryList) {\n System.out.println(entry.getKey() + \" : \" + entry.getValue());\n }\n\n}\n</code></pre>\n" }, { "answer_id": 40852723, "author": "user_3380739", "author_id": 3380739, "author_profile": "https://Stackoverflow.com/users/3380739", "pm_score": 2, "selected": false, "text": "<p>Here is the code by Java 8 with <a href=\"https://github.com/landawn/AbacusUtil\" rel=\"nofollow noreferrer\">AbacusUtil</a></p>\n\n<pre><code>Map&lt;String, Integer&gt; map = N.asMap(\"a\", 2, \"b\", 3, \"c\", 1, \"d\", 2);\nMap&lt;String, Integer&gt; sortedMap = Stream.of(map.entrySet()).sorted(Map.Entry.comparingByValue()).toMap(e -&gt; e.getKey(), e -&gt; e.getValue(),\n LinkedHashMap::new);\nN.println(sortedMap);\n// output: {c=1, a=2, d=2, b=3}\n</code></pre>\n\n<p>Declaration: I'm the developer of AbacusUtil.</p>\n" }, { "answer_id": 42337208, "author": "Tanuj Verma", "author_id": 2823380, "author_profile": "https://Stackoverflow.com/users/2823380", "pm_score": -1, "selected": false, "text": "<p>Best thing is to convert HashMap to TreeMap. TreeMap sort keys on its own.\nIf you want to sort on values than quick fix can be you can switch values with keys if your values are not duplicates.</p>\n" }, { "answer_id": 48068780, "author": "Arun Raaj", "author_id": 4334162, "author_profile": "https://Stackoverflow.com/users/4334162", "pm_score": 0, "selected": false, "text": "<pre><code>public class Test {\n public static void main(String[] args) {\n TreeMap&lt;Integer, String&gt; hm=new TreeMap();\n hm.put(3, \"arun singh\");\n hm.put(5, \"vinay singh\");\n hm.put(1, \"bandagi singh\");\n hm.put(6, \"vikram singh\");\n hm.put(2, \"panipat singh\");\n hm.put(28, \"jakarta singh\");\n\n ArrayList&lt;String&gt; al=new ArrayList(hm.values());\n Collections.sort(al, new myComparator());\n\n System.out.println(\"//sort by values \\n\");\n for(String obj: al){\n for(Map.Entry&lt;Integer, String&gt; map2:hm.entrySet()){\n if(map2.getValue().equals(obj)){\n System.out.println(map2.getKey()+\" \"+map2.getValue());\n }\n } \n }\n }\n}\n\nclass myComparator implements Comparator{\n @Override\n public int compare(Object o1, Object o2) {\n String o3=(String) o1;\n String o4 =(String) o2;\n return o3.compareTo(o4);\n } \n}\n</code></pre>\n\n<p>OUTPUT=</p>\n\n<pre><code>//sort by values \n\n3 arun singh\n1 bandagi singh\n28 jakarta singh\n2 panipat singh\n6 vikram singh\n5 vinay singh\n</code></pre>\n" }, { "answer_id": 50406218, "author": "Pankaj Singhal", "author_id": 820410, "author_profile": "https://Stackoverflow.com/users/820410", "pm_score": 3, "selected": false, "text": "<p>Late Entry.</p>\n\n<p>With the advent of Java-8, we can use streams for data manipulation in a very easy/succinct way. You can use streams to sort the map entries by value and create a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html\" rel=\"noreferrer\">LinkedHashMap</a> which preserves <em>insertion-order</em> iteration.</p>\n\n<p>Eg:</p>\n\n<pre><code>LinkedHashMap sortedByValueMap = map.entrySet().stream()\n .sorted(comparing(Entry&lt;Key,Value&gt;::getValue).thenComparing(Entry::getKey)) //first sorting by Value, then sorting by Key(entries with same value)\n .collect(LinkedHashMap::new,(map,entry) -&gt; map.put(entry.getKey(),entry.getValue()),LinkedHashMap::putAll);\n</code></pre>\n\n<hr>\n\n<p>For reverse ordering, replace:</p>\n\n<pre><code>comparing(Entry&lt;Key,Value&gt;::getValue).thenComparing(Entry::getKey)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>comparing(Entry&lt;Key,Value&gt;::getValue).thenComparing(Entry::getKey).reversed()\n</code></pre>\n" }, { "answer_id": 51457226, "author": "Kenston Choi", "author_id": 241379, "author_profile": "https://Stackoverflow.com/users/241379", "pm_score": 1, "selected": false, "text": "<p>If there is a preference of having a <code>Map</code> data structure that inherently sorts by values without having to trigger any sort methods or explicitly pass to a utility, then the following solutions may be applicable:</p>\n\n<p>(1) <a href=\"https://github.com/kiegroup/drools-chance/blob/898c619b74ebff5ea6add8dd750c505b441e17bb/drools-chance-core/src/main/java/org/drools/chance/core/util/ValueSortedMap.java\" rel=\"nofollow noreferrer\">org.drools.chance.core.util.ValueSortedMap</a> (JBoss project) maintains two maps internally one for lookup and one for maintaining the sorted values. Quite similar to previously added answers, but probably it is the abstraction and encapsulation part (including copying mechanism) that makes it safer to use from the outside. </p>\n\n<p>(2) <a href=\"http://techblog.molindo.at/2008/11/java-map-sorted-by-value.html\" rel=\"nofollow noreferrer\">http://techblog.molindo.at/2008/11/java-map-sorted-by-value.html</a> avoids maintaining two maps and instead relies/extends from Apache Common's LinkedMap. (Blog author's note: <code>as all the code here is in the public domain</code>):</p>\n\n<pre><code>// required to access LinkEntry.before and LinkEntry.after\npackage org.apache.commons.collections.map;\n\n// SNIP: imports\n\n/**\n* map implementation based on LinkedMap that maintains a sorted list of\n* values for iteration\n*/\npublic class ValueSortedHashMap extends LinkedMap {\n private final boolean _asc;\n\n // don't use super()!\n public ValueSortedHashMap(final boolean asc) {\n super(DEFAULT_CAPACITY);\n _asc = asc;\n }\n\n // SNIP: some more constructors with initial capacity and the like\n\n protected void addEntry(final HashEntry entry, final int hashIndex) {\n final LinkEntry link = (LinkEntry) entry;\n insertSorted(link);\n data[hashIndex] = entry;\n }\n\n protected void updateEntry(final HashEntry entry, final Object newValue) {\n entry.setValue(newValue);\n final LinkEntry link = (LinkEntry) entry;\n link.before.after = link.after;\n link.after.before = link.before;\n link.after = link.before = null;\n insertSorted(link);\n }\n\n private void insertSorted(final LinkEntry link) {\n LinkEntry cur = header;\n // iterate whole list, could (should?) be replaced with quicksearch\n // start at end to optimize speed for in-order insertions\n while ((cur = cur.before) != header &amp; amp; &amp; amp; !insertAfter(cur, link)) {}\n link.after = cur.after;\n link.before = cur;\n cur.after.before = link;\n cur.after = link;\n }\n\n protected boolean insertAfter(final LinkEntry cur, final LinkEntry link) {\n if (_asc) {\n return ((Comparable) cur.getValue())\n .compareTo((V) link.getValue()) &amp; lt; = 0;\n } else {\n return ((Comparable) cur.getValue())\n .compareTo((V) link.getValue()) &amp; gt; = 0;\n }\n }\n\n public boolean isAscending() {\n return _asc;\n }\n}\n</code></pre>\n\n<p>(3) Write a custom <code>Map</code> or extends from <code>LinkedHashMap</code> that will only sort during enumeration (e.g., <code>values()</code>, <code>keyset()</code>, <code>entryset()</code>) as needed. The inner implementation/behavior is abstracted from the one using this class but it appears to the client of this class that values are always sorted when requested for enumeration. This class hopes that sorting will happen mostly once if all <code>put</code> operations have been completed before enumerations. Sorting method adopts some of the previous answers to this question. </p>\n\n<pre><code>public class SortByValueMap&lt;K, V&gt; implements Map&lt;K, V&gt; {\n\n private boolean isSortingNeeded = false;\n\n private final Map&lt;K, V&gt; map = new LinkedHashMap&lt;&gt;();\n\n @Override\n public V put(K key, V value) {\n isSortingNeeded = true;\n return map.put(key, value);\n }\n\n @Override\n public void putAll(Map&lt;? extends K, ? extends V&gt; map) {\n isSortingNeeded = true;\n map.putAll(map);\n }\n\n @Override\n public Set&lt;K&gt; keySet() {\n sort();\n return map.keySet();\n }\n\n @Override\n public Set&lt;Entry&lt;K, V&gt;&gt; entrySet() {\n sort();\n return map.entrySet();\n }\n\n @Override\n public Collection&lt;V&gt; values() {\n sort();\n return map.values();\n }\n\n private void sort() {\n if (!isSortingNeeded) {\n return;\n }\n\n List&lt;Entry&lt;K, V&gt;&gt; list = new ArrayList&lt;&gt;(size());\n\n for (Iterator&lt;Map.Entry&lt;K, V&gt;&gt; it = map.entrySet().iterator(); it.hasNext();) {\n Map.Entry&lt;K, V&gt; entry = it.next();\n list.add(entry);\n it.remove();\n }\n\n Collections.sort(list);\n\n for (Entry&lt;K, V&gt; entry : list) {\n map.put(entry.getKey(), entry.getValue());\n }\n\n isSortingNeeded = false;\n }\n\n @Override\n public String toString() {\n sort();\n return map.toString();\n }\n}\n</code></pre>\n\n<p>(4) Guava offers <a href=\"https://google.github.io/guava/releases/22.0/api/docs/com/google/common/collect/ImmutableMap.Builder.html#orderEntriesByValue-java.util.Comparator-\" rel=\"nofollow noreferrer\">ImmutableMap.Builder.orderEntriesByValue(Comparator valueComparator)</a> although the resulting map will be immutable:</p>\n\n<blockquote>\n <p>Configures this Builder to order entries by value according to the\n specified comparator.</p>\n \n <p>The sort order is stable, that is, if two entries have values that\n compare as equivalent, the entry that was inserted first will be first\n in the built map's iteration order.</p>\n</blockquote>\n" }, { "answer_id": 51971086, "author": "smart-developer", "author_id": 5218673, "author_profile": "https://Stackoverflow.com/users/5218673", "pm_score": 1, "selected": false, "text": "<p>I rewrote devinmoore's method that performs sorting a map by it's value without using Iterator :</p>\n\n<pre><code>public static Map&lt;K, V&gt; sortMapByValue(Map&lt;K, V&gt; inputMap) {\n\n Set&lt;Entry&lt;K, V&gt;&gt; set = inputMap.entrySet();\n List&lt;Entry&lt;K, V&gt;&gt; list = new ArrayList&lt;Entry&lt;K, V&gt;&gt;(set);\n\n Collections.sort(list, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;()\n {\n @Override\n public int compare(Entry&lt;K, V&gt; o1, Entry&lt;K, V&gt; o2) {\n return (o1.getValue()).compareTo( o2.getValue() ); //Ascending order\n }\n } );\n\n Map&lt;K, V&gt; sortedMap = new LinkedHashMap&lt;&gt;();\n\n for(Map.Entry&lt;K, V&gt; entry : list){\n sortedMap.put(entry.getKey(), entry.getValue());\n }\n\n return sortedMap;\n}\n</code></pre>\n\n<p><code>Note:</code> that we used <code>LinkedHashMap</code> as output map, because our list has been sorted by value and now we should store our list into output map with order of inserted key,values. So if you use for example <code>TreeMap</code> as your output map, your map will be sorted by map keys again!</p>\n\n<p>This is the main method:</p>\n\n<pre><code>public static void main(String[] args) {\n Map&lt;String, String&gt; map = new HashMap&lt;&gt;();\n map.put(\"3\", \"three\");\n map.put(\"1\", \"one\");\n map.put(\"5\", \"five\");\n System.out.println(\"Input Map:\" + map);\n System.out.println(\"Sorted Map:\" + sortMapByValue(map));\n}\n</code></pre>\n\n<p>Finally, this is the output:</p>\n\n<pre><code>Input Map:{1=one, 3=three, 5=five}\nSorted Map:{5=five, 1=one, 3=three}\n</code></pre>\n" }, { "answer_id": 52688845, "author": "parsecer", "author_id": 4759176, "author_profile": "https://Stackoverflow.com/users/4759176", "pm_score": 2, "selected": false, "text": "<p><strong>The simplest</strong> brute-force <code>sortHashMap</code> method for <code>HashMap&lt;String, Long&gt;</code>: you can just <strong>copypaste it and use</strong> like this:</p>\n\n<pre><code>public class Test {\n public static void main(String[] args) {\n HashMap&lt;String, Long&gt; hashMap = new HashMap&lt;&gt;();\n hashMap.put(\"Cat\", (long) 4);\n hashMap.put(\"Human\", (long) 2);\n hashMap.put(\"Dog\", (long) 4);\n hashMap.put(\"Fish\", (long) 0);\n hashMap.put(\"Tree\", (long) 1);\n hashMap.put(\"Three-legged-human\", (long) 3);\n hashMap.put(\"Monkey\", (long) 2);\n\n System.out.println(hashMap); //{Human=2, Cat=4, Three-legged-human=3, Monkey=2, Fish=0, Tree=1, Dog=4}\n System.out.println(sortHashMap(hashMap)); //{Cat=4, Dog=4, Three-legged-human=3, Human=2, Monkey=2, Tree=1, Fish=0}\n }\n\n public LinkedHashMap&lt;String, Long&gt; sortHashMap(HashMap&lt;String, Long&gt; unsortedMap) {\n LinkedHashMap&lt;String, Long&gt; result = new LinkedHashMap&lt;&gt;();\n\n //add String keys to an array: the array would get sorted, based on those keys' values\n ArrayList&lt;String&gt; sortedKeys = new ArrayList&lt;&gt;();\n for (String key: unsortedMap.keySet()) {\n sortedKeys.add(key);\n }\n\n //sort the ArrayList&lt;String&gt; of keys \n for (int i=0; i&lt;unsortedMap.size(); i++) {\n for (int j=1; j&lt;sortedKeys.size(); j++) {\n if (unsortedMap.get(sortedKeys.get(j)) &gt; unsortedMap.get(sortedKeys.get(j-1))) {\n String temp = sortedKeys.get(j);\n sortedKeys.set(j, sortedKeys.get(j-1));\n sortedKeys.set(j-1, temp);\n }\n }\n }\n\n // construct the result Map\n for (String key: sortedKeys) {\n result.put(key, unsortedMap.get(key));\n }\n\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 57164142, "author": "Praveen Kumar Mekala", "author_id": 4675109, "author_profile": "https://Stackoverflow.com/users/4675109", "pm_score": 2, "selected": false, "text": "<p>posting my version of answer</p>\n\n<pre><code>List&lt;Map.Entry&lt;String, Integer&gt;&gt; list = new ArrayList&lt;&gt;(map.entrySet());\n Collections.sort(list, (obj1, obj2) -&gt; obj2.getValue().compareTo(obj1.getValue()));\n Map&lt;String, Integer&gt; resultMap = new LinkedHashMap&lt;&gt;();\n list.forEach(arg0 -&gt; {\n resultMap.put(arg0.getKey(), arg0.getValue());\n });\n System.out.println(resultMap);\n</code></pre>\n" }, { "answer_id": 57682518, "author": "Stanislav Levental", "author_id": 942689, "author_profile": "https://Stackoverflow.com/users/942689", "pm_score": 1, "selected": false, "text": "<p>Using Guava library:</p>\n\n<pre><code>public static &lt;K,V extends Comparable&lt;V&gt;&gt;SortedMap&lt;K,V&gt; sortByValue(Map&lt;K,V&gt; original){\n var comparator = Ordering.natural()\n .reverse() // highest first\n .nullsLast()\n .onResultOf(Functions.forMap(original, null))\n .compound(Ordering.usingToString());\n return ImmutableSortedMap.copyOf(original, comparator);\n}\n</code></pre>\n" }, { "answer_id": 58824564, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 1, "selected": false, "text": "<p><em>creates a list of entries for each value, where the values are sorted</em><br />\nrequires Java 8 or above</p>\n\n<pre><code>Map&lt;Double,List&lt;Entry&lt;String,Double&gt;&gt;&gt; sorted =\nmap.entrySet().stream().collect( Collectors.groupingBy( Entry::getValue, TreeMap::new,\n Collectors.mapping( Function.identity(), Collectors.toList() ) ) );\n</code></pre>\n\n<p>using the map {[A=99.5], [B=67.4], [C=67.4], [D=67.3]}<br />\ngets <code>{67.3=[D=67.3], 67.4=[B=67.4, C=67.4], 99.5=[A=99.5]}</code></p>\n\n<p><br /><em>…and how to access each entry one after the other:</em></p>\n\n<pre><code>sorted.entrySet().forEach( e -&gt; e.getValue().forEach( l -&gt; System.out.println( l ) ) );\n</code></pre>\n\n<p><code>D=67.3</code> <code>B=67.4</code> <code>C=67.4</code> <code>A=99.5</code></p>\n" }, { "answer_id": 58970003, "author": "Arpan Saini", "author_id": 7353562, "author_profile": "https://Stackoverflow.com/users/7353562", "pm_score": 4, "selected": false, "text": "<p><strong>Given Map</strong></p>\n<pre><code> Map&lt;String, Integer&gt; wordCounts = new HashMap&lt;&gt;();\n wordCounts.put(&quot;USA&quot;, 100);\n wordCounts.put(&quot;jobs&quot;, 200);\n wordCounts.put(&quot;software&quot;, 50);\n wordCounts.put(&quot;technology&quot;, 70);\n wordCounts.put(&quot;opportunity&quot;, 200);\n</code></pre>\n<p><strong>Sort the map based on the value in ascending order</strong></p>\n<pre><code>Map&lt;String,Integer&gt; sortedMap = wordCounts.entrySet().\n stream().\n sorted(Map.Entry.comparingByValue()).\n collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -&gt; e1, LinkedHashMap::new));\n System.out.println(sortedMap);\n \n</code></pre>\n<p><strong>Sort the map based on value in descending order</strong></p>\n<pre><code>Map&lt;String,Integer&gt; sortedMapReverseOrder = wordCounts.entrySet().\n stream().\n sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).\n collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -&gt; e1, LinkedHashMap::new));\n System.out.println(sortedMapReverseOrder);\n</code></pre>\n<p><strong>Output:</strong></p>\n<p>{software=50, technology=70, USA=100, jobs=200, opportunity=200}</p>\n<p>{jobs=200, opportunity=200, USA=100, technology=70, software=50}</p>\n" }, { "answer_id": 59212736, "author": "Mimu Saha Tishan", "author_id": 6109034, "author_profile": "https://Stackoverflow.com/users/6109034", "pm_score": 2, "selected": false, "text": "<p>Using LinkedList</p>\n\n<pre><code>//Create a list by HashMap\nList&lt;Map.Entry&lt;String, Double&gt;&gt; list = new LinkedList&lt;&gt;(hashMap.entrySet());\n\n//Sorting the list\nCollections.sort(list, new Comparator&lt;Map.Entry&lt;String, Double&gt;&gt;() {\n public int compare(Map.Entry&lt;String, Double&gt; o1, Map.Entry&lt;String, Double&gt; o2) {\n return (o1.getValue()).compareTo(o2.getValue());\n }\n});\n\n//put data from sorted list to hashmap\nHashMap&lt;String, Double&gt; sortedData = new LinkedHashMap&lt;&gt;();\nfor (Map.Entry&lt;String, Double&gt; data : list) {\n sortedData.put(data.getKey(), data.getValue());\n}\n\nSystem.out.print(sortedData);\n</code></pre>\n" }, { "answer_id": 60056821, "author": "JGFMK", "author_id": 495157, "author_profile": "https://Stackoverflow.com/users/495157", "pm_score": 2, "selected": false, "text": "<p>This has the added benefit of being able to sort ascending or descending, using Java 8</p>\n\n<pre><code>import static java.util.Comparator.comparingInt;\nimport static java.util.stream.Collectors.toMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nclass Utils {\n public static Map&lt;String, Integer&gt; sortMapBasedOnValues(Map&lt;String, Integer&gt; map, boolean descending) {\n int multiplyBy = (descending) ? -1: 1;\n Map&lt;String, Integer&gt; sorted = map.entrySet().stream()\n .sorted(comparingInt(e -&gt; multiplyBy * e.getValue() ))\n .collect(toMap(\n Map.Entry::getKey, \n Map.Entry::getValue,\n (a, b) -&gt; { throw new AssertionError();},\n LinkedHashMap::new\n ));\n return sorted;\n }\n}\n</code></pre>\n" }, { "answer_id": 60676473, "author": "avi", "author_id": 10908536, "author_profile": "https://Stackoverflow.com/users/10908536", "pm_score": 3, "selected": false, "text": "<p>Simple way to sort any map in Java 8 and above</p>\n<pre><code>Map&lt;String, Object&gt; mapToSort = new HashMap&lt;&gt;();\n\nList&lt;Map.Entry&lt;String, Object&gt;&gt; list = new LinkedList&lt;&gt;(mapToSort.entrySet());\n\nCollections.sort(list, Comparator.comparing(o -&gt; o.getValue().getAttribute()));\n\nHashMap&lt;String, Object&gt; sortedMap = new LinkedHashMap&lt;&gt;();\nfor (Map.Entry&lt;String, Object&gt; map : list) {\n sortedMap.put(map.getKey(), map.getValue());\n}\n</code></pre>\n<p>if you are using Java 7 and below</p>\n<pre><code>Map&lt;String, Object&gt; mapToSort = new HashMap&lt;&gt;();\n\nList&lt;Map.Entry&lt;String, Object&gt;&gt; list = new LinkedList&lt;&gt;(mapToSort.entrySet());\n\nCollections.sort(list, new Comparator&lt;Map.Entry&lt;String, Object&gt;&gt;() {\n @Override\n public int compare(Map.Entry&lt;String, Object&gt; o1, Map.Entry&lt;String, Object&gt; o2) {\n return o1.getValue().getAttribute().compareTo(o2.getValue().getAttribute()); \n }\n});\n\nHashMap&lt;String, Object&gt; sortedMap = new LinkedHashMap&lt;&gt;();\nfor (Map.Entry&lt;String, Object&gt; map : list) {\n sortedMap.put(map.getKey(), map.getValue());\n}\n</code></pre>\n" }, { "answer_id": 60932599, "author": "thenish", "author_id": 4088988, "author_profile": "https://Stackoverflow.com/users/4088988", "pm_score": 2, "selected": false, "text": "<pre><code>map = your hashmap;\n\nList&lt;Map.Entry&lt;String, Integer&gt;&gt; list = new LinkedList&lt;Map.Entry&lt;String, Integer&gt;&gt;(map.entrySet());\nCollections.sort(list, new cm());//IMP\n\nHashMap&lt;String, Integer&gt; sorted = new LinkedHashMap&lt;String, Integer&gt;();\nfor(Map.Entry&lt;String, Integer&gt; en: list){\n sorted.put(en.getKey(),en.getValue());\n}\n\nSystem.out.println(sorted);//sorted hashmap\n</code></pre>\n\n<p>create new class</p>\n\n<pre><code>class cm implements Comparator&lt;Map.Entry&lt;String, Integer&gt;&gt;{\n @Override\n public int compare(Map.Entry&lt;String, Integer&gt; a, \n Map.Entry&lt;String, Integer&gt; b)\n {\n return (a.getValue()).compareTo(b.getValue());\n }\n}\n</code></pre>\n" }, { "answer_id": 63848163, "author": "BlueJapan", "author_id": 8288930, "author_profile": "https://Stackoverflow.com/users/8288930", "pm_score": 1, "selected": false, "text": "<p>I can give you an example but sure this is what you need.</p>\n<pre class=\"lang-html prettyprint-override\"><code>map = {10 = 3, 11 = 1,12 = 2} \n</code></pre>\n<p>Let's say you want the top 2 most frequent key which is (10, 12)\nSo the easiest way is using a PriorityQueue to sort based on the value of the map.</p>\n<pre class=\"lang-java prettyprint-override\"><code>PriorityQueue&lt;Integer&gt; pq = new PriorityQueue&lt;&gt;((a, b) -&gt; (map.get(a) - map.get(b));\nfor(int key: map.keySets()) {\n pq.add(key);\n if(pq.size() &gt; 2) {\n pq.poll();\n }\n}\n// Now pq has the top 2 most frequent key based on value. It sorts the value. \n</code></pre>\n" }, { "answer_id": 65917002, "author": "Supreet Singh", "author_id": 6856020, "author_profile": "https://Stackoverflow.com/users/6856020", "pm_score": 3, "selected": false, "text": "<p>This could be achieved very easily with java 8</p>\n<pre><code>public static LinkedHashMap&lt;Integer, String&gt; sortByValue(HashMap&lt;Integer, String&gt; map) {\n\n List&lt;Map.Entry&lt;Integer, String&gt;&gt; list = new ArrayList&lt;&gt;(map.entrySet());\n list.sort(Map.Entry.comparingByValue());\n LinkedHashMap&lt;Integer, String&gt; sortedMap = new LinkedHashMap&lt;&gt;();\n list.forEach(e -&gt; sortedMap.put(e.getKey(), e.getValue()));\n return sortedMap;\n }\n</code></pre>\n" }, { "answer_id": 68509369, "author": "djklicks-dhananjay", "author_id": 11597506, "author_profile": "https://Stackoverflow.com/users/11597506", "pm_score": 2, "selected": false, "text": "<p>Sort any Hashmap the easiest way in Java.\nWe need not store it in treemaps, list etc.</p>\n<p>Here, I would be using Java Streams:</p>\n<p>Lets sort this map by its value (Ascending order)</p>\n<pre><code>Map&lt;String, Integer&gt; mp= new HashMap&lt;&gt;();\nmp.put(&quot;zebra&quot;, 1);\nmp.put(&quot;blossom&quot;, 2);\nmp.put(&quot;gemini&quot;, 3);\nmp.put(&quot;opera&quot;, 7);\nmp.put(&quot;adelaide&quot;, 10);\n\nMap&lt;String, Integer&gt; resultMap= mp.entrySet().stream().sorted(Map.Entry.&lt;String, Integer&gt;comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -&gt; e1, LinkedHashMap::new));\n</code></pre>\n<p>You can now printed the sorted resultMap in multiple ways like using advanced for loops or iterators.</p>\n<p>The above map can also be sorted in descending order of the value</p>\n<pre><code> Map&lt;String, Integer&gt; resultMap= mp.entrySet().stream().sorted(Map.Entry.&lt;String, Integer&gt;comparingByValue().reversed()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -&gt; e1, LinkedHashMap::new));\n</code></pre>\n<p>Lets now take another scenario where we store &quot;User&quot; in the map and sort it based on &quot;name&quot; of the &quot;User&quot; in ascending order (lexicographically):</p>\n<pre><code>User u1= new User(&quot;hi&quot;, 135);\nUser u2= new User(&quot;bismuth&quot;, 900);\nUser u3= new User(&quot;alloy&quot;, 675);\nUser u4= new User(&quot;jupiter&quot;, 342);\nUser u5= new User(&quot;lily&quot;, 941);\n\nMap&lt;String, User&gt; map2= new HashMap&lt;&gt;();\nmap2.put(&quot;zebra&quot;, u3);\nmap2.put(&quot;blossom&quot;, u5);\nmap2.put(&quot;gemini&quot;, u1);\nmap2.put(&quot;opera&quot;, u2);\nmap2.put(&quot;adelaide&quot;, u4);\n\n\nMap&lt;String, User&gt; resultMap= \n map2.entrySet().stream().sorted(Map.Entry.&lt;String, User&gt;comparingByValue( (User o1, User o2)-&gt; o1.getName().compareTo(o2.getName()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -&gt; e2, LinkedHashMap::new));\n\n\n\nclass User\n {\n String name;\n int id;\n \n\npublic User(String name, int id) {\n super();\n this.name = name;\n this.id = id;\n}\npublic String getName() {\n return name;\n}\npublic void setName(String name) {\n this.name = name;\n}\npublic int getId() {\n return id;\n}\npublic void setId(int id) {\n this.id = id;\n}\n@Override\npublic String toString() {\n return &quot;User [name=&quot; + name + &quot;, id=&quot; + id + &quot;]&quot;;\n}\n@Override\npublic int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + id;\n result = prime * result + ((name == null) ? 0 : name.hashCode());\n return result;\n}\n@Override\npublic boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n User other = (User) obj;\n if (id != other.id)\n return false;\n if (name == null) {\n if (other.name != null)\n return false;\n } else if (!name.equals(other.name))\n return false;\n return true;\n\n\n }\n }\n</code></pre>\n" }, { "answer_id": 69993629, "author": "Jayavinoth", "author_id": 761348, "author_profile": "https://Stackoverflow.com/users/761348", "pm_score": 1, "selected": false, "text": "<p>In TreeMap, keys are sorted in natural order. For example, if you sorting numbers, (notice the ordering of <code>4</code>)</p>\n<p><code>{0=0, 10=10, 20=20, 30=30, 4=4, 50=50, 60=60, 70=70}</code></p>\n<p>To fix this, In Java8, first check string length and then compare.</p>\n<pre><code>Map&lt;String, String&gt; sortedMap = new TreeMap&lt;&gt;Comparator.comparingInt(String::length)\n.thenComparing(Function.identity()));\n</code></pre>\n<p><code>{0=0, 4=4, 10=10, 20=20, 30=30, 50=50, 60=60, 70=70}</code></p>\n" }, { "answer_id": 70401747, "author": "Praveen Kishor", "author_id": 2680024, "author_profile": "https://Stackoverflow.com/users/2680024", "pm_score": 2, "selected": false, "text": "<pre><code> Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();\n map.put(&quot;b&quot;, 2);\n map.put(&quot;a&quot;, 1);\n map.put(&quot;d&quot;, 4);\n map.put(&quot;c&quot;, 3);\n \n // ----- Using Java 7 -------------------\n List&lt;Map.Entry&lt;String, Integer&gt;&gt; entries = new ArrayList&lt;&gt;(map.entrySet());\n Collections.sort(entries, (o1, o2) -&gt; o1.getValue().compareTo(o2.getValue()));\n System.out.println(entries); // [a=1, b=2, c=3, d=4]\n\n\n // ----- Using Java 8 Stream API --------\n map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println); // {a=1, b=2, c=3, d=4}\n\n \n</code></pre>\n" }, { "answer_id": 73163197, "author": "ADITYA AHLAWAT", "author_id": 15142774, "author_profile": "https://Stackoverflow.com/users/15142774", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://www.geeksforgeeks.org/sorting-a-hashmap-according-to-values/\" rel=\"nofollow noreferrer\">Geeks For Geeks on sorting the HashMap by Value</a></p>\n<pre><code>Input : Key = Math, Value = 98\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Operating System, Value = 79\n Key = Networking, Value = 80\n\nOutput : Key = Operating System, Value = 79\n Key = Networking, Value = 80\n Key = Data Structure, Value = 85\n Key = Database, Value = 91\n Key = Java, Value = 95\n Key = Math, Value = 98\nSolution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.\nBelow is the implementation of the above idea: \n\n\n\n\n// Java program to sort hashmap by values\nimport java.util.*;\nimport java.lang.*;\n \npublic class GFG {\n \n // function to sort hashmap by values\n public static HashMap&lt;String, Integer&gt; sortByValue(HashMap&lt;String, Integer&gt; hm)\n {\n // Create a list from elements of HashMap\n List&lt;Map.Entry&lt;String, Integer&gt; &gt; list =\n new LinkedList&lt;Map.Entry&lt;String, Integer&gt; &gt;(hm.entrySet());\n \n // Sort the list\n Collections.sort(list, new Comparator&lt;Map.Entry&lt;String, Integer&gt; &gt;() {\n public int compare(Map.Entry&lt;String, Integer&gt; o1,\n Map.Entry&lt;String, Integer&gt; o2)\n {\n return (o1.getValue()).compareTo(o2.getValue());\n }\n });\n \n // put data from sorted list to hashmap\n HashMap&lt;String, Integer&gt; temp = new LinkedHashMap&lt;String, Integer&gt;();\n for (Map.Entry&lt;String, Integer&gt; aa : list) {\n temp.put(aa.getKey(), aa.getValue());\n }\n return temp;\n }\n \n // Driver Code\n public static void main(String[] args)\n {\n \n HashMap&lt;String, Integer&gt; hm = new HashMap&lt;String, Integer&gt;();\n \n // enter data into hashmap\n hm.put(&quot;Math&quot;, 98);\n hm.put(&quot;Data Structure&quot;, 85);\n hm.put(&quot;Database&quot;, 91);\n hm.put(&quot;Java&quot;, 95);\n hm.put(&quot;Operating System&quot;, 79);\n hm.put(&quot;Networking&quot;, 80);\n Map&lt;String, Integer&gt; hm1 = sortByValue(hm);\n \n // print the sorted hashmap\n for (Map.Entry&lt;String, Integer&gt; en : hm1.entrySet()) {\n System.out.println(&quot;Key = &quot; + en.getKey() +\n &quot;, Value = &quot; + en.getValue());\n }\n }\n}\nOutput\nKey = Operating System, Value = 79\nKey = Networking, Value = 80\nKey = Data Structure, Value = 85\nKey = Database, Value = 91\nKey = Java, Value = 95\nKey = Math, Value = 98\n</code></pre>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9466/" ]
I am relatively new to Java, and often find that I need to sort a `Map<Key, Value>` on the values. Since the values are not unique, I find myself converting the `keySet` into an `array`, and sorting that array through **array sort** with a **custom comparator** that sorts on the value associated with the key. Is there an easier way?
Here's a generic-friendly version: ``` public class MapUtil { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Entry<K, V>> list = new ArrayList<>(map.entrySet()); list.sort(Entry.comparingByValue()); Map<K, V> result = new LinkedHashMap<>(); for (Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } } ```
109,417
<p>I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?</p>
[ { "answer_id": 109452, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 3, "selected": true, "text": "<p>how did you populate it? is the DataSource something useful like a BindlingList? \nIf it is then something like:</p>\n\n<pre><code>BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;\n//substitute your business object type for T \nT entity = bindingSource.Current as T;\n</code></pre>\n\n<p>would get you the entity bound to the row.</p>\n\n<p>Otherwise there is always the datagridview.Columns[n].Cells[n].Value but really I'd look at using the objects in the DataSource</p>\n\n<p>Edit: Ah... a datatable... righto: </p>\n\n<pre><code> var table = dataGridView1.DataSource as DataTable;\n\n foreach(DataRow row in table.Rows)\n {\n foreach(DataColumn column in table.Columns)\n {\n Console.WriteLine(row[column]);\n }\n }\n</code></pre>\n" }, { "answer_id": 109477, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 1, "selected": false, "text": "<p>You can iterate through your datagridview and retrieve each cell.</p>\n\n<pre><code>for(int i =0; i &lt; DataGridView.Rows.Count; i++){\n DataGridView.Rows.Columns[\"columnName\"].Text= \"\";\n} \n</code></pre>\n\n<p>There is an example <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=276684&amp;SiteID=1\" rel=\"nofollow noreferrer\">here</a>. </p>\n" }, { "answer_id": 109484, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>namespace WindowsFormsApplication2\n{\n public partial class Form1 : Form\n {\n public static DataTable objDataTable = new DataTable(\"UpdateAddress\");\n\n public Form1()\n {\n InitializeComponent();\n\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Stream myStream = null;\n OpenFileDialog openFileDialog1 = new OpenFileDialog();\n\n openFileDialog1.InitialDirectory = \"c:\\\\\";\n openFileDialog1.Filter = \"csv files (*.csv)|*.txt|All files (*.*)|*.*\";\n openFileDialog1.FilterIndex = 2;\n openFileDialog1.RestoreDirectory = true;\n\n if (openFileDialog1.ShowDialog() == DialogResult.OK)\n {\n try\n {\n if ((myStream = openFileDialog1.OpenFile()) != null)\n {\n string fileName = openFileDialog1.FileName;\n\n List&lt;string&gt; dataFile = new List&lt;string&gt;();\n dataFile = ReadList(fileName);\n foreach (string item in dataFile)\n {\n string[] temp = item.Split(',');\n DataRow objDR = objDataTable.NewRow();\n objDR[\"EmployeeID\"] = temp[0].ToString();\n objDR[\"Street\"] = temp[1].ToString();\n objDR[\"POBox\"] = temp[2].ToString();\n objDR[\"City\"] = temp[3].ToString();\n objDR[\"State\"] = temp[4].ToString();\n objDR[\"Zip\"] = temp[5].ToString();\n objDR[\"Country\"] = temp[6].ToString();\n objDataTable.Rows.Add(objDR);\n\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error: Could not read file from disk. Original error: \" + ex.Message);\n }\n }\n }\n\n public static List&lt;string&gt; ReadList(string filename)\n {\n List&lt;string&gt; fileData = new List&lt;string&gt;();\n StreamReader sr = new StreamReader(filename);\n while (!sr.EndOfStream)\n fileData.Add(sr.ReadLine());\n return fileData;\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n objDataTable.Columns.Add(\"EmployeeID\", typeof(int));\n objDataTable.Columns.Add(\"Street\", typeof(string));\n objDataTable.Columns.Add(\"POBox\", typeof(string));\n objDataTable.Columns.Add(\"City\", typeof(string));\n objDataTable.Columns.Add(\"State\", typeof(string));\n objDataTable.Columns.Add(\"Zip\", typeof(string));\n objDataTable.Columns.Add(\"Country\", typeof(string));\n objDataTable.Columns.Add(\"Status\", typeof(string));\n\n dataGridView1.DataSource = objDataTable;\n dataGridView1.Refresh();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n // Displays a SaveFileDialog so the user can save the backup of AD address before the update\n // assigned to Button2.\n SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n saveFileDialog1.Filter = \"BAK Files|*.BAK\";\n saveFileDialog1.Title = \"Save AD Backup\";\n saveFileDialog1.ShowDialog();\n\n if (saveFileDialog1.FileName != \"\")\n {\n TextWriter fileOut = new StreamWriter(saveFileDialog1.FileName); \n //This is where I want read from the datagridview the EmployeeID column and use it in my BackupAddress method.\n }\n\n }\n</code></pre>\n" }, { "answer_id": 109882, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>You might want to take a look at <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx\" rel=\"nofollow noreferrer\">DataTable.WriteXml</a>, and it's brother <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.readxml.aspx\" rel=\"nofollow noreferrer\">DataTable.ReadXml</a>. No fuss, no muss saving of a DataTable.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I populated a datagridview from a datatable. How do I read from the datagridview when the application is running?
how did you populate it? is the DataSource something useful like a BindlingList? If it is then something like: ``` BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource; //substitute your business object type for T T entity = bindingSource.Current as T; ``` would get you the entity bound to the row. Otherwise there is always the datagridview.Columns[n].Cells[n].Value but really I'd look at using the objects in the DataSource Edit: Ah... a datatable... righto: ``` var table = dataGridView1.DataSource as DataTable; foreach(DataRow row in table.Rows) { foreach(DataColumn column in table.Columns) { Console.WriteLine(row[column]); } } ```
109,444
<p>Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:</p> <pre><code>C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg </code></pre> <p>This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.</p>
[ { "answer_id": 109454, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 3, "selected": true, "text": "<p>Use the <a href=\"http://us.php.net/manual/en/function.stripslashes.php\" rel=\"nofollow noreferrer\"><code>stripslashes</code></a> function.</p>\n\n<p>That should make them all single slashes.</p>\n" }, { "answer_id": 109463, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 1, "selected": false, "text": "<p>Have you considered the stripslashes() function?</p>\n\n<p><a href=\"http://www.php.net/stripslashes\" rel=\"nofollow noreferrer\">http://www.php.net/stripslashes</a></p>\n" }, { "answer_id": 109624, "author": "moltenform", "author_id": 18506, "author_profile": "https://Stackoverflow.com/users/18506", "pm_score": 2, "selected": false, "text": "<p>Note that you may be running into PHP's Magic Quotes \"feature\" where incoming backslashes are turned to <code>\\\\</code>.</p>\n\n<p>See \n<a href=\"http://us2.php.net/magic_quotes\" rel=\"nofollow noreferrer\">http://us2.php.net/magic_quotes</a></p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie: ``` C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg ``` This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.
Use the [`stripslashes`](http://us.php.net/manual/en/function.stripslashes.php) function. That should make them all single slashes.
109,449
<p>Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?</p> <p>The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.</p>
[ { "answer_id": 109476, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 2, "selected": false, "text": "<p>Well, you can get the file descriptor - I forget whether the method is fd() or getfd(). <em>The implementations I've used provide such methods, but the language standard doesn't require them, I believe - the standard shouldn't care whether your platform uses fd's for files.</em></p>\n\n<p>From that, you can use fdopen(fd, mode) to get a FILE*.</p>\n\n<p>However, I think that the mechanisms the standard requires for synching STDIN/cin, STDOUT/cout and STDERR/cerr don't have to be visible to you. So if you're using both the fstream and FILE*, buffering may mess you up.</p>\n\n<p>Also, if either the fstream OR the FILE closes, they'll probably close the underlying fd, so you need to make sure you flush BOTH before closing EITHER.</p>\n" }, { "answer_id": 109522, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": true, "text": "<p>The short answer is no.</p>\n\n<p>The reason, is because the <code>std::fstream</code> is not required to use a <code>FILE*</code> as part of its implementation. So even if you manage to extract file descriptor from the <code>std::fstream</code> object and manually build a FILE object, then you will have other problems because you will now have two buffered objects writing to the same file descriptor. </p>\n\n<p>The real question is why do you want to convert the <code>std::fstream</code> object into a <code>FILE*</code>?</p>\n\n<p>Though I don't recommend it, you could try looking up <code>funopen()</code>.<br>\nUnfortunately, this is <B>not</B> a POSIX API (it's a BSD extension) so its portability is in question. Which is also probably why I can't find anybody that has wrapped a <code>std::stream</code> with an object like this.</p>\n\n<pre><code>FILE *funopen(\n const void *cookie,\n int (*readfn )(void *, char *, int),\n int (*writefn)(void *, const char *, int),\n fpos_t (*seekfn) (void *, fpos_t, int),\n int (*closefn)(void *)\n );\n</code></pre>\n\n<p>This allows you to build a <code>FILE</code> object and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from the <code>std::fstream</code> object that actually has the file open.</p>\n" }, { "answer_id": 109544, "author": "dvorak", "author_id": 19235, "author_profile": "https://Stackoverflow.com/users/19235", "pm_score": 4, "selected": false, "text": "<p>There isn't a standardized way. I assume this is because the C++ standardization group didn't want to assume that a file handle can be represented as a fd.</p>\n\n<p>Most platforms do seem to provide some non-standard way to do this.</p>\n\n<p><a href=\"http://www.ginac.de/~kreckel/fileno/\" rel=\"noreferrer\">http://www.ginac.de/~kreckel/fileno/</a> provides a good writeup of the situation and provides code that hides all the platform specific grossness, at least for GCC. Given how gross this is just on GCC, I think I'd avoid doing this all together if possible.</p>\n" }, { "answer_id": 19749019, "author": "alfC", "author_id": 225186, "author_profile": "https://Stackoverflow.com/users/225186", "pm_score": 4, "selected": false, "text": "<blockquote>\n<p>UPDATE: See @Jettatura what I think it is the best answer <a href=\"https://stackoverflow.com/a/33612982/225186\">https://stackoverflow.com/a/33612982/225186</a> (Linux only?).</p>\n</blockquote>\n<p>ORIGINAL:</p>\n<p>(Probably not cross platform, but simple)</p>\n<p>Simplifying the hack in <a href=\"http://www.ginac.de/%7Ekreckel/fileno/\" rel=\"nofollow noreferrer\">http://www.ginac.de/~kreckel/fileno/</a> (dvorak answer), and looking at this gcc extension <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00069.html#a59f78806603c619eafcd4537c920f859\" rel=\"nofollow noreferrer\">http://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00069.html#a59f78806603c619eafcd4537c920f859</a>,\nI have this solution that works on <code>GCC</code> (4.8 at least) and <code>clang</code> (3.3 at least) before C++11:</p>\n<pre><code>#include&lt;fstream&gt;\n#include&lt;ext/stdio_filebuf.h&gt;\n\ntypedef std::basic_ofstream&lt;char&gt;::__filebuf_type buffer_t;\ntypedef __gnu_cxx::stdio_filebuf&lt;char&gt; io_buffer_t; \nFILE* cfile_impl(buffer_t* const fb){\n return (static_cast&lt;io_buffer_t* const&gt;(fb))-&gt;file(); //type std::__c_file\n}\n\nFILE* cfile(std::ofstream const&amp; ofs){return cfile_impl(ofs.rdbuf());}\nFILE* cfile(std::ifstream const&amp; ifs){return cfile_impl(ifs.rdbuf());}\n</code></pre>\n<p>and can be used this,</p>\n<pre><code>int main(){\n std::ofstream ofs(&quot;file.txt&quot;);\n fprintf(cfile(ofs), &quot;sample1&quot;);\n fflush(cfile(ofs)); // ofs &lt;&lt; std::flush; doesn't help \n ofs &lt;&lt; &quot;sample2\\n&quot;;\n}\n</code></pre>\n<p><strong>Note:</strong> The <code>stdio_filebuf</code> is not used in newer versions of the library. The <code>static_cast&lt;&gt;()</code> is somewhat dangerous too. Use a <code>dynamic_cast&lt;&gt;()</code> instead of if you get a <code>nullptr</code> you need that's not the right class. You can try with <code>stdio_sync_filebuf</code> instead. Problem with that class is that the <code>file()</code> is not available at all anymore.</p>\n<p><strong>Limitations:</strong> (comments are welcome)</p>\n<ol>\n<li><p>I find that it is important to <code>fflush</code> after <code>fprintf</code> printing to <code>std::ofstream</code>, otherwise the &quot;sample2&quot; appears before &quot;sample1&quot; in the example above. I don't know if there is a better workaround for that than using <code>fflush</code>. Notably <code>ofs &lt;&lt; flush</code> doesn't help.</p>\n</li>\n<li><p>Cannot extract FILE* from <code>std::stringstream</code>, I don't even know if it is possible. (see below for an update).</p>\n</li>\n<li><p>I still don't know how to extract C's <code>stderr</code> from <code>std::cerr</code> etc., for example to use in <code>fprintf(stderr, &quot;sample&quot;)</code>, in an hypothetical code like this <code>fprintf(cfile(std::cerr), &quot;sample&quot;)</code>.</p>\n</li>\n</ol>\n<p>Regarding the last limitation, the only workaround I found is to add these overloads:</p>\n<pre><code>FILE* cfile(std::ostream const&amp; os){\n if(std::ofstream const* ofsP = dynamic_cast&lt;std::ofstream const*&gt;(&amp;os)) return cfile(*ofsP);\n if(&amp;os == &amp;std::cerr) return stderr;\n if(&amp;os == &amp;std::cout) return stdout;\n if(&amp;os == &amp;std::clog) return stderr;\n if(dynamic_cast&lt;std::ostringstream const*&gt;(&amp;os) != 0){\n throw std::runtime_error(&quot;don't know cannot extract FILE pointer from std::ostringstream&quot;);\n }\n return 0; // stream not recognized\n}\nFILE* cfile(std::istream const&amp; is){\n if(std::ifstream const* ifsP = dynamic_cast&lt;std::ifstream const*&gt;(&amp;is)) return cfile(*ifsP);\n if(&amp;is == &amp;std::cin) return stdin;\n if(dynamic_cast&lt;std::ostringstream const*&gt;(&amp;is) != 0){\n throw std::runtime_error(&quot;don't know how to extract FILE pointer from std::istringstream&quot;);\n }\n return 0; // stream not recognized\n}\n</code></pre>\n<p><strong>Attempt to handle <code>iostringstream</code></strong></p>\n<p>It is possible to read with <code>fscanf</code> from <code>istream</code> using <code>fmemopen</code>, but that requires a lot of book keeping and updating the input position of the stream after each read, if one wants to combine C-reads and C++-reads. I wasn't able to convert this into a <code>cfile</code> function like above. (Maybe a <code>cfile</code> <em>class</em> that keeps updating after each read is the way to go).</p>\n<pre><code>// hack to access the protected member of istreambuf that know the current position\nchar* access_gptr(std::basic_streambuf&lt;char, std::char_traits&lt;char&gt;&gt;&amp; bs){\n struct access_class : std::basic_streambuf&lt;char, std::char_traits&lt;char&gt;&gt;{\n char* access_gptr() const{return this-&gt;gptr();}\n };\n return ((access_class*)(&amp;bs))-&gt;access_gptr();\n}\n\nint main(){\n std::istringstream iss(&quot;11 22 33&quot;);\n // read the C++ way\n int j1; iss &gt;&gt; j1;\n std::cout &lt;&lt; j1 &lt;&lt; std::endl;\n\n // read the C way\n float j2;\n \n char* buf = access_gptr(*iss.rdbuf()); // get current position\n size_t buf_size = iss.rdbuf()-&gt;in_avail(); // get remaining characters\n FILE* file = fmemopen(buf, buf_size, &quot;r&quot;); // open buffer memory as FILE*\n fscanf(file, &quot;%f&quot;, &amp;j2); // finally!\n iss.rdbuf()-&gt;pubseekoff(ftell(file), iss.cur, iss.in); // update input stream position from current FILE position.\n\n std::cout &lt;&lt; &quot;j2 = &quot; &lt;&lt; j2 &lt;&lt; std::endl;\n\n // read again the C++ way\n int j3; iss &gt;&gt; j3;\n std::cout &lt;&lt; &quot;j3 = &quot; &lt;&lt; j3 &lt;&lt; std::endl;\n}\n</code></pre>\n" }, { "answer_id": 26746714, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 2, "selected": false, "text": "<p>In a single-threaded POSIX application you can easily get the fd number in a portable way:</p>\n\n<pre><code>int fd = dup(0);\nclose(fd);\n// POSIX requires the next opened file descriptor to be fd.\nstd::fstream file(...);\n// now fd has been opened again and is owned by file\n</code></pre>\n\n<p>This method breaks in a multi-threaded application if this code races with other threads opening file descriptors.</p>\n" }, { "answer_id": 33612982, "author": "Jettatura", "author_id": 5543125, "author_profile": "https://Stackoverflow.com/users/5543125", "pm_score": 2, "selected": false, "text": "<p>yet another way to do this in Linux:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;cassert&gt;\n\ntemplate&lt;class STREAM&gt;\nstruct STDIOAdapter\n{\n static FILE* yield(STREAM* stream)\n {\n assert(stream != NULL);\n\n static cookie_io_functions_t Cookies =\n {\n .read = NULL,\n .write = cookieWrite,\n .seek = NULL,\n .close = cookieClose\n };\n\n return fopencookie(stream, \"w\", Cookies);\n }\n\n ssize_t static cookieWrite(void* cookie,\n const char* buf,\n size_t size)\n {\n if(cookie == NULL)\n return -1;\n\n STREAM* writer = static_cast &lt;STREAM*&gt;(cookie);\n\n writer-&gt;write(buf, size);\n\n return size;\n }\n\n int static cookieClose(void* cookie)\n {\n return EOF;\n }\n}; // STDIOAdapter\n</code></pre>\n\n<p>Usage, for example:</p>\n\n<pre><code>#include &lt;boost/iostreams/filtering_stream.hpp&gt;\n#include &lt;boost/iostreams/filter/bzip2.hpp&gt;\n#include &lt;boost/iostreams/device/file.hpp&gt;\n\nusing namespace boost::iostreams;\n\nint main()\n{ \n filtering_ostream out;\n out.push(boost::iostreams::bzip2_compressor());\n out.push(file_sink(\"my_file.txt\"));\n\n FILE* fp = STDIOAdapter&lt;filtering_ostream&gt;::yield(&amp;out);\n assert(fp &gt; 0);\n\n fputs(\"Was up, Man\", fp);\n\n fflush (fp);\n\n fclose(fp);\n\n return 1;\n}\n</code></pre>\n" }, { "answer_id": 44577546, "author": "yanpas", "author_id": 4355809, "author_profile": "https://Stackoverflow.com/users/4355809", "pm_score": 2, "selected": false, "text": "<p>There is a way to get file descriptor from <code>fstream</code> and then convert it to <code>FILE*</code> (via <code>fdopen</code>). Personally I don't see any need in <code>FILE*</code>, but with file descriptor you may do many interesting things such as redirecting (<code>dup2</code>).</p>\n\n<p>Solution:\n</p>\n\n<pre><code>#define private public\n#define protected public\n#include &lt;fstream&gt;\n#undef private\n#undef protected\n\nstd::ifstream file(\"some file\");\nauto fno = file._M_filebuf._M_file.fd();\n</code></pre>\n\n<p>The last string works for libstdc++. If you are using some other library you will need to reverse-engineer it a bit. </p>\n\n<p>This trick is dirty and will expose all private and public members of fstream. If you would like to use it in your production code I suggest you to create separate <code>.cpp</code> and <code>.h</code> with single function <code>int getFdFromFstream(std::basic_ios&lt;char&gt;&amp; fstr);</code>. Header file must not include fstream.</p>\n" }, { "answer_id": 72932388, "author": "Alexis Wilke", "author_id": 212378, "author_profile": "https://Stackoverflow.com/users/212378", "pm_score": 0, "selected": false, "text": "<p>I ran in that problem when I was faced with <code>isatty()</code> only working on a file descriptor.</p>\n<p>In newer versions of the C++ standard library (at least since C++11), the solution proposed by alfC does not work anymore because that one class was changed to a new class.</p>\n<p>The old method will still work if you use very old versions of the compiler. In newer version, you need to use <code>std::basic_filebuf&lt;&gt;()</code>. But that does not work with the standard I/O such as <code>std::cout</code>. For those, you need to use <code>__gnu_cxx::stdio_sync_filebuf&lt;&gt;()</code>.</p>\n<p>I have a functional example in my implementation of <a href=\"https://github.com/m2osw/snapdev/blob/main/snapdev/isatty.h\" rel=\"nofollow noreferrer\"><code>isatty()</code></a> for C++ streams here. You should be able to lift off that one file and reuse it in your own project. In your case, though, you wanted the <code>FILE*</code> pointer, so just return that instead of the result of <code>::isatty(fileno(&lt;of FILE*&gt;))</code>.</p>\n<p>Here is a copy of the template function:</p>\n<pre><code>template&lt;typename _CharT\n , typename _Traits = std::char_traits&lt;_CharT&gt;&gt;\nbool isatty(std::basic_ios&lt;_CharT, _Traits&gt; const &amp; s)\n{\n { // cin, cout, cerr, and clog\n typedef __gnu_cxx::stdio_sync_filebuf&lt;_CharT, _Traits&gt; io_sync_buffer_t;\n io_sync_buffer_t * buffer(dynamic_cast&lt;io_sync_buffer_t *&gt;(s.rdbuf()));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer-&gt;file()));\n }\n }\n\n { // modern versions\n typedef std::basic_filebuf&lt;_CharT, _Traits&gt; file_buffer_t;\n file_buffer_t * file_buffer(dynamic_cast&lt;file_buffer_t *&gt;(s.rdbuf()));\n if(file_buffer != nullptr)\n {\n typedef detail::our_basic_filebuf&lt;_CharT, _Traits&gt; hack_buffer_t;\n hack_buffer_t * buffer(static_cast&lt;hack_buffer_t *&gt;(file_buffer));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer-&gt;file()));\n }\n }\n }\n\n { // older versions\n typedef __gnu_cxx::stdio_filebuf&lt;_CharT, _Traits&gt; io_buffer_t;\n io_buffer_t * buffer(dynamic_cast&lt;io_buffer_t *&gt;(s.rdbuf()));\n if(buffer != nullptr)\n {\n return ::isatty(fileno(buffer-&gt;file()));\n }\n }\n\n return false;\n}\n</code></pre>\n<p>Now, you should be asking: <em>But what is that detail class <code>our_basic_filebuf</code></em>?!?</p>\n<p>And that's a good question. The fact is that the <code>_M_file</code> pointer is protected and there is no <code>file()</code> (or <code>fd()</code>) in the <code>std::basic_filebuf</code>. For that reason, I created a <em>shell class</em> which has access to the protected fields and that way I can return the <code>FILE*</code> pointer.</p>\n<pre><code>template&lt;typename _CharT\n , typename _Traits = std::char_traits&lt;_CharT&gt;&gt;\nclass our_basic_filebuf\n : public std::basic_filebuf&lt;_CharT, _Traits&gt;\n{\npublic:\n std::__c_file * file() throw()\n {\n return this-&gt;_M_file.file();\n }\n};\n</code></pre>\n<p>This is somewhat ugly, but cleanest I could think off to gain access to the <code>_M_file</code> field.</p>\n" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a (cross-platform) way to get a C FILE\* handle from a C++ std::fstream ? The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE\*.
The short answer is no. The reason, is because the `std::fstream` is not required to use a `FILE*` as part of its implementation. So even if you manage to extract file descriptor from the `std::fstream` object and manually build a FILE object, then you will have other problems because you will now have two buffered objects writing to the same file descriptor. The real question is why do you want to convert the `std::fstream` object into a `FILE*`? Though I don't recommend it, you could try looking up `funopen()`. Unfortunately, this is **not** a POSIX API (it's a BSD extension) so its portability is in question. Which is also probably why I can't find anybody that has wrapped a `std::stream` with an object like this. ``` FILE *funopen( const void *cookie, int (*readfn )(void *, char *, int), int (*writefn)(void *, const char *, int), fpos_t (*seekfn) (void *, fpos_t, int), int (*closefn)(void *) ); ``` This allows you to build a `FILE` object and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from the `std::fstream` object that actually has the file open.