qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
79,592 | <p><strong>problem</strong></p>
<p>how to best parse/access/extract "excel file" data stored as binary data in an SQL 2005 field?</p>
<p>(so all the data can ultimately be stored in other fields of other tables.)</p>
<p><strong>background</strong></p>
<p>basically, our customer is requiring a large volume of verbose data from their users. unfortunately, our customer cannot require any kind of db export from their user. so our customer must supply some sort of UI for their user to enter the data. the UI our customer decided would be acceptable to all of their users was excel as it has a reasonably robust UI. so given all that, and our customer needs this data parsed and stored in their db automatically.</p>
<p>we've tried to convince our customer that the users will do this exactly once and then insist on db export! but the customer can not <em>require</em> db export of their users.</p>
<ul>
<li>our customer is requiring us to parse an excel file</li>
<li>the customer's users are using excel as the "best" user interface to enter all the required data</li>
<li>the users are given blank excel templates that they must fill out
<ul>
<li>these templates have a fixed number of uniquely named tabs</li>
<li>these templates have a number of fixed areas (cells) that must be completed</li>
<li>these templates also have areas where the user will insert up to thousands of identically formatted rows</li>
</ul></li>
<li>when complete, the excel file is submitted from the user by standard html file upload</li>
<li>our customer stores this file raw into their SQL database</li>
</ul>
<p><strong>given</strong></p>
<ul>
<li>a standard excel (".xls") file (native format, not comma or tab separated)</li>
<li>file is stored raw in a <code>varbinary(max)</code> SQL 2005 field</li>
<li>excel file data may not necessarily be "uniform" between rows -- i.e., we can't just assume one column is all the same data type (e.g., there may be row headers, column headers, empty cells, different "formats", ...)</li>
</ul>
<p><strong>requirements</strong></p>
<ul>
<li>code completely within SQL 2005 (stored procedures, SSIS?)</li>
<li>be able to access values on any worksheet (tab)</li>
<li>be able to access values in any cell (no formula data or dereferencing needed)</li>
<li>cell values must not be assumed to be "uniform" between rows -- i.e., we can't just assume one column is all the same data type (e.g., there may be row headers, column headers, empty cells, formulas, different "formats", ...)</li>
</ul>
<p><strong>preferences</strong></p>
<ul>
<li>no filesystem access (no writing temporary .xls files)</li>
<li>retrieve values in defined format (e.g., actual date value instead of a raw number like 39876)</li>
</ul>
| [{'answer_id': 79607, 'author': 'dreamlax', 'author_id': 10320, 'author_profile': 'https://Stackoverflow.com/users/10320', 'pm_score': 1, 'selected': False, 'text': "<p>It sounds like you're trying to store an entire database table inside a spreadsheet and then inside a single table's field. Wouldn't it be simpler to store the data in a database table to begin with and then export it as an XLS when required?</p>\n\n<p>Without opening up an instance Excel and having Excel resolve worksheet references I'm not sure it's doable at all.</p>\n"}, {'answer_id': 79716, 'author': 'David Lay', 'author_id': 6359, 'author_profile': 'https://Stackoverflow.com/users/6359', 'pm_score': 2, 'selected': False, 'text': "<p>My thought is that anything can be done, but there is a price to pay. In this particular case, the price seems to bee too high. </p>\n\n<p>I don't have a tested solution for you, but I can share how I would give my first try on a problem like that.</p>\n\n<p>My first approach would be to install excel on the SqlServer machine and code some assemblies to consume the file on your rows using excel API and then load them on Sql server as assembly procedures.</p>\n\n<p>As I said, This is just a idea, I don't have details, but I'm sure others here can complement or criticize my idea.</p>\n\n<p>But my real advice is to rethink the whole project. It makes no sense to read tabular data on binary files stored on a cell of a row of a table on database. </p>\n"}, {'answer_id': 81713, 'author': 'Mike Woodhouse', 'author_id': 1060, 'author_profile': 'https://Stackoverflow.com/users/1060', 'pm_score': 2, 'selected': False, 'text': '<p>This looks like an "I wouldn\'t start from here" kind of a question.</p>\n\n<p>The "install Excel on the server and start coding" answer looks like the only route, but it simply has to be worth exploring alternatives first: it\'s going to be painful, expensive and time-consuming.</p>\n\n<p>I strongly feel that we\'re looking at a "requirement" that is the answer to the wrong problem.</p>\n\n<p>What business problem is creating this need? What\'s driving that? Try the <a href="http://en.wikipedia.org/wiki/5_Whys" rel="nofollow noreferrer">Five Whys</a> as a possible way to explore the history.</p>\n'}, {'answer_id': 425689, 'author': 'Neil', 'author_id': 52115, 'author_profile': 'https://Stackoverflow.com/users/52115', 'pm_score': 1, 'selected': False, 'text': "<p>Could you write the varbinary to a Raw File Destination? And then use an Excel Source as your input to whatever step is next in your precedence constraints.</p>\n\n<p>I haven't tried it, but that's what I would try.</p>\n"}, {'answer_id': 561976, 'author': 'marc_s', 'author_id': 13302, 'author_profile': 'https://Stackoverflow.com/users/13302', 'pm_score': 1, 'selected': False, 'text': '<p>Well, the whole setup seems a bit twisted :-) as others have already pointed out.</p>\n\n<p>If you really cannot change the requirements and the whole setup: why don\'t you explore components such as <a href="http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx" rel="nofollow noreferrer">Aspose.Cells</a> or <a href="http://www.syncfusion.com/products/xlsio/backoffice/default.aspx" rel="nofollow noreferrer">Syncfusion XlsIO</a>, native .NET components, that allow you to read and interpret native Excel (XLS) files. I\'m pretty such with either of the two, you should be able to read your binary Excel into a MemoryStream and then feed that into one of those Excel-reading components, and off you go.</p>\n\n<p>So with a bit of .NET development and SQL CLR, I guess this should be doable - not sure if it\'s the best way to do it, but it should work.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12293/'] |
79,594 | <p>I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice. </p>
<p>Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out there in the wide world?</p>
| [{'answer_id': 79614, 'author': 'Jason Jackson', 'author_id': 13103, 'author_profile': 'https://Stackoverflow.com/users/13103', 'pm_score': 3, 'selected': True, 'text': '<p>I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML. You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for translation in case of changes to the object breaks things.</p>\n\n<p>There are a number of XSLT editors on the market that will help you do the mappings, but I prefer to just use a regular XML editor.</p>\n'}, {'answer_id': 79621, 'author': 'Don', 'author_id': 6845, 'author_profile': 'https://Stackoverflow.com/users/6845', 'pm_score': 1, 'selected': False, 'text': "<p>ya, I think you're heading down the right path with MapForce. If you don't want to write code to preform the actual transformation, MapForce can do that for you also. THis may be better long term b/c it's less code to maintain.</p>\n\n<p>Steer clear of more expensive options (e.g. BizTalk) unless you really need to B2B integration and orchestration.</p>\n"}, {'answer_id': 79626, 'author': 'David Medinets', 'author_id': 219658, 'author_profile': 'https://Stackoverflow.com/users/219658', 'pm_score': 0, 'selected': False, 'text': '<p>What database are you using? Oracle has some nice XML mapping tools. There are some Java binding tools (one is <a href="http://java.sun.com/developer/technicalArticles/WebServices/jaxb" rel="nofollow noreferrer">http://java.sun.com/developer/technicalArticles/WebServices/jaxb</a>). However, if you have the luxory consider using Ruby which has nice built-in "to_xml" methods.</p>\n'}, {'answer_id': 79752, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p><strong>Tip #1: Avoid all use of XSLT.</strong> </p>\n\n<p>The tool support sucks. The resulting solution will be unmaintainable.</p>\n\n<p><strong>Tip #2: Eliminate all unnecessary steps.</strong> </p>\n\n<p>Just translate your resultset (assuming you\'re using JDBC or equiv) to the outbound XML.</p>\n\n<p><strong>Tip #3: Assume all use of a schema-based tool to be incorrect and plan accordingly.</strong> </p>\n\n<p>In other words, just fake it. If you have to squirt out some mutant SOAP (redundant, I know) payload just mock up a working SOAP message and then turn it into a template. Velocity doesn\'t suck. </p>\n\n<p>That said, the best/correct answer, is to use an "XML Writer" style solution. There\'s a few. </p>\n\n<p>The best is the one I wrote, <a href="https://lox.dev.java.net/" rel="nofollow noreferrer">LOX (Lightweight Objects for XML)</a>.</p>\n\n<p>The public API uses a Builder design pattern. Due to some magic under the hood, it\'s impossible to create malformed XML.</p>\n\n<p><strong>Please note:</strong> If XML is the answer, you\'ve asked the wrong question. Sometimes, we\'re forced against our will to use it in some way. When that happens, it\'s crucial to use tools which minimize developer effort and improve code maintainability.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14836/'] |
79,602 | <p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
| [{'answer_id': 79670, 'author': 'Jerub', 'author_id': 14648, 'author_profile': 'https://Stackoverflow.com/users/14648', 'pm_score': 3, 'selected': True, 'text': '<p>There are some pretty serious concerns here for how to send email automatically, and here are a few:</p>\n\n<p>Use an email library. Python includes one called \'email\'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from <a href="http://docs.python.org/lib/node161.html" rel="nofollow noreferrer">the Python Manual</a>.</p>\n\n<p>Some points that will stop you from getting blocked by spam filters:</p>\n\n<p>Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it\'s received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.</p>\n\n<p>The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that\'s where mail will go when the user hits \'Reply:\'. Use this to your advantage, bounces can go to one place, while reply goes to another.</p>\n\n<p>Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as \'sent\' from a programmatic point of view.</p>\n\n<p>If you have a site that is on a static ip in a datacenter of good reputation, don\'t be afraid to simply relay the mail directly to the internet. If you\'re in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.</p>\n\n<p>Don\'t send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don\'t want to annoy me.</p>\n\n<p>Verify that you\'re not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.</p>\n\n<pre><code>$ dig google.com txt\n...snip...\n;; ANSWER SECTION:\ngoogle.com. 300 IN TXT "v=spf1 include:_netblocks.google.com ~all"\n</code></pre>\n\n<p>As you can see from that result, there\'s an SPF record there. If you don\'t have SPF, there won\'t be a TXT record. Read more about <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework" rel="nofollow noreferrer">SPF on wikipedia</a>.</p>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 79743, 'author': 'NotMe', 'author_id': 2424, 'author_profile': 'https://Stackoverflow.com/users/2424', 'pm_score': 2, 'selected': False, 'text': '<p>Some general information with regards to automated mail processing...</p>\n\n<p>First, the mail server "brand" itself isn\'t that important for broadcasting or receiving emails. All of them support the standard smtp / pop3 communications protocol. Most even have IMAP support and have some level of spam filtering. That said, try to use a current generation email server.</p>\n\n<p>Second, be aware that in an effort to reduce spam a lot of the receiving mail servers out there will simply throw a message away instead of responding back that a mail account doesn\'t exist. Which means you may not receive those.</p>\n\n<p>Bear in mind that getting past spam filters is an art. A number of isp\'s watch for duplicate messages, messages that <em>look</em> like spam based on keywords or other content, etc. This is sometimes independent of the quantity of messages sent; I\'ve seen messages with as few as 50 copies get blocked by AOL even though they were legitimate emails. So, testing is your friend and look into <a href="http://en.wikipedia.org/wiki/Anti-spam_techniques_(e-mail)" rel="nofollow noreferrer">this article on wikipedia</a> on anti-spam techniques. Then make sure your not doing that crap.</p>\n\n<p>**</p>\n\n<p>As far as processing the messages, just remember it\'s a queued system. Connect to the server via POP3 to retrieve messages, open it, do some action, delete the message or archive it, and move on.</p>\n\n<p>With regards to bouncebacks, let the mail server do most of the work. You should be able to configure it to notify a certain email account on the server in the event that it is unable to deliver a message. You can check that account periodically and process the Non Delivery Reports as necessary.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/322887/'] |
79,612 | <p>Looking for a <code>Linux application</code> <em>(or Firefox extension)</em> that will allow me to scrape an HTML mockup and keep the page's integrity.</p>
<p>Firefox does an almost perfect job but doesn't grab images referenced in the CSS.</p>
<p>The Scrapbook extension for Firefox gets everything, but flattens the directory structure. </p>
<p>I wouldn't terribly mind if all folders became children of the <code>index</code> page.</p>
| [{'answer_id': 79623, 'author': 'etchasketch', 'author_id': 14640, 'author_profile': 'https://Stackoverflow.com/users/14640', 'pm_score': 2, 'selected': False, 'text': '<p>Have you tried <a href="http://linuxreviews.org/quicktips/wget/" rel="nofollow noreferrer">wget?</a></p>\n'}, {'answer_id': 79642, 'author': 'X-Cubed', 'author_id': 10808, 'author_profile': 'https://Stackoverflow.com/users/10808', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.tenmax.com/teleport/pro/home.htm" rel="nofollow noreferrer">Teleport Pro</a> is great for this sort of thing. You can point it at complete websites and it will download a copy locally maintaining directory structure, and replacing absolute links with relative ones as necessary. You can also specify whether you want content from other third-party websites linked to from the original site.</p>\n'}, {'answer_id': 79645, 'author': 'Gilean', 'author_id': 6305, 'author_profile': 'https://Stackoverflow.com/users/6305', 'pm_score': 4, 'selected': True, 'text': '<p>See <a href="http://www.devarticles.com/c/a/Web-Services/Website-Mirroring-With-wget/1/" rel="noreferrer">Website Mirroring With wget</a></p>\n\n<pre><code>wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com\n</code></pre>\n'}, {'answer_id': 79657, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 1, 'selected': False, 'text': '<p><code>wget -r</code> does what you want, and if not, there are plenty of flags to configure it. See <code>man wget</code>.</p>\n\n<p>Another option is <code>curl</code>, which is even more powerful. See <a href="http://curl.haxx.se/" rel="nofollow noreferrer">http://curl.haxx.se/</a>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13320/'] |
79,632 | <p>I have a two tables joined with a join table - this is just pseudo code:</p>
<pre><code>Library
Book
LibraryBooks
</code></pre>
<p>What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.</p>
<p>So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?</p>
<p>I was thinking:</p>
<pre><code>l = Library.find(1)
allLibraries = l.books.libraries
</code></pre>
<p>But that doesn't seem to work. Suggestions?</p>
| [{'answer_id': 79646, 'author': 'Jim Puls', 'author_id': 6010, 'author_profile': 'https://Stackoverflow.com/users/6010', 'pm_score': 2, 'selected': False, 'text': '<p>Perhaps:</p>\n\n<pre><code>l.books.map {|b| b.libraries}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>l.books.map {|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>if you want it all in a flat array.</p>\n\n<p>Of course, you should really define this as a method on Library, so as to uphold the noble cause of encapsulation.</p>\n'}, {'answer_id': 79770, 'author': 'bouchard', 'author_id': 14843, 'author_profile': 'https://Stackoverflow.com/users/14843', 'pm_score': 2, 'selected': False, 'text': '<p>If you want a one-dimensional array of libraries returned, with duplicates removed.</p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n'}, {'answer_id': 81287, 'author': 'Ben Scofield', 'author_id': 6478, 'author_profile': 'https://Stackoverflow.com/users/6478', 'pm_score': 2, 'selected': False, 'text': "<p>One problem with </p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>is that it will generate one SQL call for each book in l. A better approach (assuming I understand your schema) might be:</p>\n\n<pre><code>LibraryBook.find(:all, :conditions => ['book_id IN (?)', l.book_ids]).map(&:library_id).uniq\n</code></pre>\n"}, {'answer_id': 81752, 'author': 'Ryan Bigg', 'author_id': 15245, 'author_profile': 'https://Stackoverflow.com/users/15245', 'pm_score': 4, 'selected': True, 'text': '<pre><code>l = Library.find(:all, :include => :books)\nl.books.map { |b| b.library_ids }.flatten.uniq\n</code></pre>\n\n<p>Note that <code>map(&:library_ids)</code> is slower than <code>map { |b| b.library_ids }</code> in Ruby 1.8.6, and faster in 1.9.0.</p>\n\n<p>I should also mention that if you used <code>:joins</code> instead of <code>include</code> there, it would find the library and related books all in the same query speeding up the database time. <code>:joins</code> will only work however if a library has books. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4322/'] |
79,658 | <p>A Java6 application sits in the system tray. It needs to be activated using a hotkey (e.g. Super-G or Ctrl-Shift-L etc) and do something (e.g. showing an input box).</p>
<h2>How do I do that on:</h2>
<ul>
<li>Windows (XP or Vista)</li>
<li>OS/X</li>
<li>Linux (Gnome or KDE)</li>
</ul>
| [{'answer_id': 79683, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 3, 'selected': False, 'text': '<p>It seems that this is not doable in a cross-platform fashion without using the native interfaces.</p>\n\n<p>On Windows, you can use the free <a href="http://melloware.com/products/jintellitype/index.html" rel="nofollow noreferrer">JIntellitype</a> library.</p>\n'}, {'answer_id': 202272, 'author': 'Torsten Uhlmann', 'author_id': 7143, 'author_profile': 'https://Stackoverflow.com/users/7143', 'pm_score': 3, 'selected': False, 'text': '<p>For Linux (X11) there is JXGrabKey: <a href="http://sourceforge.net/projects/jxgrabkey/" rel="noreferrer">http://sourceforge.net/projects/jxgrabkey/</a></p>\n\n<p>There is also a tutorial for grabbing a global hotkey on Linux: <a href="http://ubuntuforums.org/showthread.php?t=864566" rel="noreferrer">http://ubuntuforums.org/showthread.php?t=864566</a></p>\n\n<p>I didn\'t though find a solution for OS X yet.</p>\n\n<p>To build something for all 3 platforms I\'d suggest stripping down JIntellitype (it\'s Apache license) to it\'s global hotkey functionality and extending it with the OS X and X11 functionality...</p>\n'}, {'answer_id': 240741, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>If anyone wants to do the OSX or Linux versions of the JNI part of Jintellitype I would be more than happy to add those to the JIntellitype library.</p>\n\n<p>Melloware</p>\n\n<p><a href="http://www.melloware.com" rel="nofollow noreferrer">http://www.melloware.com</a></p>\n'}, {'answer_id': 6096179, 'author': 'cracked_all', 'author_id': 188524, 'author_profile': 'https://Stackoverflow.com/users/188524', 'pm_score': 1, 'selected': False, 'text': '<p>I found <a href="http://biletnikov-dev.blogspot.com/2009/09/global-hotkeys-for-java-applications_25.html" rel="nofollow">this</a> solution to work just great on windows. It does not require you to install any software like JIntelliType. Note that this is 32 bit dll and you can recompile for 64-bit JVM is do desire. All credits to original author of the blog.</p>\n'}, {'answer_id': 6422079, 'author': 'Denis Tulskiy', 'author_id': 143585, 'author_profile': 'https://Stackoverflow.com/users/143585', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve compiled a library for global hotkeys in java using JNA. It currently supports Windows, Linux and Mac OSX. It also supports media keys on windows and linux.</p>\n\n<p>if anyone is interested, try <a href="https://github.com/tulskiy/jkeymaster" rel="noreferrer">https://github.com/tulskiy/jkeymaster</a> </p>\n\n<p>I would appreciate any feedback.</p>\n\n<p>Thank you.</p>\n'}, {'answer_id': 65066501, 'author': 'vda8888', 'author_id': 1974520, 'author_profile': 'https://Stackoverflow.com/users/1974520', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ve written a Java library for global key/mouse events here. This works for Windows, Linux X11, and OSX.</p>\n<p><a href="https://github.com/repeats/SimpleNativeHooks" rel="nofollow noreferrer">https://github.com/repeats/SimpleNativeHooks</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
79,662 | <p>I've been having trouble to make a JFormattedTextField to use dates with the format dd/MM/yyyy. Specifically, as the user types, the cursor should "jump" the slashes, and get directly to the next number position.</p>
<p>Also, the JFormattedTextField must verify if the date entered is valid, and reject it somehow if the date is invalid, or "correct it" to a valid date, such as if the user input "13" as month, set it as "01" and add +1 to the year.</p>
<p>I tried using a mask ("##/##/####") with the validate() method of JFormattedTextField to check if the date is valid, but it appears that those two don't work well together (or I'm too green on Java to know how... :), and then the user can type anything on the field. </p>
<p>Any help is really appreciated! Thanks!</p>
| [{'answer_id': 79674, 'author': 'Gero', 'author_id': 13116, 'author_profile': 'https://Stackoverflow.com/users/13116', 'pm_score': 1, 'selected': False, 'text': '<p>try using JCalendar</p>\n'}, {'answer_id': 83024, 'author': 'Spyder', 'author_id': 7546, 'author_profile': 'https://Stackoverflow.com/users/7546', 'pm_score': 1, 'selected': True, 'text': '<p>You may have to use a regular JTextField and call setDocument() with a custom document. I recommend extending PlainDocument, this makes it easy to validate input as the document changes, and add slashes as appropriate. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14544/'] |
79,669 | <p>I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: </p>
<p>1) creating each destination database<br>
2) using the "<a href="http://msdn.microsoft.com/en-us/library/ms140052.aspx" rel="noreferrer">Tasks->Export Data</a>" command to create and populate tables for each database individually<br>
3) rebuilding all of the indexes for each database with a SQL script </p>
<p>Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?</p>
| [{'answer_id': 79673, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 2, 'selected': False, 'text': '<p>Backup -> Restore is the simplest, if not to use the replication.</p>\n'}, {'answer_id': 79679, 'author': 'X-Cubed', 'author_id': 10808, 'author_profile': 'https://Stackoverflow.com/users/10808', 'pm_score': 1, 'selected': False, 'text': '<p>Backup the databases using the standard SQL backup tool in Enterprise Manager, then when you restore on the second server you can specify the name of the new database.</p>\n\n<p>This is the best way to maintain the schema in its entirety.</p>\n'}, {'answer_id': 79682, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>use backups to restore the databases to the new server with the new names.</p>\n'}, {'answer_id': 79687, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Maybe the easiest is to detach/reattach. Right-click in the server manager on the DB, tasks --> detach. Then copy the MDF/LDF files to the new server and then reattach by clicking on the server icon and tasks-->attach. It will ask you for the MDF file - make sure the name etc is accurate.</p>\n'}, {'answer_id': 79691, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 7, 'selected': True, 'text': "<p>Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.</p>\n\n<p>This is a backup script that i keep around. \nGet it working for one file and then modify it for many.</p>\n\n<pre><code>(on source server...)\nBACKUP DATABASE Northwind\n TO DISK = 'c:\\Northwind.bak'\n\n(target server...)\nRESTORE FILELISTONLY\n FROM DISK = 'c:\\Northwind.bak'\n\n(look at the device names... and determine where you want the mdf and\nldf files to go on this target server)\n\nRESTORE DATABASE TestDB\n FROM DISK = 'c:\\Northwind.bak'\n WITH MOVE 'Northwind' TO 'c:\\test\\testdb.mdf',\n MOVE 'Northwind_log' TO 'c:\\test\\testdb.ldf'\nGO\n</code></pre>\n"}, {'answer_id': 79703, 'author': 'stephbu', 'author_id': 12702, 'author_profile': 'https://Stackoverflow.com/users/12702', 'pm_score': 2, 'selected': False, 'text': "<p>In order of ease</p>\n\n<ul>\n<li>stop server/fcopy/attach is probably easiest.</li>\n<li>backup/restore - can be done disconnected pretty simple and easy</li>\n<li>transfer DTS task - needs file copy permissions</li>\n<li>replication - furthest from simple to setup</li>\n</ul>\n\n<p>Things to think about permissions, users and groups at the destination server esp. if you're transferring or restoring.</p>\n"}, {'answer_id': 79715, 'author': 'Kevin Sheffield', 'author_id': 590, 'author_profile': 'https://Stackoverflow.com/users/590', 'pm_score': 0, 'selected': False, 'text': '<p>Redgate SQL Compare and SQL Data Compare. The Comparison Bundle was by far the best investment a company I worked for ever made. Moving e-training content was a breeze with it.</p>\n'}, {'answer_id': 80221, 'author': 'MotoWilliams', 'author_id': 2730, 'author_profile': 'https://Stackoverflow.com/users/2730', 'pm_score': 2, 'selected': False, 'text': '<p><strong><em>There are better answers already but this is an \'also ran\' because it is just another option.</em></strong></p>\n\n<p>For the low low price of free you could look at the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en" rel="nofollow noreferrer">Microsoft SQL Server Database Publishing Wizard</a>. This tool allows you to script the schema, data or data and schema. Plus is can be run from a UI or command line <- think CI process.</p>\n'}, {'answer_id': 82212, 'author': 'Mike L', 'author_id': 4796, 'author_profile': 'https://Stackoverflow.com/users/4796', 'pm_score': 2, 'selected': False, 'text': '<p>If you use the Backup/Restore solution you\'re likely to have orphaned users so be sure to check out <a href="http://technet.microsoft.com/en-us/library/ms175475.aspx" rel="nofollow noreferrer">this article</a><microsoft> on how to fix them.</p>\n'}, {'answer_id': 1064956, 'author': 'Yordan Georgiev', 'author_id': 65706, 'author_profile': 'https://Stackoverflow.com/users/65706', 'pm_score': 0, 'selected': False, 'text': '<p>Check those links:</p>\n\n<ul>\n<li><a href="http://ysgitdiary.blogspot.com/2009/06/backup-sql-server-2005-2008-databases.html" rel="nofollow noreferrer">For multiple db\'s backup</a></li>\n<li><a href="http://ysgitdiary.blogspot.com/2009/06/restore-db-from-file-on-sql-server-2005.html" rel="nofollow noreferrer">and single db restore</a></li>\n</ul>\n'}, {'answer_id': 1818024, 'author': 'Doug', 'author_id': 115749, 'author_profile': 'https://Stackoverflow.com/users/115749', 'pm_score': 2, 'selected': False, 'text': '<p>Another one to check out that is quick and simple:</p>\n\n<p>Simple SQL BULK Copy</p>\n\n<p><a href="http://projects.c3o.com/files/3/plugins/entry11.aspx" rel="nofollow noreferrer">http://projects.c3o.com/files/3/plugins/entry11.aspx</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13728/'] |
79,677 | <p>I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.</p>
<p>How I started was I changed floats to ints and whenever I needed to convert them, I used <strong>x>>8</strong> to convert the fixed-point variable x to the actual number and <strong>x<<8</strong> to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)</p>
<p>My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point?</p>
| [{'answer_id': 79700, 'author': 'jfm3', 'author_id': 11138, 'author_profile': 'https://Stackoverflow.com/users/11138', 'pm_score': 0, 'selected': False, 'text': "<p>Whichever way you decide to go (I'd lean toward a typedef and some CPP macros for converting), you will need to be careful to convert back and forth with some discipline.</p>\n\n<p>You might find that you never need to convert back and forth. Just imagine everything in the whole system is x256.</p>\n"}, {'answer_id': 79701, 'author': 'Bart', 'author_id': 4343, 'author_profile': 'https://Stackoverflow.com/users/4343', 'pm_score': 3, 'selected': False, 'text': '<p>Changing fixed point representations is commonly called \'scaling\'.</p>\n\n<p>If you can do this with a class with no performance penalty, then that\'s the way to go. It depends heavily on the compiler and how it inlines. If there is a performance penalty using classes, then you need a more traditional C-style approach. The OOP approach will give you compiler-enforced type safety which the traditional implementation only approximates.</p>\n\n<p>@cibyr has a good OOP implementation. Now for the more traditional one.</p>\n\n<p>To keep track of which variables are scaled, you need to use a consistent convention. Make a notation at the end of each variable name to indicate whether the value is scaled or not, and write macros SCALE() and UNSCALE() that expand to x>>8 and x<<8. </p>\n\n<pre><code>#define SCALE(x) (x>>8)\n#define UNSCALE(x) (x<<8)\n\nxPositionUnscaled = UNSCALE(10);\nxPositionScaled = SCALE(xPositionUnscaled);\n</code></pre>\n\n<p>It may seem like extra work to use so much notation, but notice how you can tell at a glance that any line is correct without looking at other lines. For example:</p>\n\n<pre><code>xPositionScaled = SCALE(xPositionScaled);\n</code></pre>\n\n<p>is obviously wrong, by inspection.</p>\n\n<p>This is a variation of the <strong>Apps Hungarian</strong> idea that <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow noreferrer">Joel mentions in this post</a>.</p>\n'}, {'answer_id': 79717, 'author': 'Ana Betts', 'author_id': 5728, 'author_profile': 'https://Stackoverflow.com/users/5728', 'pm_score': 3, 'selected': False, 'text': '<p>The original version of <a href="https://rads.stackoverflow.com/amzn/click/com/0672305070" rel="nofollow noreferrer" rel="nofollow noreferrer">Tricks of the Game Programming Gurus</a> has an entire chapter on implementing fixed-point math.</p>\n'}, {'answer_id': 79735, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 5, 'selected': False, 'text': '<p>In modern C++ implementations, there will be no performance penalty for using simple and lean abstractions, such as concrete classes. Fixed-point computation is <strong>precisely</strong> the place where using a properly engineered class will save you from lots of bugs.</p>\n\n<p>Therefore, <strong>you should write a FixedPoint8 class</strong>. Test and debug it thoroughly. If you have to convince yourself of its performance as compared to using plain integers, measure it.</p>\n\n<p>It will save you from many a trouble by moving the complexity of fixed-point calculation to a single place.</p>\n\n<p>If you like, you can further increase the utility of your class by making it a template and replacing the old <code>FixedPoint8</code> with, say, <code>typedef FixedPoint<short, 8> FixedPoint8;</code> But on your target architecture this is not probably necessary, so avoid the complexity of templates at first.</p>\n\n<p>There is probably a good fixed point class somewhere in the internet - I\'d start looking from the <a href="http://www.boost.org/" rel="noreferrer">Boost</a> libraries.</p>\n'}, {'answer_id': 79763, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre><code>template <int precision = 8> class FixedPoint {\nprivate:\n int val_;\npublic:\n inline FixedPoint(int val) : val_ (val << precision) {};\n inline operator int() { return val_ >> precision; }\n // Other operators...\n};\n</code></pre>\n'}, {'answer_id': 79771, 'author': 'paxdiablo', 'author_id': 14860, 'author_profile': 'https://Stackoverflow.com/users/14860', 'pm_score': 3, 'selected': False, 'text': "<p>I wouldn't use floating point at all on a CPU without special hardware for handling it. My advice is to treat ALL numbers as integers scaled to a specific factor. For example, all monetary values are in cents as integers rather than dollars as floats. For example, 0.72 is represented as the integer 72.</p>\n\n<p>Addition and subtraction are then a very simple integer operation such as (0.72 + 1 becomes 72 + 100 becomes 172 becomes 1.72).</p>\n\n<p>Multiplication is slightly more complex as it needs an integer multiply followed by a scale back such as (0.72 * 2 becomes 72 * 200 becomes 14400 becomes 144 (scaleback) becomes 1.44).</p>\n\n<p>That may require special functions for performing more complex math (sine, cosine, etc) but even those can be sped up by using lookup tables. Example: since you're using fixed-2 representation, there's only 100 values in the range (0.0,1] (0-99) and sin/cos repeat outside this range so you only need a 100-integer lookup table.</p>\n\n<p>Cheers,\nPax.</p>\n"}, {'answer_id': 79784, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Does your floating point code actually make use of the decimal point? If so:</p>\n\n<p>First you have to read Randy Yates\'s paper on Intro to Fixed Point Math:\n<a href="http://www.digitalsignallabs.com/fp.pdf" rel="noreferrer">http://www.digitalsignallabs.com/fp.pdf</a></p>\n\n<p>Then you need to do "profiling" on your floating point code to figure out the appropriate range of fixed-point values required at "critical" points in your code, e.g. U(5,3) = 5 bits to the left, 3 bits to the right, unsigned.</p>\n\n<p>At this point, you can apply the arithmetic rules in the paper mentioned above; the rules specify how to interpret the bits which result from arithmetic operations. You can write macros or functions to perform the operations.</p>\n\n<p>It\'s handy to keep the floating point version around, in order to compare the floating point vs fixed point results.</p>\n'}, {'answer_id': 79942, 'author': 'Evan Teran', 'author_id': 13430, 'author_profile': 'https://Stackoverflow.com/users/13430', 'pm_score': 6, 'selected': False, 'text': '<p>You can try my fixed point class (Latest available @ <a href="https://github.com/eteran/cpp-utilities" rel="noreferrer">https://github.com/eteran/cpp-utilities</a>)</p>\n\n<pre><code>// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h\n// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math\n/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2015 Evan Teran\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the "Software"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef FIXED_H_\n#define FIXED_H_\n\n#include <ostream>\n#include <exception>\n#include <cstddef> // for size_t\n#include <cstdint>\n#include <type_traits>\n\n#include <boost/operators.hpp>\n\nnamespace numeric {\n\ntemplate <size_t I, size_t F>\nclass Fixed;\n\nnamespace detail {\n\n// helper templates to make magic with types :)\n// these allow us to determine resonable types from\n// a desired size, they also let us infer the next largest type\n// from a type which is nice for the division op\ntemplate <size_t T>\nstruct type_from_size {\n static const bool is_specialized = false;\n typedef void value_type;\n};\n\n#if defined(__GNUC__) && defined(__x86_64__)\ntemplate <>\nstruct type_from_size<128> {\n static const bool is_specialized = true;\n static const size_t size = 128;\n typedef __int128 value_type;\n typedef unsigned __int128 unsigned_type;\n typedef __int128 signed_type;\n typedef type_from_size<256> next_size;\n};\n#endif\n\ntemplate <>\nstruct type_from_size<64> {\n static const bool is_specialized = true;\n static const size_t size = 64;\n typedef int64_t value_type;\n typedef uint64_t unsigned_type;\n typedef int64_t signed_type;\n typedef type_from_size<128> next_size;\n};\n\ntemplate <>\nstruct type_from_size<32> {\n static const bool is_specialized = true;\n static const size_t size = 32;\n typedef int32_t value_type;\n typedef uint32_t unsigned_type;\n typedef int32_t signed_type;\n typedef type_from_size<64> next_size;\n};\n\ntemplate <>\nstruct type_from_size<16> {\n static const bool is_specialized = true;\n static const size_t size = 16;\n typedef int16_t value_type;\n typedef uint16_t unsigned_type;\n typedef int16_t signed_type;\n typedef type_from_size<32> next_size;\n};\n\ntemplate <>\nstruct type_from_size<8> {\n static const bool is_specialized = true;\n static const size_t size = 8;\n typedef int8_t value_type;\n typedef uint8_t unsigned_type;\n typedef int8_t signed_type;\n typedef type_from_size<16> next_size;\n};\n\n// this is to assist in adding support for non-native base\n// types (for adding big-int support), this should be fine\n// unless your bit-int class doesn\'t nicely support casting\ntemplate <class B, class N>\nB next_to_base(const N& rhs) {\n return static_cast<B>(rhs);\n}\n\nstruct divide_by_zero : std::exception {\n};\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(numerator.to_raw());\n t <<= fractional_bits;\n\n Fixed<I,F> quotient;\n\n quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw()));\n remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw()));\n\n return quotient;\n}\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n // NOTE(eteran): division is broken for large types :-(\n // especially when dealing with negative quantities\n\n typedef typename Fixed<I,F>::base_type base_type;\n typedef typename Fixed<I,F>::unsigned_type unsigned_type;\n\n static const int bits = Fixed<I,F>::total_bits;\n\n if(denominator == 0) {\n throw divide_by_zero();\n } else {\n\n int sign = 0;\n\n Fixed<I,F> quotient;\n\n if(numerator < 0) {\n sign ^= 1;\n numerator = -numerator;\n }\n\n if(denominator < 0) {\n sign ^= 1;\n denominator = -denominator;\n }\n\n base_type n = numerator.to_raw();\n base_type d = denominator.to_raw();\n base_type x = 1;\n base_type answer = 0;\n\n // egyptian division algorithm\n while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {\n x <<= 1;\n d <<= 1;\n }\n\n while(x != 0) {\n if(n >= d) {\n n -= d;\n answer += x;\n }\n\n x >>= 1;\n d >>= 1;\n }\n\n unsigned_type l1 = n;\n unsigned_type l2 = denominator.to_raw();\n\n // calculate the lower bits (needs to be unsigned)\n // unfortunately for many fractions this overflows the type still :-/\n const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw();\n\n quotient = Fixed<I,F>::from_base((answer << F) | lo);\n remainder = n;\n\n if(sign) {\n quotient = -quotient;\n }\n\n return quotient;\n }\n}\n\n// this is the usual implementation of multiplication\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw()));\n t >>= fractional_bits;\n result = Fixed<I,F>::from_base(next_to_base<base_type>(t));\n}\n\n// this is the fall back version we use when we don\'t have a next size\n// it is slightly slower, but is more robust since it doesn\'t\n// require and upgraded type\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n static const size_t integer_mask = Fixed<I,F>::integer_mask;\n static const size_t fractional_mask = Fixed<I,F>::fractional_mask;\n\n // more costly but doesn\'t need a larger type\n const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type a_lo = (lhs.to_raw() & fractional_mask);\n const base_type b_lo = (rhs.to_raw() & fractional_mask);\n\n const base_type x1 = a_hi * b_hi;\n const base_type x2 = a_hi * b_lo;\n const base_type x3 = a_lo * b_hi;\n const base_type x4 = a_lo * b_lo;\n\n result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));\n\n}\n}\n\n/*\n * inheriting from boost::operators enables us to be a drop in replacement for base types\n * without having to specify all the different versions of operators manually\n */\ntemplate <size_t I, size_t F>\nclass Fixed : boost::operators<Fixed<I,F>> {\n static_assert(detail::type_from_size<I + F>::is_specialized, "invalid combination of sizes");\n\npublic:\n static const size_t fractional_bits = F;\n static const size_t integer_bits = I;\n static const size_t total_bits = I + F;\n\n typedef detail::type_from_size<total_bits> base_type_info;\n\n typedef typename base_type_info::value_type base_type;\n typedef typename base_type_info::next_size::value_type next_type;\n typedef typename base_type_info::unsigned_type unsigned_type;\n\npublic:\n static const size_t base_size = base_type_info::size;\n static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits);\n static const base_type integer_mask = ~fractional_mask;\n\npublic:\n static const base_type one = base_type(1) << fractional_bits;\n\npublic: // constructors\n Fixed() : data_(0) {\n }\n\n Fixed(long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(float n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(double n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(const Fixed &o) : data_(o.data_) {\n }\n\n Fixed& operator=(const Fixed &o) {\n data_ = o.data_;\n return *this;\n }\n\nprivate:\n // this makes it simpler to create a fixed point object from\n // a native type without scaling\n // use "Fixed::from_base" in order to perform this.\n struct NoScale {};\n\n Fixed(base_type n, const NoScale &) : data_(n) {\n }\n\npublic:\n static Fixed from_base(base_type n) {\n return Fixed(n, NoScale());\n }\n\npublic: // comparison operators\n bool operator==(const Fixed &o) const {\n return data_ == o.data_;\n }\n\n bool operator<(const Fixed &o) const {\n return data_ < o.data_;\n }\n\npublic: // unary operators\n bool operator!() const {\n return !data_;\n }\n\n Fixed operator~() const {\n Fixed t(*this);\n t.data_ = ~t.data_;\n return t;\n }\n\n Fixed operator-() const {\n Fixed t(*this);\n t.data_ = -t.data_;\n return t;\n }\n\n Fixed operator+() const {\n return *this;\n }\n\n Fixed& operator++() {\n data_ += one;\n return *this;\n }\n\n Fixed& operator--() {\n data_ -= one;\n return *this;\n }\n\npublic: // basic math operators\n Fixed& operator+=(const Fixed &n) {\n data_ += n.data_;\n return *this;\n }\n\n Fixed& operator-=(const Fixed &n) {\n data_ -= n.data_;\n return *this;\n }\n\n Fixed& operator&=(const Fixed &n) {\n data_ &= n.data_;\n return *this;\n }\n\n Fixed& operator|=(const Fixed &n) {\n data_ |= n.data_;\n return *this;\n }\n\n Fixed& operator^=(const Fixed &n) {\n data_ ^= n.data_;\n return *this;\n }\n\n Fixed& operator*=(const Fixed &n) {\n detail::multiply(*this, n, *this);\n return *this;\n }\n\n Fixed& operator/=(const Fixed &n) {\n Fixed temp;\n *this = detail::divide(*this, n, temp);\n return *this;\n }\n\n Fixed& operator>>=(const Fixed &n) {\n data_ >>= n.to_int();\n return *this;\n }\n\n Fixed& operator<<=(const Fixed &n) {\n data_ <<= n.to_int();\n return *this;\n }\n\npublic: // conversion to basic types\n int to_int() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n unsigned int to_uint() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n float to_float() const {\n return static_cast<float>(data_) / Fixed::one;\n }\n\n double to_double() const {\n return static_cast<double>(data_) / Fixed::one;\n }\n\n base_type to_raw() const {\n return data_;\n }\n\npublic:\n void swap(Fixed &rhs) {\n using std::swap;\n swap(data_, rhs.data_);\n }\n\npublic:\n base_type data_;\n};\n\n// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l + r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l - r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l * r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l / r;\n}\n\ntemplate <size_t I, size_t F>\nstd::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) {\n os << f.to_double();\n return os;\n}\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::fractional_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::integer_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::total_bits;\n\n}\n\n#endif\n</code></pre>\n\n<p>It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency).</p>\n\n<p>BTW, common usage could be something like this:</p>\n\n<pre><code>using namespace numeric;\ntypedef Fixed<16, 16> fixed;\nfixed f;\n</code></pre>\n\n<p>The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64.</p>\n'}, {'answer_id': 80281, 'author': 'ryan_s', 'author_id': 13728, 'author_profile': 'https://Stackoverflow.com/users/13728', 'pm_score': 3, 'selected': False, 'text': '<p>When I first encountered fixed point numbers I found Joe Lemieux\'s article, <a href="http://www.embedded.com/columns/15201575?_requestid=65598" rel="noreferrer">Fixed-point Math in C</a>, very helpful, and it does suggest one way of representing fixed-point values.</p>\n\n<p>I didn\'t wind up using his union representation for fixed-point numbers though. I mostly have experience with fixed-point in C, so I haven\'t had the option to use a class either. For the most part though, I think that defining your number of fraction bits in a macro and using descriptive variable names makes this fairly easy to work with. Also, I\'ve found that it is best to have macros or functions for multiplication and especially division, or you quickly get unreadable code.</p>\n\n<p>For example, with 24.8 values:</p>\n\n<pre><code> #include "stdio.h"\n\n/* Declarations for fixed point stuff */\n\ntypedef int int_fixed;\n\n#define FRACT_BITS 8\n#define FIXED_POINT_ONE (1 << FRACT_BITS)\n#define MAKE_INT_FIXED(x) ((x) << FRACT_BITS)\n#define MAKE_FLOAT_FIXED(x) ((int_fixed)((x) * FIXED_POINT_ONE))\n#define MAKE_FIXED_INT(x) ((x) >> FRACT_BITS)\n#define MAKE_FIXED_FLOAT(x) (((float)(x)) / FIXED_POINT_ONE)\n\n#define FIXED_MULT(x, y) ((x)*(y) >> FRACT_BITS)\n#define FIXED_DIV(x, y) (((x)<<FRACT_BITS) / (y))\n\n/* tests */\nint main()\n{\n int_fixed fixed_x = MAKE_FLOAT_FIXED( 4.5f );\n int_fixed fixed_y = MAKE_INT_FIXED( 2 );\n\n int_fixed fixed_result = FIXED_MULT( fixed_x, fixed_y );\n printf( "%.1f\\n", MAKE_FIXED_FLOAT( fixed_result ) );\n\n fixed_result = FIXED_DIV( fixed_result, fixed_y );\n printf( "%.1f\\n", MAKE_FIXED_FLOAT( fixed_result ) );\n\n return 0;\n}\n</code></pre>\n\n<p>Which writes out </p>\n\n<pre>\n9.0\n4.5\n</pre>\n\n<p>Note that there are all kinds of integer overflow issues with those macros, I just wanted to keep the macros simple. This is just a quick and dirty example of how I\'ve done this in C. In C++ you could make something a lot cleaner using operator overloading. Actually, you could easily make that C code a lot prettier too...</p>\n\n<p>I guess this is a long-winded way of saying: I think it\'s OK to use a typedef and macro approach. So long as you\'re clear about what variables contain fixed point values it isn\'t too hard to maintain, but it probably won\'t be as pretty as a C++ class. </p>\n\n<p>If I was in your position, I would try to get some profiling numbers to show where the bottlenecks are. If there are relatively few of them then go with a typedef and macros. If you decide that you need a global replacement of all floats with fixed-point math though, then you\'ll probably be better off with a class.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813/'] |
79,688 | <p>What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?</p>
<p>I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:</p>
<pre><code>Group MinScore MaxScore AvgScore pct25 median pct75
----- -------- -------- -------- ----- ------ -----
T1 52 96 74 68 76 84
T2 48 98 74 68 75 85
</code></pre>
| [{'answer_id': 79758, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>i'd probably use a the sql server 2005 </p>\n\n<blockquote>\n <p>row_number() over (order by score ) / (select count(*) from scores)</p>\n</blockquote>\n\n<p>or something along those lines. </p>\n"}, {'answer_id': 79766, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>i'd do something like:</p>\n\n<pre><code>select @n = count(*) from tbl1\nselect @median = @n / 2\nselect @p75 = @n * 3 / 4\nselect @p90 = @n * 9 / 10\n\nselect top 1 score from (select top @median score from tbl1 order by score asc) order by score desc\n</code></pre>\n\n<p>is this right?</p>\n"}, {'answer_id': 79990, 'author': 'Matt', 'author_id': 4154, 'author_profile': 'https://Stackoverflow.com/users/4154', 'pm_score': 4, 'selected': False, 'text': '<p>I would think that this would be the simplest solution:</p>\n\n<pre><code>SELECT TOP N PERCENT FROM TheTable ORDER BY TheScore DESC\n</code></pre>\n\n<p>Where N = (100 - desired percentile). So if you wanted all rows in the 90th percentile, you\'d select the top 10%.</p>\n\n<p>I\'m not sure what you mean by "preferably in a single record". Do you mean calculate which percentile a given score for a single record would fall into? e.g. do you want to be able to make statements like "your score is 83, which puts you in the 91st percentile." ?</p>\n\n<p>EDIT: OK, I thought some more about your question and came up with this interpretation. Are you asking how to calculate the cutoff score for a particular percentile? e.g. something like this: to be in the 90th percentile you must have a score greater than 78.</p>\n\n<p>If so, this query works. I dislike sub-queries though, so depending on what it was for, I\'d probably try to find a more elegant solution. It does, however, return a single record with a single score.</p>\n\n<pre><code>-- Find the minimum score for all scores in the 90th percentile\nSELECT Min(subq.TheScore) FROM\n(SELECT TOP 10 PERCENT TheScore FROM TheTable\nORDER BY TheScore DESC) AS subq\n</code></pre>\n'}, {'answer_id': 342502, 'author': 'Soldarnal', 'author_id': 3420, 'author_profile': 'https://Stackoverflow.com/users/3420', 'pm_score': 1, 'selected': False, 'text': "<p>I've been working on this a little more, and here's what I've come up with so far:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[TestGetPercentile]\n\n@percentile as float,\n@resultval as float output\n\nAS\n\nBEGIN\n\nWITH scores(score, prev_rank, curr_rank, next_rank) AS (\n SELECT dblScore,\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) - 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [prev_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 0.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [curr_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [next_rank]\n FROM TestScores\n)\n\nSELECT @resultval = (\n SELECT TOP 1 \n CASE WHEN t1.score = t2.score\n THEN t1.score\n ELSE\n t1.score + (t2.score - t1.score) * ((@percentile - t1.curr_rank) / (t2.curr_rank - t1.curr_rank))\n END\n FROM scores t1, scores t2\n WHERE (t1.curr_rank = @percentile OR (t1.curr_rank < @percentile AND t1.next_rank > @percentile))\n AND (t2.curr_rank = @percentile OR (t2.curr_rank > @percentile AND t2.prev_rank < @percentile))\n)\n\nEND\n</code></pre>\n\n<p>Then in another stored procedure I do this:</p>\n\n<pre><code>DECLARE @pct25 float;\nDECLARE @pct50 float;\nDECLARE @pct75 float;\n\nexec SurveyGetPercentile .25, @pct25 output\nexec SurveyGetPercentile .50, @pct50 output\nexec SurveyGetPercentile .75, @pct75 output\n\nSelect\n min(dblScore) as minScore,\n max(dblScore) as maxScore,\n avg(dblScore) as avgScore,\n @pct25 as percentile25,\n @pct50 as percentile50,\n @pct75 as percentile75\nFrom TestScores\n</code></pre>\n\n<p>It still doesn't do quite what I'm looking for. This will get the stats for all tests; whereas I would like to be able to select from a TestScores table that has multiple different tests in it and get back the same stats for each different test (like I have in my example table in my question).</p>\n"}, {'answer_id': 6504968, 'author': 'Kay Aliu', 'author_id': 818956, 'author_profile': 'https://Stackoverflow.com/users/818956', 'pm_score': 1, 'selected': False, 'text': '<p>The 50th percentile is same as the median. When computing other percentile, say the 80th, sort the data for the 80 percent of data in ascending order and the other 20 percent in descending order, and take the avg of the two middle value.</p>\n\n<p>NB: The median query has been around for a long time, but cannot remember where exactly I got it from, I have only amended it to compute other percentiles.</p>\n\n<pre><code>DECLARE @Temp TABLE(Id INT IDENTITY(1,1), DATA DECIMAL(10,5))\n\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(2)\nINSERT INTO @Temp VALUES(8)\nINSERT INTO @Temp VALUES(4)\nINSERT INTO @Temp VALUES(3)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6) \nINSERT INTO @Temp VALUES(7)\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(1)\nINSERT INTO @Temp VALUES(NULL)\n\n\n--50th percentile or median\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--90th percentile \nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 90 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 10 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--75th percentile\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 75 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 25 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n</code></pre>\n'}, {'answer_id': 6512841, 'author': 'Elizabeth', 'author_id': 819953, 'author_profile': 'https://Stackoverflow.com/users/819953', 'pm_score': 3, 'selected': False, 'text': '<p>Check out the NTILE command -- it will give you percentiles pretty easily!</p>\n\n<pre><code>SELECT SalesOrderID, \n OrderQty,\n RowNum = Row_Number() OVER(Order By OrderQty),\n Rnk = RANK() OVER(ORDER BY OrderQty),\n DenseRnk = DENSE_RANK() OVER(ORDER BY OrderQty),\n NTile4 = NTILE(4) OVER(ORDER BY OrderQty)\nFROM Sales.SalesOrderDetail \nWHERE SalesOrderID IN (43689, 63181)\n</code></pre>\n'}, {'answer_id': 12291090, 'author': 'Paul', 'author_id': 1650451, 'author_profile': 'https://Stackoverflow.com/users/1650451', 'pm_score': 2, 'selected': False, 'text': '<p>How about this:</p>\n\n<pre><code>SELECT\n Group,\n 75_percentile = MAX(case when NTILE(4) OVER(ORDER BY score ASC) = 3 then score else 0 end),\n 90_percentile = MAX(case when NTILE(10) OVER(ORDER BY score ASC) = 9 then score else 0 end) \nFROM TheScore\nGROUP BY Group\n</code></pre>\n'}, {'answer_id': 55066450, 'author': 'Debasmita', 'author_id': 7025084, 'author_profile': 'https://Stackoverflow.com/users/7025084', 'pm_score': 0, 'selected': False, 'text': '<p>Percentile is calculated by </p>\n\n<p><code>(Rank -1) /(total_rows -1)</code> when you sort values in ascending order. </p>\n\n<p>The below query will give you percentile value between 0 and 1. Person with lowest marks will have 0 percentile.</p>\n\n<pre><code>SELECT Name, marks, (rank_1-1)/((select count(*) as total_1 from table)-1)as percentile_rank\nfrom\n(\nSELECT Name,\n Marks,\n RANK() OVER (ORDER BY Marks) AS rank_1\n from table\n) as A\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3420/'] |
79,693 | <p>How do you get all the classes in a namespace through reflection in C#?</p>
| [{'answer_id': 79706, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 5, 'selected': False, 'text': "<pre><code>using System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic List<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n\n List<string> namespacelist = new List<string>();\n List<string> classlist = new List<string>();\n\n foreach (Type type in asm.GetTypes())\n {\n if (type.Namespace == nameSpace)\n namespacelist.Add(type.Name);\n }\n\n foreach (string classname in namespacelist)\n classlist.Add(classname);\n\n return classlist;\n}\n</code></pre>\n\n<p>NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:</p>\n\n<pre><code>using System.Linq;\nusing System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic IEnumerable<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n return asm.GetTypes()\n .Where(type => type.Namespace == nameSpace)\n .Select(type => type.Name);\n}\n</code></pre>\n"}, {'answer_id': 79712, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 3, 'selected': False, 'text': "<p>You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.</p>\n\n<p><code>Assembly.GetTypes()</code> works on the local assembly, or you can load an assembly first then call <code>GetTypes()</code> on it.</p>\n"}, {'answer_id': 79738, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 8, 'selected': False, 'text': '<p>Following code prints names of classes in specified <code>namespace</code> defined in current assembly.<br>\nAs other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.</p>\n\n<pre><code>string nspace = "...";\n\nvar q = from t in Assembly.GetExecutingAssembly().GetTypes()\n where t.IsClass && t.Namespace == nspace\n select t;\nq.ToList().ForEach(t => Console.WriteLine(t.Name));\n</code></pre>\n'}, {'answer_id': 79785, 'author': 'TheXenocide', 'author_id': 8543, 'author_profile': 'https://Stackoverflow.com/users/8543', 'pm_score': 2, 'selected': False, 'text': '<p>Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.<a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx" rel="nofollow noreferrer">GetExportedTypes()</a> checking the value of type.<a href="http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx" rel="nofollow noreferrer">Namespace</a>. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.<a href="http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx" rel="nofollow noreferrer">GetAssemblies()</a></p>\n'}, {'answer_id': 79793, 'author': 'tsimon', 'author_id': 1685, 'author_profile': 'https://Stackoverflow.com/users/1685', 'pm_score': 4, 'selected': False, 'text': "<p>Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:</p>\n\n<pre><code>// Setup event handler to resolve assemblies\nAppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);\n\nAssembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);\na.GetTypes();\n// process types here\n\n// method later in the class:\nstatic Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)\n{\n return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);\n}\n</code></pre>\n\n<p>That should help with loading types defined in other assemblies.</p>\n\n<p>Hope that helps!</p>\n"}, {'answer_id': 762978, 'author': 'Yordan Georgiev', 'author_id': 65706, 'author_profile': 'https://Stackoverflow.com/users/65706', 'pm_score': 2, 'selected': False, 'text': '<pre><code>//a simple combined code snippet \n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace MustHaveAttributes\n{\n class Program\n {\n static void Main ( string[] args )\n {\n Console.WriteLine ( " START " );\n\n // what is in the assembly\n Assembly a = Assembly.Load ( "MustHaveAttributes" );\n Type[] types = a.GetTypes ();\n foreach (Type t in types)\n {\n\n Console.WriteLine ( "Type is {0}", t );\n }\n Console.WriteLine (\n "{0} types found", types.Length );\n\n #region Linq\n //#region Action\n\n\n //string @namespace = "MustHaveAttributes";\n\n //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()\n // where t.IsClass && t.Namespace == @namespace\n // select t;\n //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );\n\n\n //#endregion Action \n #endregion\n\n Console.ReadLine ();\n Console.WriteLine ( " HIT A KEY TO EXIT " );\n Console.WriteLine ( " END " );\n }\n } //eof Program\n\n\n class ClassOne\n {\n\n } //eof class \n\n class ClassTwo\n {\n\n } //eof class\n\n\n [System.AttributeUsage ( System.AttributeTargets.Class |\n System.AttributeTargets.Struct, AllowMultiple = true )]\n public class AttributeClass : System.Attribute\n {\n\n public string MustHaveDescription { get; set; }\n public string MusHaveVersion { get; set; }\n\n\n public AttributeClass ( string mustHaveDescription, string mustHaveVersion )\n {\n MustHaveDescription = mustHaveDescription;\n MusHaveVersion = mustHaveVersion;\n }\n\n } //eof class \n\n} //eof namespace \n</code></pre>\n'}, {'answer_id': 14234375, 'author': 'JoanComasFdz', 'author_id': 383129, 'author_profile': 'https://Stackoverflow.com/users/383129', 'pm_score': 3, 'selected': False, 'text': '<p>Just like @aku answer, but using extension methods:</p>\n\n<pre><code>string @namespace = "...";\n\nvar types = Assembly.GetExecutingAssembly().GetTypes()\n .Where(t => t.IsClass && t.Namespace == @namespace)\n .ToList();\n\ntypes.ForEach(t => Console.WriteLine(t.Name));\n</code></pre>\n'}, {'answer_id': 16504427, 'author': 'nawfal', 'author_id': 661933, 'author_profile': 'https://Stackoverflow.com/users/661933', 'pm_score': 7, 'selected': False, 'text': '<p>As FlySwat says, you can have the same namespace spanning in multiple assemblies (for eg <code>System.Collections.Generic</code>). You will have to load all those assemblies if they are not already loaded. So for a complete answer:</p>\n\n<pre><code>AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(t => t.GetTypes())\n .Where(t => t.IsClass && t.Namespace == @namespace)\n</code></pre>\n\n<p>This should work unless you want classes of other domains. To get a list of all domains, follow <a href="https://stackoverflow.com/questions/388554/list-appdomains-in-process">this link.</a></p>\n'}, {'answer_id': 27598813, 'author': 'Ivo Stoyanov', 'author_id': 2298241, 'author_profile': 'https://Stackoverflow.com/users/2298241', 'pm_score': 3, 'selected': False, 'text': '<p>Get all classes by part of Namespace name in just one row:</p>\n\n<pre><code>var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"..your namespace...")).ToList();\n</code></pre>\n'}, {'answer_id': 34869091, 'author': 'JWP', 'author_id': 1522548, 'author_profile': 'https://Stackoverflow.com/users/1522548', 'pm_score': 5, 'selected': False, 'text': '<p>For a specific Assembly, NameSpace and ClassName:</p>\n\n<pre><code>var assemblyName = "Some.Assembly.Name"\nvar nameSpace = "Some.Namespace.Name";\nvar className = "ClassNameFilter";\n\nvar asm = Assembly.Load(assemblyName);\nvar classes = asm.GetTypes().Where(p =>\n p.Namespace == nameSpace &&\n p.Name.Contains(className) \n).ToList();\n</code></pre>\n\n<p>Note: The project must reference the assembly</p>\n'}, {'answer_id': 35707879, 'author': 'Antonio Lopes', 'author_id': 4837664, 'author_profile': 'https://Stackoverflow.com/users/4837664', 'pm_score': 0, 'selected': False, 'text': '<p>Quite simple</p>\n\n<pre><code>Type[] types = Assembly.Load(new AssemblyName("mynamespace.folder")).GetTypes();\nforeach (var item in types)\n{\n}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
79,709 | <p>I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.</p>
<pre><code>for (dataset in list_of_datasets) {
for (datachunk in dataset) {
<process datachunk>
<store result? as vector? where?>
}
}
</code></pre>
<p>I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?</p>
<p>Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination.</p>
| [{'answer_id': 79741, 'author': 'Jeffrey', 'author_id': 3259, 'author_profile': 'https://Stackoverflow.com/users/3259', 'pm_score': -1, 'selected': False, 'text': "<p>It's tough to say definitively without knowing the language/compiler used. However, if you can simply pass a pointer/reference to the object that you're creating, then the size of the object itself has nothing to do with the speed of the function calls. Manipulating this data down the road could be a different story.</p>\n"}, {'answer_id': 79768, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 3, 'selected': False, 'text': '<p>use variables in the outer function instead of global variables. This gets you the best of both approaches: you\'re not mutating global state, and you\'re not copying a big wad of data. If you have to exit early, just return the partial results.</p>\n\n<p>(See the "Scope" section in the R manual: <a href="http://cran.r-project.org/doc/manuals/R-intro.html#Scope" rel="noreferrer">http://cran.r-project.org/doc/manuals/R-intro.html#Scope</a>)</p>\n'}, {'answer_id': 79779, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 0, 'selected': False, 'text': "<p>Third approach: inner function returns a reference to the large array, which the next statement inside the loop then dereferences and stores wherever it's needed (ideally with a single pointer store and not by having to memcopy the entire array).</p>\n\n<p>This gets rid of both the side effect and the passing of large datastructures.</p>\n"}, {'answer_id': 79788, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>It's not going to make much difference to memory use, so you might as well make the code clean.</p>\n\n<p>Since R has copy-on-modify for variables, modifying the global object will have the same memory implications as passing something up in return values.</p>\n\n<p>If you store the outputs in a database (or even in a file) you won't have the memory use issues, and the data will be incrementally available as it is created, rather than just at the end. Whether it's faster with the database depends primarily on how much memory you are using: is the reduction is garbage collection going to pay for the cost of writing to disk.</p>\n\n<p>There are both time and memory profilers in R, so you can see empirically what the impacts are.</p>\n"}, {'answer_id': 79827, 'author': 'leif', 'author_id': 14257, 'author_profile': 'https://Stackoverflow.com/users/14257', 'pm_score': 1, 'selected': False, 'text': "<p>I'm not sure I understand the question, but I have a couple of solutions.</p>\n\n<ol>\n<li><p>Inside the function, create a list of the vectors and return that.</p></li>\n<li><p>Inside the function, create an environment and store all the vectors inside of that. Just make sure that you return the environment in case of errors.</p></li>\n</ol>\n\n<p>in R:</p>\n\n<pre><code>help(environment)\n\n# You might do something like this:\n\nouter <- function(datasets) {\n # create the return environment\n ret.env <- new.env()\n for(set in dataset) {\n tmp <- inner(set)\n # check for errors however you like here. You might have inner return a list, and\n # have the list contain an error component\n assign(set, tmp, envir=ret.env)\n }\n return(ret.env)\n}\n\n#The inner function might be defined like this\n\ninner <- function(dataset) {\n # I don't know what you are doing here, but lets pretend you are reading a data file\n # that is named by dataset\n filedata <- read.table(dataset, header=T)\n return(filedata)\n}\n</code></pre>\n\n<p>leif</p>\n"}, {'answer_id': 79893, 'author': 'Rob Hansen', 'author_id': 14928, 'author_profile': 'https://Stackoverflow.com/users/14928', 'pm_score': 3, 'selected': False, 'text': '<p>Remember your Knuth. "Premature optimization is the root of all programming evil."</p>\n\n<p>Try the side effect free version. See if it meets your performance goals. If it does, great, you don\'t have a problem in the first place; if it doesn\'t, then use the side effects, and make a note for the next programmer that your hand was forced.</p>\n'}, {'answer_id': 86804, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>FYI, here\'s a full sample toy solution that avoids side effects:</p>\n\n<pre><code>outerfunc <- function(names) {\n templist <- list()\n for (aname in names) {\n templist[[aname]] <- innerfunc(aname)\n }\n templist\n}\n\ninnerfunc <- function(aname) {\n retval <- NULL\n if ("one" %in% aname) retval <- c(1)\n if ("two" %in% aname) retval <- c(1,2)\n if ("three" %in% aname) retval <- c(1,2,3)\n retval\n}\n\nnames <- c("one","two","three")\n\nname_vals <- outerfunc(names)\n\nfor (name in names) assign(name, name_vals[[name]])\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
79,727 | <p>In the vxWorks RTOS, there is a shell that allows you to issue command to your embedded system.<br>
The documentation refers to kernel shell, host shell and target shell. What is the difference between the three?</p>
| [{'answer_id': 88771, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 4, 'selected': True, 'text': '<p>The target shell and kernel shell are the same. They refer to a shell that runs on the target. You can connect to the shell using either a serial port, or a telnet session.\nA task runs on the target and parses all the commands received and acts on them, outputting data back to the port.</p>\n\n<p>The host shell is a process that runs on the development station. It communicates with the debug agent on the target. All the commands are actually parsed on the host and only simplified requests are sent to the target agent:</p>\n\n<ul>\n<li>Read/Write Memory</li>\n<li>Set/Remove Breakpoints</li>\n<li>Create/Delete/Suspend/Resume Tasks</li>\n<li>Invoke a function</li>\n</ul>\n\n<p>This results in less real-time impact to the target.</p>\n\n<p>Both shells allow the user to perform low level debugging (dissassembly, breakpoints, etc..) and invoke functions on the target.</p>\n'}, {'answer_id': 385438, 'author': 'zhongshu', 'author_id': 47936, 'author_profile': 'https://Stackoverflow.com/users/47936', 'pm_score': 0, 'selected': False, 'text': '<p>There are some differences between host shell and target shell, you can use h command to get the actual commands the two shell support.</p>\n\n<p>The host shell support more command line edit functions like auto complement and symbol lookup etc.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10703/'] |
79,736 | <p>This is my first real question of need for any of those Gridview experts out there in the .NET world.</p>
<p>I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns. Although, I do add the comma in the number fields from codebehind. When I load it to the Gridview, I have the sorting ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.</p>
<p>So I need help. Anyone willing to give this one a shot? I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.</p>
| [{'answer_id': 79835, 'author': 'tsimon', 'author_id': 1685, 'author_profile': 'https://Stackoverflow.com/users/1685', 'pm_score': 1, 'selected': False, 'text': '<p>If you do end up implementing your own comparer and sorting them as strings, the algorithm for treating numbers \'properly\' is called Natural Sorting. Jeff wrote a pretty good entry on it here:<br>\n<a href="https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow noreferrer">Sorting for Humans : Natural Sort Order</a></p>\n\n<p>You can find a pretty good implementation in C# here:<br>\n<a href="http://www.codeproject.com/KB/string/NaturalSortComparer.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/string/NaturalSortComparer.aspx</a></p>\n'}, {'answer_id': 80367, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': '<p>Depending on exactly how you are doing sorting you could use one of the above methods, or you could return to the DB and get the sorting done there if the columns are actually a number type, then add your decoration to it later.</p>\n'}, {'answer_id': 97441, 'author': 'TonyOssa', 'author_id': 3276, 'author_profile': 'https://Stackoverflow.com/users/3276', 'pm_score': 0, 'selected': False, 'text': '<p>P-Invoke is your friend.</p>\n\n<pre><code>[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]\nprivate static extern int StrCmpLogicalW(string psz1, string psz2);\n</code></pre>\n\n<p>Then you could use it as your own comparer.</p>\n\n<p>For example (in VS2005),</p>\n\n<pre><code>Array.Sort(tringArray, delegate(string left, string right)\n{\n return StrCmpLogicalW(left, right);\n});\n</code></pre>\n'}, {'answer_id': 668269, 'author': 'SpoiledTechie.com', 'author_id': 7644, 'author_profile': 'https://Stackoverflow.com/users/7644', 'pm_score': 1, 'selected': True, 'text': '<p>Instead, I just resorted to the JQUERY Table Sorter.</p>\n\n<p>can be found here: <a href="http://tablesorter.com/docs/" rel="nofollow noreferrer">tablesorter</a></p>\n'}, {'answer_id': 9037720, 'author': 'Naikrovek', 'author_id': 137427, 'author_profile': 'https://Stackoverflow.com/users/137427', 'pm_score': 0, 'selected': False, 'text': "<p>I realize this is really old, but you're mixing data with presentation; that's what's screwing up the sort. Get the number out of SQL without adding commas, then add them in the presentation layer.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7644/'] |
79,737 | <p>This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.</p>
<p>HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.</p>
<p>In any case, what's the best way to export bug tracking data from hosted HP Quality Center?</p>
| [{'answer_id': 80813, 'author': 'granth', 'author_id': 11210, 'author_profile': 'https://Stackoverflow.com/users/11210', 'pm_score': 4, 'selected': True, 'text': '<p>You can use this QC API Code to modify bugs/requirements.</p>\n\n<pre><code>TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection(); \nconnection.InitConnectionEx("http://SERVER:8080/qcbin"); \nconnection.Login("USERNAME", "PASSWORD"); \nconnection.Connect("QCDOMAIN", "QCPROJECT"); \nTDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory; \nTDAPIOLELib.List bugList = bugFactory.NewList(""); \nforeach (TDAPIOLELib.Bug bug in bugList) \n{ \n // View / Modify the properties \n // bug.ID, bug.Name, etc. \n // Save them when done \n // bug.Post(); \n}\n</code></pre>\n'}, {'answer_id': 217898, 'author': 'JonnyGold', 'author_id': 2665, 'author_profile': 'https://Stackoverflow.com/users/2665', 'pm_score': 1, 'selected': False, 'text': "<p>Personally, I like the COM API and I use it to generate both Word and Excel reports. I have done some experiments with VS2005 and the results are encouraging.</p>\n\n<p>If you don't want to go this route, I have a couple of suggestions.</p>\n\n<ol>\n<li>If you use the charting options (Analysis > Graphs). Each graph has a tab called data grid that lets you export data to Excel and a bunch of other data formats.</li>\n<li>If you are an admin, or friendely with your admin, you can dump the whole database into access and then import into Excel. Of course, you'll loose all your table relationships, but it's better than nothing. It's also a really good way to learn the db schema.</li>\n</ol>\n"}, {'answer_id': 217944, 'author': 'Tobias Kunze', 'author_id': 6070, 'author_profile': 'https://Stackoverflow.com/users/6070', 'pm_score': 0, 'selected': False, 'text': '<p>If manual export (i.e., not using a program) is possible for you, the following will be the easiest way to export defect data.</p>\n\n<p>In QC 9.2 (maybe present in earlier versions, too), there is <code>Export/All</code> in the <code>Defects</code> menu, which exports defects in your defects grid into an Excel sheet.</p>\n\n<p>The fields exported are those shown in the defects grid, which can be customized using the "Select Columns" button (looks like a green grid).</p>\n'}, {'answer_id': 425057, 'author': 'LiorH', 'author_id': 52954, 'author_profile': 'https://Stackoverflow.com/users/52954', 'pm_score': 1, 'selected': False, 'text': "<p>Unfortunately QC doesn't expose any web-services at the moment.\nI think the easiest way would be to query the DB directly. The data you are looking for is in the project's schema in BUG table.</p>\n\n<p>QC also have an excel add-in you might want to try that, but it's mainly for adding defects from excel to QC.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3048/'] |
79,745 | <p>We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.</p>
| [{'answer_id': 79801, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 0, 'selected': False, 'text': '<p>According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \\Samples\\Multimedia\\DXMisc\\GetDXVer.</p>\n'}, {'answer_id': 79817, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': True, 'text': '<p>Call DirectXSetupGetVersion: <a href="http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion</a></p>\n\n<p>You\'ll need to include dsetup.h</p>\n\n<p>Here\'s the sample code from the site:</p>\n\n<pre><code>DWORD dwVersion;\nDWORD dwRevision;\nif (DirectXSetupGetVersion(&dwVersion, &dwRevision))\n{\n printf("DirectX version is %d.%d.%d.%d\\n",\n HIWORD(dwVersion), LOWORD(dwVersion),\n HIWORD(dwRevision), LOWORD(dwRevision));\n}\n</code></pre>\n'}, {'answer_id': 79887, 'author': 'kooshmoose', 'author_id': 7436, 'author_profile': 'https://Stackoverflow.com/users/7436', 'pm_score': 0, 'selected': False, 'text': '<p>A quick Google search turns up <a href="http://www.codersource.net/win32_registry_operations.html" rel="nofollow noreferrer">this article</a> which identifies the location of the version number in the registry and then provides a case statement which maps the internal version number to the version number we\'re more familiar with.</p>\n\n<p>Another quick Google search turns up an example in C++ for <a href="http://www.codersource.net/win32_registry_operations.html" rel="nofollow noreferrer">reading from the registry</a>.</p>\n\n<p>Enjoy...</p>\n'}, {'answer_id': 1141111, 'author': 'legalize', 'author_id': 139855, 'author_profile': 'https://Stackoverflow.com/users/139855', 'pm_score': 0, 'selected': False, 'text': '<p>Yes, use the mechanism shown in the DirectX Install sample in the March 2009 DirectX SDK. (Look under "System" category in the sample browser.)</p>\n\n<p>Do not use the registry! That stuff is undocumented and not guaranteed to work.</p>\n\n<p>The only supported way is to use the DirectSetup API, which is shown in the DirectX Install sample. I also cover this stuff in Chapter 24. Installation and Setup in my book <a href="http://www.xmission.com/~legalize/book/download/" rel="nofollow noreferrer">The Direct3D Graphics Pipeline</a>. You can download that chapter for free at the above URL.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5022/'] |
79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| [{'answer_id': 79826, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 3, 'selected': False, 'text': "<p>Don't try to run <code>unittest.main()</code> from IDLE. It's trying to access <code>sys.argv</code>, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call <code>unittest.main()</code> in its own Python process.</p>\n"}, {'answer_id': 79833, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 5, 'selected': True, 'text': '<p>Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing</p>\n\n<pre><code>unittest.main()\n</code></pre>\n\n<p>to</p>\n\n<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n</code></pre>\n\n<p>More information is available <a href="http://docs.python.org/library/unittest.html#basic-example" rel="noreferrer">here</a> in the Python Library Reference.</p>\n'}, {'answer_id': 79932, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 3, 'selected': False, 'text': '<p>Pop open the source code to <code>unittest.py</code>. <code>unittest.main()</code> is hard-coded to call <code>sys.exit()</code> after running all tests. Use <code>TextTestRunner</code> to run test suites from the prompt.</p>\n'}, {'answer_id': 407950, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<pre><code>try:\n sys.exit()\nexcept SystemExit:\n print('Simple as that, but you should really use a TestRunner instead')\n</code></pre>\n"}, {'answer_id': 3215505, 'author': 'dmeister', 'author_id': 4194, 'author_profile': 'https://Stackoverflow.com/users/4194', 'pm_score': 5, 'selected': False, 'text': '<p>In new Python 2.7 release, <a href="http://docs.python.org/library/unittest.html#unittest.main" rel="noreferrer">unittest.main()</a> has a new argument.</p>\n\n<p>If \'exit\' is set to <code>False</code>, <code>sys.exit()</code> is not called during the execution of <code>unittest.main()</code>.</p>\n'}, {'answer_id': 21262077, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 3, 'selected': False, 'text': "<p>It's nice to be able to demonstrate that your tests work when first trying out the unittest module, and to know that you won't exit your Python shell. However, these solutions are version dependent.</p>\n\n<h2>Python 2.6</h2>\n\n<p>I'm using Python 2.6 at work, <code>import</code>ing <code>unittest2 as unittest</code> (which is the <code>unittest</code> module supposedly found in Python 2.7). </p>\n\n<p>The <code>unittest.main(exit=False)</code> doesn't work in Python 2.6's unittest2, while JoeSkora's solution does, and to reiterate it:</p>\n\n<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n</code></pre>\n\n<p>To break this down into its components and default arguments, with correct semantic names for the various composed objects:</p>\n\n<pre><code>import sys # sys.stderr is used in below default args\n\ntest_loader = unittest.TestLoader()\nloaded_test_suite = test_loader.loadTestsFromTestCase(Test)\n # Default args:\ntext_test_runner = unittest.TextTestRunner(stream=sys.stderr,\n descriptions=True, \n verbosity=1)\ntext_test_runner.run(loaded_test_suite)\n</code></pre>\n\n<h2>Python 2.7 and 3</h2>\n\n<p>In Python 2.7 and higher, the following should work.</p>\n\n<pre><code>unittest.main(exit=False)\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3176/'] |
79,764 | <p>I know there have been a few threads on this before, but I have tried absolutely everything suggested (that I could find) and nothing has worked for me thus far...</p>
<p>With that in mind, here is what I'm trying to do:</p>
<p>First, I want to allow users to publish pages and give them each a subdomain of their choice (ex: <code>user.example.com</code>). From what I can gather, the best way to do this is to map <code>user.example.com</code> to <code>example.com/user</code> with mod_rewrite and <code>.htaccess</code> - is that correct?</p>
<p>If that is correct, can somebody give me explicit instructions on how to do this?</p>
<p>Also, I am doing all of my development locally, using MAMP, so if somebody could tell me how to set up my local environment to work in the same manner (I've read this is more difficult), I would greatly appreciate it. Honestly, I have been trying a everything to no avail, and since this is my first time doing something like this, I am completely lost.</p>
<p><em>Some of these answers have been REALLY helpful, but for the system I have in mind, manually adding a subdomain for each user is not an option. What I'm really asking is how to do this on the fly, and redirect <code>wildcard.example.com</code> to <code>example.com/wildcard</code> -- the way Tumblr is set up is a perfect example of what I'd like to do.</em></p>
| [{'answer_id': 79807, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>First, I want to allow users to\n publish pages and give them each a\n subdomain of their choice (ex:\n user.mysite.com). From what I can\n gather, the best way to do this is to\n map user.mysite.com to mysite.com/user\n with mod_rewrite and .htaccess - is\n that correct?</p>\n</blockquote>\n\n<p>You may be better off using <a href="http://httpd.apache.org/docs/1.3/vhosts/" rel="nofollow noreferrer">virtual hosts</a>. That way, each user can have a webserver configuration pretty much independent of others.</p>\n\n<p>The syntax goes something like this:</p>\n\n<pre><VirtualHost *:80>\n DocumentRoot /var/www/user\n ServerName user.mysite.com\n ...\n</VirtualHost></pre>\n'}, {'answer_id': 79811, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 5, 'selected': True, 'text': "<p>As far as how to set up the DNS subdomain wildcard, that would be a function of your DNS hosting provider. This would be different steps depending on which hosting provider you have and would be a better question for them.</p>\n<p>Once you've set that up with the DNS host, from your web app you really are just URL rewriting, which can be done with some sort of module for the web server itself, such as isapi rewrite if you're on IIS (this would be the preferred route if possible). You could also handle rewriting at the application level as well (like using routing if on ASP.NET).</p>\n<p>You'd rewrite the URL so <code>http://myname.example.com</code> would become <code>http://example.com/something.aspx?name=myname</code> or something. From there on out, you just handle it as if the myname value was in the query string as normal. Does that make sense? Hope I didn't misunderstand what you're after.</p>\n<p>I am not suggesting that you create a subdomain for each user, but instead create a wildcard subdomain for the domain itself, so <em>anything</em>.example.com (basically <code>*.example.com</code>) goes to your site. I have several domains setup with MyDomain. Their instructions for setting this up is like this:</p>\n<blockquote>\n<p>Yes, you can configure a wild card but\nit will only work if you set it up as\nan A Record. Wildcards do not work\nwith a C Name. To use a wildcard, you\nuse the asterisks character '<em>'. For\nexample, if you create and A Record\nusing a wild card, <code>*.example.com</code>,\nanything that is entered in the place\nwhere the '</em>' is located, will resolve\nto the specified IP address. So if you\nenter 'www', 'ftp', 'site', or\nanything else before the domain name,\nit will always resolve to the IP\naddress</p>\n</blockquote>\n<p>I have some that are setup in just this way, having <code>*.example.com</code> go to my site. I then can read the base URL in my web app to see that <code>ryan.example.com</code> is what was currently accessed, or that <code>bill.example.com</code> is what was used. I can then either:</p>\n<ol>\n<li>Use URL rewriting so that the subdomain becomes a part of the query string OR</li>\n<li>Simply read the host value from the accessed URL and perform some logic based on that value.</li>\n</ol>\n<p>Does that make sense? I have several sites set up in just this exact way: create the wildcard for the domain with the DNS host and then simply read the host, or base domain from the URL to decide what to display based on the subdomain (which was actually a username)</p>\n<p><strong>Edit 2:</strong></p>\n<p>There is no way to do this without a DNS entry. The "online world" needs to know that <code>name1.example.com</code>, <code>name2.example.com</code>,..., <code>nameN.example.com</code> all go to the IP address for your server. The only way to do this is with the appropriate DNS entry. You have to add the wildcard DNS entry for your domain with your DNS host. Then it's just a matter of you reading the subdomain from the URL and taking the appropriate action in your code.</p>\n"}, {'answer_id': 79885, 'author': 'Scott Swezey', 'author_id': 9439, 'author_profile': 'https://Stackoverflow.com/users/9439', 'pm_score': 0, 'selected': False, 'text': '<p>From what I have seen on many webhosts, they setup a virtual host on apache.</p>\n\n<p>So if your www.mysite.com is served from /var/www, you could create a folder for each user. Then map the virtual host to that folder.</p>\n\n<p>With that, both mysite.com/user and user.mysite.com works.</p>\n\n<p>As for your test enviroment, if you are on windows, I would suggest editing your HOSTS file to map mysite.com to your local PC (127.0.0.1), as well as any subdomains you set up for testing.</p>\n'}, {'answer_id': 80122, 'author': 'joelhardi', 'author_id': 11438, 'author_profile': 'https://Stackoverflow.com/users/11438', 'pm_score': 4, 'selected': False, 'text': '<p>The best thing to do if you are running *AMP is to do what Thomas suggests and do virtual hosts in Apache. You can do this either with or without the redirect you describe.</p>\n<h2>Virtual hosts</h2>\n<p>Most likely you will want to do <a href="http://httpd.apache.org/docs/2.0/vhosts/examples.html" rel="nofollow noreferrer">name-based virtual hosts</a>, as it\'s easiest to set up and only requires one IP address (so will also be easy to set up and test on your local MAMP machine). IP-based virtual hosts is better in some other respects, but you have to have an IP address for each domain.</p>\n<p>This <a href="http://en.wikipedia.org/wiki/Virtual_hosting" rel="nofollow noreferrer">Wikipedia page</a> discusses the differences and links to a good basic walk-thru of how to do name-based vhosts at the bottom.</p>\n<p>On your local machine for testing, you\'ll also have to set up fake DNS names in <code>/etc/hosts</code> for your fake test domain names. i.e. if you have Apache listening on localhost and set up vhost1.test.domain and vhost2.test.domain in your Apache configs, you\'d just add these domains to the <code>127.0.0.1</code> line in <code>/etc/hosts</code>, after localhost:</p>\n<pre><code>127.0.0.1 localhost vhost1.test.domain vhost2.test.domain\n</code></pre>\n<p>Once you\'ve done the <code>/etc/hosts</code> edit and added the name-based virtual host configs to your Apache configuration file(s), that\'s it, restart Apache and your test domains should work.</p>\n<h2>Redirect with mod_rewrite</h2>\n<p>If you want to do redirects with mod_rewrite (so that <code>user.example.com</code> isn\'t directly hosted and instead redirects to <code>example.com/user</code>), then you will also need to do a RewriteCond to match the subdomain and redirect it:</p>\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^subdomain\\.example\\.com\nRewriteRule ^(.*)$ http://example.com/subdomain$1 [R]\n</code></pre>\n<p>You can put this in a <code>.htaccess</code> or in your main Apache config.</p>\n<p>You will need to add a pair of rules like the last two for each subdomain you want to redirect. Or, you may be able to capture the subdomain in a RewriteCond to be able to use one wildcard rule to redirect *.example.com to <code>example.com/</code></p>\n<ul>\n<li>-- but that smells really bad to me from a security standpoint.</li>\n</ul>\n<h2>All together, vhosts and redirect</h2>\n<p>It\'s better to be more explicit and set up a virtual host configuration section for each hostname you want to listen for, and put the rewrite rules for each of these hostnames inside its virtual host config. (It is always more secure and faster to put this kind of stuff inside your Apache config and not <code>.htaccess</code>, if you can help it -- <code>.htaccess</code> slows performance because Apache is constantly scouring the filesystem for <code>.htaccess</code> files and reparsing them, and it\'s less secure because these can be screwed up by users.)</p>\n<p>All together like that, the vhost config inside your Apache configs would be:</p>\n<pre><code>NameVirtualHost 127.0.0.1:80\n\n# Your "default" configuration must go first\n<VirtualHost 127.0.0.1:80>\n ServerName example.com\n ServerAlias www.example.com\n DocumentRoot /www/siteroot\n # etc.\n</VirtualHost>\n\n# First subdomain you want to redirect\n<VirtualHost 127.0.0.1:80>\n ServerName vhost1.example.com\n RewriteEngine On\n RewriteRule ^(.*)$ http://example.com/vhost1$1 [R]\n</VirtualHost>\n\n# Second subdomain you want to redirect\n<VirtualHost 127.0.0.1:80>\n ServerName vhost2.example.com\n RewriteEngine On\n RewriteRule ^(.*)$ http://example.com/vhost2$1 [R]\n</VirtualHost>\n</code></pre>\n'}, {'answer_id': 3381158, 'author': 'Arvind Gupta', 'author_id': 407820, 'author_profile': 'https://Stackoverflow.com/users/407820', 'pm_score': 1, 'selected': False, 'text': '<p>I had to do exactly the same for one of my sites. You can follow the following steps</p>\n\n<ol>\n<li><p>If you\'ve cPanel on your server, create a subdomain <code>*</code>, if not, you\'d have to set-up an A record in your DNS (for BIND see <a href="http://ma.tt/2003/10/wildcard-dns-and-sub-domains/" rel="nofollow noreferrer">http://ma.tt/2003/10/wildcard-dns-and-sub-domains/</a>). On your dev. server you\'d be far better off faking subdomains by adding each to your <code>hosts</code> file.</p></li>\n<li><p>(If you used cPanel you won\'t have to do this). You\'ll have to add soemthing like the following to your apache vhosts file. It largely depends on what type of server (shared or not) you\'re running. THE FOLLOWING CODE IS NOT COMPLETE. IT\'S JUST TO GIVE DIRECTION. NOTE: <code>ServerAlias example.com *.example.com</code> is important. </p>\n\n<pre><code><VirtualHost 127.0.0.1:80> \n DocumentRoot /var/www/ \n ServerName example.com \n ServerAlias example.com *.example.com \n</VirtualHost>\n</code></pre></li>\n<li><p>Next, since you can use the PHP script to check the "Host" header and find out the subdomain and serve content accordingly.</p></li>\n</ol>\n'}, {'answer_id': 13572237, 'author': 'Beau', 'author_id': 325758, 'author_profile': 'https://Stackoverflow.com/users/325758', 'pm_score': 3, 'selected': False, 'text': '<p>I realize that I\'m pretty late responding to this question, but I had the same problem in regards to a local development solution. In <a href="https://stackoverflow.com/questions/1562954/public-wildcard-domain-name-to-resolve-to-127-0-0-1">another SO thread</a> I found better solutions and thought I would share them for anyone with the same question in the future:</p>\n\n<p>VMware owned wild card domain that resolves any subdomain to 127.0.0.1:</p>\n\n<pre><code>vcap.me resolves to 127.0.0.1\nwww.vcap.me resolves to 127.0.0.1\n</code></pre>\n\n<p>or for more versatility 37 Signals owns a domain to map any subdomain to any given IP using a specific format:</p>\n\n<pre><code>127.0.0.1.xip.io resolves to 127.0.0.1\nwww.127.0.0.1.xip.io resolves to 127.0.0.1\ndb.192.168.0.1.xip.io resolves to 192.168.0.1\n</code></pre>\n\n<p>see <a href="http://xip.io/" rel="nofollow noreferrer">xip.io</a> for more info</p>\n'}, {'answer_id': 40946135, 'author': 'Fery W', 'author_id': 881743, 'author_profile': 'https://Stackoverflow.com/users/881743', 'pm_score': 2, 'selected': False, 'text': '<p>I am on Ubuntu 16.04 and since 14.04 I\'ve using solution provided by Dave Evans <a href="http://evans.io/legacy/posts/wildcard-subdomains-of-localhost/" rel="nofollow noreferrer">here</a> and it works fine for me.</p>\n\n<ol>\n<li><p>Install <code>dnsmasq</code></p>\n\n<pre><code>sudo apt-get install dnsmasq\n</code></pre></li>\n<li><p>Create new file <code>localhost.conf</code> under <code>/etc/dnsmasq.d</code> dir with the following line</p>\n\n<pre><code>#file /etc/dnsmasq.d/localhost.conf\naddress=/localhost/127.0.0.1\n</code></pre></li>\n<li><p>Edit <code>/etc/dhcp/dhclient.conf</code> and add the following line</p>\n\n<pre><code>prepend domain-name-servers 127.0.0.1;\n</code></pre>\n\n<p><em>(You’ll probably find that this line is already there and you just need to uncomment it.)</em></p></li>\n<li><p>Last one is restart the service</p>\n\n<pre><code>sudo systemctl restart dnsmasq\nsudo dhclient\n</code></pre></li>\n</ol>\n\n<p>Finally, you should check if it\'s working.</p>\n\n<pre><code>dig whatever.localhost\n</code></pre>\n\n<p><strong>note:</strong></p>\n\n<p>If you want to use it on your web server, you need to simply change the <code>127.0.0.0</code> to your actual IP address. </p>\n'}, {'answer_id': 51949318, 'author': 'Nicolay77', 'author_id': 82782, 'author_profile': 'https://Stackoverflow.com/users/82782', 'pm_score': 0, 'selected': False, 'text': '<p>The solution I found for Ubuntu 18.04 is similar to <a href="https://stackoverflow.com/a/40946135/82782">this one</a> but involves NetworkManager config:</p>\n\n<ol>\n<li><p>Edit the file <code>/etc/NetworkManager/NetworkManager.conf</code>, and add the line <code>dns=dnsmasq</code> to the <code>[main]</code> section</p>\n\n<pre><code>sudo editor /etc/NetworkManager/NetworkManager.conf\n</code></pre>\n\n<p>should look like this:</p>\n\n<pre><code>[main]\nplugins=ifupdown,keyfile\ndns=dnsmasq\n...\n</code></pre></li>\n<li><p>Start using NetworkManager\'s resolv.conf</p>\n\n<pre><code>sudo rm /etc/resolv.conf\nsudo ln -s /var/run/NetworkManager/resolv.conf /etc/resolv.conf\n</code></pre></li>\n<li><p>Create a file with your wildcard configuration</p>\n\n<pre><code>echo \'address=/.localhost/127.0.0.1\' | sudo tee /etc/NetworkManager/dnsmasq.d/localhost-wildcard.conf\n</code></pre></li>\n<li><p>Reload NetworkManager configuration</p>\n\n<pre><code>sudo systemctl reload NetworkManager\n</code></pre></li>\n<li><p>Test it</p>\n\n<pre><code>dig localdomain.localhost\n</code></pre></li>\n</ol>\n\n<p>You can also add any other domain, quite useful for some types of authentication when using a local development setup.</p>\n\n<pre><code>echo \'address=/.local-dev.workdomain.com/127.0.0.1\' | sudo tee /etc/NetworkManager/dnsmasq.d/workdomain-wildcard.conf\n</code></pre>\n\n<p>Then this works:</p>\n\n<pre><code>dig petproject.local-dev.workdomain.com\n\n;; ANSWER SECTION:\npetproject.local-dev.workdomain.com. 0 IN A 127.0.0.1\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14891/'] |
79,774 | <p>Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where <em>only</em> the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is.
The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008"
Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ?
thanks,
Ian</p>
| [{'answer_id': 79792, 'author': 'Yitzchok', 'author_id': 5723, 'author_profile': 'https://Stackoverflow.com/users/5723', 'pm_score': 0, 'selected': False, 'text': '<p>You can send it as UTC Time</p>\n\n<p>dateTime1.ToUniversalTime()</p>\n'}, {'answer_id': 79810, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I think sending as a timestamp string would be the quickest / easiest way although you could look at forcing a locale to stop the time conversion from occuring.</p>\n'}, {'answer_id': 79837, 'author': 'Timothy Carter', 'author_id': 4660, 'author_profile': 'https://Stackoverflow.com/users/4660', 'pm_score': 1, 'selected': True, 'text': '<p>You could create a struct Date that provides access to the details you want/need, like:</p>\n\n<pre><code>public struct Date\n{\n public int Month; //or string instead of int\n public int Day;\n public int Year;\n}\n</code></pre>\n\n<p>This is lightweight, flexible and gives you full control.</p>\n'}, {'answer_id': 79839, 'author': 'Brettski', 'author_id': 5836, 'author_profile': 'https://Stackoverflow.com/users/5836', 'pm_score': 0, 'selected': False, 'text': "<p>Why don't you send it as a string then convert it back to a date type as needed? This way it will not be converted over different timezones. Keep it simple.</p>\n\n<p>Edit: I like the Struct idea, allows for good functionality. </p>\n"}, {'answer_id': 80059, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 0, 'selected': False, 'text': "<p>The easiest way I've handled this on apps in the past is to just store the date as a string in yyyy-mm-dd format. It's unambigious and doesn't get automatically translated by anything.</p>\n\n<p>Yes, it's a pain...</p>\n"}, {'answer_id': 80764, 'author': 'Joe', 'author_id': 13087, 'author_profile': 'https://Stackoverflow.com/users/13087', 'pm_score': 1, 'selected': False, 'text': '<p>I\'m not sure what remoting technology you\'re referring to, but this is a real problem with WCF, which only currently supports serializing DateTime as xs:DateTime, inappropriate for a date-only value where you are not interested in timezones.</p>\n\n<p>.NET 3.5 introduces the new DateTimeOffset type, which is good for transferring a DateTime between timezones, but doesn\'t help with the date-only scenario.</p>\n\n<p>Ideally WCF needs to optionally support xs:Date for serializing dates as requested here:</p>\n\n<p><a href="http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=349215" rel="nofollow noreferrer">http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=349215</a></p>\n'}, {'answer_id': 81958, 'author': 'Hallgrim', 'author_id': 15454, 'author_profile': 'https://Stackoverflow.com/users/15454', 'pm_score': 1, 'selected': False, 'text': '<p>I do it like this: Whenever I have a date in memory or stored in a file it is always in a DateTime in UTC. When I show the date to the user it is always a string. When I convert between the string and the DateTime I also do the time zone conversion.</p>\n\n<p>This way I never have to deal with time zones in my logic, only in the presentation.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14871/'] |
79,780 | <p>I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?</p>
<pre><code>POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
</code></pre>
<p>I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything.</p>
| [{'answer_id': 79812, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 5, 'selected': True, 'text': '<p>You can retrieve the name/value pairs by searching for newline newline or more specifically \\r\\n\\r\\n (after this, the body of the message will start).</p>\n<p>Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs.</p>\n<p>See the <a href="https://www.rfc-editor.org/rfc/rfc2616" rel="nofollow noreferrer">HTTP 1.1 RFC</a>.</p>\n'}, {'answer_id': 79836, 'author': 'jfm3', 'author_id': 11138, 'author_profile': 'https://Stackoverflow.com/users/11138', 'pm_score': 2, 'selected': False, 'text': '<p>You need to keep parsing the stream as headers until you see the blank line. The rest is the POST data.</p>\n\n<p>You need to write a little parser for the post data. You can use C library routines to do something quick and dirty, like index, strtok, and sscanf. If you have room for it in your definition of "small", you could do something more elaborate with a regular expression library, or even with flex and bison.</p>\n\n<p>At least, I think this kind of answers your question.</p>\n'}, {'answer_id': 386101, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Once you have Content-Length in the header, you know the amount of bytes to be read right after the blank line. If, for any reason (GET or POST) Content-Length is not in the header, it means there's nothing to read after the blank line (crlf).</p>\n"}, {'answer_id': 47447856, 'author': 'Oliver', 'author_id': 2984198, 'author_profile': 'https://Stackoverflow.com/users/2984198', 'pm_score': 0, 'selected': False, 'text': '<p>IETF RFC notwithstanding, here is a more to the point answer. Assuming that you realize that there is always an extra <code>/r/n</code> after the <code>Content-Length</code> line in the header, you should be able to do the work to isolate it into a <code>char*</code> variable named <code>data</code>. This is where we start.</p>\n\n<pre><code>char *data = "f1=asfd&f2=a3f3f3";\nchar f1[100], \nchar f2[100];\nsscanf(data, "%s&%s", &f1, &f2); // get the field tuples\n\nchar f1_name[50];\nchar f1_data[50];\nsscanf(f1, "%s=%s", f1_name, f1_data); \n\nchar f2_name[50];\nchar f2_data[50];\nsscanf(f2, "%s=%s", f2_name, f2_data); \n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14877/'] |
79,789 | <p>I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.</p>
<p>For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:</p>
<p><a href="https://i.stack.imgur.com/HHrs0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HHrs0.png" alt="Example Chart"></a></p>
<p>I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.</p>
<p>I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.</p>
| [{'answer_id': 80125, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I came up with a pseudocode solution, hope it helps.</p>\n\n<pre><code>create an array named timetable with 24 entries\ninitialise timetable to zero\n\nfor each user in SQLtable\n firsthour = user.firsthour\n lasthour = user.lasthour\n\n firstminutes = 4 - (rounded down integer(user.firstminutes/15))\n lastminutes = rounded down integer(user.lastminutes/15)\n\n timetable(firsthour) = timetable(firsthour) + firstminutes\n timetable(lasthour) = timetable(lasthour) + lastminutes\n\n for index=firsthour+1 to lasthour-1\n timetable(index) = timetable(index) + 4\n next index\n\nnext user\n</code></pre>\n\n<p>Now the timetable array holds the values you desire in 15 minute granularity, ie. a value of 4 = 1 hour, 5 = 1 hour 15 minutes, 14 = 3 hours 30 minutes.</p>\n'}, {'answer_id': 80134, 'author': 'Mike Farmer', 'author_id': 4082, 'author_profile': 'https://Stackoverflow.com/users/4082', 'pm_score': 3, 'selected': True, 'text': "<p>Create a table with just time in it from midnight to midnight containing each minute of the day. In the data warehouse world we would call this a time dimension. Here's an example:</p>\n\n<pre><code>TIME_DIM\n -id\n -time_of_day\n -interval_15 \n -interval_30\n</code></pre>\n\n<p>an example of the data in the table would be</p>\n\n<pre><code>id time_of_day interval_15 interval_30\n1 00:00 00:00 00:00\n...\n30 00:23 00:15 00:00\n...\n100 05:44 05:30 05:30\n</code></pre>\n\n<p>Then all you have to do is join your table to the time dimension and then group by interval_15. For example:</p>\n\n<pre><code>SELECT b.interval_15, count(*) \nFROM my_data_table a\nINNER JOIN time_dim b ON a.time_field = b.time\nWHERE a.date_field = now()\nGROUP BY b.interval_15\n</code></pre>\n"}, {'answer_id': 80155, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s another pseudocode solution from a different angle; a bit more intensive because it does 96 queries for every 24hr period:</p>\n\n<pre><code>results = []\nfor time in range(0, 24, .25):\n amount = mysql("select count(*) from User_Activity_Table where time >= start_time and time <= end_time")\n results.append(amount)\n</code></pre>\n'}, {'answer_id': 81667, 'author': 'Mike Woodhouse', 'author_id': 1060, 'author_profile': 'https://Stackoverflow.com/users/1060', 'pm_score': 0, 'selected': False, 'text': '<p>How about this:</p>\n\n<p>Use that "times" table, but with two columns, containing the 15-minute intervals. The from_times are the 15-minutely times, the to_times are a second before the next from_times. For example 12:30:00 to 12:44:59.</p>\n\n<p>Now get your person work table, which I\'ve called "activity" here, with start_time and end_time columns.</p>\n\n<p>I added values for Alice and Bob as per the original question.</p>\n\n<p>Here\'s the query from MySQL:</p>\n\n<pre><code>SELECT HOUR(times.from_time) AS \'TIME\', count(*) / 4 AS \'HOURS\'\nFROM times\n JOIN activity\n ON times.from_time >= activity.start_time AND \n times.to_time <= activity.end_time\nGROUP BY HOUR(times.from_time)\nORDER BY HOUR(times.from_time)\n</code></pre>\n\n<p>which gives me this:</p>\n\n<pre><code>TIME HOURS\n12 0.7500\n13 1.0000\n14 1.0000\n15 1.5000\n16 2.0000\n17 1.0000\n18 1.0000\n19 0.7500\n</code></pre>\n\n<p>Looks about right...</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9867/'] |
79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| [{'answer_id': 79808, 'author': 'Chuck Callebs', 'author_id': 14877, 'author_profile': 'https://Stackoverflow.com/users/14877', 'pm_score': 5, 'selected': False, 'text': '<pre><code>def local_to_utc(t):\n secs = time.mktime(t)\n return time.gmtime(secs)\n\ndef utc_to_local(t):\n secs = calendar.timegm(t)\n return time.localtime(secs)\n</code></pre>\n\n<p>Source: <a href="http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html" rel="nofollow noreferrer">http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html</a></p>\n\n<p>Example usage from <a href="https://stackoverflow.com/users/8171/bd808">bd808</a>: If your source is a <code>datetime.datetime</code> object <code>t</code>, call as:</p>\n\n<pre><code>local_to_utc(t.timetuple())\n</code></pre>\n'}, {'answer_id': 79877, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 9, 'selected': False, 'text': '<p>First, parse the string into a naive datetime object. This is an instance of <code>datetime.datetime</code> with no attached timezone information. See its <a href="https://docs.python.org/3/library/datetime.html#available-types" rel="noreferrer">documentation</a>.</p>\n<p>Use the <a href="http://pytz.sourceforge.net/" rel="noreferrer"><code>pytz</code></a> module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.</p>\n<p>Finally, use <code>datetime.astimezone()</code> method to convert the datetime to UTC.</p>\n<p>Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":</p>\n<pre><code>from datetime import datetime \nimport pytz\n\nlocal = pytz.timezone("America/Los_Angeles")\nnaive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")\nlocal_dt = local.localize(naive, is_dst=None)\nutc_dt = local_dt.astimezone(pytz.utc)\n</code></pre>\n<p>From there, you can use the <code>strftime()</code> method to format the UTC datetime as needed:</p>\n<pre><code>utc_dt.strftime("%Y-%m-%d %H:%M:%S")\n</code></pre>\n'}, {'answer_id': 79913, 'author': 'Tom', 'author_id': 3715, 'author_profile': 'https://Stackoverflow.com/users/3715', 'pm_score': 7, 'selected': True, 'text': '<p>Thanks @rofly, the full conversion from string to string is as follows:</p>\n<pre><code>import time\ntime.strftime("%Y-%m-%d %H:%M:%S", \n time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", \n "%Y-%m-%d %H:%M:%S"))))\n</code></pre>\n<p>My summary of the <code>time</code>/<code>calendar</code> functions:</p>\n<p><code>time.strptime</code><br />\nstring --> tuple (no timezone applied, so matches string)</p>\n<p><code>time.mktime</code><br />\nlocal time tuple --> seconds since epoch (always local time)</p>\n<p><code>time.gmtime</code><br />\nseconds since epoch --> tuple in UTC</p>\n<p>and</p>\n<p><code>calendar.timegm</code><br />\ntuple in UTC --> seconds since epoch</p>\n<p><code>time.localtime</code><br />\nseconds since epoch --> tuple in local timezone</p>\n'}, {'answer_id': 1464261, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>How about - </p>\n\n<pre><code>time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n'}, {'answer_id': 2175170, 'author': 'monkut', 'author_id': 24718, 'author_profile': 'https://Stackoverflow.com/users/24718', 'pm_score': 8, 'selected': False, 'text': '<p><strong>NOTE</strong> -- As of 2020 you should not be using <code>.utcnow()</code> or <code>.utcfromtimestamp(xxx)</code>. As you\'ve presumably moved on to python3,you should be using timezone aware datetime objects.</p>\n<pre><code>>>> from datetime import timezone\n>>> \n>>> # alternative to \'.utcnow()\'\n>>> dt_now = datetime.datetime.now(datetime.timezone.utc)\n>>>\n>>> # alternative to \'.utcfromtimestamp()\'\n>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)\n</code></pre>\n<p>For details see: <a href="https://blog.ganssle.io/articles/2019/11/utcnow.html" rel="noreferrer">https://blog.ganssle.io/articles/2019/11/utcnow.html</a></p>\n<h2>original answer (from 2010):</h2>\n<p>The datetime module\'s <a href="http://docs.python.org/library/datetime.html#datetime.datetime.utcnow" rel="noreferrer">utcnow()</a> function can be used to obtain the current UTC time.</p>\n<pre><code>>>> import datetime\n>>> utc_datetime = datetime.datetime.utcnow()\n>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n\'2010-02-01 06:59:19\'\n</code></pre>\n<p>As the link mentioned above by Tom: <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a> says:</p>\n<blockquote>\n<p>UTC is a timezone without daylight saving time and still a timezone\nwithout configuration changes in the past.</p>\n<p><em>Always measure and store time in UTC</em>.</p>\n<p>If you need to record where the time was taken, store that separately.\n<em><strong>Do not</strong> store the local time + timezone information!</em></p>\n</blockquote>\n<p><strong>NOTE</strong> - If any of your data is in a region that uses DST, use <code>pytz</code> and take a look at John Millikin\'s answer.</p>\n<p>If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn\'t use DST, or you have data that is only offset from UTC without DST applied:</p>\n<p>--> using local time as the basis for the offset value:</p>\n<pre><code>>>> # Obtain the UTC Offset for the current system:\n>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()\n>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")\n>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA\n>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n\'2008-09-17 04:04:00\'\n</code></pre>\n<p>--> Or, from a known offset, using datetime.timedelta():</p>\n<pre><code>>>> UTC_OFFSET = 10\n>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)\n>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n\'2008-09-17 04:04:00\'\n</code></pre>\n<p>UPDATE:</p>\n<p>Since python 3.2 <code>datetime.timezone</code> is available. You can generate a timezone aware datetime object with the command below:</p>\n<pre><code>import datetime\n\ntimezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)\n</code></pre>\n<p>If your ready to take on timezone conversions go read this:</p>\n<p><a href="https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7" rel="noreferrer">https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7</a></p>\n'}, {'answer_id': 2347991, 'author': 'user235042', 'author_id': 235042, 'author_profile': 'https://Stackoverflow.com/users/235042', 'pm_score': 3, 'selected': False, 'text': '<p>if you prefer datetime.datetime:</p>\n\n<pre><code>dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")\nutc_struct_time = time.gmtime(time.mktime(dt.timetuple()))\nutc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))\nprint dt.strftime("%Y-%m-%d %H:%M:%S")\n</code></pre>\n'}, {'answer_id': 4113872, 'author': 'Mohammad Efazati', 'author_id': 471397, 'author_profile': 'https://Stackoverflow.com/users/471397', 'pm_score': -1, 'selected': False, 'text': '<p>How about - </p>\n\n<pre><code>time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n'}, {'answer_id': 4894920, 'author': 'Scipythonee', 'author_id': 600738, 'author_profile': 'https://Stackoverflow.com/users/600738', 'pm_score': 3, 'selected': False, 'text': "<pre><code>import time\n\nimport datetime\n\ndef Local2UTC(LocalTime):\n\n EpochSecond = time.mktime(LocalTime.timetuple())\n utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)\n\n return utcTime\n\n>>> LocalTime = datetime.datetime.now()\n\n>>> UTCTime = Local2UTC(LocalTime)\n\n>>> LocalTime.ctime()\n\n'Thu Feb 3 22:33:46 2011'\n\n>>> UTCTime.ctime()\n\n'Fri Feb 4 05:33:46 2011'\n</code></pre>\n"}, {'answer_id': 8068619, 'author': 'Dantalion', 'author_id': 384779, 'author_profile': 'https://Stackoverflow.com/users/384779', 'pm_score': 2, 'selected': False, 'text': '<p>For getting around day-light saving, etc.</p>\n\n<p>None of the above answers particularly helped me. The code below works for GMT.</p>\n\n<pre><code>def get_utc_from_local(date_time, local_tz=None):\n assert date_time.__class__.__name__ == \'datetime\'\n if local_tz is None:\n local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"\n local_time = local_tz.normalize(local_tz.localize(date_time))\n return local_time.astimezone(pytz.utc)\n\nimport pytz\nfrom datetime import datetime\n\nsummer_11_am = datetime(2011, 7, 1, 11)\nget_utc_from_local(summer_11_am)\n>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)\n\nwinter_11_am = datetime(2011, 11, 11, 11)\nget_utc_from_local(winter_11_am)\n>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)\n</code></pre>\n'}, {'answer_id': 8563126, 'author': 'Yarin', 'author_id': 165673, 'author_profile': 'https://Stackoverflow.com/users/165673', 'pm_score': 5, 'selected': False, 'text': '<p>I\'m having good luck with <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> (which is widely recommended on SO for other related questions):</p>\n\n<pre><code>from datetime import *\nfrom dateutil import *\nfrom dateutil.tz import *\n\n# METHOD 1: Hardcode zones:\nutc_zone = tz.gettz(\'UTC\')\nlocal_zone = tz.gettz(\'America/Chicago\')\n# METHOD 2: Auto-detect zones:\nutc_zone = tz.tzutc()\nlocal_zone = tz.tzlocal()\n\n# Convert time string to datetime\nlocal_time = datetime.strptime("2008-09-17 14:02:00", \'%Y-%m-%d %H:%M:%S\')\n\n# Tell the datetime object that it\'s in local time zone since \n# datetime objects are \'naive\' by default\nlocal_time = local_time.replace(tzinfo=local_zone)\n# Convert time to UTC\nutc_time = local_time.astimezone(utc_zone)\n# Generate UTC time string\nutc_string = utc_time.strftime(\'%Y-%m-%d %H:%M:%S\')\n</code></pre>\n\n<p>(Code was derived from this answer to <a href="https://stackoverflow.com/a/4771733/165673">Convert UTC datetime string to local datetime</a>)</p>\n'}, {'answer_id': 10040725, 'author': 'Paulius Sladkevičius', 'author_id': 1316954, 'author_profile': 'https://Stackoverflow.com/users/1316954', 'pm_score': 4, 'selected': False, 'text': '<p>One more example with pytz, but includes localize(), which saved my day.</p>\n\n<pre><code>import pytz, datetime\nutc = pytz.utc\nfmt = \'%Y-%m-%d %H:%M:%S\'\namsterdam = pytz.timezone(\'Europe/Amsterdam\')\n\ndt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)\nam_dt = amsterdam.localize(dt)\nprint am_dt.astimezone(utc).strftime(fmt)\n\'2012-04-06 08:00:00\'\n</code></pre>\n'}, {'answer_id': 12059267, 'author': 'Cristian Salamea', 'author_id': 218604, 'author_profile': 'https://Stackoverflow.com/users/218604', 'pm_score': 2, 'selected': False, 'text': "<p>You can do it with:</p>\n\n<pre><code>>>> from time import strftime, gmtime, localtime\n>>> strftime('%H:%M:%S', gmtime()) #UTC time\n>>> strftime('%H:%M:%S', localtime()) # localtime\n</code></pre>\n"}, {'answer_id': 12186921, 'author': 'Shu Wu', 'author_id': 1084497, 'author_profile': 'https://Stackoverflow.com/users/1084497', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve had the most success with <a href="https://dateutil.readthedocs.org/en/latest/relativedelta.html" rel="noreferrer">python-dateutil</a>:</p>\n\n<pre><code>from dateutil import tz\n\ndef datetime_to_utc(date):\n """Returns date in UTC w/o tzinfo"""\n return date.astimezone(tz.gettz(\'UTC\')).replace(tzinfo=None) if date.tzinfo else date\n</code></pre>\n'}, {'answer_id': 13084428, 'author': 'akaihola', 'author_id': 15770, 'author_profile': 'https://Stackoverflow.com/users/15770', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s a summary of common Python time conversions.</p>\n\n<p>Some methods drop fractions of seconds, and are marked with <em>(s)</em>. An explicit formula such as <code>ts = (d - epoch) / unit</code> can be used instead (thanks jfs).</p>\n\n<ul>\n<li>struct_time (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(struct_time)</code></li>\n<li>Naïve datetime (local) → POSIX <em>(s)</em>:<br><code>calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>Aware datetime → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>POSIX → struct_time (UTC, <em>s</em>):<br><code>time.gmtime(t)</code><br>(see comment from jfs)</li>\n<li>Naïve datetime (local) → struct_time (UTC, <em>s</em>):<br><code>stz.localize(dt, is_dst=None).utctimetuple()</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>Aware datetime → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>POSIX → Naïve datetime (local):<br><code>datetime.fromtimestamp(t, None)</code><br>(may fail in certain conditions, see comment from jfs below)</li>\n<li>struct_time (UTC) → Naïve datetime (local, <em>s</em>):<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Naïve datetime (local):<br><code>dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code></li>\n<li>Aware datetime → Naïve datetime (local):<br><code>dt.astimezone(tz).replace(tzinfo=None)</code></li>\n<li>POSIX → Naïve datetime (UTC):<br><code>datetime.utcfromtimestamp(t)</code></li>\n<li>struct_time (UTC) → Naïve datetime (UTC, <em>s</em>):<br><code>datetime.datetime(*struct_time[:6])</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Naïve datetime (UTC):<br><code>stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Aware datetime → Naïve datetime (UTC):<br><code>dt.astimezone(UTC).replace(tzinfo=None)</code></li>\n<li>POSIX → Aware datetime:<br><code>datetime.fromtimestamp(t, tz)</code><br>(may fail for non-pytz timezones)</li>\n<li>struct_time (UTC) → Aware datetime <em>(s)</em>:<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)</code><br>(can\'t represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Aware datetime:<br><code>stz.localize(dt, is_dst=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Aware datetime:<br><code>dt.replace(tzinfo=UTC)</code></li>\n</ul>\n\n<p>Source: <a href="http://taaviburns.ca/presentations/what_you_need_to_know_about_datetimes/" rel="noreferrer">taaviburns.ca</a></p>\n'}, {'answer_id': 42348504, 'author': 'Yash', 'author_id': 2708266, 'author_profile': 'https://Stackoverflow.com/users/2708266', 'pm_score': 2, 'selected': False, 'text': '<p>Using <a href="http://crsmithdev.com/arrow/" rel="nofollow noreferrer">http://crsmithdev.com/arrow/</a></p>\n\n<pre><code>arrowObj = arrow.Arrow.strptime(\'2017-02-20 10:00:00\', \'%Y-%m-%d %H:%M:%S\' , \'US/Eastern\')\n\narrowObj.to(\'UTC\') or arrowObj.to(\'local\') \n</code></pre>\n\n<p>This library makes life easy :)</p>\n'}, {'answer_id': 48203190, 'author': 'spedy', 'author_id': 2115494, 'author_profile': 'https://Stackoverflow.com/users/2115494', 'pm_score': -1, 'selected': False, 'text': "<p>In python3:</p>\n\n<p><code>pip install python-dateutil</code></p>\n\n<pre><code>from dateutil.parser import tz\n\nmydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) \n</code></pre>\n"}, {'answer_id': 50138694, 'author': 'uclatommy', 'author_id': 4015330, 'author_profile': 'https://Stackoverflow.com/users/4015330', 'pm_score': 3, 'selected': False, 'text': '<h2>Simple</h2>\n\n<p>I did it like this:</p>\n\n<pre><code>>>> utc_delta = datetime.utcnow()-datetime.now()\n>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta\n>>> print(utc_time)\n2008-09-17 19:01:59.999996\n</code></pre>\n\n<h2>Fancy Implementation</h2>\n\n<p>If you want to get fancy, you can turn this into a functor:</p>\n\n<pre><code>class to_utc():\n utc_delta = datetime.utcnow() - datetime.now()\n\n def __call__(cls, t):\n return t + cls.utc_delta\n</code></pre>\n\n<p>Result: </p>\n\n<pre><code>>>> utc_converter = to_utc()\n>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))\n2008-09-17 19:01:59.999996\n</code></pre>\n'}, {'answer_id': 53760225, 'author': 'franksands', 'author_id': 289368, 'author_profile': 'https://Stackoverflow.com/users/289368', 'pm_score': 1, 'selected': False, 'text': '<p>I found the best answer on another question <a href="https://stackoverflow.com/a/1596308/289368">here</a>. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case) </p>\n\n<pre><code>import time\nimport calendar\n\nlocal_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")\nlocal_seconds = time.mktime(local_time)\nutc_time = time.gmtime(local_seconds)\n</code></pre>\n\n<p>I\'m reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.</p>\n'}, {'answer_id': 62237615, 'author': 'tobixen', 'author_id': 1452887, 'author_profile': 'https://Stackoverflow.com/users/1452887', 'pm_score': 2, 'selected': False, 'text': '<p>I have this code in one of my projects:</p>\n\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\n## datetime.timezone works in newer versions of python\ntry:\n from datetime import timezone\n utc_tz = timezone.utc\nexcept:\n import pytz\n utc_tz = pytz.utc\n\ndef _to_utc_date_string(ts):\n # type (Union[date,datetime]]) -> str\n """coerce datetimes to UTC (assume localtime if nothing is given)"""\n if (isinstance(ts, datetime)):\n try:\n ## in python 3.6 and higher, ts.astimezone() will assume a\n ## naive timestamp is localtime (and so do we)\n ts = ts.astimezone(utc_tz)\n except:\n ## in python 2.7 and 3.5, ts.astimezone() will fail on\n ## naive timestamps, but we\'d like to assume they are\n ## localtime\n import tzlocal\n ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)\n return ts.strftime("%Y%m%dT%H%M%SZ")\n</code></pre>\n'}, {'answer_id': 62816943, 'author': 'Philipp', 'author_id': 2782049, 'author_profile': 'https://Stackoverflow.com/users/2782049', 'pm_score': 1, 'selected': False, 'text': '<p>If you already have a datetime object <code>my_dt</code> you can change it to UTC with:</p>\n<pre><code>datetime.datetime.utcfromtimestamp(my_dt.timestamp())\n</code></pre>\n'}, {'answer_id': 62840310, 'author': 'Alperen', 'author_id': 6900838, 'author_profile': 'https://Stackoverflow.com/users/6900838', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Briefly</strong>, to convert any <code>datetime</code> date to UTC time:</p>\n<pre><code>from datetime import datetime\n\ndef to_utc(date):\n return datetime(*date.utctimetuple()[:6])\n</code></pre>\n<hr />\n<p>Let's explain with an example. First, we need to create a <code>datetime</code> from the string:</p>\n<pre><code>>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")\n</code></pre>\n<p>Then, we can call the function:</p>\n<pre><code>>>> to_utc(date)\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n<p>Step by step how the function works:</p>\n<pre><code>>>> date.utctimetuple()\ntime.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)\n>>> date.utctimetuple()[:6]\n(2011, 2, 12, 1, 33, 54)\n>>> datetime(*date.utctimetuple()[:6])\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n"}, {'answer_id': 64097432, 'author': 'FObersteiner', 'author_id': 10197418, 'author_profile': 'https://Stackoverflow.com/users/10197418', 'pm_score': 4, 'selected': False, 'text': '<p>An option available since Python 3.6: <code>datetime.astimezone(tz=None)</code> can be used to get an aware datetime object representing local time <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone" rel="noreferrer">(docs)</a>. This can then easily be converted to UTC.</p>\n<pre><code>from datetime import datetime, timezone\ns = "2008-09-17 14:02:00"\n\n# to datetime object:\ndt = datetime.fromisoformat(s) # Python 3.7\n\n# I\'m on time zone Europe/Berlin; CEST/UTC+2 during summer 2008\ndt = dt.astimezone()\nprint(dt)\n# 2008-09-17 14:02:00+02:00\n\n# ...and to UTC:\ndtutc = dt.astimezone(timezone.utc)\nprint(dtutc)\n# 2008-09-17 12:02:00+00:00\n</code></pre>\n<p>Side-Note: While the described conversion to UTC works perfectly fine, <code>.astimezone()</code> sets <code>tzinfo</code> of the datetime object to a timedelta-derived timezone - so don\'t expect any "DST-awareness" from it.</p>\n'}, {'answer_id': 64626046, 'author': 'Zisheng Ye', 'author_id': 8102752, 'author_profile': 'https://Stackoverflow.com/users/8102752', 'pm_score': 2, 'selected': False, 'text': "<p>In python 3.9.0, after you've parsed your local time <code>local_time</code> into <code>datetime.datetime</code> object, just use <code>local_time.astimezone(datetime.timezone.utc)</code>.</p>\n"}, {'answer_id': 69031527, 'author': 'Lalit Sharma', 'author_id': 7756843, 'author_profile': 'https://Stackoverflow.com/users/7756843', 'pm_score': 1, 'selected': False, 'text': '<p>For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.</p>\n<p>For eg.</p>\n<p>let say we have local datetime string as <code>2021-09-02T19:02:00Z</code> in isoformat</p>\n<p>Now to convert this string to utc datetime. we first need to generate datetime object using this string by</p>\n<p><code>dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\')</code></p>\n<p>this will give you python datetime object, then you can use <code>astimezone(pytz.utc)</code> to get utc datetime like</p>\n<p><code>dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\') dt = dt.astimezone(pytz.utc)</code></p>\n<p>this will give you datetime object in utc, then you can convert it to string using <code>dt.strftime("%Y-%m-%d %H:%M:%S")</code></p>\n<p>full code eg:</p>\n<pre><code>from datetime import datetime\nimport pytz\n\ndef converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):\n dt = datetime.strptime(dt,\'%Y-%m-%dT%H:%M:%SZ\')\n dt = dt.astimezone(pytz.utc)\n \n if getString:\n return dt.strftime(format)\n return dt\n</code></pre>\n<p>then you can call it as</p>\n<p><code>converLocalToUTC("2021-09-02T19:02:00Z")</code></p>\n<p>took help from\n<a href="https://stackoverflow.com/a/79877/7756843">https://stackoverflow.com/a/79877/7756843</a></p>\n'}, {'answer_id': 69261133, 'author': 'Bryce', 'author_id': 11804374, 'author_profile': 'https://Stackoverflow.com/users/11804374', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s an example with the native <a href="https://docs.python.org/3/library/zoneinfo.html" rel="nofollow noreferrer">zoneinfo</a> module in <strong>Python3.9</strong>:</p>\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\nfrom zoneinfo import ZoneInfo\n\n# Get timezone we\'re trying to convert from\nlocal_tz = ZoneInfo("America/New_York")\n# UTC timezone\nutc_tz = ZoneInfo("UTC")\n\ndt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")\ndt = dt.replace(tzinfo=local_tz)\ndt_utc = dt.astimezone(utc_tz)\n\nprint(dt.strftime("%Y-%m-%d %H:%M:%S"))\nprint(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))\n</code></pre>\n<p>This may be preferred over just using <code>dt.astimezone()</code> in situations where the timezone you\'re converting from isn\'t reflective of your system\'s local timezone. Not having to rely on external libraries is nice too.</p>\n<p><strong>Note</strong>: This may not work on Windows systems, since <a href="https://docs.python.org/3/library/zoneinfo.html#data-sources" rel="nofollow noreferrer">zoneinfo relies on an IANA database</a> that may not be present. The <a href="https://tzdata.readthedocs.io/en/latest/" rel="nofollow noreferrer">tzdata</a> package can be installed as a workaround. It\'s a first-party package, but is not in the standard library.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3715/'] |
79,816 | <p>I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.<br>
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx</p>
| [{'answer_id': 79830, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 2, 'selected': False, 'text': '<p>When the button is pressed, call <code>window.setTimeout</code> with your intended time and the function <code>x</code>, and set the timer again at the end of <code>x</code> but this time with a smaller interval.</p>\n\n<p>Clear the timeout using <code>window.clearTimeout</code> upon release of the mouse button.</p>\n'}, {'answer_id': 79862, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': -1, 'selected': False, 'text': '<p>something like the psuedo code below might work..</p>\n\n<pre><code>var isClicked = false;\nvar clickCounter = 100;\nfunction fnTrackClick(){\n if(isClicked){\n clickCounter--;\n setTimeout(clickCounter * 100, fnTrackClick);\n }\n}\n\n<input type="button" value="blah" onmousedown="isClicked=true;" onmouseover="fnTrackClick();" onmouseup="isClicked = false;" />\n</code></pre>\n'}, {'answer_id': 79890, 'author': 'Glennular', 'author_id': 14753, 'author_profile': 'https://Stackoverflow.com/users/14753', 'pm_score': 2, 'selected': False, 'text': "<p>Just put the below toggleOn in the OnMouseDown and toggleOff in the OnMouseUp of the button.</p>\n\n<pre><code>var tid = 0;\nvar speed = 100;\n\nfunction toggleOn(){\n if(tid==0){\n tid=setInterval('ThingToDo()',speed);\n }\n}\nfunction toggleOff(){\n if(tid!=0){\n clearInterval(tid);\n tid=0;\n }\n}\nfunction ThingToDo{\n\n}\n</code></pre>\n"}, {'answer_id': 79970, 'author': 'neouser99', 'author_id': 10669, 'author_profile': 'https://Stackoverflow.com/users/10669', 'pm_score': 5, 'selected': True, 'text': '<pre><code>function holdit(btn, action, start, speedup) {\n var t;\n\n var repeat = function () {\n action();\n t = setTimeout(repeat, start);\n start = start / speedup;\n }\n\n btn.mousedown = function() {\n repeat();\n }\n\n btn.mouseup = function () {\n clearTimeout(t);\n }\n};\n\n/* to use */\nholdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */\n</code></pre>\n'}, {'answer_id': 43407325, 'author': 'Phuong Vu', 'author_id': 1014112, 'author_profile': 'https://Stackoverflow.com/users/1014112', 'pm_score': 0, 'selected': False, 'text': '<p>I just release a jQuery plugin, check this <a href="https://phuong.github.io/jqueryClickAndHold/" rel="nofollow noreferrer">demo</a> on this <a href="https://github.com/phuong/jqueryClickAndHold" rel="nofollow noreferrer">repo</a>.</p>\n\n<pre><code>$(\'button\').clickAndHold(function (e, n) {\n console.log("Call me baby ", n);\n});\n</code></pre>\n'}, {'answer_id': 58237538, 'author': 'cskwg', 'author_id': 4386189, 'author_profile': 'https://Stackoverflow.com/users/4386189', 'pm_score': 0, 'selected': False, 'text': "<p>@glenuular: Thanks for this interesting approach!\nThere were some small problems with it: \n- The start value was not reset, so on the second use it started too fast.\n- The start value was divided without limit, so it became very small after short time.\n- Arguments were not passed to the called method. (Now limited to 6 args, usually sufficient to pass 'ev').</p>\n\n<pre><code> function holdit( btn, method, start, speedup ) {\n var t, keep = start;\n var repeat = function () {\n var args = Array.prototype.slice.call( arguments );\n method.apply( this, args );\n t = setTimeout( repeat, start, args[0], args[1], args[2], args[3], args[4], args[5] );\n if ( start > keep / 20 ) start = start / speedup;\n }\n btn.onmousedown = btn.mousedown = repeat;\n //\n btn.onmouseout = btn.mouseout = btn.onmouseup = btn.mouseup = function () {\n clearTimeout( t );\n start = keep;\n }\n};\n</code></pre>\n"}, {'answer_id': 70521675, 'author': 'Daniel Cachro', 'author_id': 17790036, 'author_profile': 'https://Stackoverflow.com/users/17790036', 'pm_score': 0, 'selected': False, 'text': "<p>I upgraded neouser99 solution because i ran into some problems with it ^^</p>\n<pre><code>let holdIt = (btn, action, start, speedup, limit) => {\n let t;\n let startValue = start;\n\n let repeat = () => {\n action();\n t = setTimeout(repeat, startValue);\n (startValue > limit) ? startValue /= speedup: startValue = limit;\n }\n\n btn.onmousedown = () => {\n repeat();\n }\n\n const stopActionEvents = ['mouseup', 'mouseout'];\n\n stopActionEvents.forEach(event => {\n btn.addEventListener(event, () => {\n clearTimeout(t);\n startValue = start;\n })\n });\n\n};\n\nholdIt(actionButton, functionToDo, 500, 2, 5);\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14907/'] |
79,843 | <p>The situation is this:</p>
<ul>
<li>You have a Hibernate context with an
object graph that has some lazy
loading defined. </li>
<li>You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere. </li>
<li>There are different UI
contexts that require different
amounts of data. </li>
<li>The data is too
big to just eager load the whole
graph each time.</li>
</ul>
<p>What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?</p>
<p>Any help.</p>
| [{'answer_id': 79933, 'author': 'sirrocco', 'author_id': 5246, 'author_profile': 'https://Stackoverflow.com/users/5246', 'pm_score': 3, 'selected': True, 'text': "<p>Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders. </p>\n\n<p>Then I would define a Repository with a fluent interface that will allow me to say something like :</p>\n\n<pre><code>new ClientRepo().LoadClientBy(id)\n .WithOrders()\n .WithBonus()\n .OrderByName();\n</code></pre>\n\n<p>And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB)</p>\n"}, {'answer_id': 80154, 'author': 'Dónal', 'author_id': 2648, 'author_profile': 'https://Stackoverflow.com/users/2648', 'pm_score': 1, 'selected': False, 'text': "<p>If it's a webapp and you're using Spring, then OpenSessionInViewFilter could be the solution to your problems.</p>\n"}, {'answer_id': 87117, 'author': 'Roland Schneider', 'author_id': 16515, 'author_profile': 'https://Stackoverflow.com/users/16515', 'pm_score': 1, 'selected': False, 'text': '<p>An approach we use in our projects is to create a service for each view you have. Then the view fetches the sub-graph you need for this specific view, always trying to reduce the number of sqls send to the database. Therefore we are using a lot of joins to get the n:1 associated objects.</p>\n\n<p>If you are using a 2-tier desktop app directly connected to the DB you can just leave the objects attached and load additional data anytime automatically. Otherwise you have to reattach it to the session and initialize the association you need with <code>Hibernate.initialize(Object entity, String propertyName)</code></p>\n\n<p>(Out of memory, maybe not 100% correct)</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14893/'] |
79,850 | <p>Since the Google App Engine Datastore is based on <a href="http://research.google.com/archive/bigtable.html" rel="noreferrer">Bigtable</a> and we know that's not a relational database, how do you design a <strong><em>database schema</em>/<em>data model</em></strong> for applications that use this type of database system?</p>
| [{'answer_id': 80420, 'author': 'mbesso', 'author_id': 9510, 'author_profile': 'https://Stackoverflow.com/users/9510', 'pm_score': -1, 'selected': False, 'text': '<p>As GAE builds on how data is managed in Django there is a lot of info on how to address similar questions in the Django documentation (for example see <a href="http://www.djangobook.com/en/1.0/chapter05/" rel="nofollow noreferrer">here</a>, scroll down to \'Your first model\').</p>\n\n<p>In short you design you db model as a regular object model and let GAE sort out all of the object-relational mappings. </p>\n'}, {'answer_id': 80425, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 5, 'selected': True, 'text': '<p>Designing a bigtable schema is an open process, and basically requires you to think about:</p>\n\n<ul>\n<li>The access patterns you will be using and how often each will be used</li>\n<li>The relationships between your types</li>\n<li>What indices you are going to need</li>\n<li>The write patterns you will be using (in order to effectively spread load)</li>\n</ul>\n\n<p>GAE\'s datastore automatically denormalizes your data. That is, each index contains a (mostly) complete copy of the data, and thus every index adds significantly to time taken to perform a write, and the storage space used.</p>\n\n<p>If this were not the case, designing a Datastore schema would be a lot more work: You would have to think carefully about the primary key for each type, and consider the effect of your decision on the locality of data. For example, when rendering a blog post you would probably need to display the comments to go along with it, so each comment\'s key would probably begin with the associated post\'s key.</p>\n\n<p>With Datastore, this is not such a big deal: The query you use will look something like "Select * FROM Comment WHERE post_id = N." (If you want to page the comments, you would also have a limit clause, and a possible suffix of " AND comment_id > last_comment_id".) Once you add such a query, Datastore will build the index for you, and your reads will be magically fast.</p>\n\n<p>Something to keep in mind is that each additional index creates some additional cost: it is best if you can use as few access patterns as possible, since it will reduce the number of indices GAE will construct, and thus the total storage required by your data.</p>\n\n<p>Reading over this answer, I find it a little vague. Maybe a hands-on design question would help to scope this down? :-)</p>\n'}, {'answer_id': 196660, 'author': 'massimo', 'author_id': 24489, 'author_profile': 'https://Stackoverflow.com/users/24489', 'pm_score': 1, 'selected': False, 'text': '<p>You can use www.web2py.com. You build the model and the application once and it works on GAE but also witl SQLite, MySQL, Posgres, Oracle, MSSQL, FireBird</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10708/'] |
79,853 | <p>I've inherited a network spread out over a warehouse/front office consisting of approximately 50 desktop PCs, various servers, network printers, and routers/switches.</p>
<p>The "intelligent" routers live in the server room. As the company has grown, we've annexed additional space and not very elegantly run various lengths of CAT5 thru the ceilings etc. I've been finding various hubs and switches in the ceilings -- none of which is labeled or documented in any way. </p>
<p>Of course, das blinken-lights tell me that <em>someone</em> is connected to these devices, I just have no way of finding out <em>who</em>.</p>
<p>I can run traditional network map tools (there are tons of these things) and it shows me the IP-based things in the network. That's nice, but information I already have. What I need to know is the network topology -- how the switches (bridges) are interconnected etc.. And since they are off-the-shelf linksys unmanaged-types, they don't respond to SNMP so I can't use that...</p>
<p>What's the best/cheapest tool out there that I can use to analyze and detect things like hubs and switches in the network that don't respond to SNMP? </p>
<p>If there's no tool that you're aware of -- what generalized algorithm would you suggest to find this out? My guess would be that I could look at the MAC forward tables for the devices (switches, desktops, etc.) and build a chain that way, but I don't know if it's possible to get that from an unmanaged switch (let alone a hub).</p>
<p>(This patent has some neat ideas but I can't find any software built with it: <a href="http://www.freepatentsonline.com/6628623.html" rel="noreferrer">http://www.freepatentsonline.com/6628623.html</a>)</p>
<p>Thanks!!</p>
| [{'answer_id': 79904, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think unmanaged switches/hubs will have arp entries - being transparent at the mac layer is their reason for existing. </p>\n\n<p>And I don't think there's a way to get their MAC forwarding tables short of taking them apart and finding a JTAG or other port to talk to them with, which is unlikely to be feasible.</p>\n\n<p>The best idea I can come up with is to pingflood each internal IP in turn, and then while that's going on, try and ping all the other IPs. This will help because you'll only get decent responses from machines that don't share a (now congested into oblivion) link with the one you're pingflooding. Basically you're using the fact that the backplane on the switches is much faster than the interconnects between them to map out which connections are via interconnects and which are via backplanes. This also lets you watch das blinkenlights and figure out which ports are used to connect to which IPs.</p>\n\n<p>Sadly I know of no software that will do this for you.</p>\n"}, {'answer_id': 83002, 'author': 'Tubs', 'author_id': 11924, 'author_profile': 'https://Stackoverflow.com/users/11924', 'pm_score': 3, 'selected': True, 'text': "<p>An idea could be to use a program like 3com network director trial version (or The Dude). Use it to discover all of your workstations and anything else with an IP address.</p>\n\n<p>Wait for a quiet time and unplug each hub/switch ... you'll then at least begin to be able to make a map, the rest will be crawling about following cables. Network administration does mean getting dirty.</p>\n"}, {'answer_id': 83128, 'author': 'Nate', 'author_id': 12779, 'author_profile': 'https://Stackoverflow.com/users/12779', 'pm_score': 2, 'selected': False, 'text': "<p>You probably can't explicitly <strong>detect</strong> unmanaged devices... but you have MAC -> switch port mappings, on your managed ones, right? If so, you should be able to <strong>infer</strong> the presence of unmanaged switches / hubs with more than one connected client -- I don't know how you'd find a port with only one.</p>\n\n<ol>\n<li>Record the MAC addresses of all smart switches and client devices</li>\n<li>Start from one of your known smart switches</li>\n<li>For each port on the switch, list the MAC addresses it's forwarding. If it lists one client, it's direct. If it's more than one and none of the addresses are in your known switch MACs, you've got a dumb switch. If it's more than one and one address is in your set of known switches, recurse on this switch.</li>\n</ol>\n\n<p>You probably don't have any accidental loops in your network topology (or your network probably wouldn't work) so you can probably assume a tree structure outside your core.</p>\n"}, {'answer_id': 101836, 'author': 'Alex Dupuy', 'author_id': 18829, 'author_profile': 'https://Stackoverflow.com/users/18829', 'pm_score': 2, 'selected': False, 'text': "<p>You could try to get spanning-tree protocol information out of the smart switches; even unmanaged switches have to participate in this protocol (this doesn't apply to hubs, though).</p>\n"}, {'answer_id': 104622, 'author': 'Jay', 'author_id': 12479, 'author_profile': 'https://Stackoverflow.com/users/12479', 'pm_score': 1, 'selected': False, 'text': "<p>If you haven't already, try HP Openview trial version, and apart of using SNMP, it also uses ARP tables to figure out your topology.</p>\n"}, {'answer_id': 398624, 'author': 'oz10', 'author_id': 14069, 'author_profile': 'https://Stackoverflow.com/users/14069', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve personally had the same issue. Fun. I partially solved the problem by installing new Cisco Catalyst Switches in the main data closet and setting the Smart Ports profile on each port to "Desktop". This limits the port to 1 MAC address.</p>\n\n<p>Any port with an unmanaged hub/switch attached will be automatically disabled the first time more than one device is activated on the unmanaged device. </p>\n\n<p>As I located unmanaged hubs/switches I replaced them with managed switches configured to limit each port to 1 MAC. </p>\n\n<p>If your budget won\'t allow this, the alternative is to trace each wire visually and manually verify the presence of unmanaged networking equipment. </p>\n'}, {'answer_id': 468184, 'author': 'user57792', 'author_id': 57792, 'author_profile': 'https://Stackoverflow.com/users/57792', 'pm_score': 1, 'selected': False, 'text': "<p>You can expect these features in release of AdventNet's opmanager8.0 next month</p>\n"}, {'answer_id': 1408629, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You can try NetskateKoban, that will give you the map with the number of terminals connected to each port of the managed switch. You can know the presence of unmanged device from there by the vendor name. </p>\n\n<p>We have seen a similar kind of problem, where a network admin had to figure out how many switches (managed/unmanaged) are present. It will give you the location of such places. Try it out... all the best</p>\n'}, {'answer_id': 32201387, 'author': 'parsley72', 'author_id': 264822, 'author_profile': 'https://Stackoverflow.com/users/264822', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve been looking into this and I found this old research paper <a href="http://www.wand.net.nz/~salcock/discovery/discovery.html" rel="nofollow">Using VPS Probing to Discover Layer 2 Topology</a>. The theory is that you can use Variable Packet Size (VPS) probing to discover layer 2 switches by the delay they introduce. I haven\'t had a chance to try it in practice yet.</p>\n\n<p>Update: I found a later version of the paper called <a href="http://wand.net.nz/pubs/223/pdf/PAM_paper.pdf" rel="nofollow">Using Simple Per-Hop Capacity Metrics to Discover Link Layer Network Topology</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2590/'] |
79,856 | <p>In a stored procedure, I need to get the count of the results of another stored procedure. Specifically, I need to know if it returns any results, or an empty set.</p>
<p>I could create a temp table/table variable, exec the stored procedure into it, and then run a select count on that data. But I really don't care about the data itself, all I need is the count (or presence/absence of data). I was wondering if there is a more efficient way of getting just that information.</p>
<p>I don't want to just copy the contents of the other stored procedure and rewrite it as a select count. The stored procedure changes too frequently for that to be workable.</p>
| [{'answer_id': 79865, 'author': 'Nescio', 'author_id': 14484, 'author_profile': 'https://Stackoverflow.com/users/14484', 'pm_score': 1, 'selected': False, 'text': '<p>@@ROWCOUNT</p>\n'}, {'answer_id': 79866, 'author': 'Milan Babuškov', 'author_id': 14690, 'author_profile': 'https://Stackoverflow.com/users/14690', 'pm_score': 0, 'selected': False, 'text': '<p>If you can rewrite other procedure to be a simple function that returns a resultset, you can simply select count(*) from it.</p>\n'}, {'answer_id': 79870, 'author': 'Booji Boy', 'author_id': 1433, 'author_profile': 'https://Stackoverflow.com/users/1433', 'pm_score': 1, 'selected': False, 'text': '<p>use an out parameter</p>\n'}, {'answer_id': 79871, 'author': 'Matt Rogish', 'author_id': 2590, 'author_profile': 'https://Stackoverflow.com/users/2590', 'pm_score': 2, 'selected': False, 'text': '<p>Well, depending on how the stored procedures work, @@ROWCOUNT returns the # of results for ANYthing that SP will do (including updates):\n<a href="http://msdn.microsoft.com/en-us/library/ms187316.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187316.aspx</a></p>\n\n<p>This will only work if the LAST thing you do in the sp is returning the rows to the client... Otherwise you\'re going to get the results of some other statement. Make sense?</p>\n'}, {'answer_id': 80006, 'author': 'Min', 'author_id': 14461, 'author_profile': 'https://Stackoverflow.com/users/14461', 'pm_score': 1, 'selected': False, 'text': '<p>I would think you could return the number of rows (using RETURN) or use an out parameter to get the value.</p>\n'}, {'answer_id': 80158, 'author': 'Ricardo C', 'author_id': 232589, 'author_profile': 'https://Stackoverflow.com/users/232589', 'pm_score': 0, 'selected': False, 'text': '<p>It seems that is someone else altering the other stored procedure and you need something to effectively check on the results no matter the changes to such procedure.</p>\n\n<p>Create a tempt table and insert the result from that procedure in it.</p>\n\n<p>Then you can perform a row count on the results. It is not the most efficient but most reliable solution if I understand correctly your problem.</p>\n\n<p>Snipet:</p>\n\n<pre><code>DECLARE @res AS TABLE (\n [EmpID] [int] NOT NULL,\n [EmpName] [varchar](30) NULL,\n [MgrID] [int] NULL\n)\n\nINSERT @res \nEXEC dbo.ProcFoo\n\nSELECT COUNT(*) FROM @res\n</code></pre>\n'}, {'answer_id': 82603, 'author': 'Josef', 'author_id': 5581, 'author_profile': 'https://Stackoverflow.com/users/5581', 'pm_score': 0, 'selected': False, 'text': "<p>Given that you don't really need to know the count, merely whether there is or isn't data for your sproc, I'd recommend something like this:</p>\n\n<pre><code>CREATE PROCEDURE subProcedure @param1, @param2, @Param3 tinyint OUTPUT\nAS\nBEGIN\n IF EXISTS(SELECT * FROM table1 WHERE we have something to work with)\n BEGIN\n -- The body of your sproc\n SET @Param3 = 1\n END\n ELSE\n SET @Param3 = 0\nEND\n</code></pre>\n\n<p>Now you can execute the sproc and check the value of @Param3:</p>\n\n<pre><code>DECLARE @ThereWasData tinyint\nexec subProcedure 'foo', 'bar', @ThereWasData OUTPUT\nIF @ThereWasData = 1 \n PRINT 'subProcedure had data'\nELSE\n PRINT 'subProcedure had NO data'\n</code></pre>\n"}, {'answer_id': 12804872, 'author': 'Rikki', 'author_id': 1623728, 'author_profile': 'https://Stackoverflow.com/users/1623728', 'pm_score': 0, 'selected': False, 'text': "<p>I think you should do something like this:</p>\n\n<pre><code>Create Procedure [dbo].[GetResult] (\n @RowCount BigInt = -1 Output\n) As Begin\n\n /*\n You can do whatever else you should do here.\n */\n\n Select @RowCount = Count_Big(*)\n From dbo.SomeLargeOrSmallTable\n Where SomeColumn = 'Somefilters'\n ;\n\n /*\n You can do whatever else you should do here.\n */\n\n --Reporting how your procedure has done the statements. It's just a sample to show you how to work with the procedures. There are many ways for doing these things.\n Return @@Error;\n\nEnd;\n</code></pre>\n\n<p>After writing that you can get the output result like this:</p>\n\n<pre><code>Declare @RowCount BigInt\n, @Result Int\n;\n\nExecute @Result = [dbo].[GetResult] @RowCount Out\n\nSelect @RowCount\n, @Result\n;\n</code></pre>\n\n<p>Cheers</p>\n"}, {'answer_id': 39282002, 'author': 'M.Hassan', 'author_id': 3142139, 'author_profile': 'https://Stackoverflow.com/users/3142139', 'pm_score': 0, 'selected': False, 'text': '<pre><code> create proc test\n as\n begin\n select top 10 * from customers\n end\n go\n\n\n create proc test2 (@n int out)\n as\n begin\n exec test\n set @n = @@rowcount\n --print @n\n end\n go\n\n declare @n1 int =0\n\n exec test2 @n1 out\n print @n1\n --output result: 10\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10630/'] |
79,875 | <p>I'd like to create a utility in C# to allow someone to easily create a Certificate Authority (CA) in Windows. Any ideas/suggestions?</p>
<p>I know I can use OpenSSL to do this. In the end, I'll want this utility to do more than just generate a CA. I'd also like to avoid requiring the installation of OpenSSL in order to run my utility.</p>
| [{'answer_id': 79900, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 3, 'selected': True, 'text': '<p>Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.</p>\n\n<p>(Maybe you can even link the native code straight into your .NET executable? Not sure about that.)</p>\n'}, {'answer_id': 2228742, 'author': 'Guy van den Berg', 'author_id': 189895, 'author_profile': 'https://Stackoverflow.com/users/189895', 'pm_score': 1, 'selected': False, 'text': '<p>Take a look at BouncyCastle <a href="http://www.bouncycastle.org/csharp/" rel="nofollow noreferrer">http://www.bouncycastle.org/csharp/</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13348/'] |
79,880 | <p>I'm looking for a variation on the <code>#save</code> method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.</p>
<p>By "valid attributes", I mean those attributes that give nil when calling @model_instance.errors.on(:attribute)</p>
<p>Anyone have an idea of how to accomplish this?</p>
<p>So far, I have the following:</p>
<pre><code>def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
</code></pre>
<p>This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start_date", and two methods defined:</p>
<pre><code>def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
</code></pre>
<p>These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:</p>
<pre><code>def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
</code></pre>
<p>The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.</p>
<p>Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge.</p>
| [{'answer_id': 79900, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 3, 'selected': True, 'text': '<p>Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.</p>\n\n<p>(Maybe you can even link the native code straight into your .NET executable? Not sure about that.)</p>\n'}, {'answer_id': 2228742, 'author': 'Guy van den Berg', 'author_id': 189895, 'author_profile': 'https://Stackoverflow.com/users/189895', 'pm_score': 1, 'selected': False, 'text': '<p>Take a look at BouncyCastle <a href="http://www.bouncycastle.org/csharp/" rel="nofollow noreferrer">http://www.bouncycastle.org/csharp/</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14843/'] |
79,891 | <p>While we try to set up as many unit tests as time allows for our applications, I always find the amount of UI-level tests lacking. There are many options out there, but I'm not sure what would be a good place to start. </p>
<p>What is your preferred unit testing tool for testing Swing applications? Why do you like it?</p>
| [{'answer_id': 80184, 'author': 'zurk', 'author_id': 14907, 'author_profile': 'https://Stackoverflow.com/users/14907', 'pm_score': 1, 'selected': False, 'text': '<p>try pounder : <a href="http://pounder.sourceforge.net/" rel="nofollow noreferrer">http://pounder.sourceforge.net/</a></p>\n'}, {'answer_id': 80222, 'author': 'gizmo', 'author_id': 9396, 'author_profile': 'https://Stackoverflow.com/users/9396', 'pm_score': 5, 'selected': True, 'text': '<p>On our side, we use to test SWING GUI with <a href="http://code.google.com/p/fest/" rel="noreferrer">FEST</a>. This is an adapter on the classical swing robot, but it ease dramatically its use. </p>\n\n<p>Combined with TestNG, We found it an easy way to simulate "human" actions trough the GUI.</p>\n'}, {'answer_id': 87000, 'author': 'Roland Schneider', 'author_id': 16515, 'author_profile': 'https://Stackoverflow.com/users/16515', 'pm_score': 2, 'selected': False, 'text': '<p>I had the chance to play around with QF-TEST once. It is commercial, but offers a lot of functionality. Maybe you have a look at it: <a href="http://www.qftest.de/en/index.html" rel="nofollow noreferrer">http://www.qftest.de/en/index.html</a></p>\n'}, {'answer_id': 122284, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Consider Marathon (<a href="http://www.marathontesting.com/Home.html)--tests" rel="nofollow noreferrer">http://www.marathontesting.com/Home.html)--tests</a> are written in Jython, so it\'s easy to write any sort of predicates based on object state.</p>\n'}, {'answer_id': 142382, 'author': 'Tom', 'author_id': 22850, 'author_profile': 'https://Stackoverflow.com/users/22850', 'pm_score': 1, 'selected': False, 'text': '<p>I like Jemmy, the library written to test Netbeans.</p>\n'}, {'answer_id': 1001008, 'author': 'Dema', 'author_id': 407003, 'author_profile': 'https://Stackoverflow.com/users/407003', 'pm_score': 2, 'selected': False, 'text': '<p>You can try to use <a href="http://cukes.info" rel="nofollow noreferrer">Cucumber</a> and <a href="http://github.com/demetriusnunes/swinger" rel="nofollow noreferrer">Swinger</a> for writing functional acceptance tests in plain english for Swing GUI applications. Swinger uses Netbeans\' <a href="http://jemmy.dev.java.net" rel="nofollow noreferrer">Jemmy</a> library under the hood to drive the app.</p>\n\n<p>Cucumber allows you to write tests like this:</p>\n\n<pre><code> Scenario: Dialog manipulation\n Given the frame "SwingSet" is visible\n And the frame "SwingSet" is the container\n When I click the menu "File/About"\n Then I should see the dialog "About Swing!"\n Given the dialog "About Swing!" is the container\n When I click the button "OK"\n Then I should not see the dialog "About Swing!"\n</code></pre>\n\n<p>Take a look at this <a href="http://blog.demetriusnunes.com/past/2009/6/9/who_said_you_cant_test_swing_apps/" rel="nofollow noreferrer">Swinger video demo</a> to see it in action.</p>\n'}, {'answer_id': 1671337, 'author': 'bguiz', 'author_id': 194982, 'author_profile': 'https://Stackoverflow.com/users/194982', 'pm_score': 3, 'selected': False, 'text': '<p>If your target application has <strong>custom components</strong>, I would definitely recommend <a href="http://www.marathontesting.com/" rel="noreferrer">Marathon</a> to automate your tests.</p>\n\n<p>I was given the task of automating an application with several <em>extremely</em> complicated custom components, written in-house from the ground up. I went through a review process that lasted two months, in which I made the decision on which test tool to use, from a list of close to 30 test tools that were available, both commercial and FOSS.</p>\n\n<p>It was the <em>only</em> test tool that was able to successfully automate our particular custom components; where IBM\'s Rational Functional Tester, Microfocus\' TestPartner, QF-Test, Abbot & FEST <strong>failed</strong>.</p>\n\n<p>I have since been able to successfully integrate the tests with Cruise Control such that they run upon completing each build of the application.</p>\n\n<p>A word of warning though:<br>\n1) it is rather rough around the edges in the way it handles JTables. I got around this by writing my own proxy class for them.<br>\n2) Does not support record/replay of drag-and-drop actions yet.</p>\n'}, {'answer_id': 6246981, 'author': 'NullPumpkinException', 'author_id': 294439, 'author_profile': 'https://Stackoverflow.com/users/294439', 'pm_score': 2, 'selected': False, 'text': '<p>I can highly recommend QFTest. I have used it for my commercial product and it works very well with almost zero code (my app requires the use java client APIs for some things). It handles identification of swing components well, and is pretty tolerant of updates to your GUI - (resizing,repositioning and adding components does not break existing tests). I have done major updates to functionality and have my tests still work.</p>\n\n<p>Its expensive, but I think it will pay itself off in a couple of months.</p>\n\n<p>Before QFTest I tried:</p>\n\n<p>1) Automatedqa - good tool, but windows centric and does not understand Swing. Similar to Quick test Pro.</p>\n\n<p>2)UISpec4J - After devoting a solid 50 hour week to this, I had issues with fragility and the arcane java code it produced. Using it was just too arduous - trying to debug/update hundreds of lines of java performing a sequence of a dozen GUI operations just did not work for my brain. I ended up avoiding writing tests because it much more complicated than actually writing the app itself!</p>\n'}, {'answer_id': 12822044, 'author': 'Tim Ottinger', 'author_id': 15929, 'author_profile': 'https://Stackoverflow.com/users/15929', 'pm_score': 2, 'selected': False, 'text': "<p>Not an answer, but a refining.</p>\n\n<p>Record-and-playback is the wrong thing to want. Teams need the ability to write tests before the code has been written. Otherwise, the coders finish their work and wait around while the testers scramble to record tests (interrupted by fixes when they spot issues). </p>\n\n<p>In a BDD/TDD/ATDD kind of setup, you really need some kind of tool that allows you to script tests for code that hasn't been written yet, specifying UI element names and the like. </p>\n\n<p>Are there tools that work for non-waterfall testing? </p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13812/'] |
79,892 | <p>We have two tasks (T1 and T2) in our vxWorks embedded system that have the same priority (110).<br>
How does the regular vxWorks scheduler deal with this if both tasks are ready to run?<br>
Which task executes first?</p>
| [{'answer_id': 80240, 'author': 'unwieldy', 'author_id': 14963, 'author_profile': 'https://Stackoverflow.com/users/14963', 'pm_score': 4, 'selected': True, 'text': '<p>The task that will run first is the task that is spawned first as realized by the VxWorks scheduler task. VxWorks uses <strong>priority-based scheduling</strong> by default. So in your case, since T1 and T2 have the same priority, whichever one gets the CPU first will continue to run indefinitely until it is explicitly blocked (using <em>taskSuspend</em> or <em>taskDelay</em>), at which time the other READY task will execute until it is blocked, and so on. This ought to be controlled by semaphores or mutexes (mutices?)</p>\n\n<p>The main problem with priority-based scheduling is illuminated by this exact problem. How do we determine how long to let these tasks run? The fact that they have the same priority complicates things. Another concern is that VxWorks tasks that have high priority (lower number means higher priority) can preempt your application which you must be prepared for in your code. These problems can be solved by using <strong>round-robin scheduling</strong>. The additional problems posed by round-robin scheduling and the solutions are all described <a href="http://www.cs.ru.nl/lab/vxworks/vxworksOS.html" rel="noreferrer">here</a>.</p>\n'}, {'answer_id': 88820, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 2, 'selected': False, 'text': '<p>VxWorks has 256 priority levels (0 is highest, 255 is lowest). At any given time, the highest priority task runs on the CPU. Each priority level conceptually has a queue where multiple tasks queue up for execution.</p>\n\n<p>We have 3 tasks at the same priority A, B, C. Assume A is executing.<br>\nWhen A blocks (taskDelay, SemTake, msgQReceive), B will start execution.<br>\nWhen A unblocks, it is put at the end of the queue. We now have B, C, A.<br>\nWhen B blocks, C takes over, etc...</p>\n\n<p>If Round Robin scheduling (Time slicing) is enabled, the same concept applies, but the task gets put at the end of the queue when its time slice is over.</p>\n\n<p>Note that a task being pre-empted by a higher priority task will NOT affect the order of the queue. If A was running and gets pre-empted, it will continue execution when the higher priority task is done. It does not get put at the end of the queue.</p>\n'}, {'answer_id': 879630, 'author': 'robert.berger', 'author_id': 108743, 'author_profile': 'https://Stackoverflow.com/users/108743', 'pm_score': 1, 'selected': False, 'text': '<p>By default the one which is spawned first will be executing and unless it gives up the CPU the other will never run.</p>\n\n<p>You can explicitly enable round robin, than they will timeslice.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10703/'] |
79,898 | <p>Is there a way to prevent mspdbsrv.exe from continuing to run
after finishing the compilation? or even after I terminate visual studio? or perhaps even prevent it from even spawning in the first place?</p>
<p>what is this guy good for anyway?</p>
<p>using vs2005</p>
| [{'answer_id': 80163, 'author': 'Jeff Hill', 'author_id': 14742, 'author_profile': 'https://Stackoverflow.com/users/14742', 'pm_score': 4, 'selected': False, 'text': '<p>mspdbsrv.exe is the process Visual Studio uses to create .pdb files when you compile; these are the symbol files that let you debug an application. Sometimes it goes berserk and doesn\'t shutdown correctly when you exit Visual Studio. I\'ve had this cause bad compiles even after quitting and restarting Visual Studio. Use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653" rel="noreferrer">Process Explorer</a> or the task list (Ctrl+Alt+Delete in Windows) to manually kill mspdbsrv.exe if it\'s broken on you.</p>\n\n<p>For what it\'s worth, I haven\'t seen this problem happen in Visual Studio 2008 as of yet, but I\'ve only been using it a few days.</p>\n'}, {'answer_id': 426325, 'author': 'JesperE', 'author_id': 13051, 'author_profile': 'https://Stackoverflow.com/users/13051', 'pm_score': 2, 'selected': False, 'text': "<p>A little googling seems to indicate that mspdbsrv.exe zombies are a known issue in VS2005. We've had similar (intermittent) problems, but there did not seem to be a solution.</p>\n\n<p>Yes, it sucks.</p>\n"}, {'answer_id': 2363682, 'author': 'sum1stolemyname', 'author_id': 264347, 'author_profile': 'https://Stackoverflow.com/users/264347', 'pm_score': 4, 'selected': False, 'text': '<p>MS recommends to add a postbuild-event to the Project options <a href="http://blogs.msdn.com/ravi_kumar/archive/2009/06/17/my-2-cents-on-mspdbsrv-exe.aspx" rel="noreferrer">here</a>.</p>\n\n<blockquote>\n <p>[...]Sometimes it is possible that\n mspdbsrv.exe stays alive even after\n the build is over. In such scenarios,\n it is safe to add a post build event\n to kill the mspdbsrv.exe. </p>\n</blockquote>\n\n<p>Background infos on postbuild-Events can be found on the <a href="http://blogs.msdn.com/ravi_kumar/archive/2009/06/17/my-2-cents-on-mspdbsrv-exe.aspx" rel="noreferrer">linked</a> page.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9611/'] |
79,918 | <p>How are folks integrating various static analysis tools such as PMD, Checkstyle, and FindBugs so that they are used together in some uniform way? In particular, I'm interested in generating a single uniform report that includes warnings from all tools. Also, I want to be able to mark-up my code with reasonably consistent looking warning suppressions.</p>
<p>My question here is not meant to address tool "overlap" where, say, PMD and Checkstyle are looking for the same things. That is another issue.</p>
<p>Please see some of my <a href="https://stackoverflow.com/questions/4080/what-code-analysis-tools-do-you-use-for-your-java-projects#79845"> thoughts on the matter in an answer</a> to <a href="https://stackoverflow.com/questions/4080/what-code-analysis-tools-do-you-use-for-your-java-projects">a related question</a>.</p>
| [{'answer_id': 79948, 'author': 'user11087', 'author_id': 11087, 'author_profile': 'https://Stackoverflow.com/users/11087', 'pm_score': 1, 'selected': False, 'text': '<p>I am not clear on what qualifies as a single uniform report in your book but here is what I do.</p>\n\n<p>I use Maven2 for builds and with it you can configure a series of reporting plugins (including PMD, CPD, checkstyle, coberturba, etc). Maven will also auto-generate a website (site plugin) for your project which contains all the reports in a nice easy-to-navigate webpage format.</p>\n'}, {'answer_id': 79952, 'author': 'Dónal', 'author_id': 2648, 'author_profile': 'https://Stackoverflow.com/users/2648', 'pm_score': 0, 'selected': False, 'text': '<p>If you build your project with Maven, and you have those tools "plugged in" to your Maven build, then the Maven report that is generated for the build will include the output of those static analysis tools.</p>\n'}, {'answer_id': 84051, 'author': 'Greg Mattes', 'author_id': 13940, 'author_profile': 'https://Stackoverflow.com/users/13940', 'pm_score': 0, 'selected': False, 'text': '<p>Thanks for the responses!</p>\n\n<p>The goal here is to configure these tools so that they behave in some similar manner with respect to each other. This goes beyond simply dumping whatever report they generate automatically, or using whatever warning suppression hint they use out-of-the-box.</p>\n\n<p>For example, I have PMD, Checkstyle, and FindBugs configured to report all warnings in the following format:</p>\n\n<pre><code>/absolute-path/filename:line-number:column-number: warning(tool-name): message</code></pre>\n\n<p><p>So a warning might look like this:</p>\n\n<pre><code>/project/src/com/example/Foo.java:425:9: warning(Checkstyle): Missing a Javadoc comment.</code></pre>\n\n<p><p>Also, all warning suppressions in my source code are marked with a symbol that includes the string "<code>SuppressWarnings</code>" regardless of the static analysis tool being surpressed. Sometimes this symbol is an annotation, sometimes it\'s in a comment, but it always has that name.</p>\n\n<p><p>I explain these ideas in a bit more detail <a href="https://stackoverflow.com/questions/4080/what-code-analysis-tools-do-you-use-for-your-java-projects#79845">here</a>.</p>\n'}, {'answer_id': 203360, 'author': 'Alex Varju', 'author_id': 18208, 'author_profile': 'https://Stackoverflow.com/users/18208', 'pm_score': 2, 'selected': False, 'text': '<p>I stumbled across <a href="http://www.jcoderz.org/fawkez/wiki/JcReport" rel="nofollow noreferrer">JcReport</a> today, which I think does exactly what you are looking for. At least, it handles the reports in a combined way; suppressions are still tool-specific. This tool claims to support automatically integrating the output of PMD, CPD, FindBugs, CheckStyle, and Cobertura into a single HTML report.</p>\n\n<p>I haven\'t tried it yet, but definitely intend to soon.</p>\n'}, {'answer_id': 208080, 'author': 'Dave', 'author_id': 28068, 'author_profile': 'https://Stackoverflow.com/users/28068', 'pm_score': 2, 'selected': False, 'text': '<p>Another option is glean. <a href="http://jbrugge.com/glean/" rel="nofollow noreferrer">http://jbrugge.com/glean/</a></p>\n\n<p>From their website: Glean is a framework of Ant scripts for generating feedback on a team\'s source code. Glean\'s goal is to make it possible to add feedback to your build cycle with as little pain as possible. The scripts drive a number of open-source tools and collect the resulting HTML for you to deploy to a project website or some other common team area. Add it at the end of a daily build cycle and it is a quick way to keep a number of feedback sources up to date and in one place. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13940/'] |
79,923 | <ul>
<li>What are the stack and heap?</li>
<li>Where are they located physically in a computer's memory?</li>
<li>To what extent are they controlled by the OS or language run-time?</li>
<li>What is their scope?</li>
<li>What determines their sizes?</li>
<li>What makes one faster?</li>
</ul>
| [{'answer_id': 79936, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 11, 'selected': False, 'text': '<p><strong>Stack:</strong></p>\n\n<ul>\n<li>Stored in computer RAM just like the heap.</li>\n<li>Variables created on the stack will go out of scope and are automatically deallocated.</li>\n<li>Much faster to allocate in comparison to variables on the heap.</li>\n<li>Implemented with an actual stack data structure.</li>\n<li>Stores local data, return addresses, used for parameter passing.</li>\n<li>Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).</li>\n<li>Data created on the stack can be used without pointers.</li>\n<li>You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.</li>\n<li>Usually has a maximum size already determined when your program starts.</li>\n</ul>\n\n<p><strong>Heap:</strong></p>\n\n<ul>\n<li>Stored in computer RAM just like the stack.</li>\n<li>In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with <code>delete</code>, <code>delete[]</code>, or <code>free</code>.</li>\n<li>Slower to allocate in comparison to variables on the stack.</li>\n<li>Used on demand to allocate a block of data for use by the program.</li>\n<li>Can have fragmentation when there are a lot of allocations and deallocations.</li>\n<li>In C++ or C, data created on the heap will be pointed to by pointers and allocated with <code>new</code> or <code>malloc</code> respectively.</li>\n<li>Can have allocation failures if too big of a buffer is requested to be allocated.</li>\n<li>You would use the heap if you don\'t know exactly how much data you will need at run time or if you need to allocate a lot of data.</li>\n<li>Responsible for memory leaks.</li>\n</ul>\n\n<p><strong>Example:</strong></p>\n\n<pre class="lang-cpp prettyprint-override"><code>int foo()\n{\n char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).\n bool b = true; // Allocated on the stack.\n if(b)\n {\n //Create 500 bytes on the stack\n char buffer[500];\n\n //Create 500 bytes on the heap\n pBuffer = new char[500];\n\n }//<-- buffer is deallocated here, pBuffer is not\n}//<--- oops there\'s a memory leak, I should have called delete[] pBuffer;\n</code></pre>\n'}, {'answer_id': 79988, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 8, 'selected': False, 'text': '<p><strong>The Stack</strong>\nWhen you call a function the arguments to that function plus some other overhead is put on the stack. Some info (such as where to go on return) is also stored there.\nWhen you declare a variable inside your function, that variable is also allocated on the stack. </p>\n\n<p>Deallocating the stack is pretty simple because you always deallocate in the reverse order in which you allocate. Stack stuff is added as you enter functions, the corresponding data is removed as you exit them. This means that you tend to stay within a small region of the stack unless you call lots of functions that call lots of other functions (or create a recursive solution).</p>\n\n<p><strong>The Heap</strong>\nThe heap is a generic name for where you put the data that you create on the fly. If you don\'t know how many spaceships your program is going to create, you are likely to use the new (or malloc or equivalent) operator to create each spaceship. This allocation is going to stick around for a while, so it is likely we will free things in a different order than we created them. </p>\n\n<p>Thus, the heap is far more complex, because there end up being regions of memory that are unused interleaved with chunks that are - memory gets fragmented. Finding free memory of the size you need is a difficult problem. This is why the heap should be avoided (though it is still often used).</p>\n\n<p><strong>Implementation</strong>\nImplementation of both the stack and heap is usually down to the runtime / OS. Often games and other applications that are performance critical create their own memory solutions that grab a large chunk of memory from the heap and then dish it out internally to avoid relying on the OS for memory. </p>\n\n<p>This is only practical if your memory usage is quite different from the norm - i.e for games where you load a level in one huge operation and can chuck the whole lot away in another huge operation.</p>\n\n<p><strong>Physical location in memory</strong>\nThis is less relevant than you think because of a technology called <a href="http://en.wikipedia.org/wiki/Virtual_memory" rel="noreferrer">Virtual Memory</a> which makes your program think that you have access to a certain address where the physical data is somewhere else (even on the hard disc!). The addresses you get for the stack are in increasing order as your call tree gets deeper. The addresses for the heap are un-predictable (i.e implimentation specific) and frankly not important.</p>\n'}, {'answer_id': 79997, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 7, 'selected': False, 'text': "<p>The stack is a portion of memory that can be manipulated via several key assembly language instructions, such as 'pop' (remove and return a value from the stack) and 'push' (push a value to the stack), but also call (call a subroutine - this pushes the address to return to the stack) and return (return from a subroutine - this pops the address off of the stack and jumps to it). It's the region of memory below the stack pointer register, which can be set as needed. The stack is also used for passing arguments to subroutines, and also for preserving the values in registers before calling subroutines.</p>\n\n<p>The heap is a portion of memory that is given to an application by the operating system, typically through a syscall like malloc. On modern OSes this memory is a set of pages that only the calling process has access to.</p>\n\n<p>The size of the stack is determined at runtime, and generally does not grow after the program launches. In a C program, the stack needs to be large enough to hold every variable declared within each function. The heap will grow dynamically as needed, but the OS is ultimately making the call (it will often grow the heap by more than the value requested by malloc, so that at least some future mallocs won't need to go back to the kernel to get more memory. This behavior is often customizable)</p>\n\n<p>Because you've allocated the stack before launching the program, you never need to malloc before you can use the stack, so that's a slight advantage there. In practice, it's very hard to predict what will be fast and what will be slow in modern operating systems that have virtual memory subsystems, because how the pages are implemented and where they are stored is an implementation detail. </p>\n"}, {'answer_id': 80094, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 7, 'selected': False, 'text': '<p>Others have answered the broad strokes pretty well, so I\'ll throw in a few details.</p>\n\n<ol>\n<li><p>Stack and heap need not be singular. A common situation in which you have more than one stack is if you have more than one thread in a process. In this case each thread has its own stack. You can also have more than one heap, for example some DLL configurations can result in different DLLs allocating from different heaps, which is why it\'s generally a bad idea to release memory allocated by a different library.</p></li>\n<li><p>In C you can get the benefit of variable length allocation through the use of <a href="https://www.freebsd.org/cgi/man.cgi?alloca" rel="noreferrer">alloca</a>, which allocates on the stack, as opposed to alloc, which allocates on the heap. This memory won\'t survive your return statement, but it\'s useful for a scratch buffer.</p></li>\n<li><p>Making a huge temporary buffer on Windows that you don\'t use much of is not free. This is because the compiler will generate a stack probe loop that is called every time your function is entered to make sure the stack exists (because Windows uses a single guard page at the end of your stack to detect when it needs to grow the stack. If you access memory more than one page off the end of the stack you will crash). Example:</p></li>\n</ol>\n\n<pre class="lang-cpp prettyprint-override"><code>void myfunction()\n{\n char big[10000000];\n // Do something that only uses for first 1K of big 99% of the time.\n}\n</code></pre>\n'}, {'answer_id': 80113, 'author': 'Jeff Hill', 'author_id': 14742, 'author_profile': 'https://Stackoverflow.com/users/14742', 'pm_score': 14, 'selected': True, 'text': '<p>The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.</p>\n<p>The heap is memory set aside for dynamic allocation. Unlike the stack, there\'s no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.</p>\n<p>Each thread gets a stack, while there\'s typically only one heap for the application (although it isn\'t uncommon to have multiple heaps for different types of allocation).</p>\n<p>To answer your questions directly:</p>\n<blockquote>\n<p><em>To what extent are they controlled by the OS or language runtime?</em></p>\n</blockquote>\n<p>The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.</p>\n<blockquote>\n<p><em>What is their scope?</em></p>\n</blockquote>\n<p>The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.</p>\n<blockquote>\n<p><em>What determines the size of each of them?</em></p>\n</blockquote>\n<p>The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).</p>\n<blockquote>\n<p><em>What makes one faster?</em></p>\n</blockquote>\n<p>The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor\'s cache, making it very fast. Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with "all" other heap accesses in the program.</p>\n<p>A clear demonstration:\n<img src="https://i.stack.imgur.com/i6k0Z.png" alt="" />\n<br/><sub>Image source: <a href="http://vikashazrati.wordpress.com/2007/10/01/quicktip-java-basics-stack-and-heap/" rel="noreferrer">vikashazrati.wordpress.com</a></sub></p>\n'}, {'answer_id': 80142, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<p>I think many other people have given you mostly correct answers on this matter.</p>\n\n<p>One detail that has been missed, however, is that the "heap" should in fact probably be called the "free store". The reason for this distinction is that the original free store was implemented with a data structure known as a "binomial heap." For that reason, allocating from early implementations of malloc()/free() was allocation from a heap. However, in this modern day, most free stores are implemented with very elaborate data structures that are not binomial heaps.</p>\n'}, {'answer_id': 80740, 'author': 'bk1e', 'author_id': 8090, 'author_profile': 'https://Stackoverflow.com/users/8090', 'pm_score': 7, 'selected': False, 'text': '<p>Others have directly answered your question, but when trying to understand the stack and the heap, I think it is helpful to consider the memory layout of a traditional UNIX process (without threads and <code>mmap()</code>-based allocators). The <a href="https://www.memorymanagement.org/glossary/b.html#term-brk" rel="nofollow noreferrer">Memory Management Glossary</a> web page has a diagram of this memory layout.</p>\n<p>The stack and heap are traditionally located at opposite ends of the process\'s virtual address space. The stack grows automatically when accessed, up to a size set by the kernel (which can be adjusted with <code>setrlimit(RLIMIT_STACK, ...)</code>). The heap grows when the memory allocator invokes the <code>brk()</code> or <code>sbrk()</code> system call, mapping more pages of physical memory into the process\'s virtual address space.</p>\n<p>In systems without virtual memory, such as some embedded systems, the same basic layout often applies, except the stack and heap are fixed in size. However, in other embedded systems (such as those based on Microchip PIC microcontrollers), the program stack is a separate block of memory that is not addressable by data movement instructions, and can only be modified or read indirectly through program flow instructions (call, return, etc.). Other architectures, such as Intel Itanium processors, have <a href="https://devblogs.microsoft.com/oldnewthing/20050421-28/?p=35833" rel="nofollow noreferrer">multiple stacks</a>. In this sense, the stack is an element of the CPU architecture.</p>\n'}, {'answer_id': 662454, 'author': 'thomasrutter', 'author_id': 53212, 'author_profile': 'https://Stackoverflow.com/users/53212', 'pm_score': 11, 'selected': False, 'text': '<p>The most important point is that heap and stack are generic terms for ways in which memory can be allocated. They can be implemented in many different ways, and the terms apply to the basic concepts.</p>\n\n<ul>\n<li><p>In a stack of items, items sit one on top of the other in the order they were placed there, and you can only remove the top one (without toppling the whole thing over).</p>\n\n<p><img src="https://i.stack.imgur.com/ZLzMV.jpg" alt="Stack like a stack of papers"></p>\n\n<p>The simplicity of a stack is that you do not need to maintain a table containing a record of each section of allocated memory; the only state information you need is a single pointer to the end of the stack. To allocate and de-allocate, you just increment and decrement that single pointer. Note: a stack can sometimes be implemented to start at the top of a section of memory and extend downwards rather than growing upwards.</p></li>\n<li><p>In a heap, there is no particular order to the way items are placed. You can reach in and remove items in any order because there is no clear \'top\' item.</p>\n\n<p><img src="https://i.stack.imgur.com/kINqo.jpg" alt="Heap like a heap of licorice allsorts"></p>\n\n<p>Heap allocation requires maintaining a full record of what memory is allocated and what isn\'t, as well as some overhead maintenance to reduce fragmentation, find contiguous memory segments big enough to fit the requested size, and so on. Memory can be deallocated at any time leaving free space. Sometimes a memory allocator will perform maintenance tasks such as defragmenting memory by moving allocated memory around, or garbage collecting - identifying at runtime when memory is no longer in scope and deallocating it. </p></li>\n</ul>\n\n<p>These images should do a fairly good job of describing the two ways of allocating and freeing memory in a stack and a heap. Yum!</p>\n\n<ul>\n<li><p>To what extent are they controlled by the OS or language runtime?</p>\n\n<p>As mentioned, heap and stack are general terms, and can be implemented in many ways. Computer programs typically have a stack called a <a href="http://en.wikipedia.org/wiki/Call_stack" rel="noreferrer">call stack</a> which stores information relevant to the current function such as a pointer to whichever function it was called from, and any local variables. Because functions call other functions and then return, the stack grows and shrinks to hold information from the functions further down the call stack. A program doesn\'t really have runtime control over it; it\'s determined by the programming language, OS and even the system architecture.</p>\n\n<p>A heap is a general term used for any memory that is allocated dynamically and randomly; i.e. out of order. The memory is typically allocated by the OS, with the application calling API functions to do this allocation. There is a fair bit of overhead required in managing dynamically allocated memory, which is usually handled by the runtime code of the programming language or environment used.</p></li>\n<li><p>What is their scope?</p>\n\n<p>The call stack is such a low level concept that it doesn\'t relate to \'scope\' in the sense of programming. If you disassemble some code you\'ll see relative pointer style references to portions of the stack, but as far as a higher level language is concerned, the language imposes its own rules of scope. One important aspect of a stack, however, is that once a function returns, anything local to that function is immediately freed from the stack. That works the way you\'d expect it to work given how your programming languages work. In a heap, it\'s also difficult to define. The scope is whatever is exposed by the OS, but your programming language probably adds its rules about what a "scope" is in your application. The processor architecture and the OS use virtual addressing, which the processor translates to physical addresses and there are page faults, etc. They keep track of what pages belong to which applications. You never really need to worry about this, though, because you just use whatever method your programming language uses to allocate and free memory, and check for errors (if the allocation/freeing fails for any reason).</p></li>\n<li><p>What determines the size of each of them?</p>\n\n<p>Again, it depends on the language, compiler, operating system and architecture. A stack is usually pre-allocated, because by definition it must be contiguous memory. The language compiler or the OS determine its size. You don\'t store huge chunks of data on the stack, so it\'ll be big enough that it should never be fully used, except in cases of unwanted endless recursion (hence, "stack overflow") or other unusual programming decisions.</p>\n\n<p>A heap is a general term for anything that can be dynamically allocated. Depending on which way you look at it, it is constantly changing size. In modern processors and operating systems the exact way it works is very abstracted anyway, so you don\'t normally need to worry much about how it works deep down, except that (in languages where it lets you) you mustn\'t use memory that you haven\'t allocated yet or memory that you have freed.</p></li>\n<li><p>What makes one faster?</p>\n\n<p>The stack is faster because all free memory is always contiguous. No list needs to be maintained of all the segments of free memory, just a single pointer to the current top of the stack. Compilers usually store this pointer in a special, fast <a href="http://en.wikipedia.org/wiki/Stack_register" rel="noreferrer">register</a> for this purpose. What\'s more, subsequent operations on a stack are usually concentrated within very nearby areas of memory, which at a very low level is good for optimization by the processor on-die caches.</p></li>\n</ul>\n'}, {'answer_id': 662570, 'author': 'T.E.D.', 'author_id': 29639, 'author_profile': 'https://Stackoverflow.com/users/29639', 'pm_score': 7, 'selected': False, 'text': '<p>Simply, the stack is where local variables get created. Also, every time you call a subroutine the program counter (pointer to the next machine instruction) and any important registers, and sometimes the parameters get pushed on the stack. Then any local variables inside the subroutine are pushed onto the stack (and used from there). When the subroutine finishes, that stuff all gets popped back off the stack. The PC and register data gets and put back where it was as it is popped, so your program can go on its merry way.</p>\n\n<p>The heap is the area of memory dynamic memory allocations are made out of (explicit "new" or "allocate" calls). It is a special data structure that can keep track of blocks of memory of varying sizes and their allocation status.</p>\n\n<p>In "classic" systems RAM was laid out such that the stack pointer started out at the bottom of memory, the heap pointer started out at the top, and they grew towards each other. If they overlap, you are out of RAM. That doesn\'t work with modern multi-threaded OSes though. Every thread has to have its own stack, and those can get created dynamicly.</p>\n'}, {'answer_id': 662783, 'author': 'Peter', 'author_id': 80094, 'author_profile': 'https://Stackoverflow.com/users/80094', 'pm_score': 7, 'selected': False, 'text': '<p>You can do some interesting things with the stack. For instance, you have functions like <a href="http://everything2.com/title/alloca%2528%2529" rel="noreferrer">alloca</a> (assuming you can get past the copious warnings concerning its use), which is a form of malloc that specifically uses the stack, not the heap, for memory.</p>\n\n<p>That said, stack-based memory errors are some of the worst I\'ve experienced. If you use heap memory, and you overstep the bounds of your allocated block, you have a decent chance of triggering a segment fault. (Not 100%: your block may be incidentally contiguous with another that you have previously allocated.) But since variables created on the stack are always contiguous with each other, writing out of bounds can change the value of another variable. I have learned that whenever I feel that my program has stopped obeying the laws of logic, it is probably buffer overflow.</p>\n'}, {'answer_id': 707970, 'author': 'devXen', 'author_id': 50021, 'author_profile': 'https://Stackoverflow.com/users/50021', 'pm_score': 6, 'selected': False, 'text': '<p>From WikiAnwser.</p>\n\n<h3>Stack</h3>\n\n<p>When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value.</p>\n\n<p>This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other.</p>\n\n<p>The stack is important to consider in exception handling and thread executions.</p>\n\n<h3>Heap</h3>\n\n<p>The heap is simply the memory used by programs to store variables.\nElement of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.</p>\n'}, {'answer_id': 1213360, 'author': 'Martin Liversage', 'author_id': 98607, 'author_profile': 'https://Stackoverflow.com/users/98607', 'pm_score': 10, 'selected': False, 'text': '<p>(I have moved this answer from another question that was more or less a dupe of this one.)</p>\n<p>The answer to your question is implementation specific and may vary across compilers and processor architectures. However, here is a simplified explanation.</p>\n<ul>\n<li>Both the stack and the heap are memory areas allocated from the underlying operating system (often virtual memory that is mapped to physical memory on demand).</li>\n<li>In a multi-threaded environment each thread will have its own completely independent stack but they will share the heap. Concurrent access has to be controlled on the heap and is not possible on the stack.</li>\n</ul>\n<h2>The heap</h2>\n<ul>\n<li>The heap contains a linked list of used and free blocks. New allocations on the heap (by <code>new</code> or <code>malloc</code>) are satisfied by creating a suitable block from one of the free blocks. This requires updating the list of blocks on the heap. This <em>meta information</em> about the blocks on the heap is also stored on the heap often in a small area just in front of every block.</li>\n<li>As the heap grows new blocks are often allocated from lower addresses towards higher addresses. Thus you can think of the heap as a <em>heap</em> of memory blocks that grows in size as memory is allocated. If the heap is too small for an allocation the size can often be increased by acquiring more memory from the underlying operating system.</li>\n<li>Allocating and deallocating many small blocks may leave the heap in a state where there are a lot of small free blocks interspersed between the used blocks. A request to allocate a large block may fail because none of the free blocks are large enough to satisfy the allocation request even though the combined size of the free blocks may be large enough. This is called <em>heap fragmentation</em>.</li>\n<li>When a used block that is adjacent to a free block is deallocated the new free block may be merged with the adjacent free block to create a larger free block effectively reducing the fragmentation of the heap.</li>\n</ul>\n<p><img src="https://i.stack.imgur.com/0Obi0.png" alt="The heap" /></p>\n<h2>The stack</h2>\n<ul>\n<li>The stack often works in close tandem with a special register on the CPU named the <em>stack pointer</em>. Initially the stack pointer points to the top of the stack (the highest address on the stack).</li>\n<li>The CPU has special instructions for <em>pushing</em> values onto the stack and <em>popping</em> them off the stack. Each <em>push</em> stores the value at the current location of the stack pointer and decreases the stack pointer. A <em>pop</em> retrieves the value pointed to by the stack pointer and then increases the stack pointer (don\'t be confused by the fact that <em>adding</em> a value to the stack <em>decreases</em> the stack pointer and <em>removing</em> a value <em>increases</em> it. Remember that the stack grows to the bottom). The values stored and retrieved are the values of the CPU registers.</li>\n<li>If a function has parameters, these are pushed onto the stack before the call to the function. The code in the function is then able to navigate up the stack from the current stack pointer to locate these values.</li>\n<li>When a function is called the CPU uses special instructions that push the current <em>instruction pointer</em> onto the stack, i.e. the address of the code executing on the stack. The CPU then jumps to the function by setting the instruction pointer to the address of the function called. Later, when the function returns, the old instruction pointer is popped off the stack and execution resumes at the code just after the call to the function.</li>\n<li>When a function is entered, the stack pointer is decreased to allocate more space on the stack for local (automatic) variables. If the function has one local 32 bit variable four bytes are set aside on the stack. When the function returns, the stack pointer is moved back to free the allocated area.</li>\n<li>Nesting function calls work like a charm. Each new call will allocate function parameters, the return address and space for local variables and these <em>activation records</em> can be stacked for nested calls and will unwind in the correct way when the functions return.</li>\n<li>As the stack is a limited block of memory, you can cause a <em>stack overflow</em> by calling too many nested functions and/or allocating too much space for local variables. Often the memory area used for the stack is set up in such a way that writing below the bottom (the lowest address) of the stack will trigger a trap or exception in the CPU. This exceptional condition can then be caught by the runtime and converted into some kind of stack overflow exception.</li>\n</ul>\n<p><img src="https://i.stack.imgur.com/9UshP.png" alt="The stack" /></p>\n<blockquote>\n<p>Can a function be allocated on the heap instead of a stack?</p>\n</blockquote>\n<p>No, activation records for functions (i.e. local or automatic variables) are allocated on the stack that is used not only to store these variables, but also to keep track of nested function calls.</p>\n<p>How the heap is managed is really up to the runtime environment. C uses <code>malloc</code> and C++ uses <code>new</code>, but many other languages have garbage collection.</p>\n<p>However, the stack is a more low-level feature closely tied to the processor architecture. Growing the heap when there is not enough space isn\'t too hard since it can be implemented in the library call that handles the heap. However, growing the stack is often impossible as the stack overflow only is discovered when it is too late; and shutting down the thread of execution is the only viable option.</p>\n'}, {'answer_id': 13308092, 'author': 'Snowcrash', 'author_id': 343204, 'author_profile': 'https://Stackoverflow.com/users/343204', 'pm_score': 9, 'selected': False, 'text': '<p>In the following C# code</p>\n<pre class="lang-cs prettyprint-override"><code>public void Method1()\n{\n int i = 4;\n int y = 2;\n class1 cls1 = new class1();\n}\n</code></pre>\n<p>Here\'s how the memory is managed</p>\n<p><img src="https://i.stack.imgur.com/NS0k7.jpg" alt="Picture of variables on the stack" /></p>\n<p><code>Local Variables</code> that only need to last as long as the function invocation go in the stack. The heap is used for variables whose lifetime we don\'t really know up front but we expect them to last a while. In most languages it\'s critical that we know at compile time how large a variable is if we want to store it on the stack.</p>\n<p>Objects (which vary in size as we update them) go on the heap because we don\'t know at creation time how long they are going to last. In many languages the heap is garbage collected to find objects (such as the cls1 object) that no longer have any references.</p>\n<p>In Java, most objects go directly into the heap. In languages like C / C++, structs and classes can often remain on the stack when you\'re not dealing with pointers.</p>\n<p>More information can be found here:</p>\n<p><a href="https://web.archive.org/web/20200216082556/http://timmurphy.org/2010/08/11/the-difference-between-stack-and-heap-memory-allocation/" rel="noreferrer">The difference between stack and heap memory allocation « timmurphy.org</a></p>\n<p>and here:</p>\n<p><a href="https://root.cern.ch/root/htmldoc/guides/users-guide/ALittleC++.html#creating-objects-on-the-stack-and-heap" rel="noreferrer">Creating Objects on the Stack and Heap</a></p>\n<p>This article is the source of picture above: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types#Stack%20and%20Heap" rel="noreferrer">Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing - CodeProject</a></p>\n<p>but be aware it may contain some inaccuracies.</p>\n'}, {'answer_id': 13326916, 'author': 'davec', 'author_id': 1763801, 'author_profile': 'https://Stackoverflow.com/users/1763801', 'pm_score': 8, 'selected': False, 'text': '<p>Other answers just avoid explaining what static allocation means. So I will explain the three main forms of allocation and how they usually relate to the heap, stack, and data segment below. I also will show some examples in both C/C++ and Python to help people understand.</p>\n<p>"Static" (AKA statically allocated) variables are not allocated on the stack. Do not assume so - many people do only because "static" sounds a lot like "stack". They actually exist in neither the stack nor the heap. They are part of what\'s called the <a href="http://en.wikipedia.org/wiki/Data_segment" rel="noreferrer">data segment</a>.</p>\n<p>However, it is generally better to consider "<strong>scope</strong>" and "<strong>lifetime</strong>" rather than "stack" and "heap".</p>\n<p>Scope refers to what parts of the code can access a variable. Generally we think of <strong>local scope</strong> (can only be accessed by the current function) versus <strong>global scope</strong> (can be accessed anywhere) although scope can get much more complex.</p>\n<p>Lifetime refers to when a variable is allocated and deallocated during program execution. Usually we think of <strong>static allocation</strong> (variable will persist through the entire duration of the program, making it useful for storing the same information across several function calls) versus <strong>automatic allocation</strong> (variable only persists during a single call to a function, making it useful for storing information that is only used during your function and can be discarded once you are done) versus <strong>dynamic allocation</strong> (variables whose duration is defined at runtime, instead of compile time like static or automatic).</p>\n<p>Although most compilers and interpreters implement this behavior similarly in terms of using stacks, heaps, etc, a compiler may sometimes break these conventions if it wants as long as behavior is correct. For instance, due to optimization a local variable may only exist in a register or be removed entirely, even though most local variables exist in the stack. As has been pointed out in a few comments, you are free to implement a compiler that doesn\'t even use a stack or a heap, but instead some other storage mechanisms (rarely done, since stacks and heaps are great for this).</p>\n<p>I will provide some simple annotated C code to illustrate all of this. The best way to learn is to run a program under a debugger and watch the behavior. If you prefer to read python, skip to the end of the answer :)</p>\n<pre class="lang-cpp prettyprint-override"><code>// Statically allocated in the data segment when the program/DLL is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in the code\nint someGlobalVariable;\n\n// Statically allocated in the data segment when the program is first loaded\n// Deallocated when the program/DLL exits\n// scope - can be accessed from anywhere in this particular code file\nstatic int someStaticVariable;\n\n// "someArgument" is allocated on the stack each time MyFunction is called\n// "someArgument" is deallocated when MyFunction returns\n// scope - can be accessed only within MyFunction()\nvoid MyFunction(int someArgument) {\n\n // Statically allocated in the data segment when the program is first loaded\n // Deallocated when the program/DLL exits\n // scope - can be accessed only within MyFunction()\n static int someLocalStaticVariable;\n\n // Allocated on the stack each time MyFunction is called\n // Deallocated when MyFunction returns\n // scope - can be accessed only within MyFunction()\n int someLocalVariable;\n\n // A *pointer* is allocated on the stack each time MyFunction is called\n // This pointer is deallocated when MyFunction returns\n // scope - the pointer can be accessed only within MyFunction()\n int* someDynamicVariable;\n\n // This line causes space for an integer to be allocated in the heap\n // when this line is executed. Note this is not at the beginning of\n // the call to MyFunction(), like the automatic variables\n // scope - only code within MyFunction() can access this space\n // *through this particular variable*.\n // However, if you pass the address somewhere else, that code\n // can access it too\n someDynamicVariable = new int;\n\n\n // This line deallocates the space for the integer in the heap.\n // If we did not write it, the memory would be "leaked".\n // Note a fundamental difference between the stack and heap\n // the heap must be managed. The stack is managed for us.\n delete someDynamicVariable;\n\n // In other cases, instead of deallocating this heap space you\n // might store the address somewhere more permanent to use later.\n // Some languages even take care of deallocation for you... but\n // always it needs to be taken care of at runtime by some mechanism.\n\n // When the function returns, someArgument, someLocalVariable\n // and the pointer someDynamicVariable are deallocated.\n // The space pointed to by someDynamicVariable was already\n // deallocated prior to returning.\n return;\n}\n\n// Note that someGlobalVariable, someStaticVariable and\n// someLocalStaticVariable continue to exist, and are not\n// deallocated until the program exits.\n</code></pre>\n<p>A particularly poignant example of why it\'s important to distinguish between lifetime and scope is that a variable can have local scope but static lifetime - for instance, "someLocalStaticVariable" in the code sample above. Such variables can make our common but informal naming habits very confusing. For instance when we say "<em>local</em>" we usually mean "<em>locally scoped automatically allocated variable</em>" and when we say global we usually mean "<em>globally scoped statically allocated variable</em>". Unfortunately when it comes to things like "<em>file scoped statically allocated variables</em>" many people just say... "<em>huh???</em>".</p>\n<p>Some of the syntax choices in C/C++ exacerbate this problem - for instance many people think global variables are not "static" because of the syntax shown below.</p>\n<pre class="lang-cpp prettyprint-override"><code>int var1; // Has global scope and static allocation\nstatic int var2; // Has file scope and static allocation\n\nint main() {return 0;}\n</code></pre>\n<p>Note that putting the keyword "static" in the declaration above prevents var2 from having global scope. Nevertheless, the global var1 has static allocation. This is not intuitive! For this reason, I try to never use the word "static" when describing scope, and instead say something like "file" or "file limited" scope. However many people use the phrase "static" or "static scope" to describe a variable that can only be accessed from one code file. In the context of lifetime, "static" <em>always</em> means the variable is allocated at program start and deallocated when program exits.</p>\n<p>Some people think of these concepts as C/C++ specific. They are not. For instance, the Python sample below illustrates all three types of allocation (there are some subtle differences possible in interpreted languages that I won\'t get into here).</p>\n<pre class="lang-py prettyprint-override"><code>from datetime import datetime\n\nclass Animal:\n _FavoriteFood = \'Undefined\' # _FavoriteFood is statically allocated\n\n def PetAnimal(self):\n curTime = datetime.time(datetime.now()) # curTime is automatically allocatedion\n print("Thank you for petting me. But it\'s " + str(curTime) + ", you should feed me. My favorite food is " + self._FavoriteFood)\n\nclass Cat(Animal):\n _FavoriteFood = \'tuna\' # Note since we override, Cat class has its own statically allocated _FavoriteFood variable, different from Animal\'s\n\nclass Dog(Animal):\n _FavoriteFood = \'steak\' # Likewise, the Dog class gets its own static variable. Important to note - this one static variable is shared among all instances of Dog, hence it is not dynamic!\n\n\nif __name__ == "__main__":\n whiskers = Cat() # Dynamically allocated\n fido = Dog() # Dynamically allocated\n rinTinTin = Dog() # Dynamically allocated\n\n whiskers.PetAnimal()\n fido.PetAnimal()\n rinTinTin.PetAnimal()\n\n Dog._FavoriteFood = \'milkbones\'\n whiskers.PetAnimal()\n fido.PetAnimal()\n rinTinTin.PetAnimal()\n\n# Output is:\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is steak\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is tuna\n# Thank you for petting me. But it\'s 13:05:02.255000, you should feed me. My favorite food is milkbones\n# Thank you for petting me. But it\'s 13:05:02.256000, you should feed me. My favorite food is milkbones\n</code></pre>\n'}, {'answer_id': 21449421, 'author': 'unknown', 'author_id': 1152398, 'author_profile': 'https://Stackoverflow.com/users/1152398', 'pm_score': 6, 'selected': False, 'text': "<p><strong>Stack</strong></p>\n\n<ul>\n<li>Very fast access</li>\n<li>Don't have to explicitly de-allocate variables</li>\n<li>Space is managed efficiently by CPU, memory will not become fragmented</li>\n<li>Local variables only</li>\n<li>Limit on stack size (OS-dependent)</li>\n<li>Variables cannot be resized</li>\n</ul>\n\n<p><strong>Heap</strong></p>\n\n<ul>\n<li>Variables can be accessed globally</li>\n<li>No limit on memory size</li>\n<li>(Relatively) slower access</li>\n<li>No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed</li>\n<li>You must manage memory (you're in charge of allocating and freeing variables)</li>\n<li>Variables can be resized using realloc()</li>\n</ul>\n"}, {'answer_id': 24171266, 'author': 'Shreyos Adikari', 'author_id': 838841, 'author_profile': 'https://Stackoverflow.com/users/838841', 'pm_score': 7, 'selected': False, 'text': '<p><strong>What is a stack?</strong></p>\n<p>A stack is a pile of objects, typically one that is neatly arranged.</p>\n<p><a href="https://i.stack.imgur.com/GTa97.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/GTa97.jpg" alt="Enter image description here" /></a></p>\n<blockquote>\n<blockquote>\n<p>Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out manner. <br/>\nIn a multi-threaded application, each thread will have its own stack.</p>\n</blockquote>\n</blockquote>\n<p><strong>What is a heap?</strong></p>\n<p>A heap is an untidy collection of things piled up haphazardly.</p>\n<p><a href="https://i.stack.imgur.com/rz43z.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/rz43z.jpg" alt="Enter image description here" /></a></p>\n<blockquote>\n<blockquote>\n<p>In computing architectures the heap is an area of dynamically-allocated memory that is managed automatically by the operating system or the memory manager library. <br/>\nMemory on the heap is allocated, deallocated, and resized regularly during program execution, and this can lead to a problem called fragmentation. <br/>\nFragmentation occurs when memory objects are allocated with small spaces in between that are too small to hold additional memory objects. <br/>\nThe net result is a percentage of the heap space that is not usable for further memory allocations.</p>\n</blockquote>\n</blockquote>\n<p><strong>Both together</strong></p>\n<blockquote>\n<blockquote>\n<p>In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. <br/>\nBecause the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.</p>\n</blockquote>\n</blockquote>\n<p><strong>Which is faster – the stack or the heap? And why?</strong></p>\n<blockquote>\n<blockquote>\n<p>The stack is much faster than the heap. <br/>\nThis is because of the way that memory is allocated on the stack. <br/>\nAllocating memory on the stack is as simple as moving the stack pointer up.</p>\n</blockquote>\n</blockquote>\n<p>For people new to programming, it’s probably a good idea to use the stack since it’s easier. <br/>\nBecause the stack is small, you would want to use it when you know exactly how much memory you will need for your data, or if you know the size of your data is very small. <br/>\nIt’s better to use the heap when you know that you will need a lot of memory for your data, or you just are not sure how much memory you will need (like with a dynamic array).</p>\n<h3>Java Memory Model</h3>\n<p><a href="https://i.stack.imgur.com/yZK6t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yZK6t.png" alt="Enter image description here" /></a></p>\n<p>The stack is the area of memory where local variables (including method parameters) are stored. When it comes to object variables, these are merely references (pointers) to the actual objects on the heap.<br>\nEvery time an object is instantiated, a chunk of heap memory is set aside to hold the data (state) of that object. Since objects can contain other objects, some of this data can in fact hold references to those nested objects.</p>\n'}, {'answer_id': 28801420, 'author': 'shakurov', 'author_id': 2212026, 'author_profile': 'https://Stackoverflow.com/users/2212026', 'pm_score': 5, 'selected': False, 'text': '<p>Since some answers went nitpicking, I\'m going to contribute my mite.</p>\n\n<p>Surprisingly, no one has mentioned that multiple (i.e. not related to the number of running OS-level threads) call stacks are to be found not only in exotic languages (PostScript) or platforms (Intel Itanium), but also in <a href="http://en.wikipedia.org/wiki/Fiber_(computer_science)" rel="noreferrer"><em>fibers</em></a>, <a href="http://en.wikipedia.org/wiki/Green_threads" rel="noreferrer"><em>green threads</em></a> and some implementations of <a href="http://en.wikipedia.org/wiki/Coroutine" rel="noreferrer"><em>coroutines</em></a>.</p>\n\n<p>Fibers, green threads and coroutines are in many ways similar, which leads to much confusion. The difference between fibers and green threads is that the former use cooperative multitasking, while the latter may feature either cooperative or preemptive one (or even both). For the distinction between fibers and coroutines, see <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4024.pdf" rel="noreferrer">here</a>.</p>\n\n<p>In any case, the purpose of both fibers, green threads and coroutines is having multiple functions executing concurrently, but <strong>not</strong> in parallel (see <a href="https://stackoverflow.com/questions/1050222/concurrency-vs-parallelism-what-is-the-difference">this SO question</a> for the distinction) within a single OS-level thread, transferring control back and forth from one another in an organized fashion.</p>\n\n<p>When using fibers, green threads or coroutines, you <em>usually</em> have a separate stack per function. (Technically, not just a stack but a whole context of execution is per function. Most importantly, CPU registers.) For every thread there\'re as many stacks as there\'re concurrently running functions, and the thread is switching between executing each function according to the logic of your program. When a function runs to its end, its stack is destroyed. So, <strong>the number and lifetimes of stacks</strong> are dynamic and <strong>are not determined by the number of OS-level threads!</strong></p>\n\n<p>Note that I said "<em>usually</em> have a separate stack per function". There\'re both <em>stackful</em> and <em>stackless</em> implementations of couroutines. Most notable stackful C++ implementations are <a href="http://www.boost.org/doc/libs/1_53_0/libs/coroutine/doc/html/index.html" rel="noreferrer">Boost.Coroutine</a> and <a href="https://msdn.microsoft.com/en-us/library/dd492418.aspx" rel="noreferrer">Microsoft PPL</a>\'s <code>async/await</code>. (However, C++\'s <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf" rel="noreferrer">resumable functions</a> (a.k.a. "<code>async</code> and <code>await</code>"), which were proposed to C++17, are likely to use stackless coroutines.)</p>\n\n<p>Fibers proposal to the C++ standard library is forthcoming. Also, there\'re some third-party <a href="https://stackoverflow.com/questions/1285714/lightweight-portable-c-fibers-mit-license">libraries</a>. Green threads are extremely popular in languages like Python and Ruby.</p>\n'}, {'answer_id': 29309167, 'author': 'jlettvin', 'author_id': 1363592, 'author_profile': 'https://Stackoverflow.com/users/1363592', 'pm_score': 5, 'selected': False, 'text': '<p>In the 1980s, UNIX propagated like bunnies with big companies rolling their own.\nExxon had one as did dozens of brand names lost to history.\nHow memory was laid out was at the discretion of the many implementors.</p>\n\n<p>A typical C program was laid out flat in memory with\nan opportunity to increase by changing the brk() value.\nTypically, the HEAP was just below this brk value\nand increasing brk increased the amount of available heap.</p>\n\n<p>The single STACK was typically an area below HEAP which was a tract of memory\ncontaining nothing of value until the top of the next fixed block of memory.\nThis next block was often CODE which could be overwritten by stack data\nin one of the famous hacks of its era.</p>\n\n<p>One typical memory block was BSS (a block of zero values)\nwhich was accidentally not zeroed in one manufacturer\'s offering.\nAnother was DATA containing initialized values, including strings and numbers.\nA third was CODE containing CRT (C runtime), main, functions, and libraries.</p>\n\n<p>The advent of virtual memory in UNIX changes many of the constraints.\nThere is no objective reason why these blocks need be contiguous,\nor fixed in size, or ordered a particular way now.\nOf course, before UNIX was Multics which didn\'t suffer from these constraints.\nHere is a schematic showing one of the memory layouts of that era.</p>\n\n<p><img src="https://i.stack.imgur.com/eeefv.png" alt="A typical 1980s style UNIX C program memory layout"></p>\n'}, {'answer_id': 34337843, 'author': 'Maxim Akristiniy', 'author_id': 4176813, 'author_profile': 'https://Stackoverflow.com/users/4176813', 'pm_score': 5, 'selected': False, 'text': '<p>A couple of cents: I think, it will be good to draw memory graphical and more simple:</p>\n\n<p><a href="https://i.stack.imgur.com/nlb7A.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nlb7A.jpg" alt="This is my vision of process memory construction with simplification for more easy understanding wht happening"></a></p>\n\n<p><br>\nArrows - show where grow stack and heap, process stack size have limit, defined in OS, thread stack size limits by parameters in thread create API usually. Heap usually limiting by process maximum virtual memory size, for 32 bit 2-4 GB for example.</p>\n\n<p>So simple way: process heap is general for process and all threads inside, using for memory allocation in common case with something like <strong>malloc()</strong>.</p>\n\n<p>Stack is quick memory for store in common case function return pointers and variables, processed as parameters in function call, local function variables.</p>\n'}, {'answer_id': 36982240, 'author': 'Abrar Jahin', 'author_id': 2193439, 'author_profile': 'https://Stackoverflow.com/users/2193439', 'pm_score': 6, 'selected': False, 'text': '<h2>In Short</h2>\n\n<p>A stack is used for static memory allocation and a heap for dynamic memory allocation, both stored in the computer\'s RAM.</p>\n\n<hr>\n\n<h2>In Detail</h2>\n\n<p><strong>The Stack</strong></p>\n\n<p>The stack is a "LIFO" (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.</p>\n\n<p>The advantage of using the stack to store variables, is that memory is managed for you. You don\'t have to allocate memory by hand, or free it once you don\'t need it any more. What\'s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.</p>\n\n<p>More can be found <strong><a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)" rel="noreferrer">here</a></strong>.</p>\n\n<hr>\n\n<p><strong>The Heap</strong></p>\n\n<p>The heap is a region of your computer\'s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don\'t need it any more.</p>\n\n<p>If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won\'t be available to other processes). As we will see in the debugging section, there is a tool called <a href="http://en.wikipedia.org/wiki/Valgrind" rel="noreferrer">Valgrind</a> that can help you detect memory leaks.</p>\n\n<p>Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.</p>\n\n<p>Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.</p>\n\n<p>More can be found <strong><a href="https://en.wikipedia.org/wiki/Memory_management" rel="noreferrer">here</a></strong>.</p>\n\n<hr>\n\n<p>Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.</p>\n\n<p>Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. Elements of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.</p>\n\n<p><a href="https://i.stack.imgur.com/KdBPf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KdBPf.png" alt="Enter image description here"></a></p>\n\n<p>You can use the stack if you know exactly how much data you need to allocate before compile time, and it is not too big. You can use the heap if you don\'t know exactly how much data you will need at runtime or if you need to allocate a lot of data.</p>\n\n<p>In a multi-threaded situation each thread will have its own completely independent stack, but they will share the heap. The stack is thread specific and the heap is application specific. The stack is important to consider in exception handling and thread executions.</p>\n\n<p>Each thread gets a stack, while there\'s typically only one heap for the application (although it isn\'t uncommon to have multiple heaps for different types of allocation).</p>\n\n<p><a href="https://i.stack.imgur.com/J0teH.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/J0teH.gif" alt="Enter image description here"></a></p>\n\n<p>At run-time, if the application needs more heap, it can allocate memory from free memory and if the stack needs memory, it can allocate memory from free memory allocated memory for the application.</p>\n\n<p>Even, more detail is given <a href="http://net-informations.com/faq/net/stack-heap.htm" rel="noreferrer"><strong>here</strong></a> and <a href="http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html" rel="noreferrer"><strong>here</strong></a>.</p>\n\n<hr>\n\n<p>Now come to <strong>your question\'s answers</strong>.</p>\n\n<blockquote>\n <p><strong>To what extent are they controlled by the OS or language runtime?</strong></p>\n</blockquote>\n\n<p>The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.</p>\n\n<p>More can be found <strong><a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/80113#80113">here</a></strong>.</p>\n\n<blockquote>\n <p><strong>What is their scope?</strong></p>\n</blockquote>\n\n<p>Already given in top.</p>\n\n<blockquote>\n <p>"You can use the stack if you know exactly how much data you need to allocate before compile time, and it is not too big. You can use the heap if you don\'t know exactly how much data you will need at runtime or if you need to allocate a lot of data."</p>\n</blockquote>\n\n<p>More can be found in <a href="https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c">here</a>.</p>\n\n<blockquote>\n <p><strong>What determines the size of each of them?</strong></p>\n</blockquote>\n\n<p>The size of the stack is set by <a href="https://en.wikipedia.org/wiki/Operating_system" rel="noreferrer">OS</a> when a thread is created. The size of the heap is set on application startup, but it can grow as space is needed (the allocator requests more memory from the operating system).</p>\n\n<blockquote>\n <p><strong>What makes one faster?</strong></p>\n</blockquote>\n\n<p>Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.</p>\n\n<p>Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.</p>\n\n<p>Details can be found from <strong><a href="https://stackoverflow.com/questions/161053/which-is-faster-stack-allocation-or-heap-allocation">here</a></strong>.</p>\n'}, {'answer_id': 45170558, 'author': 'Alireza', 'author_id': 5423108, 'author_profile': 'https://Stackoverflow.com/users/5423108', 'pm_score': 6, 'selected': False, 'text': '<p><strong>OK,</strong> simply and in short words, they mean <strong>ordered</strong> and <strong>not ordered</strong>...!</p>\n\n<p><strong>Stack</strong>: In stack items, things get on the top of each-other, means gonna be faster and more efficient to be processed!... </p>\n\n<p>So there is always an index to point the specific item, also processing gonna be faster, there is relationship between the items as well!...</p>\n\n<p><strong>Heap</strong>: No order, processing gonna be slower and values are messed up together with no specific order or index... there are random and there is no relationship between them... so execution and usage time could be vary...</p>\n\n<p>I also create the image below to show how they may look like:</p>\n\n<p><a href="https://i.stack.imgur.com/9c2VH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9c2VH.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 45361888, 'author': 'ingconti', 'author_id': 927333, 'author_profile': 'https://Stackoverflow.com/users/927333', 'pm_score': 3, 'selected': False, 'text': "<p>A lot of answers are correct as concepts, but we must note that a stack is needed by the hardware (i.e. microprocessor) to allow calling subroutines (CALL in assembly language..). (OOP guys will call it <em>methods</em>)</p>\n\n<p>On the stack you save return addresses and call → push / ret → pop is managed directly in hardware.</p>\n\n<p>You can use the stack to pass parameters.. even if it is slower than using registers (would a microprocessor guru say or a good 1980s BIOS book...)</p>\n\n<ul>\n<li>Without stack <strong>no</strong> microprocessor can work. (we can't imagine a program, even in assembly language, without subroutines/functions)</li>\n<li>Without the heap it can. (An assembly language program can work without, as the heap is a OS concept, as malloc, that is a OS/Lib call.</li>\n</ul>\n\n<p>Stack usage is faster as:</p>\n\n<ul>\n<li>Is hardware, and even push/pop are very efficient.</li>\n<li>malloc requires entering kernel mode, use lock/semaphore (or other synchronization primitives) executing some code and manage some structures needed to keep track of allocation.</li>\n</ul>\n"}, {'answer_id': 46225186, 'author': 'Yousha Aleayoub', 'author_id': 1429432, 'author_profile': 'https://Stackoverflow.com/users/1429432', 'pm_score': 5, 'selected': False, 'text': '<p><strong>stack</strong>, <strong>heap</strong> and <strong>data</strong> of each process in virtual memory:</p>\n\n<p><a href="https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg" rel="noreferrer"><img src="https://bayanbox.ir/view/581244719208138556/virtual-memory.jpg" alt="stack, heap and static data"></a></p>\n'}, {'answer_id': 47314733, 'author': 'pkthapa', 'author_id': 1163286, 'author_profile': 'https://Stackoverflow.com/users/1163286', 'pm_score': 5, 'selected': False, 'text': '<p>I have something to share, although the major points are already covered.</p>\n\n<p><strong>Stack</strong> </p>\n\n<ul>\n<li>Very fast access.</li>\n<li>Stored in RAM.</li>\n<li>Function calls are loaded here along with the local variables and function parameters passed.</li>\n<li>Space is freed automatically when program goes out of a scope.</li>\n<li>Stored in sequential memory.</li>\n</ul>\n\n<p><strong>Heap</strong></p>\n\n<ul>\n<li>Slow access comparatively to Stack.</li>\n<li>Stored in RAM.</li>\n<li>Dynamically created variables are stored here, which later requires freeing the allocated memory after use.</li>\n<li>Stored wherever memory allocation is done, accessed by pointer always.</li>\n</ul>\n\n<p><strong>Interesting note:</strong></p>\n\n<ul>\n<li>Should the function calls had been stored in heap, it would had resulted in 2 messy points: \n\n<ol>\n<li>Due to sequential storage in stack, execution is faster. Storage in heap would have resulted in huge time consumption thus making the whole program execute slower.</li>\n<li>If functions were stored in heap (messy storage pointed by pointer), there would have been no way to return to the caller address back (which stack gives due to sequential storage in memory).</li>\n</ol></li>\n</ul>\n'}, {'answer_id': 54777773, 'author': 'ar18', 'author_id': 6147643, 'author_profile': 'https://Stackoverflow.com/users/6147643', 'pm_score': 4, 'selected': False, 'text': '<p>Wow! So many answers and I don\'t think one of them got it right...</p>\n\n<p>1) Where and what are they (physically in a real computer\'s memory)?</p>\n\n<p>The stack is memory that begins as the highest memory address allocated to your program image, and it then decrease in value from there. It is reserved for called function parameters and for all temporary variables used in functions.</p>\n\n<p>There are two heaps: public and private.</p>\n\n<p>The private heap begins on a 16-byte boundary (for 64-bit programs) or a 8-byte boundary (for 32-bit programs) after the last byte of code in your program, and then increases in value from there. It is also called the default heap.</p>\n\n<p>If the private heap gets too large it will overlap the stack area, as will the stack overlap the heap if it gets too big. Because the stack starts at a higher address and works its way down to lower address, with proper hacking you can get make the stack so large that it will overrun the private heap area and overlap the code area. The trick then is to overlap enough of the code area that you can hook into the code. It\'s a little tricky to do and you risk a program crash, but it\'s easy and very effective.</p>\n\n<p>The public heap resides in it\'s own memory space outside of your program image space. It is this memory that will be siphoned off onto the hard disk if memory resources get scarce.</p>\n\n<p>2) To what extent are they controlled by the OS or language runtime?</p>\n\n<p>The stack is controlled by the programmer, the private heap is managed by the OS, and the public heap is not controlled by anyone because it is an OS service -- you make requests and either they are granted or denied.</p>\n\n<p>2b) What is their scope?</p>\n\n<p>They are all global to the program, but their contents can be private, public, or global.</p>\n\n<p>2c) What determines the size of each of them?</p>\n\n<p>The size of the stack and the private heap are determined by your compiler runtime options. The public heap is initialized at runtime using a size parameter.</p>\n\n<p>2d) What makes one faster?</p>\n\n<p>They are not designed to be fast, they are designed to be useful. How the programmer utilizes them determines whether they are "fast" or "slow"</p>\n\n<p>REF:</p>\n\n<p><a href="https://norasandler.com/2019/02/18/Write-a-Compiler-10.html" rel="noreferrer">https://norasandler.com/2019/02/18/Write-a-Compiler-10.html</a></p>\n\n<p><a href="https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-getprocessheap" rel="noreferrer">https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-getprocessheap</a></p>\n\n<p><a href="https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-heapcreate" rel="noreferrer">https://learn.microsoft.com/en-us/windows/desktop/api/heapapi/nf-heapapi-heapcreate</a></p>\n'}, {'answer_id': 60795592, 'author': 'nCardot', 'author_id': 8888320, 'author_profile': 'https://Stackoverflow.com/users/8888320', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n <p>The stack is essentially an easy-to-access memory that simply manages its items \n as a - well - stack. Only <strong>items for which the size is known in advance can go onto the stack</strong>. This is the case for numbers, strings, booleans.</p>\n \n <p>The <strong>heap is a memory for items of which you can’t predetermine the\n exact size and structure</strong>. Since objects and arrays can be mutated and\n change at runtime, they have to go into the heap.</p>\n</blockquote>\n\n<p>Source: <a href="https://academind.com/learn/javascript/reference-vs-primitive-values/" rel="nofollow noreferrer">Academind</a></p>\n'}, {'answer_id': 61124687, 'author': 'aquagremlin', 'author_id': 3418334, 'author_profile': 'https://Stackoverflow.com/users/3418334', 'pm_score': 0, 'selected': False, 'text': '<p>Thank you for a really good discussion but as a real noob I wonder where instructions are kept? In the BEGINNING scientists were deciding between two architectures (von NEUMANN where everything is considered DATA and HARVARD where an area of memory was reserved for instructions and another for data). Ultimately, we went with the von Neumann design and now everything is considered \'the same\'. This made it hard for me when I was learning assembly \n<a href="https://www.cs.virginia.edu/~evans/cs216/guides/x86.html" rel="nofollow noreferrer">https://www.cs.virginia.edu/~evans/cs216/guides/x86.html</a>\nbecause they talk about registers and stack pointers. </p>\n\n<p>Everything above talks about DATA. My guess is that since an instruction is a defined thing with a specific memory footprint, it would go on the stack and so all \'those\' registers discussed in assembly are on the stack. Of course then came object oriented programming with instructions and data comingled into a structure that was dynamic so now instructions would be kept on the heap as well?</p>\n'}, {'answer_id': 62739706, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>CPU stack and heap are physically related to how CPU and registers works with memory, how machine-assembly language works, not high-level languages themselves, even if these languages can decide little things.</p>\n<p>All modern CPUs work with the "same" microprocessor theory: they are all based on what\'s called "registers" and some are for "stack" to gain performance. All CPUs have stack registers since the beginning and they had been always here, way of talking, as I know. Assembly languages are the same since the beginning, despite variations... up to Microsoft and its Intermediate Language (IL) that changed the paradigm to have a OO virtual machine assembly language. So we\'ll be able to have some CLI/CIL CPU in the future (one project of MS).</p>\n<p>CPUs have stack registers to speed up memories access, but they are limited compared to the use of others registers to get full access to all the available memory for the processus. It why we talked about stack and heap allocations.</p>\n<p>In summary, and in general, the heap is hudge and slow and is for "global" instances and objects content, as the stack is little and fast and for "local" variables and references (hidden pointers to forget to manage them).</p>\n<p>So when we use the new keyword in a method, the reference (an int) is created in the stack, but the object and all its content (value-types as well as objects) is created in the heap, if I remember. But local elementary value-types and arrays are created in the stack.</p>\n<p>The difference in memory access is at the cells referencing level: addressing the heap, the overall memory of the process, requires more complexity in terms of handling CPU registers, than the stack which is "more" locally in terms of addressing because the CPU stack register is used as base address, if I remember.</p>\n<p>It is why when we have very long or infinite recurse calls or loops, we got stack overflow quickly, without freezing the system on modern computers...</p>\n<p><a href="https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/" rel="nofollow noreferrer">C# Heap(ing) Vs Stack(ing) In .NET</a></p>\n<p><a href="https://www.guru99.com/stack-vs-heap.html" rel="nofollow noreferrer">Stack vs Heap: Know the Difference </a></p>\n<p><a href="https://stackoverflow.com/questions/33562199/static-class-memory-allocation-where-it-is-stored-c-sharp">Static class memory allocation where it is stored C#</a></p>\n<p><a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap">What and where are the stack and heap?</a></p>\n<p><a href="https://en.wikipedia.org/wiki/Memory_management" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Memory_management</a></p>\n<p><a href="https://en.wikipedia.org/wiki/Stack_register" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Stack_register</a></p>\n<p>Assembly language resources:</p>\n<p><a href="https://www.tutorialspoint.com/assembly_programming/index.htm" rel="nofollow noreferrer">Assembly Programming Tutorial</a></p>\n<p><a href="https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html" rel="nofollow noreferrer">Intel® 64 and IA-32 Architectures Software Developer Manuals</a></p>\n'}, {'answer_id': 69523039, 'author': 'anshkun', 'author_id': 3484350, 'author_profile': 'https://Stackoverflow.com/users/3484350', 'pm_score': 0, 'selected': False, 'text': '<p>When a process is created then after loading code and data OS setup heap start just after data ends and stack to top of address space based on architecture</p>\n<p>When more heap is required OS will allocate dynamically and heap chunk is always virtually contiguous</p>\n<p>Please see <code>brk()</code>, <code>sbrk()</code> and <code>alloca()</code> system call in linux</p>\n'}, {'answer_id': 70050292, 'author': 'A. Hendry', 'author_id': 8748308, 'author_profile': 'https://Stackoverflow.com/users/8748308', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n<p>Where and what are they (physically in a real computer's memory)?</p>\n</blockquote>\n<p><strong>ANSWER:</strong> <strong>Both are in RAM.</strong></p>\n<p><strong>ASIDE:</strong></p>\n<p><em>RAM is like a desk and HDDs/SSDs (permanent storage) are like bookshelves. To read anything, you must have a book open on your desk, and you can only have as many books open as fit on your desk. To get a book, you pull it from your bookshelf and open it on your desk. To return a book, you close the book on your desk and return it to its bookshelf.</em></p>\n<p><em>Stack and heap are names we give to two ways compilers store different kinds of data in the same place (i.e. in RAM).</em></p>\n<blockquote>\n<p>What is their scope?<br />\nWhat determines the size of each of them?<br />\nWhat makes one faster?</p>\n</blockquote>\n<p><strong>ANSWER:</strong></p>\n<ol>\n<li><p><strong>The stack is for static (fixed size) data</strong></p>\n<p>a. <em>At compile time, the compiler reads the variable types used in your code.</em></p>\n<p>i. It allocates a fixed amount of memory for these variables.<br />\nii. This size of this memory cannot grow.</p>\n<p>b. <em>The memory is contiguous (a single block), so access is</em> <strong>sometimes</strong> <em>faster than the heap</em></p>\n<p>c. <em>An object placed on the stack that grows in memory during runtime beyond the size of the stack causes a</em> <strong>stack overflow error</strong></p>\n</li>\n<li><p><strong>The heap is for dynamic (changing size) data</strong></p>\n<p>a. <em>The amount of memory is limited only by the amount of empty space available in RAM</em><br />\ni. The amount used can grow or shrink as needed at runtime</p>\n<p>b. <em>Since items are allocated on the heap by finding empty space wherever it exists in RAM, data is not always in a contiguous section, which</em> <strong>sometimes</strong> <em>makes access slower than the stack</em></p>\n<p>c. <em>Programmers manually put items on the heap with the <code>new</code> keyword and MUST manually deallocate this memory when they are finished using it.</em><br />\ni. Code that repeatedly allocates new memory without deallocating it when it is no longer needed leads to a <strong>memory leak.</strong></p>\n</li>\n</ol>\n<p><strong>ASIDE:</strong></p>\n<p>The stack and heap were not primarily introduced to improve speed; they were introduced to handle memory overflow. The first concern regarding use of the stack vs. the heap should be whether memory overflow will occur. If an object is intended to grow in size to an unknown amount (like a linked list or an object whose members can hold an arbitrary amount of data), place it on the heap. As far as possible, use the C++ standard library (STL) containers <strong>vector</strong>, <strong>map</strong>, and <strong>list</strong> as they are memory and speed efficient and added to make your life easier (you don't need to worry about memory allocation/deallocation).</p>\n<p>After getting your code to run, if you find it is running unacceptably slow, then go back and refactor your code and see if it can be programmed more efficiently. It may turn out the problem has nothing to do with the stack or heap directly at all (e.g. use an iterative algorithm instead of a recursive one, look at I/O vs. CPU-bound tasks, perhaps add multithreading or multiprocessing).</p>\n<p>I say <em>sometimes</em> slower/faster above because the speed of the program might not have anything to do with items being allocated on the stack or heap.</p>\n<blockquote>\n<p>To what extent are they controlled by the OS or language run-time?</p>\n</blockquote>\n<p><strong>ANSWER:</strong></p>\n<ul>\n<li><p><strong>The stack size is determined at compile time by the compiler.</strong></p>\n</li>\n<li><p><strong>The heap size varies during runtime.</strong> (<em>The heap works with the OS during runtime to allocate memory.</em>)</p>\n</li>\n</ul>\n<p><strong>ASIDE:</strong></p>\n<p>Below is a little more about control and compile-time vs. runtime operations.</p>\n<p>Each computer has a unique <strong>instruction set architecture (ISA)</strong>, which are its hardware commands (e.g. "MOVE", "JUMP", "ADD", etc.).</p>\n<ul>\n<li><p>An OS is nothing more than a resource manager (controls how/when/ and where to use memory, processors, devices, and information).</p>\n</li>\n<li><p>The ISA of the OS is called the <strong>bare machine</strong> and the remaining commands are called the <strong>extended machine</strong>. The <strong>kernel</strong> is the first layer of the extended machine. It controls things like</p>\n<ul>\n<li>determining what tasks get to use a processor (the scheduler),</li>\n<li>how much memory or how many hardware registers to allocate to a task (the dispatcher), and</li>\n<li>the order in which tasks should be performed (the traffic controller).</li>\n</ul>\n</li>\n<li><p>When we say "compiler", we generally mean the compiler, assembler, and linker together</p>\n<ul>\n<li>The compiler turns source code into assembly language and passes it to the assembler,</li>\n<li>The assembler turns the assembly language into machine code (ISA commands), and passes it to the linker</li>\n<li>The linker takes all machine code (possibly generated from multiple source files) and combines it into one program.</li>\n</ul>\n</li>\n<li><p>The machine code gets passed to the kernel when executed, which determines when it should run and take control, but the machine code itself contains ISA commands for requesting files, requesting memory, etc. So the code issues ISA commands, but everything has to pass by the kernel.</p>\n</li>\n</ul>\n"}, {'answer_id': 73615900, 'author': 'Shivprasad Koirala', 'author_id': 993672, 'author_profile': 'https://Stackoverflow.com/users/993672', 'pm_score': 1, 'selected': False, 'text': '<p>Below are answers but I would surely recommend you to watch this video where stack, heap inside memory addresses are shown , how stack memory addresses are contiguous are shown which gives a fair idea on how stack and heaps work. <a href="https://www.youtube.com/watch?v=7O4JPdKjc30" rel="nofollow noreferrer">https://www.youtube.com/watch?v=7O4JPdKjc30</a></p>\n<p><strong>What are the stack and heap?</strong></p>\n<p>Stack and Heap are memory types allocated to an application while its running. In Stack local primitive types, structures,object reference pointers are stored while in heap actual object data is stored. *** Heap can also store primitive types / structures only if they are part of the object.</p>\n<p><strong>Where are they located physically in a computer\'s memory?</strong></p>\n<p>They are allocated on RAM ( Random Access Memory)</p>\n<p><strong>To what extent are they controlled by the OS or language run-time?</strong></p>\n<p>Everything is controlled by OS.</p>\n<p><strong>What is their scope?</strong></p>\n<p>Stack memory is cleared as soon the function , method is executed. While heap is cleared later by garbage collector. Garbage collector runs in his own mood. So even though the function has finised execution its very much possible that GC will come little later and give the memory back to OS.</p>\n<p><strong>What determines their sizes?</strong></p>\n<p>Primitive data types are fixed size depending on datatype for example int is 32 bit , long 64 and so on. But when it comes to objects there is no fixed size , it can be huge image object or it can be a small object with two 3 properties.</p>\n<p><strong>What makes one faster?</strong></p>\n<p>Stack is surely faster as the memory addresses are contiguous so its very easy to allocate and deallocate. While heaps are allocated in random addresses so allocating and deallocating both is tedious task. Especially deallocating memory is most resource intensive and that\'s what garbage collector does.</p>\n<p>Think for while is it easy find a book in stack or in heap.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13161/'] |
79,928 | <p>I want to run text through a filter to ensure it is all UTF-8 encoded. What is the recommended way to do this with PHP?</p>
| [{'answer_id': 79950, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 2, 'selected': False, 'text': '<p>Your question is unclear, are you trying to encode something? If so <a href="http://us2.php.net/manual/en/function.utf8-encode.php" rel="nofollow noreferrer"><strong>utf8_encode</strong></a> is your friend. Are you trying to determine if it doesn\'t need to be encoded? If so, <strong>utf8_encode</strong> is still your friend, because you can check that the result is the same as the input!</p>\n'}, {'answer_id': 79982, 'author': 'Bahadır Yağan', 'author_id': 3812, 'author_profile': 'https://Stackoverflow.com/users/3812', 'pm_score': 1, 'selected': False, 'text': '<p>Check the multi-byte string functions <a href="http://be.php.net/manual/en/ref.mbstring.php" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 80013, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 0, 'selected': False, 'text': '<p>You need to know in what character set your input string is encoded, or this will go nowhere fast.</p>\n\n<p>If you want to do it correctly, this article may be helpful: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></p>\n'}, {'answer_id': 80019, 'author': 'DGM', 'author_id': 14253, 'author_profile': 'https://Stackoverflow.com/users/14253', 'pm_score': 0, 'selected': False, 'text': "<p>Given a stream of bytes, you have to know what encoding it is to begin with - email use mime headers to specify the encoding, http uses http headers to specify the encoding. Also, you can specify the encoding in a meta tag in a web page, but it is not always honored.</p>\n\n<p>Anyway, once you know what encoding you want to convert from, use <strong>iconv</strong> to convert it to utf8. look at the iconv section of the php docs, there's lots of good info there.</p>\n\n<p>Ah, Thomas posted the link I was looking for. A must read.</p>\n"}, {'answer_id': 83711, 'author': 'Tometzky', 'author_id': 15862, 'author_profile': 'https://Stackoverflow.com/users/15862', 'pm_score': 0, 'selected': False, 'text': "<p>The easiest way to check for <em>UTF-8</em> validity:</p>\n\n<ol>\n<li><p>If only one line allowed:</p>\n\n<pre><code>preg_match('/^.*$/Du', $value)\n</code></pre></li>\n<li><p>If multiple lines allowed:</p>\n\n<pre><code>preg_match('/^.*$/sDu', $value)\n</code></pre></li>\n</ol>\n\n<p>This works for <strong>PHP >= 4.3.5</strong> and does not require any non-default PHP modules.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
79,929 | <p>I'm sure there were several, but the one I was thinking of would display a nice text screen when you crashed the computer thoroughly. </p>
<p>The Text was "Well smoke me a kipper."</p>
| [{'answer_id': 80056, 'author': 'Dori', 'author_id': 10936, 'author_profile': 'https://Stackoverflow.com/users/10936', 'pm_score': 3, 'selected': False, 'text': '<p>No one else has answered this, so I\'ll answer the part I can: the original Macintosh debugger was <a href="http://en.wikipedia.org/wiki/MacsBug" rel="nofollow noreferrer">MacsBug</a>. </p>\n\n<p>So far as the kipper quote goes, the only thing that comes to mind is the <strong><a href="http://virus.wikidot.com/pathogen" rel="nofollow noreferrer">Pathogen</a></strong> computer virus.</p>\n'}, {'answer_id': 80208, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>There was another 68000 Macintosh debugger called TMON. I don't remember the kipper quote being in it, but it's been a while.</p>\n"}, {'answer_id': 3828384, 'author': 'foobie', 'author_id': 462545, 'author_profile': 'https://Stackoverflow.com/users/462545', 'pm_score': 4, 'selected': True, 'text': '<p>The name of the assembler was Fantasm.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1327/'] |
79,935 | <p>Is there an equivalent to Java's Robot class (java.awt.Robot) for Perl?</p>
| [{'answer_id': 79976, 'author': 'bmdhacks', 'author_id': 14032, 'author_profile': 'https://Stackoverflow.com/users/14032', 'pm_score': 1, 'selected': False, 'text': '<p>There is on Linux/Unix:</p>\n\n<p><a href="http://sourceforge.net/projects/x11guitest" rel="nofollow noreferrer"><a href="http://sourceforge.net/projects/x11guitest" rel="nofollow noreferrer">http://sourceforge.net/projects/x11guitest</a></a></p>\n\n<p>I\'m not familiar of anything similar for Windows or Mac that uses Perl.</p>\n'}, {'answer_id': 80004, 'author': 'Fhoxh', 'author_id': 14785, 'author_profile': 'https://Stackoverflow.com/users/14785', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re looking for a way to control a browser for the purpose of functional testing, Selenium has Perl bindings: <a href="http://selenium.openqa.org/" rel="nofollow noreferrer">http://selenium.openqa.org/</a></p>\n'}, {'answer_id': 80399, 'author': 'cjm', 'author_id': 8355, 'author_profile': 'https://Stackoverflow.com/users/8355', 'pm_score': 2, 'selected': False, 'text': '<p>For X (Linux/Unix), there\'s <a href="http://search.cpan.org/perldoc?X11::GUITest" rel="nofollow noreferrer">X11::GUITest</a>.</p>\n\n<p>For Windows, there\'s <a href="http://search.cpan.org/perldoc?Win32::CtrlGUI" rel="nofollow noreferrer">Win32::CtrlGUI</a>, although it can be a bit tricky to install its prerequisites.</p>\n'}, {'answer_id': 83794, 'author': 'Mr. Muskrat', 'author_id': 2657951, 'author_profile': 'https://Stackoverflow.com/users/2657951', 'pm_score': 2, 'selected': False, 'text': '<p>On Windows, I\'ve always used <a href="http://search.cpan.org/~karasik/Win32-GuiTest-1.54/lib/Win32/GuiTest.pm" rel="nofollow noreferrer">Win32::GuiTest</a>.</p>\n'}, {'answer_id': 87112, 'author': 'Bob_Gneu', 'author_id': 16703, 'author_profile': 'https://Stackoverflow.com/users/16703', 'pm_score': 3, 'selected': False, 'text': '<p>Alternatively, you can surely use the <a href="http://search.cpan.org/~petdance/WWW-Mechanize-1.34/lib/WWW/Mechanize.pm" rel="nofollow noreferrer">WWW::Mechanize</a> module to create an agent as we do here at work. We have a tool called AppMon that is really just a dramatized wrapper around Mechanize. </p>\n\n<p>The Mechanize module allows you to use scripts that look a lot like this: </p>\n\n<pre><code>use WWW::Mechanize;\n\nmy $Agent = WWW::Mechanize->new(cookie_jar => {});\n\n$Agent->get("http://www.google.com/search?q=stack+overflow+mechanize");\nprint "Found Mechanize" $Agent->content =~ /WWW::Mechanize/;\n</code></pre>\n\n<p>and will result in "Found Mechanize" being output. This is a very simple script, but rest assured you can interact with forms quite well.</p>\n\n<p>You can also move to Ruby and use Watir, or Selenium as another alternative, albeit not as interesting (in terms of coding) or automate-able. Selenium has a firefox extension that is quite useful for creating the selenium scripts and can change them between the various languages that it supports, which is pretty extensive in terms of automation.</p>\n\n<h2>Update - Nov 2016</h2>\n\n<p>Although I haven\'t had much of an opportunity to play with it, there are also webdriver packages for most languages, and Perl is no different. </p>\n\n<p><a href="http://search.cpan.org/~aivaturi/Selenium-Remote-Driver-0.15/lib/Selenium/Remote/Driver.pm" rel="nofollow noreferrer">Selenium::Remote::Driver</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14948/'] |
79,939 | <p>I have the following (pretty standard) table structure:</p>
<pre><code>Post <-> PostTag <-> Tag
</code></pre>
<p>Suppose I have the following records:</p>
<pre><code>PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
</code></pre>
<p>In other words, the first post has two tags, the second has one and the third one doesn't have any.</p>
<p><strong>I'd like to load all posts and it's tags in one query</strong> but haven't been able to find the right combination of operators. I've been able to load either <em>posts with tags only</em> or <em>repeated posts when more than one tag</em>.</p>
<p>Given the database above, <strong>I'd like to receive three posts and their tags (if any) in a collection property of the Post objects</strong>. Is it possible at all?</p>
<p>Thanks</p>
| [{'answer_id': 79979, 'author': 'sirrocco', 'author_id': 5246, 'author_profile': 'https://Stackoverflow.com/users/5246', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ve answered this in another post : <a href="https://stackoverflow.com/questions/50169/optimizing-a-linq-to-sql-query#50240">About eager loading</a>. In your case it would probably be something like :</p>\n\n<pre><code>DataLoadOptions options = new DataLoadOptions(); \noptions.LoadWith<Post>(p => p.PostTag);\noptions.LoadWith<PostTag>(pt => pt.Tag); \n</code></pre>\n\n<p>Though be careful - the DataLoadOptions must be set BEFORE ANY query is sent to the database - if not, an exception is thrown (no idea why it\'s like this in Linq2Sql - probably will be fixed in a later version).</p>\n'}, {'answer_id': 80038, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I'm sorry no, Eager Loading will execute one extra query per tag per post.</p>\n\n<p>Tested with this code:</p>\n\n<pre><code>var options = new DataLoadOptions();\noptions.LoadWith<Post>(p => p.PostTags);\noptions.LoadWith<PostTag>(pt => pt.Tag);\nusing (var db = new BlogDataContext())\n{\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed\n orderby p.PublishDateGmt descending\n select p);\n}\n</code></pre>\n\n<p>In the example database it would execute 4 queries which is not acceptable in production. Can anyone suggest another solution?</p>\n\n<p>Thanks</p>\n"}, {'answer_id': 80629, 'author': 'sirrocco', 'author_id': 5246, 'author_profile': 'https://Stackoverflow.com/users/5246', 'pm_score': 1, 'selected': False, 'text': "<p>It's a bit strange because </p>\n\n<pre><code>DataLoadOptions o = new DataLoadOptions ( );\no.LoadWith<Listing> ( l => l.ListingStaffs );\no.LoadWith<ListingStaff> ( ls => ls.MerchantStaff );\nctx.LoadOptions = o;\n\nIQueryable<Listing> listings = (from a in ctx.Listings\n where a.IsActive == false \n select a);\nList<Listing> list = listings.ToList ( );\n</code></pre>\n\n<p>results in a query like : </p>\n\n<pre><code>SELECT [t0].*, [t1].*, [t2].*, (\nSELECT COUNT(*)\nFROM [dbo].[LStaff] AS [t3]\nINNER JOIN [dbo].[MStaff] AS [t4] ON [t4].[MStaffId] = [t3].[MStaffId]\nWHERE [t3].[ListingId] = [t0].[ListingId]\n) AS [value]\nFROM [dbo].[Listing] AS [t0]\nLEFT OUTER JOIN ([dbo].[LStaff] AS [t1]\nINNER JOIN [dbo].[MStaff] AS [t2] ON [t2].[MStaffId] = [t1].[MStaffId]) ON \n[t1].[LId] = [t0].[LId] WHERE NOT ([t0].[IsActive] = 1) \nORDER BY [t0].[LId], [t1].[LStaffId], [t2].[MStaffId]\n</code></pre>\n\n<p>(I've shortened the names and added the * on the select).</p>\n\n<p>So it seems to do the select ok.</p>\n"}, {'answer_id': 83396, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I'm sorry. The solution you give works, but I found out that it breaks when paginating with Take(N). The complete method I'm using is the following:</p>\n\n<pre><code>public IList<Post> GetPosts(int page, int records)\n{\n var options = new DataLoadOptions();\n options.LoadWith<Post>(p => p.PostTags);\n options.LoadWith<PostTag>(pt => pt.Tag);\n using (var db = new BlogDataContext())\n {\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed\n orderby p.PublishDateGmt descending\n select p)\n .Skip(page * records)\n //.Take(records)\n .ToList();\n }\n}\n</code></pre>\n\n<p>With the Take() method commented it generates a query similar to to what you posted but if I add the Take() again it generates 1 + N x M queries.</p>\n\n<p>So, I guess my question now is: <strong>Is there a replacement to the Take() method to paginate records?</strong></p>\n\n<p>Thanks</p>\n"}, {'answer_id': 83771, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Yay! It worked. </p>\n\n<p>If anyone is having the same problem here's what I did:</p>\n\n<pre><code>public IList<Post> GetPosts(int page, int record)\n{\n var options = new DataLoadOptions();\n options.LoadWith<Post>(p => p.PostTags);\n options.LoadWith<PostTag>(pt => pt.Tag);\n using (var db = new DatabaseDataContext(m_connectionString))\n {\n var publishDateGmt = (from p in db.Posts\n where p.Status != PostStatus.Hidden\n orderby p.PublishDateGmt descending\n select p.PublishDateGmt)\n .Skip(page * record)\n .Take(record)\n .ToList()\n .Last();\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed \n && p.PublishDateGmt >= publishDateGmt\n orderby p.PublishDateGmt descending\n select p)\n .Skip(page * record)\n .ToList();\n }\n}\n</code></pre>\n\n<p>This executes only two queries and loads all tags for each post.</p>\n\n<p>The idea is to get some value to limit the query at the last post that we need (in this case the PublishDateGmt column will suffice) and then limit the second query with that value instead of Take().</p>\n\n<p>Thanks for your help sirrocco.</p>\n"}, {'answer_id': 3980733, 'author': 'jordanbtucker', 'author_id': 164430, 'author_profile': 'https://Stackoverflow.com/users/164430', 'pm_score': 0, 'selected': False, 'text': '<p>I know this is an old post, but I have discovered a way to use Take() while only performing one query. The trick is to perform the Take() inside of a nested query.</p>\n\n<pre><code>var q = from p in db.Posts\n where db.Posts.Take(10).Contains(p)\n select p;\n</code></pre>\n\n<p>Using DataLoadOptions with the query above will give you the first ten posts, including their associated tags, all in one query. The resulting SQL will be a much less concise version of the following:</p>\n\n<pre><code>SELECT p.PostID, p.Title, pt.PostID, pt.TagID, t.TagID, t.Name FROM Posts p\nJOIN PostsTags pt ON p.PostID = pt.PostID\nJOIN Tags t ON pt.TagID = t.TagID\nWHERE p.PostID IN (SELECT TOP 10 PostID FROM Posts)\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
79,949 | <p>Scenario:
A stored procedure receives from code a DateTime with, let's say DateTime.Now value, as a datetime parameter.
The stored procedure needs to store only the date part of the datetime on the row, but preserving all date related arithmetics for, to say, do searches over time intervals and doing reports based on dates.</p>
<p>I know there is a couple of ways, but what is the better having in mind performance and wasted space? </p>
| [{'answer_id': 79961, 'author': 'Jared', 'author_id': 1980, 'author_profile': 'https://Stackoverflow.com/users/1980', 'pm_score': 0, 'selected': False, 'text': '<p>store the date with time = midnight</p>\n\n<p>EDIT: i was assuming MS SQL Server</p>\n'}, {'answer_id': 80002, 'author': 'Encoder', 'author_id': 14629, 'author_profile': 'https://Stackoverflow.com/users/14629', 'pm_score': 0, 'selected': False, 'text': "<p>Essentially you're only going to store the Date part of your DateTime object. This means regardless of how you wish to handle querying the data the Date returned will always be set to 00:00:00.</p>\n\n<p>Time related functions are useless in this scenario (even though your original DateTime object uses them) as your database drops this info.</p>\n\n<p>Date related arithmetics will still apply though you will have to assume a time of midnight for each date returned from the database.</p>\n"}, {'answer_id': 80026, 'author': 'Tom Carr', 'author_id': 14954, 'author_profile': 'https://Stackoverflow.com/users/14954', 'pm_score': 3, 'selected': True, 'text': "<p>Business Logic should be handled outside of the proc. The procs jobs should be to save the data passed to it. If the requirment is to only store Date and not time, then the BL/DL should pass in DateTime.Now**.Date** (or the equiv...basically the Date part of your DateTime object).</p>\n\n<p>If you can't control the code for some reason, there's always convert(varchar(10), @YOURDATETIME, 101)</p>\n"}, {'answer_id': 80190, 'author': 'TonyOssa', 'author_id': 3276, 'author_profile': 'https://Stackoverflow.com/users/3276', 'pm_score': 0, 'selected': False, 'text': '<p>SQL Server 2008 has a date only type (DATE) that does not store the time. Consider upgrading.</p>\n\n<p><a href="http://www.sqlteam.com/article/using-the-date-data-type-in-sql-server-2008" rel="nofollow noreferrer">http://www.sqlteam.com/article/using-the-date-data-type-in-sql-server-2008</a></p>\n'}, {'answer_id': 86232, 'author': 'Mike McAllister', 'author_id': 16247, 'author_profile': 'https://Stackoverflow.com/users/16247', 'pm_score': 0, 'selected': False, 'text': "<p>If you're working on Oracle, inside your stored procedure use the TRUNC function on the datetime. This will return ONLY the date portion.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6359/'] |
79,953 | <p>I've used db4o with much success on many projects in the past. Over time it seems to have evolved greatly, and with modern trends like LINQ on everyone's tongue it has peaked my interest again, especially now that I know that it is starting to support transparent activation and persistence which intrigue me quite a bit, but a friend posed a very good question to me when I first mentioned db4o and, even with modern innovation, I'm still not sure how to answer it. </p>
<p>What are the best/fastest/most common methods to generate reports similar to the large cross-table complex constraint reports that can be done so effectively on platforms such as SQL? I understand quite well how much time, effort and development time are saved and even many of the performance gains, especially over ORMs, but some applications require complex reports that I'm not sure how to express using objects and object queries and I am also concerned about performance, since it can be overwhelming to optimize and maintain complex reports even on systems designed specifically for that purpose.</p>
<p>--<br>
Edit:</p>
<p>To be more clear, object data sources and the like can be used to pull db4o into the same data-rich controls as SqlDataSource et al. I've been referred to documents on the db4o site about using it with ReportViewer as well as advised to denormalize data into a reporting database, but the question is meant to pose a conceptual challenge on what can be done to accomplish the types of queries that RDBMSs perform so well on that they hold the industry. I love db4o, but I can't think of a truly efficient means of reporting on aggregate data that exists across several different types (or tables in SQL) without pulling all of the relevant objects out of the database, activating them and performing the calculations in application-level code. I may be wrong, but this seems like it couldn't hope to compete with the optimizations possible with an RDBMS. </p>
<p>I'm hoping amongst the bright minds we've managed to gather here that somebody knows something I don't or has innovative ideas for future implementation that could expand the ODBMS arena. I know that various ORMs implement methodologies for complex reporting objects and I'm wondering if anybody with experience with any of these technologies might have something creative that doesn't depend on any technologies outside of my code and db4o (I can generate reports with an SQL server alone).</p>
| [{'answer_id': 83833, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 1, 'selected': False, 'text': '<p>My limited understanding of the issue is that currently reporting is very difficult to do with DB4O, due to some missing functionality such as Count, Aggregate, etc. As it stands, you have to implement these yourself with all the poor performance that implies (e.g. activating all records, then doing a Count operation on the records).</p>\n'}, {'answer_id': 84194, 'author': 'David Thibault', 'author_id': 5903, 'author_profile': 'https://Stackoverflow.com/users/5903', 'pm_score': 2, 'selected': False, 'text': "<p>In order to work around the performance cost of reporting via db4o, I'd suggest maintaining a highly denormalized (sqlite ?) database in parallel to your db4o container. Run reports against the db and normal app logic against db4o.</p>\n\n<p>Yes it's more work, but this way you'll have high performance reporting while keeping the usefulness of db4o.</p>\n\n<p>If you have properly separated your data access code, it should be easy to update any code that saves objects to also update the reporting db.</p>\n"}, {'answer_id': 106202, 'author': 'Horcrux7', 'author_id': 12631, 'author_profile': 'https://Stackoverflow.com/users/12631', 'pm_score': 1, 'selected': False, 'text': '<p>I am not familiar with db4o. But I know some over reporting software. Some of it have a data interface that you can write your own connector like <a href="http://www.inetsoftware.de/" rel="nofollow noreferrer">i-net Crystal-Clear</a>. If you can query a plain list of simple objects (Strings, Numbers, ... ) then it is simple.</p>\n\n<p>Another simple solution is to write a dummy JDBC driver. There is a sample for it. The queries that you want run on your db4o will be available as virtual stored procedure. With the optional parameters you can filter your data on db4o for best performance. Such dummy JDBC driver can be written 3-4 hours.</p>\n'}, {'answer_id': 169851, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Please see <a href="http://developer.db4o.com/Resources/view.aspx/Reference/Implementation_Strategies/Reporting/" rel="nofollow noreferrer">this page</a>.</p>\n\n<p>Best,</p>\n\n<p>German</p>\n'}, {'answer_id': 3816666, 'author': 'Mark', 'author_id': 64084, 'author_profile': 'https://Stackoverflow.com/users/64084', 'pm_score': 1, 'selected': False, 'text': "<p>It <em>may</em> also boil down to what reporting tool you use. For example, I've implemented a project which uses Microsoft's Reporting Services client-side engine to render reports - no dependency on SQL server - just feed it objects. All of the aggregation is performed by the reporting engine, which means that your code merely needs to find and materialize the underlying objects. </p>\n"}, {'answer_id': 6776242, 'author': 'RobLeather', 'author_id': 621273, 'author_profile': 'https://Stackoverflow.com/users/621273', 'pm_score': 0, 'selected': False, 'text': '<p>Far too late to be useful to you. But I suggest that people who find this question might want to look at Jasper Reports. There is a "commercial" version of the product. However, it\'s actually an open source solution and can be found on <a href="http://sourceforge.net/projects/jasperreports/" rel="nofollow">sourceforge</a>.</p>\n\n<p>Seems it\'s actually pretty good. There\'s even a <a href="http://sourceforge.net/projects/jasperserver/" rel="nofollow">report server</a> and BI functionality (again, all open source). So it might be worth a look for somebody who is a bit interested.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8543/'] |
79,954 | <p>When I debug in Visual Studio, Firefox opens and that is annoying because of the hookups that Internet Explorer and Visual Studio have, such as when you close the Internet Explorer browser that starting debug opened, Visual Studio stops debugging. How can I get Visual Studio to open Internet Explorer instead without having to set Internet Explorer as my default browser?</p>
| [{'answer_id': 79964, 'author': 'tsimon', 'author_id': 1685, 'author_profile': 'https://Stackoverflow.com/users/1685', 'pm_score': 5, 'selected': False, 'text': "<p>Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.</p>\n"}, {'answer_id': 79965, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 9, 'selected': True, 'text': '<p>Scott Guthrie has made a post on <a href="http://weblogs.asp.net/scottgu/archive/2005/11/18/430943.aspx" rel="noreferrer">how to change Visual Studio\'s default browser</a>:</p>\n\n<blockquote>\n <p>1) Right click on a .aspx page in your\n solution explorer</p>\n \n <p>2) Select the "browse with" context\n menu option</p>\n \n <p>3) In the dialog you can select or add\n a browser. If you want Firefox in the\n list, click "add" and point to the\n firefox.exe filename</p>\n \n <p>4) Click the "Set as Default" button\n to make this the default browser when\n you run any page on the site.</p>\n</blockquote>\n\n<p>I however dislike the fact that this isn\'t as straightforward as it should be.</p>\n'}, {'answer_id': 79966, 'author': 'rp.', 'author_id': 2536, 'author_profile': 'https://Stackoverflow.com/users/2536', 'pm_score': 2, 'selected': False, 'text': '<p>In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.</p>\n\n<p>Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.</p>\n'}, {'answer_id': 1189612, 'author': 'jasonpenny', 'author_id': 28445, 'author_profile': 'https://Stackoverflow.com/users/28445', 'pm_score': 3, 'selected': False, 'text': '<p>Also may be helpful for ASP.NET MVC:</p>\n\n<blockquote>\n <p>In an MVC app, you have to right-click\n on Default.aspx, which is the only\n ‘real’ web page in that solution. The\n default page displays ‘Browse with…’</p>\n</blockquote>\n\n<p>From <a href="http://avaricesoft.wordpress.com/2008/08/04/change-the-default-browser-in-visual-studio-2008-and-visual-web-developer/" rel="noreferrer"><a href="http://avaricesoft.wordpress.com/2008/08/04/" rel="noreferrer">http://avaricesoft.wordpress.com/2008/08/04/</a>...</a></p>\n'}, {'answer_id': 2501770, 'author': 'Geoff', 'author_id': 300106, 'author_profile': 'https://Stackoverflow.com/users/300106', 'pm_score': 2, 'selected': False, 'text': "<p>Quick note if you don't have an .aspx in your project (i.e. its XBAP) but you still need to debug using IE, just add a htm page to your project and right click on that to set the default. It's hacky, but it works :P</p>\n"}, {'answer_id': 3710985, 'author': 'Tim Santeford', 'author_id': 78685, 'author_profile': 'https://Stackoverflow.com/users/78685', 'pm_score': 7, 'selected': False, 'text': '<p>In Visual Studio 2010 the default browser gets reset often (just about every time an IDE setting is changed or even after restarting Visual Studio). There is now a default browser selector extension for 2010 to help combat this:</p>\n\n<p><strong>!!!Update!!!</strong> It appears that the WoVS Default Browser Switcher is no longer available for free according to <a href="https://stackoverflow.com/users/74757/cory">@Cory</a>. You might try <a href="http://visualstudiogallery.msdn.microsoft.com/233945ae-0b7b-47e7-9b02-c5a11798afb5" rel="nofollow noreferrer">Default Browser Changer</a> instead but I have not tested it. If you already have the WoVS plugin I would recommend backing it up so that you can install it later.</p>\n\n<p><strong>The following solution may no longer work:</strong></p>\n\n<p><strong>WoVS Default Browser Switcher</strong>: \n<a href="http://visualstudiogallery.msdn.microsoft.com/en-us/bb424812-f742-41ef-974a-cdac607df921" rel="nofollow noreferrer">http://visualstudiogallery.msdn.microsoft.com/en-us/bb424812-f742-41ef-974a-cdac607df921</a></p>\n\n<p><img src="https://i.stack.imgur.com/EJESt.png" alt="WoVS Default Browser Switcher "> </p>\n\n<p><strong>Edit:</strong> This works with <strong>ASP.NET MVC</strong> applications as well.</p>\n\n<p><strong>Note:</strong> One negative side effect of installing this extension is that it seems to nag to be updated about once a month. This has caused some to uninstall it because, to them, its more bothersome then the problem it fixes. Regardless it is easily updated through the extension manager and I still find it very useful.</p>\n\n<p>You will see the following error when starting VS:</p>\n\n<blockquote>\n <p>The Default Browser Switcher beta bits have expired. Please use the\n Extension Manager or visit the VS Gallery to download updated bits.</p>\n</blockquote>\n'}, {'answer_id': 6338587, 'author': 'Misho', 'author_id': 796936, 'author_profile': 'https://Stackoverflow.com/users/796936', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re running an MVC 3 application - in your solution explorer click the show all files icon and then under the Global.asax file there should be a file called YourProjectName.Publish.XML right-click it and then click "Browse With..." and select your favorite browser as the default.</p>\n'}, {'answer_id': 7610169, 'author': 'Davut Gürbüz', 'author_id': 413032, 'author_profile': 'https://Stackoverflow.com/users/413032', 'pm_score': 1, 'selected': False, 'text': "<p>You may debug by firefox also. </p>\n\n<p>Follow these steps: <code>Tool</code>-><code>Attach to process</code> and select <code>firefox.exe</code> or your default browser. Then debugger will work with this browser. But I had some trouble when firefox is 32 bit and and VS2010 is 64 bit. </p>\n\n<p>Anyway right click the current document, browse with <code>--></code> than choose your browser, than set it as default. This way is better. B'cause firefox's process id may change, so you will be annoyed for attaching the process again.</p>\n"}, {'answer_id': 10815497, 'author': 'Ani', 'author_id': 779968, 'author_profile': 'https://Stackoverflow.com/users/779968', 'pm_score': 5, 'selected': False, 'text': '<p>For <strong>MVC3</strong> you <em>don\'t have to</em> add any dummy files to set a certain browser. All you have to do is:</p>\n\n<ul>\n<li>"Show all files" for the project</li>\n<li>go to bin folder</li>\n<li>right click the only .xml file to find the "Browse With..." option</li>\n</ul>\n\n<p><img src="https://i.stack.imgur.com/dWpO3.png" alt="setting MVC3 project default browser"></p>\n'}, {'answer_id': 12141847, 'author': 'Jennelle', 'author_id': 1627633, 'author_profile': 'https://Stackoverflow.com/users/1627633', 'pm_score': -1, 'selected': False, 'text': "<p>Another way is to do the following in Visual Studio:</p>\n\n<ol>\n<li>Select Debug</li>\n<li>Options and Settings</li>\n<li>Expand Environment</li>\n<li>Select Web Browser</li>\n<li>Click the '<strong>Internet Explorer Options</strong>' button</li>\n<li>Select the '<strong>Programs</strong>' tab</li>\n<li>Select '<strong>Make Default</strong>' button for Internet Explorer</li>\n</ol>\n"}, {'answer_id': 31257293, 'author': 'user5087270', 'author_id': 5087270, 'author_profile': 'https://Stackoverflow.com/users/5087270', 'pm_score': 0, 'selected': False, 'text': '<p>You mentioned Visual Studio. This is for Visual Studio 2013. In the "Menu and Tools" in the second line , right below Debug you have a dropdown box giving you the list / option of "Emulators" .Your IE should be in the option , select that and you are good to go. Easy way .</p>\n'}, {'answer_id': 43505066, 'author': 'Bryan Legend', 'author_id': 52771, 'author_profile': 'https://Stackoverflow.com/users/52771', 'pm_score': 1, 'selected': False, 'text': '<p>With VS 2017, debugging ASP.NET project with Chrome doesn\'t sign you in with your Google account.</p>\n\n<p>To fix that go to Tools -> Options -> Debugging -> General and turn off the setting Enable JavaScript Debugging for ASP.NET (Chrome and IE).</p>\n\n<p><a href="https://i.stack.imgur.com/WOXe1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WOXe1.png" alt="https://msdnshared.blob.core.windows.net/media/2016/11/debugger-settings-1024x690.png"></a></p>\n'}, {'answer_id': 43731185, 'author': 'Giri', 'author_id': 7950373, 'author_profile': 'https://Stackoverflow.com/users/7950373', 'pm_score': 1, 'selected': False, 'text': '<p>In visual studio 2013, this can be done as follows:</p>\n\n<p>1) Ensure you have selected a start up project from your solution explore window\n2) This brings a drop down to the left of the debug drop down. You can choose browser from this new drop down. </p>\n\n<p>Key is there should be a project selected as start up</p>\n'}, {'answer_id': 55870382, 'author': 'CPHPython', 'author_id': 6225838, 'author_profile': 'https://Stackoverflow.com/users/6225838', 'pm_score': 0, 'selected': False, 'text': '<p>Your project <strong>might not have aspx files</strong> since it might be another kind of web project.</p>\n\n<p>However, if it has a <strong><em>ClientApp</em> folder</strong>:</p>\n\n<ol>\n<li>go to the standard view of the <em>Solution Explorer</em> (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>L</kbd>) where you can find <em>your-project</em> name solution (click on the folders icon at the top to be sure (saying "Solutions and Folders"))</li>\n<li><strong>right-click on the <em>ClientApp</em> folder</strong> itself</li>\n<li><em>Browse with...</em> will show up near the top (near <em>View in Browser</em> option), click on it and the browsers dialog shows up</li>\n<li>click on your preferred browser</li>\n<li>click on <em>Set as Default</em></li>\n<li>click on <em>Browse</em> to confirm (this will open the browser you just chose on that folder)</li>\n</ol>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590/'] |
79,960 | <p>I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last <i>word</i> before 200 chars.</p>
| [{'answer_id': 79986, 'author': 'Grey Panther', 'author_id': 1265, 'author_profile': 'https://Stackoverflow.com/users/1265', 'pm_score': 9, 'selected': True, 'text': '<p>By using the <a href="http://www.php.net/wordwrap" rel="noreferrer">wordwrap</a> function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:</p>\n\n<pre><code>substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\\n"));\n</code></pre>\n\n<p>One thing this oneliner doesn\'t handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:</p>\n\n<pre><code>if (strlen($string) > $your_desired_width) \n{\n $string = wordwrap($string, $your_desired_width);\n $string = substr($string, 0, strpos($string, "\\n"));\n}\n</code></pre>\n\n<hr>\n\n<p>The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:</p>\n\n<pre><code>function tokenTruncate($string, $your_desired_width) {\n $parts = preg_split(\'/([\\s\\n\\r]+)/\', $string, null, PREG_SPLIT_DELIM_CAPTURE);\n $parts_count = count($parts);\n\n $length = 0;\n $last_part = 0;\n for (; $last_part < $parts_count; ++$last_part) {\n $length += strlen($parts[$last_part]);\n if ($length > $your_desired_width) { break; }\n }\n\n return implode(array_slice($parts, 0, $last_part));\n}\n</code></pre>\n\n<p>Also, here is the PHPUnit testclass used to test the implementation:</p>\n\n<pre><code>class TokenTruncateTest extends PHPUnit_Framework_TestCase {\n public function testBasic() {\n $this->assertEquals("1 3 5 7 9 ",\n tokenTruncate("1 3 5 7 9 11 14", 10));\n }\n\n public function testEmptyString() {\n $this->assertEquals("",\n tokenTruncate("", 10));\n }\n\n public function testShortString() {\n $this->assertEquals("1 3",\n tokenTruncate("1 3", 10));\n }\n\n public function testStringTooLong() {\n $this->assertEquals("",\n tokenTruncate("toooooooooooolooooong", 10));\n }\n\n public function testContainingNewline() {\n $this->assertEquals("1 3\\n5 7 9 ",\n tokenTruncate("1 3\\n5 7 9 11 14", 10));\n }\n}\n</code></pre>\n\n<h1><strong>EDIT :</strong></h1>\n\n<p>Special UTF8 characters like \'à\' are not handled. Add \'u\' at the end of the REGEX to handle it:</p>\n\n<p><code>$parts = preg_split(\'/([\\s\\n\\r]+)/u\', $string, null, PREG_SPLIT_DELIM_CAPTURE);</code></p>\n'}, {'answer_id': 80001, 'author': 'Lucas Oman', 'author_id': 6726, 'author_profile': 'https://Stackoverflow.com/users/6726', 'pm_score': 3, 'selected': False, 'text': '<p>Use strpos and substr:</p>\n\n<pre><code><?php\n\n$longString = "I have a code snippet written in PHP that pulls a block of text.";\n$truncated = substr($longString,0,strpos($longString,\' \',30));\n\necho $truncated;\n</code></pre>\n\n<p>This will give you a string truncated at the first space after 30 characters.</p>\n'}, {'answer_id': 80014, 'author': 'UnkwnTech', 'author_id': 115, 'author_profile': 'https://Stackoverflow.com/users/115', 'pm_score': 3, 'selected': False, 'text': "<p>Here you go:</p>\n\n<pre><code>function neat_trim($str, $n, $delim='…') {\n $len = strlen($str);\n if ($len > $n) {\n preg_match('/(.{' . $n . '}.*?)\\b/', $str, $matches);\n return rtrim($matches[1]) . $delim;\n }\n else {\n return $str;\n }\n}\n</code></pre>\n"}, {'answer_id': 80030, 'author': 'Justin Poliey', 'author_id': 6967, 'author_profile': 'https://Stackoverflow.com/users/6967', 'pm_score': 2, 'selected': False, 'text': '<p>I would use the preg_match function to do this, as what you want is a pretty simple expression.</p>\n\n<pre><code>$matches = array();\n$result = preg_match("/^(.{1,199})[\\s]/i", $text, $matches);\n</code></pre>\n\n<p>The expression means "match any substring starting from the beginning of length 1-200 that ends with a space." The result is in $result, and the match is in $matches. That takes care of your original question, which is specifically ending on any space. If you want to make it end on newlines, change the regular expression to:</p>\n\n<pre><code>$result = preg_match("/^(.{1,199})[\\n]/i", $text, $matches);\n</code></pre>\n'}, {'answer_id': 80066, 'author': 'mattmac', 'author_id': 14935, 'author_profile': 'https://Stackoverflow.com/users/14935', 'pm_score': 7, 'selected': False, 'text': "<p>This will return the first 200 characters of words:</p>\n\n<pre><code>preg_replace('/\\s+?(\\S+)?$/', '', substr($string, 0, 201));\n</code></pre>\n"}, {'answer_id': 80450, 'author': 'Garrett Albright', 'author_id': 11023, 'author_profile': 'https://Stackoverflow.com/users/11023', 'pm_score': 3, 'selected': False, 'text': '<p>Keep in mind whenever you\'re splitting by "word" anywhere that some languages such as Chinese and Japanese do not use a space character to split words. Also, a malicious user could simply enter text without any spaces, or using some Unicode look-alike to the standard space character, in which case any solution you use may end up displaying the entire text anyway. A way around this may be to check the string length after splitting it on spaces as normal, then, if the string is still above an abnormal limit - maybe 225 characters in this case - going ahead and splitting it dumbly at that limit.</p>\n\n<p>One more caveat with things like this when it comes to non-ASCII characters; strings containing them may be interpreted by PHP\'s standard strlen() as being longer than they really are, because a single character may take two or more bytes instead of just one. If you just use the strlen()/substr() functions to split strings, you may split a string in the middle of a character! When in doubt, <a href="http://us3.php.net/manual/en/function.mb-strlen.php" rel="nofollow noreferrer">mb_strlen()</a>/<a href="http://php.net/mb_substr" rel="nofollow noreferrer">mb_substr()</a> are a little more foolproof.</p>\n'}, {'answer_id': 2523223, 'author': 'Camsoft', 'author_id': 248848, 'author_profile': 'https://Stackoverflow.com/users/248848', 'pm_score': 3, 'selected': False, 'text': '<p>Here is my function based on @Cd-MaN\'s approach.</p>\n\n<pre><code>function shorten($string, $width) {\n if(strlen($string) > $width) {\n $string = wordwrap($string, $width);\n $string = substr($string, 0, strpos($string, "\\n"));\n }\n\n return $string;\n}\n</code></pre>\n'}, {'answer_id': 4400574, 'author': 'amateur barista', 'author_id': 467453, 'author_profile': 'https://Stackoverflow.com/users/467453', 'pm_score': 1, 'selected': False, 'text': '<p>Based on @Justin Poliey\'s regex:</p>\n\n<pre><code>// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.\nif(strlen($very_long_text) > 120) {\n $matches = array();\n preg_match("/^(.{1,120})[\\s]/i", $very_long_text, $matches);\n $trimmed_text = $matches[0]. \'...\';\n}\n</code></pre>\n'}, {'answer_id': 4665347, 'author': 'Dave', 'author_id': 382927, 'author_profile': 'https://Stackoverflow.com/users/382927', 'pm_score': 6, 'selected': False, 'text': "<pre><code>$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));\n</code></pre>\n\n<p>And there you have it — a reliable method of truncating any string to the nearest whole word, while staying under the maximum string length.</p>\n\n<p>I've tried the other examples above and they did not produce the desired results.</p>\n"}, {'answer_id': 7904269, 'author': 'Yo-L', 'author_id': 310108, 'author_profile': 'https://Stackoverflow.com/users/310108', 'pm_score': 2, 'selected': False, 'text': '<p>Ok so I got another version of this based on the above answers but taking more things in account(utf-8, \\n and &nbsp ; ), also a line stripping the wordpress shortcodes commented if used with wp.</p>\n\n<pre><code>function neatest_trim($content, $chars) \n if (strlen($content) > $chars) \n {\n $content = str_replace(\'&nbsp;\', \' \', $content);\n $content = str_replace("\\n", \'\', $content);\n // use with wordpress \n //$content = strip_tags(strip_shortcodes(trim($content)));\n $content = strip_tags(trim($content));\n $content = preg_replace(\'/\\s+?(\\S+)?$/\', \'\', mb_substr($content, 0, $chars));\n\n $content = trim($content) . \'...\';\n return $content;\n }\n</code></pre>\n'}, {'answer_id': 8072672, 'author': 'tanc', 'author_id': 1037075, 'author_profile': 'https://Stackoverflow.com/users/1037075', 'pm_score': 2, 'selected': False, 'text': "<p>This is a small fix for mattmac's answer:</p>\n\n<pre><code>preg_replace('/\\s+?(\\S+)?$/', '', substr($string . ' ', 0, 201));\n</code></pre>\n\n<p>The only difference is to add a space at the end of $string. This ensures the last word isn't cut off as per ReX357's comment.</p>\n\n<p>I don't have enough rep points to add this as a comment.</p>\n"}, {'answer_id': 10026115, 'author': 'Bud Damyanov', 'author_id': 632524, 'author_profile': 'https://Stackoverflow.com/users/632524', 'pm_score': 2, 'selected': False, 'text': '<pre><code>/*\nCut the string without breaking any words, UTF-8 aware \n* param string $str The text string to split\n* param integer $start The start position, defaults to 0\n* param integer $words The number of words to extract, defaults to 15\n*/\nfunction wordCutString($str, $start = 0, $words = 15 ) {\n $arr = preg_split("/[\\s]+/", $str, $words+1);\n $arr = array_slice($arr, $start, $words);\n return join(\' \', $arr);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$input = \'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\';\necho wordCutString($input, 0, 10); \n</code></pre>\n\n<p>This will output first 10 words.</p>\n\n<p>The <code>preg_split</code> function is used to split a string into substrings. The boundaries along which the string is to be split, are specified using a regular expressions pattern.</p>\n\n<p><code>preg_split</code> function takes 4 parameters, but only the first 3 are relevant to us right now.</p>\n\n<p>First Parameter – Pattern\nThe first parameter is the regular expressions pattern along which the string is to be split. In our case, we want to split the string across word boundaries. Therefore we use a predefined character class <code>\\s</code> which matches white space characters such as space, tab, carriage return and line feed.</p>\n\n<p>Second Parameter – Input String\nThe second parameter is the long text string which we want to split.</p>\n\n<p>Third Parameter – Limit\nThe third parameter specifies the number of substrings which should be returned. If you set the limit to <code>n</code>, preg_split will return an array of n elements. The first <code>n-1</code> elements will contain the substrings. The last <code>(n th)</code> element will contain the rest of the string.</p>\n'}, {'answer_id': 15089518, 'author': 'gosukiwi', 'author_id': 1015566, 'author_profile': 'https://Stackoverflow.com/users/1015566', 'pm_score': 0, 'selected': False, 'text': '<p>I know this is old, but...</p>\n\n<pre><code>function _truncate($str, $limit) {\n if(strlen($str) < $limit)\n return $str;\n $uid = uniqid();\n return array_shift(explode($uid, wordwrap($str, $limit, $uid)));\n}\n</code></pre>\n'}, {'answer_id': 17852480, 'author': 'Sergiy Sokolenko', 'author_id': 131337, 'author_profile': 'https://Stackoverflow.com/users/131337', 'pm_score': 5, 'selected': False, 'text': '<p>The following solution was born when I\'ve noticed a $break parameter of <a href="http://php.net/wordwrap" rel="noreferrer">wordwrap</a> function:</p>\n\n<blockquote>\n <p>string wordwrap ( string $str [, int $width = 75 [, string $break =\n "\\n" [, bool $cut = false ]]] )</p>\n</blockquote>\n\n<p>Here is <strong>the solution</strong>:</p>\n\n<pre><code>/**\n * Truncates the given string at the specified length.\n *\n * @param string $str The input string.\n * @param int $width The number of chars at which the string will be truncated.\n * @return string\n */\nfunction truncate($str, $width) {\n return strtok(wordwrap($str, $width, "...\\n"), "\\n");\n}\n</code></pre>\n\n<p><strong>Example #1.</strong></p>\n\n<pre><code>print truncate("This is very long string with many chars.", 25);\n</code></pre>\n\n<p>The above example will output:</p>\n\n<pre><code>This is very long string...\n</code></pre>\n\n<p><strong>Example #2.</strong></p>\n\n<pre><code>print truncate("This is short string.", 25);\n</code></pre>\n\n<p>The above example will output:</p>\n\n<pre><code>This is short string.\n</code></pre>\n'}, {'answer_id': 21659546, 'author': 'Yousef Altaf', 'author_id': 454012, 'author_profile': 'https://Stackoverflow.com/users/454012', 'pm_score': -1, 'selected': False, 'text': '<p>I used this before</p>\n\n<pre><code><?php\n $your_desired_width = 200;\n $string = $var->content;\n if (strlen($string) > $your_desired_width) {\n $string = wordwrap($string, $your_desired_width);\n $string = substr($string, 0, strpos($string, "\\n")) . " More...";\n }\n echo $string;\n?>\n</code></pre>\n'}, {'answer_id': 22783274, 'author': 'slash3b', 'author_id': 3478120, 'author_profile': 'https://Stackoverflow.com/users/3478120', 'pm_score': -1, 'selected': False, 'text': '<p>May be this will help someone:</p>\n\n<pre><code><?php\n\n $string = "Your line of text";\n $spl = preg_match("/([, \\.\\d\\-\'\'\\"\\"_()]*\\w+[, \\.\\d\\-\'\'\\"\\"_()]*){50}/", $string, $matches);\n if (isset($matches[0])) {\n $matches[0] .= "...";\n echo "<br />" . $matches[0];\n } else {\n echo "<br />" . $string;\n }\n\n?>\n</code></pre>\n'}, {'answer_id': 24204404, 'author': 'Rikudou_Sennin', 'author_id': 3601208, 'author_profile': 'https://Stackoverflow.com/users/3601208', 'pm_score': 1, 'selected': False, 'text': '<p>I have a function that does almost what you want, if you\'ll do a few edits, it will fit exactly:</p>\n\n<pre><code><?php\nfunction stripByWords($string,$length,$delimiter = \'<br>\') {\n $words_array = explode(" ",$string);\n $strlen = 0;\n $return = \'\';\n foreach($words_array as $word) {\n $strlen += mb_strlen($word,\'utf8\');\n $return .= $word." ";\n if($strlen >= $length) {\n $strlen = 0;\n $return .= $delimiter;\n }\n }\n return $return;\n}\n?>\n</code></pre>\n'}, {'answer_id': 24557257, 'author': 'Artem P', 'author_id': 712308, 'author_profile': 'https://Stackoverflow.com/users/712308', 'pm_score': 3, 'selected': False, 'text': '<pre><code>$shorttext = preg_replace(\'/^([\\s\\S]{1,200})[\\s]+?[\\s\\S]+/\', \'$1\', $fulltext);\n</code></pre>\n\n<p>Description:</p>\n\n<ul>\n<li><code>^</code> - start from beginning of string</li>\n<li><code>([\\s\\S]{1,200})</code> - get from 1 to 200 of any character</li>\n<li><code>[\\s]+?</code> - not include spaces at the end of short text so we can avoid <code>word ...</code> instead of <code>word...</code></li>\n<li><code>[\\s\\S]+</code> - match all other content</li>\n</ul>\n\n<p>Tests:</p>\n\n<ol>\n<li><a href="http://regex101.com/r/bV7dJ6/3" rel="nofollow noreferrer"><code>regex101.com</code></a> let\'s add to <code>or</code> few other <code>r</code></li>\n<li><a href="http://regex101.com/r/bV7dJ6/4" rel="nofollow noreferrer"><code>regex101.com</code></a> <code>orrrr</code> exactly 200 characters.</li>\n<li><a href="http://regex101.com/r/bV7dJ6/5" rel="nofollow noreferrer"><code>regex101.com</code></a> after fifth <code>r</code> <code>orrrrr</code> excluded.</li>\n</ol>\n\n<p>Enjoy.</p>\n'}, {'answer_id': 27420699, 'author': 'Shashank Saxena', 'author_id': 2735410, 'author_profile': 'https://Stackoverflow.com/users/2735410', 'pm_score': 1, 'selected': False, 'text': '<p>This is how i did it:</p>\n\n<pre><code>$string = "I appreciate your service & idea to provide the branded toys at a fair rent price. This is really a wonderful to watch the kid not just playing with variety of toys but learning faster compare to the other kids who are not using the BooksandBeyond service. We wish you all the best";\n\nprint_r(substr($string, 0, strpos(wordwrap($string, 250), "\\n")));\n</code></pre>\n'}, {'answer_id': 31030129, 'author': 'evandro777', 'author_id': 1671683, 'author_profile': 'https://Stackoverflow.com/users/1671683', 'pm_score': 0, 'selected': False, 'text': "<p>I create a function more similar to substr, and using the idea of @Dave.</p>\n\n<pre><code>function substr_full_word($str, $start, $end){\n $pos_ini = ($start == 0) ? $start : stripos(substr($str, $start, $end), ' ') + $start;\n if(strlen($str) > $end){ $pos_end = strrpos(substr($str, 0, ($end + 1)), ' '); } // IF STRING SIZE IS LESSER THAN END\n if(empty($pos_end)){ $pos_end = $end; } // FALLBACK\n return substr($str, $pos_ini, $pos_end);\n}\n</code></pre>\n\n<p>Ps.: The full length cut may be less than substr.</p>\n"}, {'answer_id': 32227063, 'author': 'Abhijeet kumar sharma', 'author_id': 1101353, 'author_profile': 'https://Stackoverflow.com/users/1101353', 'pm_score': -1, 'selected': False, 'text': "<p>Here you can try this</p>\n\n<pre><code>substr( $str, 0, strpos($str, ' ', 200) ); \n</code></pre>\n"}, {'answer_id': 32340759, 'author': 'orrd', 'author_id': 1257764, 'author_profile': 'https://Stackoverflow.com/users/1257764', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s surprising how tricky it is to find the perfect solution to this problem. I haven\'t yet found an answer on this page that doesn\'t fail in at least some situations (especially if the string contains newlines or tabs, or if the word break is anything other than a space, or if the string has UTF-8 multibyte characters).</p>\n\n<p>Here is a simple solution that works in all cases. There were similar answers here, but the "s" modifier is important if you want it to work with multi-line input, and the "u" modifier makes it correctly evaluate UTF-8 multibyte characters.</p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount) \n{\n if (preg_match("/^.{1,$characterCount}\\b/su", $s, $match)) return $match[0];\n return $s;\n}\n</code></pre>\n\n<p>One possible edge case with this... if the string doesn\'t have any whitespace at all in the first $characterCount characters, it will return the entire string. If you prefer it forces a break at $characterCount even if it isn\'t a word boundary, you can use this:</p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount) \n{\n if (preg_match("/^.{1,$characterCount}\\b/su", $s, $match)) return $match[0];\n return mb_substr($return, 0, $characterCount);\n}\n</code></pre>\n\n<p>One last option, if you want to have it add ellipsis if it truncates the string... </p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount, $addEllipsis = \' …\') \n{\n $return = $s;\n if (preg_match("/^.{1,$characterCount}\\b/su", $s, $match)) \n $return = $match[0];\n else\n $return = mb_substr($return, 0, $characterCount);\n if (strlen($s) > strlen($return)) $return .= $addEllipsis;\n return $return;\n}\n</code></pre>\n'}, {'answer_id': 35061022, 'author': 'jdorenbush', 'author_id': 2321998, 'author_profile': 'https://Stackoverflow.com/users/2321998', 'pm_score': 0, 'selected': False, 'text': '<p>Added IF/ELSEIF statements to the code from <a href="https://stackoverflow.com/a/4665347/2321998">Dave</a> and <a href="https://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara/4665347#comment36125374_4665347">AmalMurali</a> for handling strings without spaces</p>\n\n<pre><code>if ((strpos($string, \' \') !== false) && (strlen($string) > 200)) { \n $WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), \' \')); \n} \nelseif (strlen($string) > 200) {\n $WidgetText = substr($string, 0, 200);\n}\n</code></pre>\n'}, {'answer_id': 49194868, 'author': 'Namida', 'author_id': 9467793, 'author_profile': 'https://Stackoverflow.com/users/9467793', 'pm_score': -1, 'selected': False, 'text': "<p>I believe this is the easiest way to do it:</p>\n\n<pre><code>$lines = explode('♦♣♠',wordwrap($string, $length, '♦♣♠'));\n$newstring = $lines[0] . ' &bull; &bull; &bull;';\n</code></pre>\n\n<p>I'm using the special characters to split the text and cut it.</p>\n"}, {'answer_id': 50290843, 'author': 'Mat Barnett', 'author_id': 2098954, 'author_profile': 'https://Stackoverflow.com/users/2098954', 'pm_score': 0, 'selected': False, 'text': '<p>I find this works:</p>\n<pre><code>function abbreviate_string_to_whole_word($string, $max_length, $buffer) {\n if (strlen($string) > $max_length) {\n $string_cropped = substr($string, 0, $max_length - $buffer);\n $last_space = strrpos($string_cropped, " ");\n if ($last_space > 0) {\n $string_cropped = substr($string_cropped, 0, $last_space);\n }\n $abbreviated_string = $string_cropped . "&nbsp;...";\n }\n else {\n $abbreviated_string = $string;\n }\n return $abbreviated_string;\n}\n</code></pre>\n<p>The buffer allows you to adjust the length of the returned string.</p>\n'}, {'answer_id': 53894324, 'author': 'Mahbub Alam', 'author_id': 6659365, 'author_profile': 'https://Stackoverflow.com/users/6659365', 'pm_score': -1, 'selected': False, 'text': "<p>Use this: </p>\n\n<p>the following code will remove ','. If you have anyother character or sub-string, you may use that instead of ','</p>\n\n<pre><code>substr($string, 0, strrpos(substr($string, 0, $comparingLength), ','))\n</code></pre>\n\n<p>// if you have another string account for </p>\n\n<pre><code>substr($string, 0, strrpos(substr($string, 0, $comparingLength-strlen($currentString)), ','))\n</code></pre>\n"}, {'answer_id': 61022066, 'author': 'Will B.', 'author_id': 1144627, 'author_profile': 'https://Stackoverflow.com/users/1144627', 'pm_score': 1, 'selected': False, 'text': '<p>While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+.</p>\n\n<p>You can use the <a href="https://www.php.net/manual/en/function.sprintf.php" rel="nofollow noreferrer"><code>sprintf</code></a> family of functions to truncate text, by using the <code>%.ℕs</code> precision modifier.</p>\n\n<blockquote>\n <p>A period <code>.</code> followed by an integer who\'s meaning depends on the\n specifier:</p>\n \n <ul>\n <li>For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). </li>\n <li>For g and G specifiers: this is the maximum number of significant digits to be printed.</li>\n <li><strong>For s specifier: it acts as a cutoff point, setting a maximum character limit to the string</strong></li>\n </ul>\n</blockquote>\n\n<h2>Simple Truncation <a href="https://3v4l.org/QJDJU" rel="nofollow noreferrer">https://3v4l.org/QJDJU</a></h2>\n\n<pre class="lang-php prettyprint-override"><code>$string = \'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\';\nvar_dump(sprintf(\'%.10s\', $string));\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>string(10) "0123456789"\n</code></pre>\n\n<hr>\n\n<h2>Expanded Truncation <a href="https://3v4l.org/FCD21" rel="nofollow noreferrer">https://3v4l.org/FCD21</a></h2>\n\n<p>Since <code>sprintf</code> functions similarly to <code>substr</code> and will partially cut off words. The below approach will ensure words are not cutoff by using <code>strpos(wordwrap(..., \'[break]\'), \'[break]\')</code> with a special delimiter. This allows us to retrieve the position and ensure we do not match on standard sentence structures.</p>\n\n<p>Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.</p>\n\n<pre class="lang-php prettyprint-override"><code>function truncate($string, $width, $on = \'[break]\') {\n if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {\n $string = sprintf(\'%.\'. $p . \'s\', $string);\n }\n return $string;\n}\nvar_dump(truncate(\'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\', 20));\n\nvar_dump(truncate("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 20));\n\nvar_dump(truncate("Lorem Ipsum\\nis simply dummy text of the printing and typesetting industry.", 20));\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>/* \nstring(36) "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" \nstring(14) "Lorem Ipsum is" \nstring(14) "Lorem Ipsum\nis" \n*/\n</code></pre>\n\n<p>Results using <code>wordwrap($string, $width)</code> or <code>strtok(wordwrap($string, $width), "\\n")</code></p>\n\n<pre><code>/*\nstring(14) "Lorem Ipsum is"\nstring(11) "Lorem Ipsum"\n*/\n</code></pre>\n'}, {'answer_id': 66559438, 'author': 'HOSSEIN B', 'author_id': 14182190, 'author_profile': 'https://Stackoverflow.com/users/14182190', 'pm_score': 2, 'selected': False, 'text': "<p>You can use this:</p>\n<pre><code>function word_shortener($text, $words=10, $sp='...'){\n\n $all = explode(' ', $text);\n $str = '';\n $count = 1;\n\n foreach($all as $key){\n $str .= $key . ($count >= $words ? '' : ' ');\n $count++;\n if($count > $words){\n break;\n }\n }\n\n return $str . (count($all) <= $words ? '' : $sp);\n\n}\n</code></pre>\n<p>Examples:</p>\n<pre><code>word_shortener("Hello world, this is a text", 3); // Hello world, this...\nword_shortener("Hello world, this is a text", 3, ''); // Hello world, this\nword_shortener("Hello world, this is a text", 3, '[read more]'); // Hello world, this[read more]\n</code></pre>\n<h1>Edit</h1>\n<p>How it's work:</p>\n<p><strong>1. Explode space from input text:</strong></p>\n<pre><code>$all = explode(' ', $text);\n</code></pre>\n<p>for example, if <code>$text</code> will be "Hello world" then <code>$all</code> is an array with exploded values:</p>\n<p><code>["Hello", "world"]</code></p>\n<p><strong>2. For each word:</strong></p>\n<p>Select each element in exploded text:</p>\n<pre><code>foreach($all as $key){...\n</code></pre>\n<p>Append current word(<code>$key</code>) to <code>$str</code> and space if it's the last word:</p>\n<pre><code>$str .= $key . ($count >= $words ? '' : ' ');\n</code></pre>\n<p>Then add 1 to <code>$count</code> and check if it's greater than max limit(<code>$words</code>) break the loop:</p>\n<pre><code>if($count > $words){\n break;\n}\n</code></pre>\n<p>Then return <code>$str</code> and separator(<code>$sp</code>) only if the final text is less than input text:</p>\n<pre><code>return $str . (count($all) <= $words ? '' : $sp);\n</code></pre>\n"}, {'answer_id': 69532106, 'author': 'JesusIniesta', 'author_id': 3198983, 'author_profile': 'https://Stackoverflow.com/users/3198983', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n<p>As far as I\'ve seen, all the solutions here are only valid for the case when the starting point is fixed.</p>\n<p>Allowing you to turn this:</p>\n<pre class="lang-php prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam.\n</code></pre>\n<p>Into this:</p>\n<pre class="lang-php prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur...\n</code></pre>\n<h3>What if you want to truncate words surrounding a specific set of keywords?</h3>\n</blockquote>\n<h1>Truncate the text surrounding a specific set of keywords.</h1>\n<p>The goal is to be able to convert this:</p>\n<pre class="lang-php prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam.\n</code></pre>\n<p>Into this:</p>\n<pre class="lang-php prettyprint-override"><code>...consectetur adipisicing elit, sed do eiusmod tempor...\n</code></pre>\n<p>Which is a very common situation when displaying search results, excerpts, etc. To achieve this we can use these two methods combined:</p>\n<pre class="lang-php prettyprint-override"><code> /**\n * Return the index of the $haystack matching $needle,\n * or NULL if there is no match.\n *\n * This function is case-insensitive \n * \n * @param string $needle\n * @param array $haystack\n * @return false|int\n */\n function regexFindInArray(string $needle, array $haystack): ?int\n {\n for ($i = 0; $i < count($haystack); $i++) {\n if (preg_match(\'/\' . preg_quote($needle) . \'/i\', $haystack[$i]) === 1) {\n return $i;\n }\n }\n return null;\n }\n\n /**\n * If the keyword is not present, it returns the maximum number of full \n * words that the max number of characters provided by $maxLength allow,\n * starting from the left.\n *\n * If the keyword is present, it adds words to both sides of the keyword\n * keeping a balanace between the length of the suffix and the prefix.\n *\n * @param string $text\n * @param string $keyword\n * @param int $maxLength\n * @param string $ellipsis\n * @return string\n */\n function truncateWordSurroundingsByLength(string $text, string $keyword, \n int $maxLength, string $ellipsis): string\n {\n if (strlen($text) < $maxLength) {\n return $text;\n }\n\n $pattern = \'/\' . \'^(.*?)\\s\' .\n \'([^\\s]*\' . preg_quote($keyword) . \'[^\\s]*)\' .\n \'\\s(.*)$\' . \'/i\';\n preg_match($pattern, $text, $matches);\n\n // break everything into words except the matching keywords, \n // which can contain spaces\n if (count($matches) == 4) {\n $words = preg_split("/\\s+/", $matches[1], -1, PREG_SPLIT_NO_EMPTY);\n $words[] = $matches[2];\n $words = array_merge($words, \n preg_split("/\\s+/", $matches[3], -1, PREG_SPLIT_NO_EMPTY));\n } else {\n $words = preg_split("/\\s+/", $text, -1, PREG_SPLIT_NO_EMPTY);\n }\n\n // find the index of the matching word\n $firstMatchingWordIndex = regexFindInArray($keyword, $words) ?? 0;\n\n $length = false;\n $prefixLength = $suffixLength = 0;\n $prefixIndex = $firstMatchingWordIndex - 1;\n $suffixIndex = $firstMatchingWordIndex + 1;\n\n // Initialize the text with the matching word\n $text = $words[$firstMatchingWordIndex];\n\n while (($prefixIndex >= 0 or $suffixIndex <= count($words))\n and strlen($text) < $maxLength and strlen($text) !== $length) {\n $length = strlen($text);\n if (isset($words[$prefixIndex])\n and (strlen($text) + strlen($words[$prefixIndex]) <= $maxLength)\n and ($prefixLength <= $suffixLength \n or strlen($text) + strlen($words[$suffixIndex]) <= $maxLength)) {\n $prefixLength += strlen($words[$prefixIndex]);\n $text = $words[$prefixIndex] . \' \' . $text;\n $prefixIndex--;\n }\n if (isset($words[$suffixIndex])\n and (strlen($text) + strlen($words[$suffixIndex]) <= $maxLength)\n and ($suffixLength <= $prefixLength \n or strlen($text) + strlen($words[$prefixIndex]) <= $maxLength)) {\n $suffixLength += strlen($words[$suffixIndex]);\n $text = $text . \' \' . $words[$suffixIndex];\n $suffixIndex++;\n }\n }\n\n if ($prefixIndex > 0) {\n $text = $ellipsis . \' \' . $text;\n }\n if ($suffixIndex < count($words)) {\n $text = $text . \' \' . $ellipsis;\n }\n\n return $text;\n }\n</code></pre>\n<p>Now you can do:</p>\n<pre class="lang-php prettyprint-override"><code>$text = \'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\' .\n \'iusmod tempor incididunt ut labore et dolore magna liqua. Ut enim\' .\n \'ad minim veniam.\';\n\n$text = truncateWordSurroundingsByLength($text, \'elit\', 25, \'...\');\n\nvar_dump($text); // string(32) "... adipisicing elit, sed do ..."\n</code></pre>\n<p><a href="http://sandbox.onlinephpfunctions.com/code/4f8a17dba1b7937c00a496424731b17917b9af9e" rel="nofollow noreferrer">Run code</a>.</p>\n'}, {'answer_id': 70406161, 'author': 'younghallaji', 'author_id': 16925848, 'author_profile': 'https://Stackoverflow.com/users/16925848', 'pm_score': 0, 'selected': False, 'text': "<pre><code>function trunc($phrase, $max_words) {\n $phrase_array = explode(' ',$phrase);\n if(count($phrase_array) > $max_words && $max_words > 0)\n $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';\n return $phrase;\n }\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14956/'] |
79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this', 'is', 'a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| [{'answer_id': 79985, 'author': 'Jerub', 'author_id': 14648, 'author_profile': 'https://Stackoverflow.com/users/14648', 'pm_score': 10, 'selected': True, 'text': '<p>You want <code>split</code>, from the built-in <a href="https://docs.python.org/library/shlex.html" rel="noreferrer"><code>shlex</code></a> module.</p>\n<pre><code>>>> import shlex\n>>> shlex.split(\'this is "a test"\')\n[\'this\', \'is\', \'a test\']\n</code></pre>\n<p>This should do exactly what you want.</p>\n<p>If you want to preserve the quotation marks, then you can pass the <code>posix=False</code> kwarg.</p>\n<pre><code>>>> shlex.split(\'this is "a test"\', posix=False)\n[\'this\', \'is\', \'"a test"\']\n</code></pre>\n'}, {'answer_id': 79989, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 6, 'selected': False, 'text': '<p>Have a look at the <code>shlex</code> module, particularly <code>shlex.split</code>.</p>\n\n<pre><code>>>> import shlex\n>>> shlex.split(\'This is "a test"\')\n[\'This\', \'is\', \'a test\']\n</code></pre>\n'}, {'answer_id': 80015, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': -1, 'selected': False, 'text': '<p>Try this:</p>\n\n<pre><code> def adamsplit(s):\n result = []\n inquotes = False\n for substring in s.split(\'"\'):\n if not inquotes:\n result.extend(substring.split())\n else:\n result.append(substring)\n inquotes = not inquotes\n return result\n</code></pre>\n\n<p>Some test strings:</p>\n\n<pre><code>\'This is "a test"\' -> [\'This\', \'is\', \'a test\']\n\'"This is \\\'a test\\\'"\' -> ["This is \'a test\'"]\n</code></pre>\n'}, {'answer_id': 80361, 'author': 'Gregory', 'author_id': 14351, 'author_profile': 'https://Stackoverflow.com/users/14351', 'pm_score': -1, 'selected': False, 'text': '<p>If you don\'t care about sub strings than a simple</p>\n\n<pre><code>>>> \'a short sized string with spaces \'.split()\n</code></pre>\n\n<p>Performance:</p>\n\n<pre><code>>>> s = " (\'a short sized string with spaces \'*100).split() "\n>>> t = timeit.Timer(stmt=s)\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n171.39 usec/pass\n</code></pre>\n\n<p>Or string module</p>\n\n<pre><code>>>> from string import split as stringsplit; \n>>> stringsplit(\'a short sized string with spaces \'*100)\n</code></pre>\n\n<p>Performance: String module seems to perform better than string methods</p>\n\n<pre><code>>>> s = "stringsplit(\'a short sized string with spaces \'*100)"\n>>> t = timeit.Timer(s, "from string import split as stringsplit")\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n154.88 usec/pass\n</code></pre>\n\n<p>Or you can use RE engine</p>\n\n<pre><code>>>> from re import split as resplit\n>>> regex = \'\\s+\'\n>>> medstring = \'a short sized string with spaces \'*100\n>>> resplit(regex, medstring)\n</code></pre>\n\n<p>Performance</p>\n\n<pre><code>>>> s = "resplit(regex, medstring)"\n>>> t = timeit.Timer(s, "from re import split as resplit; regex=\'\\s+\'; medstring=\'a short sized string with spaces \'*100")\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n540.21 usec/pass\n</code></pre>\n\n<p>For very long strings you should not load the entire string into memory and instead either split the lines or use an iterative loop</p>\n'}, {'answer_id': 80449, 'author': 'elifiner', 'author_id': 15109, 'author_profile': 'https://Stackoverflow.com/users/15109', 'pm_score': 3, 'selected': False, 'text': '<p>Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \\x00, then split by spaces, then replace the \\x00 back to spaces in each part.</p>\n\n<p>Both versions do the same thing, but splitter is a bit more readable then splitter2.</p>\n\n<pre><code>import re\n\ns = \'this is "a test" some text "another test"\'\n\ndef splitter(s):\n def replacer(m):\n return m.group(0).replace(" ", "\\x00")\n parts = re.sub(\'".+?"\', replacer, s).split()\n parts = [p.replace("\\x00", " ") for p in parts]\n return parts\n\ndef splitter2(s):\n return [p.replace("\\x00", " ") for p in re.sub(\'".+?"\', lambda m: m.group(0).replace(" ", "\\x00"), s).split()]\n\nprint splitter2(s)\n</code></pre>\n'}, {'answer_id': 524796, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe "whitespace or thing-surrounded-by-quotes", and most regex engines (including Python\'s) can split on a regex. So if you\'re going to use regexes, why not just say exactly what you mean?:</p>\n\n<pre><code>test = \'this is "a test"\' # or "this is \'a test\'"\n# pieces = [p for p in re.split("( |[\\\\\\"\'].*[\\\\\\"\'])", test) if p.strip()]\n# From comments, use this:\npieces = [p for p in re.split("( |\\\\\\".*?\\\\\\"|\'.*?\')", test) if p.strip()]\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>[\\\\\\"\'] = double-quote or single-quote\n.* = anything\n( |X) = space or X\n.strip() = remove space and empty-string separators\n</code></pre>\n\n<p>shlex probably provides more features, though.</p>\n'}, {'answer_id': 525011, 'author': 'Ryan Ginstrom', 'author_id': 10658, 'author_profile': 'https://Stackoverflow.com/users/10658', 'pm_score': 5, 'selected': False, 'text': '<p>Depending on your use case, you may also want to check out the <a href="https://docs.python.org/library/csv.html" rel="noreferrer"><code>csv</code></a> module:</p>\n\n<pre><code>import csv\nlines = [\'this is "a string"\', \'and more "stuff"\']\nfor row in csv.reader(lines, delimiter=" "):\n print(row)\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>[\'this\', \'is\', \'a string\']\n[\'and\', \'more\', \'stuff\']\n</code></pre>\n'}, {'answer_id': 2159337, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Hmm, can\'t seem to find the "Reply" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:</p>\n\n<pre><code> [i.strip(\'"\').strip("\'") for i in re.split(r\'(\\s+|(?<!\\\\)".*?(?<!\\\\)"|(?<!\\\\)\\\'.*?(?<!\\\\)\\\')\', string) if i.strip()]\n</code></pre>\n\n<p>This works on strings like <code>\'This is " a \\\\\\"test\\\\\\"\\\\\\\'s substring"\'</code> (the insane markup is unfortunately necessary to keep Python from removing the escapes).</p>\n\n<p>If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:</p>\n\n<pre><code>[i.strip(\'"\').strip("\'").decode(\'string_escape\') for i in re.split(r\'(\\s+|(?<!\\\\)".*?(?<!\\\\)"|(?<!\\\\)\\\'.*?(?<!\\\\)\\\')\', string) if i.strip()]\n</code></pre>\n'}, {'answer_id': 11194593, 'author': 'moschlar', 'author_id': 1175818, 'author_profile': 'https://Stackoverflow.com/users/1175818', 'pm_score': 1, 'selected': False, 'text': "<p>To get around the unicode issues in some Python 2 versions, I suggest:</p>\n\n<pre><code>from shlex import split as _split\nsplit = lambda a: [b.decode('utf-8') for b in _split(a.encode('utf-8'))]\n</code></pre>\n"}, {'answer_id': 23155180, 'author': 'Daniel Dai', 'author_id': 1089262, 'author_profile': 'https://Stackoverflow.com/users/1089262', 'pm_score': 4, 'selected': False, 'text': '<p>I use shlex.split to process 70,000,000 lines of squid log, it\'s so slow. So I switched to re.</p>\n\n<p>Please try this, if you have performance problem with shlex.</p>\n\n<pre><code>import re\n\ndef line_split(line):\n return re.findall(r\'[^"\\s]\\S*|".+?"\', line)\n</code></pre>\n'}, {'answer_id': 32480710, 'author': 'hussic', 'author_id': 4111130, 'author_profile': 'https://Stackoverflow.com/users/4111130', 'pm_score': 0, 'selected': False, 'text': '<p>I suggest:</p>\n\n<p>test string:</p>\n\n<pre><code>s = \'abc "ad" \\\'fg\\\' "kk\\\'rdt\\\'" zzz"34"zzz "" \\\'\\\'\'\n</code></pre>\n\n<p>to capture also "" and \'\':</p>\n\n<pre><code>import re\nre.findall(r\'"[^"]*"|\\\'[^\\\']*\\\'|[^"\\\'\\s]+\',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>[\'abc\', \'"ad"\', "\'fg\'", \'"kk\\\'rdt\\\'"\', \'zzz\', \'"34"\', \'zzz\', \'""\', "\'\'"]\n</code></pre>\n\n<p>to ignore empty "" and \'\':</p>\n\n<pre><code>import re\nre.findall(r\'"[^"]+"|\\\'[^\\\']+\\\'|[^"\\\'\\s]+\',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>[\'abc\', \'"ad"\', "\'fg\'", \'"kk\\\'rdt\\\'"\', \'zzz\', \'"34"\', \'zzz\']\n</code></pre>\n'}, {'answer_id': 43035638, 'author': 'THE_MAD_KING', 'author_id': 7771160, 'author_profile': 'https://Stackoverflow.com/users/7771160', 'pm_score': 2, 'selected': False, 'text': '<p>To preserve quotes use this function:</p>\n\n<pre><code>def getArgs(s):\n args = []\n cur = \'\'\n inQuotes = 0\n for char in s.strip():\n if char == \' \' and not inQuotes:\n args.append(cur)\n cur = \'\'\n elif char == \'"\' and not inQuotes:\n inQuotes = 1\n cur += char\n elif char == \'"\' and inQuotes:\n inQuotes = 0\n cur += char\n else:\n cur += char\n args.append(cur)\n return args\n</code></pre>\n'}, {'answer_id': 49791573, 'author': 'har777', 'author_id': 1851428, 'author_profile': 'https://Stackoverflow.com/users/1851428', 'pm_score': 3, 'selected': False, 'text': '<p>Speed test of different answers:</p>\n\n<pre><code>import re\nimport shlex\nimport csv\n\nline = \'this is "a test"\'\n\n%timeit [p for p in re.split("( |\\\\\\".*?\\\\\\"|\'.*?\')", line) if p.strip()]\n100000 loops, best of 3: 5.17 µs per loop\n\n%timeit re.findall(r\'[^"\\s]\\S*|".+?"\', line)\n100000 loops, best of 3: 2.88 µs per loop\n\n%timeit list(csv.reader([line], delimiter=" "))\nThe slowest run took 9.62 times longer than the fastest. This could mean that an intermediate result is being cached.\n100000 loops, best of 3: 2.4 µs per loop\n\n%timeit shlex.split(line)\n10000 loops, best of 3: 50.2 µs per loop\n</code></pre>\n'}, {'answer_id': 51560564, 'author': 'Ton van den Heuvel', 'author_id': 79111, 'author_profile': 'https://Stackoverflow.com/users/79111', 'pm_score': 3, 'selected': False, 'text': '<p>The main problem with the accepted <code>shlex</code> approach is that it does not ignore escape characters outside quoted substrings, and gives slightly unexpected results in some corner cases.</p>\n<p>I have the following use case, where I need a split function that splits input strings such that either single-quoted or double-quoted substrings are preserved, with the ability to escape quotes within such a substring. Quotes within an unquoted string should not be treated differently from any other character. Some example test cases with the expected output:</p>\n<pre> input string | expected output\n===============================================\n \'abc def\' | [\'abc\', \'def\']\n "abc \\\\s def" | [\'abc\', \'\\\\s\', \'def\']\n \'"abc def" ghi\' | [\'abc def\', \'ghi\']\n "\'abc def\' ghi" | [\'abc def\', \'ghi\']\n \'"abc \\\\" def" ghi\' | [\'abc " def\', \'ghi\']\n "\'abc \\\\\' def\' ghi" | ["abc \' def", \'ghi\']\n "\'abc \\\\s def\' ghi" | [\'abc \\\\s def\', \'ghi\']\n \'"abc \\\\s def" ghi\' | [\'abc \\\\s def\', \'ghi\']\n \'"" test\' | [\'\', \'test\']\n "\'\' test" | [\'\', \'test\']\n "abc\'def" | ["abc\'def"]\n "abc\'def\'" | ["abc\'def\'"]\n "abc\'def\' ghi" | ["abc\'def\'", \'ghi\']\n "abc\'def\'ghi" | ["abc\'def\'ghi"]\n \'abc"def\' | [\'abc"def\']\n \'abc"def"\' | [\'abc"def"\']\n \'abc"def" ghi\' | [\'abc"def"\', \'ghi\']\n \'abc"def"ghi\' | [\'abc"def"ghi\']\n "r\'AA\' r\'.*_xyz$\'" | ["r\'AA\'", "r\'.*_xyz$\'"]\n \'abc"def ghi"\' | [\'abc"def ghi"\']\n \'abc"def ghi""jkl"\' | [\'abc"def ghi""jkl"\']\n \'a"b c"d"e"f"g h"\' | [\'a"b c"d"e"f"g h"\']\n \'c="ls /" type key\' | [\'c="ls /"\', \'type\', \'key\']\n "abc\'def ghi\'" | ["abc\'def ghi\'"]\n "c=\'ls /\' type key" | ["c=\'ls /\'", \'type\', \'key\']</pre>\n<p>I ended up with the following function to split a string such that the expected output results for all input strings:</p>\n<pre><code>import re\n\ndef quoted_split(s):\n def strip_quotes(s):\n if s and (s[0] == \'"\' or s[0] == "\'") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace(\'\\\\"\', \'"\').replace("\\\\\'", "\'") \\\n for p in re.findall(r\'(?:[^"\\s]*"(?:\\\\.|[^"])*"[^"\\s]*)+|(?:[^\\\'\\s]*\\\'(?:\\\\.|[^\\\'])*\\\'[^\\\'\\s]*)+|[^\\s]+\', s)]\n</code></pre>\n<p>It ain\'t pretty; but it works. The following test application checks the results of other approaches (<code>shlex</code> and <code>csv</code> for now) and the custom split implementation:</p>\n<pre><code>#!/bin/python2.7\n\nimport csv\nimport re\nimport shlex\n\nfrom timeit import timeit\n\ndef test_case(fn, s, expected):\n try:\n if fn(s) == expected:\n print \'[ OK ] %s -> %s\' % (s, fn(s))\n else:\n print \'[FAIL] %s -> %s\' % (s, fn(s))\n except Exception as e:\n print \'[FAIL] %s -> exception: %s\' % (s, e)\n\ndef test_case_no_output(fn, s, expected):\n try:\n fn(s)\n except:\n pass\n\ndef test_split(fn, test_case_fn=test_case):\n test_case_fn(fn, \'abc def\', [\'abc\', \'def\'])\n test_case_fn(fn, "abc \\\\s def", [\'abc\', \'\\\\s\', \'def\'])\n test_case_fn(fn, \'"abc def" ghi\', [\'abc def\', \'ghi\'])\n test_case_fn(fn, "\'abc def\' ghi", [\'abc def\', \'ghi\'])\n test_case_fn(fn, \'"abc \\\\" def" ghi\', [\'abc " def\', \'ghi\'])\n test_case_fn(fn, "\'abc \\\\\' def\' ghi", ["abc \' def", \'ghi\'])\n test_case_fn(fn, "\'abc \\\\s def\' ghi", [\'abc \\\\s def\', \'ghi\'])\n test_case_fn(fn, \'"abc \\\\s def" ghi\', [\'abc \\\\s def\', \'ghi\'])\n test_case_fn(fn, \'"" test\', [\'\', \'test\'])\n test_case_fn(fn, "\'\' test", [\'\', \'test\'])\n test_case_fn(fn, "abc\'def", ["abc\'def"])\n test_case_fn(fn, "abc\'def\'", ["abc\'def\'"])\n test_case_fn(fn, "abc\'def\' ghi", ["abc\'def\'", \'ghi\'])\n test_case_fn(fn, "abc\'def\'ghi", ["abc\'def\'ghi"])\n test_case_fn(fn, \'abc"def\', [\'abc"def\'])\n test_case_fn(fn, \'abc"def"\', [\'abc"def"\'])\n test_case_fn(fn, \'abc"def" ghi\', [\'abc"def"\', \'ghi\'])\n test_case_fn(fn, \'abc"def"ghi\', [\'abc"def"ghi\'])\n test_case_fn(fn, "r\'AA\' r\'.*_xyz$\'", ["r\'AA\'", "r\'.*_xyz$\'"])\n test_case_fn(fn, \'abc"def ghi"\', [\'abc"def ghi"\'])\n test_case_fn(fn, \'abc"def ghi""jkl"\', [\'abc"def ghi""jkl"\'])\n test_case_fn(fn, \'a"b c"d"e"f"g h"\', [\'a"b c"d"e"f"g h"\'])\n test_case_fn(fn, \'c="ls /" type key\', [\'c="ls /"\', \'type\', \'key\'])\n test_case_fn(fn, "abc\'def ghi\'", ["abc\'def ghi\'"])\n test_case_fn(fn, "c=\'ls /\' type key", ["c=\'ls /\'", \'type\', \'key\'])\n\ndef csv_split(s):\n return list(csv.reader([s], delimiter=\' \'))[0]\n\ndef re_split(s):\n def strip_quotes(s):\n if s and (s[0] == \'"\' or s[0] == "\'") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace(\'\\\\"\', \'"\').replace("\\\\\'", "\'") for p in re.findall(r\'(?:[^"\\s]*"(?:\\\\.|[^"])*"[^"\\s]*)+|(?:[^\\\'\\s]*\\\'(?:\\\\.|[^\\\'])*\\\'[^\\\'\\s]*)+|[^\\s]+\', s)]\n\nif __name__ == \'__main__\':\n print \'shlex\\n\'\n test_split(shlex.split)\n print\n\n print \'csv\\n\'\n test_split(csv_split)\n print\n\n print \'re\\n\'\n test_split(re_split)\n print\n\n iterations = 100\n setup = \'from __main__ import test_split, test_case_no_output, csv_split, re_split\\nimport shlex, re\'\n def benchmark(method, code):\n print \'%s: %.3fms per iteration\' % (method, (1000 * timeit(code, setup=setup, number=iterations) / iterations))\n benchmark(\'shlex\', \'test_split(shlex.split, test_case_no_output)\')\n benchmark(\'csv\', \'test_split(csv_split, test_case_no_output)\')\n benchmark(\'re\', \'test_split(re_split, test_case_no_output)\')\n</code></pre>\n<p>Output:</p>\n<pre>\nshlex\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[FAIL] abc \\s def -> [\'abc\', \'s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[ OK ] \'abc def\' ghi -> [\'abc def\', \'ghi\']\n[ OK ] "abc \\" def" ghi -> [\'abc " def\', \'ghi\']\n[FAIL] \'abc \\\' def\' ghi -> exception: No closing quotation\n[ OK ] \'abc \\s def\' ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[ OK ] \'\' test -> [\'\', \'test\']\n[FAIL] abc\'def -> exception: No closing quotation\n[FAIL] abc\'def\' -> [\'abcdef\']\n[FAIL] abc\'def\' ghi -> [\'abcdef\', \'ghi\']\n[FAIL] abc\'def\'ghi -> [\'abcdefghi\']\n[FAIL] abc"def -> exception: No closing quotation\n[FAIL] abc"def" -> [\'abcdef\']\n[FAIL] abc"def" ghi -> [\'abcdef\', \'ghi\']\n[FAIL] abc"def"ghi -> [\'abcdefghi\']\n[FAIL] r\'AA\' r\'.*_xyz$\' -> [\'rAA\', \'r.*_xyz$\']\n[FAIL] abc"def ghi" -> [\'abcdef ghi\']\n[FAIL] abc"def ghi""jkl" -> [\'abcdef ghijkl\']\n[FAIL] a"b c"d"e"f"g h" -> [\'ab cdefg h\']\n[FAIL] c="ls /" type key -> [\'c=ls /\', \'type\', \'key\']\n[FAIL] abc\'def ghi\' -> [\'abcdef ghi\']\n[FAIL] c=\'ls /\' type key -> [\'c=ls /\', \'type\', \'key\']\n\ncsv\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[ OK ] abc \\s def -> [\'abc\', \'\\\\s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[FAIL] \'abc def\' ghi -> ["\'abc", "def\'", \'ghi\']\n[FAIL] "abc \\" def" ghi -> [\'abc \\\\\', \'def"\', \'ghi\']\n[FAIL] \'abc \\\' def\' ghi -> ["\'abc", "\\\\\'", "def\'", \'ghi\']\n[FAIL] \'abc \\s def\' ghi -> ["\'abc", \'\\\\s\', "def\'", \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[FAIL] \'\' test -> ["\'\'", \'test\']\n[ OK ] abc\'def -> ["abc\'def"]\n[ OK ] abc\'def\' -> ["abc\'def\'"]\n[ OK ] abc\'def\' ghi -> ["abc\'def\'", \'ghi\']\n[ OK ] abc\'def\'ghi -> ["abc\'def\'ghi"]\n[ OK ] abc"def -> [\'abc"def\']\n[ OK ] abc"def" -> [\'abc"def"\']\n[ OK ] abc"def" ghi -> [\'abc"def"\', \'ghi\']\n[ OK ] abc"def"ghi -> [\'abc"def"ghi\']\n[ OK ] r\'AA\' r\'.*_xyz$\' -> ["r\'AA\'", "r\'.*_xyz$\'"]\n[FAIL] abc"def ghi" -> [\'abc"def\', \'ghi"\']\n[FAIL] abc"def ghi""jkl" -> [\'abc"def\', \'ghi""jkl"\']\n[FAIL] a"b c"d"e"f"g h" -> [\'a"b\', \'c"d"e"f"g\', \'h"\']\n[FAIL] c="ls /" type key -> [\'c="ls\', \'/"\', \'type\', \'key\']\n[FAIL] abc\'def ghi\' -> ["abc\'def", "ghi\'"]\n[FAIL] c=\'ls /\' type key -> ["c=\'ls", "/\'", \'type\', \'key\']\n\nre\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[ OK ] abc \\s def -> [\'abc\', \'\\\\s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[ OK ] \'abc def\' ghi -> [\'abc def\', \'ghi\']\n[ OK ] "abc \\" def" ghi -> [\'abc " def\', \'ghi\']\n[ OK ] \'abc \\\' def\' ghi -> ["abc \' def", \'ghi\']\n[ OK ] \'abc \\s def\' ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[ OK ] \'\' test -> [\'\', \'test\']\n[ OK ] abc\'def -> ["abc\'def"]\n[ OK ] abc\'def\' -> ["abc\'def\'"]\n[ OK ] abc\'def\' ghi -> ["abc\'def\'", \'ghi\']\n[ OK ] abc\'def\'ghi -> ["abc\'def\'ghi"]\n[ OK ] abc"def -> [\'abc"def\']\n[ OK ] abc"def" -> [\'abc"def"\']\n[ OK ] abc"def" ghi -> [\'abc"def"\', \'ghi\']\n[ OK ] abc"def"ghi -> [\'abc"def"ghi\']\n[ OK ] r\'AA\' r\'.*_xyz$\' -> ["r\'AA\'", "r\'.*_xyz$\'"]\n[ OK ] abc"def ghi" -> [\'abc"def ghi"\']\n[ OK ] abc"def ghi""jkl" -> [\'abc"def ghi""jkl"\']\n[ OK ] a"b c"d"e"f"g h" -> [\'a"b c"d"e"f"g h"\']\n[ OK ] c="ls /" type key -> [\'c="ls /"\', \'type\', \'key\']\n[ OK ] abc\'def ghi\' -> ["abc\'def ghi\'"]\n[ OK ] c=\'ls /\' type key -> ["c=\'ls /\'", \'type\', \'key\']\n\nshlex: 0.335ms per iteration\ncsv: 0.036ms per iteration\nre: 0.068ms per iteration\n</pre>\n<p>So performance is much better than <code>shlex</code>, and can be improved further by precompiling the regular expression, in which case it will outperform the <code>csv</code> approach.</p>\n'}, {'answer_id': 53210803, 'author': 'hochl', 'author_id': 589206, 'author_profile': 'https://Stackoverflow.com/users/589206', 'pm_score': 4, 'selected': False, 'text': '<p>It seems that for performance reasons <code>re</code> is faster. Here is my solution using a least greedy operator that preserves the outer quotes:</p>\n\n<pre><code>re.findall("(?:\\".*?\\"|\\S)+", s)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[\'this\', \'is\', \'"a test"\']\n</code></pre>\n\n<p>It leaves constructs like <code>aaa"bla blub"bbb</code> together as these tokens are not separated by spaces. If the string contains escaped characters, you can match like that:</p>\n\n<pre><code>>>> a = "She said \\"He said, \\\\\\"My name is Mark.\\\\\\"\\""\n>>> a\n\'She said "He said, \\\\"My name is Mark.\\\\""\'\n>>> for i in re.findall("(?:\\".*?[^\\\\\\\\]\\"|\\S)+", a): print(i)\n...\nShe\nsaid\n"He said, \\"My name is Mark.\\""\n</code></pre>\n\n<p>Please note that this also matches the empty string <code>""</code> by means of the <code>\\S</code> part of the pattern.</p>\n'}, {'answer_id': 60929888, 'author': 'Mikhail Zakharov', 'author_id': 9127614, 'author_profile': 'https://Stackoverflow.com/users/9127614', 'pm_score': 1, 'selected': False, 'text': '<p>As an option try tssplit:</p>\n\n<pre><code>In [1]: from tssplit import tssplit\nIn [2]: tssplit(\'this is "a test"\', quote=\'"\', delimiter=\'\')\nOut[2]: [\'this\', \'is\', \'a test\']\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5324/'] |
79,992 | <p>Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying. </p>
<p>Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block.<p>
I would feel better knowing what the exact issue is with the VS.NET debugger.<p>
Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code. <P></p>
<p>System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro.
I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64.<p>
Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And <em>YES</em> vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger.</p>
| [{'answer_id': 79985, 'author': 'Jerub', 'author_id': 14648, 'author_profile': 'https://Stackoverflow.com/users/14648', 'pm_score': 10, 'selected': True, 'text': '<p>You want <code>split</code>, from the built-in <a href="https://docs.python.org/library/shlex.html" rel="noreferrer"><code>shlex</code></a> module.</p>\n<pre><code>>>> import shlex\n>>> shlex.split(\'this is "a test"\')\n[\'this\', \'is\', \'a test\']\n</code></pre>\n<p>This should do exactly what you want.</p>\n<p>If you want to preserve the quotation marks, then you can pass the <code>posix=False</code> kwarg.</p>\n<pre><code>>>> shlex.split(\'this is "a test"\', posix=False)\n[\'this\', \'is\', \'"a test"\']\n</code></pre>\n'}, {'answer_id': 79989, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 6, 'selected': False, 'text': '<p>Have a look at the <code>shlex</code> module, particularly <code>shlex.split</code>.</p>\n\n<pre><code>>>> import shlex\n>>> shlex.split(\'This is "a test"\')\n[\'This\', \'is\', \'a test\']\n</code></pre>\n'}, {'answer_id': 80015, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': -1, 'selected': False, 'text': '<p>Try this:</p>\n\n<pre><code> def adamsplit(s):\n result = []\n inquotes = False\n for substring in s.split(\'"\'):\n if not inquotes:\n result.extend(substring.split())\n else:\n result.append(substring)\n inquotes = not inquotes\n return result\n</code></pre>\n\n<p>Some test strings:</p>\n\n<pre><code>\'This is "a test"\' -> [\'This\', \'is\', \'a test\']\n\'"This is \\\'a test\\\'"\' -> ["This is \'a test\'"]\n</code></pre>\n'}, {'answer_id': 80361, 'author': 'Gregory', 'author_id': 14351, 'author_profile': 'https://Stackoverflow.com/users/14351', 'pm_score': -1, 'selected': False, 'text': '<p>If you don\'t care about sub strings than a simple</p>\n\n<pre><code>>>> \'a short sized string with spaces \'.split()\n</code></pre>\n\n<p>Performance:</p>\n\n<pre><code>>>> s = " (\'a short sized string with spaces \'*100).split() "\n>>> t = timeit.Timer(stmt=s)\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n171.39 usec/pass\n</code></pre>\n\n<p>Or string module</p>\n\n<pre><code>>>> from string import split as stringsplit; \n>>> stringsplit(\'a short sized string with spaces \'*100)\n</code></pre>\n\n<p>Performance: String module seems to perform better than string methods</p>\n\n<pre><code>>>> s = "stringsplit(\'a short sized string with spaces \'*100)"\n>>> t = timeit.Timer(s, "from string import split as stringsplit")\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n154.88 usec/pass\n</code></pre>\n\n<p>Or you can use RE engine</p>\n\n<pre><code>>>> from re import split as resplit\n>>> regex = \'\\s+\'\n>>> medstring = \'a short sized string with spaces \'*100\n>>> resplit(regex, medstring)\n</code></pre>\n\n<p>Performance</p>\n\n<pre><code>>>> s = "resplit(regex, medstring)"\n>>> t = timeit.Timer(s, "from re import split as resplit; regex=\'\\s+\'; medstring=\'a short sized string with spaces \'*100")\n>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)\n540.21 usec/pass\n</code></pre>\n\n<p>For very long strings you should not load the entire string into memory and instead either split the lines or use an iterative loop</p>\n'}, {'answer_id': 80449, 'author': 'elifiner', 'author_id': 15109, 'author_profile': 'https://Stackoverflow.com/users/15109', 'pm_score': 3, 'selected': False, 'text': '<p>Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \\x00, then split by spaces, then replace the \\x00 back to spaces in each part.</p>\n\n<p>Both versions do the same thing, but splitter is a bit more readable then splitter2.</p>\n\n<pre><code>import re\n\ns = \'this is "a test" some text "another test"\'\n\ndef splitter(s):\n def replacer(m):\n return m.group(0).replace(" ", "\\x00")\n parts = re.sub(\'".+?"\', replacer, s).split()\n parts = [p.replace("\\x00", " ") for p in parts]\n return parts\n\ndef splitter2(s):\n return [p.replace("\\x00", " ") for p in re.sub(\'".+?"\', lambda m: m.group(0).replace(" ", "\\x00"), s).split()]\n\nprint splitter2(s)\n</code></pre>\n'}, {'answer_id': 524796, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe "whitespace or thing-surrounded-by-quotes", and most regex engines (including Python\'s) can split on a regex. So if you\'re going to use regexes, why not just say exactly what you mean?:</p>\n\n<pre><code>test = \'this is "a test"\' # or "this is \'a test\'"\n# pieces = [p for p in re.split("( |[\\\\\\"\'].*[\\\\\\"\'])", test) if p.strip()]\n# From comments, use this:\npieces = [p for p in re.split("( |\\\\\\".*?\\\\\\"|\'.*?\')", test) if p.strip()]\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>[\\\\\\"\'] = double-quote or single-quote\n.* = anything\n( |X) = space or X\n.strip() = remove space and empty-string separators\n</code></pre>\n\n<p>shlex probably provides more features, though.</p>\n'}, {'answer_id': 525011, 'author': 'Ryan Ginstrom', 'author_id': 10658, 'author_profile': 'https://Stackoverflow.com/users/10658', 'pm_score': 5, 'selected': False, 'text': '<p>Depending on your use case, you may also want to check out the <a href="https://docs.python.org/library/csv.html" rel="noreferrer"><code>csv</code></a> module:</p>\n\n<pre><code>import csv\nlines = [\'this is "a string"\', \'and more "stuff"\']\nfor row in csv.reader(lines, delimiter=" "):\n print(row)\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>[\'this\', \'is\', \'a string\']\n[\'and\', \'more\', \'stuff\']\n</code></pre>\n'}, {'answer_id': 2159337, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Hmm, can\'t seem to find the "Reply" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:</p>\n\n<pre><code> [i.strip(\'"\').strip("\'") for i in re.split(r\'(\\s+|(?<!\\\\)".*?(?<!\\\\)"|(?<!\\\\)\\\'.*?(?<!\\\\)\\\')\', string) if i.strip()]\n</code></pre>\n\n<p>This works on strings like <code>\'This is " a \\\\\\"test\\\\\\"\\\\\\\'s substring"\'</code> (the insane markup is unfortunately necessary to keep Python from removing the escapes).</p>\n\n<p>If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:</p>\n\n<pre><code>[i.strip(\'"\').strip("\'").decode(\'string_escape\') for i in re.split(r\'(\\s+|(?<!\\\\)".*?(?<!\\\\)"|(?<!\\\\)\\\'.*?(?<!\\\\)\\\')\', string) if i.strip()]\n</code></pre>\n'}, {'answer_id': 11194593, 'author': 'moschlar', 'author_id': 1175818, 'author_profile': 'https://Stackoverflow.com/users/1175818', 'pm_score': 1, 'selected': False, 'text': "<p>To get around the unicode issues in some Python 2 versions, I suggest:</p>\n\n<pre><code>from shlex import split as _split\nsplit = lambda a: [b.decode('utf-8') for b in _split(a.encode('utf-8'))]\n</code></pre>\n"}, {'answer_id': 23155180, 'author': 'Daniel Dai', 'author_id': 1089262, 'author_profile': 'https://Stackoverflow.com/users/1089262', 'pm_score': 4, 'selected': False, 'text': '<p>I use shlex.split to process 70,000,000 lines of squid log, it\'s so slow. So I switched to re.</p>\n\n<p>Please try this, if you have performance problem with shlex.</p>\n\n<pre><code>import re\n\ndef line_split(line):\n return re.findall(r\'[^"\\s]\\S*|".+?"\', line)\n</code></pre>\n'}, {'answer_id': 32480710, 'author': 'hussic', 'author_id': 4111130, 'author_profile': 'https://Stackoverflow.com/users/4111130', 'pm_score': 0, 'selected': False, 'text': '<p>I suggest:</p>\n\n<p>test string:</p>\n\n<pre><code>s = \'abc "ad" \\\'fg\\\' "kk\\\'rdt\\\'" zzz"34"zzz "" \\\'\\\'\'\n</code></pre>\n\n<p>to capture also "" and \'\':</p>\n\n<pre><code>import re\nre.findall(r\'"[^"]*"|\\\'[^\\\']*\\\'|[^"\\\'\\s]+\',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>[\'abc\', \'"ad"\', "\'fg\'", \'"kk\\\'rdt\\\'"\', \'zzz\', \'"34"\', \'zzz\', \'""\', "\'\'"]\n</code></pre>\n\n<p>to ignore empty "" and \'\':</p>\n\n<pre><code>import re\nre.findall(r\'"[^"]+"|\\\'[^\\\']+\\\'|[^"\\\'\\s]+\',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>[\'abc\', \'"ad"\', "\'fg\'", \'"kk\\\'rdt\\\'"\', \'zzz\', \'"34"\', \'zzz\']\n</code></pre>\n'}, {'answer_id': 43035638, 'author': 'THE_MAD_KING', 'author_id': 7771160, 'author_profile': 'https://Stackoverflow.com/users/7771160', 'pm_score': 2, 'selected': False, 'text': '<p>To preserve quotes use this function:</p>\n\n<pre><code>def getArgs(s):\n args = []\n cur = \'\'\n inQuotes = 0\n for char in s.strip():\n if char == \' \' and not inQuotes:\n args.append(cur)\n cur = \'\'\n elif char == \'"\' and not inQuotes:\n inQuotes = 1\n cur += char\n elif char == \'"\' and inQuotes:\n inQuotes = 0\n cur += char\n else:\n cur += char\n args.append(cur)\n return args\n</code></pre>\n'}, {'answer_id': 49791573, 'author': 'har777', 'author_id': 1851428, 'author_profile': 'https://Stackoverflow.com/users/1851428', 'pm_score': 3, 'selected': False, 'text': '<p>Speed test of different answers:</p>\n\n<pre><code>import re\nimport shlex\nimport csv\n\nline = \'this is "a test"\'\n\n%timeit [p for p in re.split("( |\\\\\\".*?\\\\\\"|\'.*?\')", line) if p.strip()]\n100000 loops, best of 3: 5.17 µs per loop\n\n%timeit re.findall(r\'[^"\\s]\\S*|".+?"\', line)\n100000 loops, best of 3: 2.88 µs per loop\n\n%timeit list(csv.reader([line], delimiter=" "))\nThe slowest run took 9.62 times longer than the fastest. This could mean that an intermediate result is being cached.\n100000 loops, best of 3: 2.4 µs per loop\n\n%timeit shlex.split(line)\n10000 loops, best of 3: 50.2 µs per loop\n</code></pre>\n'}, {'answer_id': 51560564, 'author': 'Ton van den Heuvel', 'author_id': 79111, 'author_profile': 'https://Stackoverflow.com/users/79111', 'pm_score': 3, 'selected': False, 'text': '<p>The main problem with the accepted <code>shlex</code> approach is that it does not ignore escape characters outside quoted substrings, and gives slightly unexpected results in some corner cases.</p>\n<p>I have the following use case, where I need a split function that splits input strings such that either single-quoted or double-quoted substrings are preserved, with the ability to escape quotes within such a substring. Quotes within an unquoted string should not be treated differently from any other character. Some example test cases with the expected output:</p>\n<pre> input string | expected output\n===============================================\n \'abc def\' | [\'abc\', \'def\']\n "abc \\\\s def" | [\'abc\', \'\\\\s\', \'def\']\n \'"abc def" ghi\' | [\'abc def\', \'ghi\']\n "\'abc def\' ghi" | [\'abc def\', \'ghi\']\n \'"abc \\\\" def" ghi\' | [\'abc " def\', \'ghi\']\n "\'abc \\\\\' def\' ghi" | ["abc \' def", \'ghi\']\n "\'abc \\\\s def\' ghi" | [\'abc \\\\s def\', \'ghi\']\n \'"abc \\\\s def" ghi\' | [\'abc \\\\s def\', \'ghi\']\n \'"" test\' | [\'\', \'test\']\n "\'\' test" | [\'\', \'test\']\n "abc\'def" | ["abc\'def"]\n "abc\'def\'" | ["abc\'def\'"]\n "abc\'def\' ghi" | ["abc\'def\'", \'ghi\']\n "abc\'def\'ghi" | ["abc\'def\'ghi"]\n \'abc"def\' | [\'abc"def\']\n \'abc"def"\' | [\'abc"def"\']\n \'abc"def" ghi\' | [\'abc"def"\', \'ghi\']\n \'abc"def"ghi\' | [\'abc"def"ghi\']\n "r\'AA\' r\'.*_xyz$\'" | ["r\'AA\'", "r\'.*_xyz$\'"]\n \'abc"def ghi"\' | [\'abc"def ghi"\']\n \'abc"def ghi""jkl"\' | [\'abc"def ghi""jkl"\']\n \'a"b c"d"e"f"g h"\' | [\'a"b c"d"e"f"g h"\']\n \'c="ls /" type key\' | [\'c="ls /"\', \'type\', \'key\']\n "abc\'def ghi\'" | ["abc\'def ghi\'"]\n "c=\'ls /\' type key" | ["c=\'ls /\'", \'type\', \'key\']</pre>\n<p>I ended up with the following function to split a string such that the expected output results for all input strings:</p>\n<pre><code>import re\n\ndef quoted_split(s):\n def strip_quotes(s):\n if s and (s[0] == \'"\' or s[0] == "\'") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace(\'\\\\"\', \'"\').replace("\\\\\'", "\'") \\\n for p in re.findall(r\'(?:[^"\\s]*"(?:\\\\.|[^"])*"[^"\\s]*)+|(?:[^\\\'\\s]*\\\'(?:\\\\.|[^\\\'])*\\\'[^\\\'\\s]*)+|[^\\s]+\', s)]\n</code></pre>\n<p>It ain\'t pretty; but it works. The following test application checks the results of other approaches (<code>shlex</code> and <code>csv</code> for now) and the custom split implementation:</p>\n<pre><code>#!/bin/python2.7\n\nimport csv\nimport re\nimport shlex\n\nfrom timeit import timeit\n\ndef test_case(fn, s, expected):\n try:\n if fn(s) == expected:\n print \'[ OK ] %s -> %s\' % (s, fn(s))\n else:\n print \'[FAIL] %s -> %s\' % (s, fn(s))\n except Exception as e:\n print \'[FAIL] %s -> exception: %s\' % (s, e)\n\ndef test_case_no_output(fn, s, expected):\n try:\n fn(s)\n except:\n pass\n\ndef test_split(fn, test_case_fn=test_case):\n test_case_fn(fn, \'abc def\', [\'abc\', \'def\'])\n test_case_fn(fn, "abc \\\\s def", [\'abc\', \'\\\\s\', \'def\'])\n test_case_fn(fn, \'"abc def" ghi\', [\'abc def\', \'ghi\'])\n test_case_fn(fn, "\'abc def\' ghi", [\'abc def\', \'ghi\'])\n test_case_fn(fn, \'"abc \\\\" def" ghi\', [\'abc " def\', \'ghi\'])\n test_case_fn(fn, "\'abc \\\\\' def\' ghi", ["abc \' def", \'ghi\'])\n test_case_fn(fn, "\'abc \\\\s def\' ghi", [\'abc \\\\s def\', \'ghi\'])\n test_case_fn(fn, \'"abc \\\\s def" ghi\', [\'abc \\\\s def\', \'ghi\'])\n test_case_fn(fn, \'"" test\', [\'\', \'test\'])\n test_case_fn(fn, "\'\' test", [\'\', \'test\'])\n test_case_fn(fn, "abc\'def", ["abc\'def"])\n test_case_fn(fn, "abc\'def\'", ["abc\'def\'"])\n test_case_fn(fn, "abc\'def\' ghi", ["abc\'def\'", \'ghi\'])\n test_case_fn(fn, "abc\'def\'ghi", ["abc\'def\'ghi"])\n test_case_fn(fn, \'abc"def\', [\'abc"def\'])\n test_case_fn(fn, \'abc"def"\', [\'abc"def"\'])\n test_case_fn(fn, \'abc"def" ghi\', [\'abc"def"\', \'ghi\'])\n test_case_fn(fn, \'abc"def"ghi\', [\'abc"def"ghi\'])\n test_case_fn(fn, "r\'AA\' r\'.*_xyz$\'", ["r\'AA\'", "r\'.*_xyz$\'"])\n test_case_fn(fn, \'abc"def ghi"\', [\'abc"def ghi"\'])\n test_case_fn(fn, \'abc"def ghi""jkl"\', [\'abc"def ghi""jkl"\'])\n test_case_fn(fn, \'a"b c"d"e"f"g h"\', [\'a"b c"d"e"f"g h"\'])\n test_case_fn(fn, \'c="ls /" type key\', [\'c="ls /"\', \'type\', \'key\'])\n test_case_fn(fn, "abc\'def ghi\'", ["abc\'def ghi\'"])\n test_case_fn(fn, "c=\'ls /\' type key", ["c=\'ls /\'", \'type\', \'key\'])\n\ndef csv_split(s):\n return list(csv.reader([s], delimiter=\' \'))[0]\n\ndef re_split(s):\n def strip_quotes(s):\n if s and (s[0] == \'"\' or s[0] == "\'") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace(\'\\\\"\', \'"\').replace("\\\\\'", "\'") for p in re.findall(r\'(?:[^"\\s]*"(?:\\\\.|[^"])*"[^"\\s]*)+|(?:[^\\\'\\s]*\\\'(?:\\\\.|[^\\\'])*\\\'[^\\\'\\s]*)+|[^\\s]+\', s)]\n\nif __name__ == \'__main__\':\n print \'shlex\\n\'\n test_split(shlex.split)\n print\n\n print \'csv\\n\'\n test_split(csv_split)\n print\n\n print \'re\\n\'\n test_split(re_split)\n print\n\n iterations = 100\n setup = \'from __main__ import test_split, test_case_no_output, csv_split, re_split\\nimport shlex, re\'\n def benchmark(method, code):\n print \'%s: %.3fms per iteration\' % (method, (1000 * timeit(code, setup=setup, number=iterations) / iterations))\n benchmark(\'shlex\', \'test_split(shlex.split, test_case_no_output)\')\n benchmark(\'csv\', \'test_split(csv_split, test_case_no_output)\')\n benchmark(\'re\', \'test_split(re_split, test_case_no_output)\')\n</code></pre>\n<p>Output:</p>\n<pre>\nshlex\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[FAIL] abc \\s def -> [\'abc\', \'s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[ OK ] \'abc def\' ghi -> [\'abc def\', \'ghi\']\n[ OK ] "abc \\" def" ghi -> [\'abc " def\', \'ghi\']\n[FAIL] \'abc \\\' def\' ghi -> exception: No closing quotation\n[ OK ] \'abc \\s def\' ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[ OK ] \'\' test -> [\'\', \'test\']\n[FAIL] abc\'def -> exception: No closing quotation\n[FAIL] abc\'def\' -> [\'abcdef\']\n[FAIL] abc\'def\' ghi -> [\'abcdef\', \'ghi\']\n[FAIL] abc\'def\'ghi -> [\'abcdefghi\']\n[FAIL] abc"def -> exception: No closing quotation\n[FAIL] abc"def" -> [\'abcdef\']\n[FAIL] abc"def" ghi -> [\'abcdef\', \'ghi\']\n[FAIL] abc"def"ghi -> [\'abcdefghi\']\n[FAIL] r\'AA\' r\'.*_xyz$\' -> [\'rAA\', \'r.*_xyz$\']\n[FAIL] abc"def ghi" -> [\'abcdef ghi\']\n[FAIL] abc"def ghi""jkl" -> [\'abcdef ghijkl\']\n[FAIL] a"b c"d"e"f"g h" -> [\'ab cdefg h\']\n[FAIL] c="ls /" type key -> [\'c=ls /\', \'type\', \'key\']\n[FAIL] abc\'def ghi\' -> [\'abcdef ghi\']\n[FAIL] c=\'ls /\' type key -> [\'c=ls /\', \'type\', \'key\']\n\ncsv\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[ OK ] abc \\s def -> [\'abc\', \'\\\\s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[FAIL] \'abc def\' ghi -> ["\'abc", "def\'", \'ghi\']\n[FAIL] "abc \\" def" ghi -> [\'abc \\\\\', \'def"\', \'ghi\']\n[FAIL] \'abc \\\' def\' ghi -> ["\'abc", "\\\\\'", "def\'", \'ghi\']\n[FAIL] \'abc \\s def\' ghi -> ["\'abc", \'\\\\s\', "def\'", \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[FAIL] \'\' test -> ["\'\'", \'test\']\n[ OK ] abc\'def -> ["abc\'def"]\n[ OK ] abc\'def\' -> ["abc\'def\'"]\n[ OK ] abc\'def\' ghi -> ["abc\'def\'", \'ghi\']\n[ OK ] abc\'def\'ghi -> ["abc\'def\'ghi"]\n[ OK ] abc"def -> [\'abc"def\']\n[ OK ] abc"def" -> [\'abc"def"\']\n[ OK ] abc"def" ghi -> [\'abc"def"\', \'ghi\']\n[ OK ] abc"def"ghi -> [\'abc"def"ghi\']\n[ OK ] r\'AA\' r\'.*_xyz$\' -> ["r\'AA\'", "r\'.*_xyz$\'"]\n[FAIL] abc"def ghi" -> [\'abc"def\', \'ghi"\']\n[FAIL] abc"def ghi""jkl" -> [\'abc"def\', \'ghi""jkl"\']\n[FAIL] a"b c"d"e"f"g h" -> [\'a"b\', \'c"d"e"f"g\', \'h"\']\n[FAIL] c="ls /" type key -> [\'c="ls\', \'/"\', \'type\', \'key\']\n[FAIL] abc\'def ghi\' -> ["abc\'def", "ghi\'"]\n[FAIL] c=\'ls /\' type key -> ["c=\'ls", "/\'", \'type\', \'key\']\n\nre\n\n[ OK ] abc def -> [\'abc\', \'def\']\n[ OK ] abc \\s def -> [\'abc\', \'\\\\s\', \'def\']\n[ OK ] "abc def" ghi -> [\'abc def\', \'ghi\']\n[ OK ] \'abc def\' ghi -> [\'abc def\', \'ghi\']\n[ OK ] "abc \\" def" ghi -> [\'abc " def\', \'ghi\']\n[ OK ] \'abc \\\' def\' ghi -> ["abc \' def", \'ghi\']\n[ OK ] \'abc \\s def\' ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "abc \\s def" ghi -> [\'abc \\\\s def\', \'ghi\']\n[ OK ] "" test -> [\'\', \'test\']\n[ OK ] \'\' test -> [\'\', \'test\']\n[ OK ] abc\'def -> ["abc\'def"]\n[ OK ] abc\'def\' -> ["abc\'def\'"]\n[ OK ] abc\'def\' ghi -> ["abc\'def\'", \'ghi\']\n[ OK ] abc\'def\'ghi -> ["abc\'def\'ghi"]\n[ OK ] abc"def -> [\'abc"def\']\n[ OK ] abc"def" -> [\'abc"def"\']\n[ OK ] abc"def" ghi -> [\'abc"def"\', \'ghi\']\n[ OK ] abc"def"ghi -> [\'abc"def"ghi\']\n[ OK ] r\'AA\' r\'.*_xyz$\' -> ["r\'AA\'", "r\'.*_xyz$\'"]\n[ OK ] abc"def ghi" -> [\'abc"def ghi"\']\n[ OK ] abc"def ghi""jkl" -> [\'abc"def ghi""jkl"\']\n[ OK ] a"b c"d"e"f"g h" -> [\'a"b c"d"e"f"g h"\']\n[ OK ] c="ls /" type key -> [\'c="ls /"\', \'type\', \'key\']\n[ OK ] abc\'def ghi\' -> ["abc\'def ghi\'"]\n[ OK ] c=\'ls /\' type key -> ["c=\'ls /\'", \'type\', \'key\']\n\nshlex: 0.335ms per iteration\ncsv: 0.036ms per iteration\nre: 0.068ms per iteration\n</pre>\n<p>So performance is much better than <code>shlex</code>, and can be improved further by precompiling the regular expression, in which case it will outperform the <code>csv</code> approach.</p>\n'}, {'answer_id': 53210803, 'author': 'hochl', 'author_id': 589206, 'author_profile': 'https://Stackoverflow.com/users/589206', 'pm_score': 4, 'selected': False, 'text': '<p>It seems that for performance reasons <code>re</code> is faster. Here is my solution using a least greedy operator that preserves the outer quotes:</p>\n\n<pre><code>re.findall("(?:\\".*?\\"|\\S)+", s)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[\'this\', \'is\', \'"a test"\']\n</code></pre>\n\n<p>It leaves constructs like <code>aaa"bla blub"bbb</code> together as these tokens are not separated by spaces. If the string contains escaped characters, you can match like that:</p>\n\n<pre><code>>>> a = "She said \\"He said, \\\\\\"My name is Mark.\\\\\\"\\""\n>>> a\n\'She said "He said, \\\\"My name is Mark.\\\\""\'\n>>> for i in re.findall("(?:\\".*?[^\\\\\\\\]\\"|\\S)+", a): print(i)\n...\nShe\nsaid\n"He said, \\"My name is Mark.\\""\n</code></pre>\n\n<p>Please note that this also matches the empty string <code>""</code> by means of the <code>\\S</code> part of the pattern.</p>\n'}, {'answer_id': 60929888, 'author': 'Mikhail Zakharov', 'author_id': 9127614, 'author_profile': 'https://Stackoverflow.com/users/9127614', 'pm_score': 1, 'selected': False, 'text': '<p>As an option try tssplit:</p>\n\n<pre><code>In [1]: from tssplit import tssplit\nIn [2]: tssplit(\'this is "a test"\', quote=\'"\', delimiter=\'\')\nOut[2]: [\'this\', \'is\', \'a test\']\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10972/'] |
79,999 | <p>If you were writing a new application from scratch today, and wanted it to scale to all the cores you could throw at it tomorrow, what parallel programming model/system/language/library would you choose? Why?</p>
<p>I am particularly interested in answers along these axes:</p>
<ol>
<li>Programmer productivity / ease of use (can mortals successfully use it?)</li>
<li>Target application domain (what problems is it (not) good at?)</li>
<li>Concurrency style (does it support tasks, pipelines, data parallelism, messages...?)
<li>Maintainability / future-proofing (will anybody still be using it in 20 years?)</li>
<li>Performance (how does it scale on what kinds of hardware?)</li>
</ol>
<p>I am being deliberately vague on the nature of the application in anticipation of getting good general answers useful for a variety of applications.</p>
| [{'answer_id': 80024, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>For .NET application I choose "<a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx" rel="nofollow noreferrer">.NET Parallel Extensions (PLINQ)</a>" it\'s extremely easy to use and allows me to parallelize existing code in minutes.</p>\n\n<ol>\n<li>It\'s simple to learn</li>\n<li>Used to perform complex operations over large arrays of objects, so I can\'t comment on other applications</li>\n<li>Supports tasks and piplines</li>\n<li>Should be supported for a next couple of years, but who knows for sure?</li>\n<li>CTP version has some performance issues, but already looks very promising.</li>\n</ol>\n\n<p>Mono <a href="http://tirania.org/blog/archive/2008/Jul-26-1.html" rel="nofollow noreferrer">will likely get</a> support for PLINQ, so it could be a cross-platform solution as well.</p>\n'}, {'answer_id': 80034, 'author': 'fulmicoton', 'author_id': 446497, 'author_profile': 'https://Stackoverflow.com/users/446497', 'pm_score': 1, 'selected': False, 'text': '<p>Qt concurrent offers an implementation of MapReduce for multicore which is really easy to use. It is multiOS.</p>\n'}, {'answer_id': 80037, 'author': 'zurk', 'author_id': 14907, 'author_profile': 'https://Stackoverflow.com/users/14907', 'pm_score': 0, 'selected': False, 'text': "<p>I'd use Java - its portable so future processors wont be a problem. I'd also code my application with layers seperating interface / logic and data (more like 3 tier web app) with standard mutex routines as a library (less debugging of parallel code). Remember that web servers scale to many processors really well and are the least painful path to multicore. Either that or look at the old Connection Machine model with a virtual processor tied to data. </p>\n"}, {'answer_id': 80039, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 4, 'selected': False, 'text': "<p>The mapreduce/hadoop paradigm is useful, and relevant. Especially for people who are used to languages like perl, the idea of mapping over an array and doing some action on each element should come pretty fluidly and naturally, and mapreduce/hadoop just takes it to the next stage and says that there's no reason that each element of the array need be processed on the same machine. </p>\n\n<p>In a sense it's more battle tested, because Google is using mapreduce and plenty of people have been using hadoop, and has shown that it works well for scaling applications across multiple machines over the network. And if you can scale over multiple machines across the network, you can scale over multiple cores in a single machine.</p>\n"}, {'answer_id': 80044, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m betting on communicating event loops with promises, as realized in systems like <a href="http://twistedmatrix.com" rel="nofollow noreferrer">Twisted</a>, <a href="http://erights.org" rel="nofollow noreferrer">E</a>, <a href="http://prog.vub.ac.be/amop/start" rel="nofollow noreferrer">AmbientTalk</a>, and others. They retain the ability to write code with the same execution-model assumptions as non-concurrent/parallel applications, but scaling to distributed and parallel systems. (That\'s why I\'m working on <a href="http://launchpad.net/ecru" rel="nofollow noreferrer">Ecru</a>.)</p>\n'}, {'answer_id': 80064, 'author': 'Kevin Little', 'author_id': 14028, 'author_profile': 'https://Stackoverflow.com/users/14028', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://www.erlang.org/" rel="nofollow noreferrer">Erlang</a>. Google for it, and watch the various presentations and videos. Many of the programmers and architects I respect are quite taken with its scalability. We\'re using it where I work pretty heavily...</p>\n'}, {'answer_id': 80079, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 3, 'selected': False, 'text': '<p>For heavy computations and the like, purely functional languages like <a href="http://www.haskell.org/" rel="noreferrer">Haskell</a> are easily <a href="http://www.macs.hw.ac.uk/~dsg/gph/" rel="noreferrer">parallelizable</a> without any effort on the part of the programmer. Apart from learning Haskell, that is.</p>\n\n<p>However, I do not think that this is the way of the (near) future, simply because too many programmers are too used to the imperative programming paradigm.</p>\n'}, {'answer_id': 80150, 'author': 'Daniel', 'author_id': 13615, 'author_profile': 'https://Stackoverflow.com/users/13615', 'pm_score': 1, 'selected': False, 'text': '<p>If your problem domain permits try to think about a share nothing model. The less you share between processes and threads the less you have to design complex concurrency models.</p>\n'}, {'answer_id': 80176, 'author': 'Jörg W Mittag', 'author_id': 2988, 'author_profile': 'https://Stackoverflow.com/users/2988', 'pm_score': 4, 'selected': False, 'text': '<p>Two solutions I really like are <a href="http://Moscova.Inria.Fr/join/" rel="noreferrer">join calculus</a> (<a href="http://JoCaml.Inria.Fr/" rel="noreferrer">JoCaml</a>, <a href="http://Research.Microsoft.Com/~nick/polyphony/" rel="noreferrer">Polyphonic C#</a>, <a href="http://Research.Microsoft.Com/COmega/" rel="noreferrer">Cω</a>) and the <a href="http://Wikipedia.Org/wiki/Actor_model" rel="noreferrer">actor model</a> (<a href="http://Erlang.Org/" rel="noreferrer">Erlang</a>, <a href="http://Scala-Lang.Org/" rel="noreferrer">Scala</a>, <a href="http://ERights.Org/" rel="noreferrer">E</a>, <a href="http://IoLanguage.Com/" rel="noreferrer">Io</a>).</p>\n\n<p>I\'m not particularly impressed with <a href="http://Wikipedia.Org/wiki/Software_transactional_memory" rel="noreferrer">Software Transactional Memory</a>. It just feels like it\'s only there to allow threads to cling on to life a little while longer, even though they should have died decades ago. However, it does have three major advantages:</p>\n\n<ol>\n<li>People understand transactions in databases</li>\n<li>There is already talk of transactional RAM hardware</li>\n<li>As much as we all wish them gone, threads are probably going to be the dominant concurrency model for the next couple of decades, sad as that may be. STM could significantly reduce the pain.</li>\n</ol>\n'}, {'answer_id': 84271, 'author': 'emk', 'author_id': 12089, 'author_profile': 'https://Stackoverflow.com/users/12089', 'pm_score': 5, 'selected': False, 'text': '<p>Multi-core programming may actually require more than one paradigm. Some current contenders are:</p>\n\n<ol>\n<li><a href="http://labs.google.com/papers/mapreduce.html" rel="noreferrer">MapReduce</a>. This works well where a problem can be easily decomposed into parallel chunks.</li>\n<li><a href="http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell" rel="noreferrer">Nested Data Parallelism</a>. This is similar to MapReduce, but actually supports recursive decomposition of a problem, even when the recursive chunks are of irregular size. Look for NDP to be a big win in purely functional languages running on massively parallel but limited hardware (like GPUs).</li>\n<li><a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">Software Transactional Memory</a>. If you need traditional threads, STM makes them bearable. You pay a 50% performance hit in critical sections, but you can scale complex locking schemes to 100s of processors without pain. This will not, however, work for distributed systems.</li>\n<li><a href="http://www.erlang.org/" rel="noreferrer">Parallel object threads with messaging</a>. This really clever model is used by Erlang. Each "object" becomes a lightweight thread, and objects communicate by asynchronous messages and pattern matching. It\'s basically true parallel OO. This has succeeded nicely in several real-world applications, and it works great for unreliable distributed systems.</li>\n</ol>\n\n<p>Some of these paradigms give you maximum performance, but only work if the problem decomposes cleanly. Others sacrifice some performance, but allow a wider variety of algorithms. I suspect that some combination of the above will ultimately become a standard toolkit.</p>\n'}, {'answer_id': 84547, 'author': 'smo', 'author_id': 16080, 'author_profile': 'https://Stackoverflow.com/users/16080', 'pm_score': 2, 'selected': False, 'text': '<p>As mentioned, purely functional languages are inherently parallelizable. However, imperative languages are much more intuitive for many people, and we are deeply entrenched in imperative legacy code. The fundamental issue is that pure functional languages express side-effects explicitly, while side effects are expressed implicitly in imperative languages by the order of statements.</p>\n\n<p>I believe that techniques to declaratively express side effects (e.g., in an object oriented framework) will allow compilers to decompose imperative statements into their functional relationships. This should then allow the code to be automatically parallelized in much the same way pure functional code would be.</p>\n\n<p>Of course, just as today it is still desirable to write certain performance-critical code in assembly language, it will still be necessary to write performance-critical explicitly parallel code tomorrow. However, techniques such as I outlined should help automatically take advantage of manycore architectures with minimal effort expended by the developer.</p>\n'}, {'answer_id': 89155, 'author': 'Sam Hasler', 'author_id': 2541, 'author_profile': 'https://Stackoverflow.com/users/2541', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.kamaelia.org/Home" rel="nofollow noreferrer">kamaelia</a> is a <strong>python framework</strong> for building applications with lots of communicating processes.</p>\n<blockquote>\n<h1><img src="https://i.stack.imgur.com/I1E9Z.png" width="100" height="93"> Kamaelia - Concurrency made useful, fun</h1>\n<p>In Kamaelia you build systems from <strong>simple components that talk to each other</strong>. This speeds development, massively aids maintenance and also means you <strong>build naturally concurrent software</strong>. It\'s intended to be accessible by <strong>any</strong> developer, including novices. It also makes it fun :)</p>\n<p>What sort of systems? Network servers, clients, desktop applications, pygame based games, transcode systems and pipelines, digital TV systems, spam eradicators, teaching tools, and a fair amount more :)</p>\n</blockquote>\n<p>See also the Question <a href="https://stackoverflow.com/questions/121674/multi-core-and-concurrency-languages-libraries-and-development-techniques">Multi-Core and Concurrency - Languages, Libraries and Development Techniques</a></p>\n'}, {'answer_id': 229336, 'author': 'Sam Hasler', 'author_id': 2541, 'author_profile': 'https://Stackoverflow.com/users/2541', 'pm_score': 1, 'selected': False, 'text': '<p>See also the question <a href="https://stackoverflow.com/questions/121674/multi-core-and-concurrency-languages-libraries-and-development-techniques">Multi-Core and Concurrency - Languages, Libraries and Development Techniques</a></p>\n'}, {'answer_id': 229360, 'author': 'AlePani', 'author_id': 24276, 'author_profile': 'https://Stackoverflow.com/users/24276', 'pm_score': 0, 'selected': False, 'text': '<p>Erlang is the more "mature solution" and is portable and open source. I fiddled around with Polyphonic C# , I don\'t know how it would be to program everyday in it.</p>\n\n<p>There are libraries and extensions for almost every language/OS under the sun, google transactional memory . It\'s an interesting approach from MS.</p>\n'}, {'answer_id': 658601, 'author': 'Jed', 'author_id': 33208, 'author_profile': 'https://Stackoverflow.com/users/33208', 'pm_score': 2, 'selected': False, 'text': "<p>I'm surprised nobody has suggested MPI (Message Passing Interface). While designed for distributed memory, MPI programs with essential and frequent global coupling (solving linear and nonlinear equations with billions of unknowns) have been shown to scale to 200k cores.</p>\n"}, {'answer_id': 940345, 'author': 'Paul Morrison', 'author_id': 408718, 'author_profile': 'https://Stackoverflow.com/users/408718', 'pm_score': 2, 'selected': False, 'text': '<p>This question seems to keep appearing with different wording - maybe there are different constituencies within StackOverflow. <a href="http://www.jpaulmorrison.com/fbp/" rel="nofollow noreferrer"> Flow-Based Programming </a> (FBP) is a concept/methodology that has been around for over 30 years, and is being used to handle most of the batch processing at a major Canadian bank. It has thread-based implementations in Java and C#, although earlier implementations were fiber-based (C++, and mainframe Assembler - the one used at the bank). Most approaches to the problem of taking advantage of multicore involve trying to take a conventional single-threaded program and figure out which parts can run in parallel. FBP takes a different approach: the application is designed from the start in terms of multiple "black-box" components running asynchronously (think of a manufacturing assembly line). Since the interface between components is data streams, FBP is essentially language-independent, and therefore supports mixed-language applications, and domain-specific languages. For the same reason, side-effects are minimized. It could also be described as a "share nothing" model, and a MOM (message-oriented middleware). MapReduce seems to be a special case of FBP. FBP differs from Erlang mostly in that Erlang operates in terms of many short-lived threads, so green threads are more appropriate there, whereas FBP uses fewer (typically a few 10s to a few hundred) longer-lived threads. For a <em>piece</em> of a batch network that has been in daily use for over 30 years, see <a href="http://www.jpaulmorrison.com/fbp/image010.jpg" rel="nofollow noreferrer"> part of batch network</a>. For a high-level design of an interactive app, see <a href="http://www.jpaulmorrison.com/cgi-bin/wiki.pl?BrokerageApplication" rel="nofollow noreferrer"> Brokerage app high-level design</a>. FBP has been found to result in much more maintainable applications, and improved elapsed times - even on single core machines!</p>\n'}, {'answer_id': 940631, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 1, 'selected': False, 'text': "<p>A job-queue with multiple workers system (not sure of the correct terminology - message queue?)</p>\n\n<p>Why?</p>\n\n<p>Mainly, because it's an absurdly simple concept. You have a list of stuff that needs processing, then a bunch of processes that get jobs and process them.</p>\n\n<p>Also, unlike the reasons, say, Haskell or Erlang are so concurrent/parallelisable(?), it's entirely language-agnostic - you can trivially implement such a system in C, or Python, or any other language (even using shell scripting), whereas I doubt bash will get software transactional memory or join-calculus anytime soon.</p>\n"}, {'answer_id': 1344944, 'author': 'Ira Baxter', 'author_id': 120163, 'author_profile': 'https://Stackoverflow.com/users/120163', 'pm_score': 1, 'selected': False, 'text': '<p>We\'ve been using <a href="http://www.semanticdesigns.com/Products/PARLANSE" rel="nofollow noreferrer">PARLANSE</a>, a parallel programming langauge with explicit partial-order specification of concurrency for the last decade, to implement a scalable program analysis and transformation system (<a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow noreferrer">DMS Software Reengineering Toolkit</a>) that mostly does symbolic rather than numeric computation. PARLANSE is a compiled, C-like language with traditional scalar data types character, integer, float, dynamic data types string and array, compound data types structure and union, and lexically-scoped functions. While most of the language is vanilla (arithmetic expressions over operands, if-then-else statements, do loops, function calls), the parallelism is not. Parallelism is expressed by defining a "precedes" relation over blocks of code (e.g, a before b, a before c, d before c)\nwritten as</p>\n\n<pre><code>(|; a (... a\'s computation)\n (<< a) b ( ... b\'s computation ... )\n (<< a) c ( ....c\'s computation ...)\n (>> c) d ( ... d\'s computation...)\n)|;\n</code></pre>\n\n<p>where the << and >> operators refer to "order in time". The PARLANSE compiler can see these parallel computations and preallocate all the structures necessary for computation\ngrains a,b,c,d, and generate custom code to start/stop each one, thus minimizing the overhead to start and stop these parallel grains.</p>\n\n<p>See this link for <a href="https://stackoverflow.com/questions/1862599/multithreading-puzzles/1866161#1866161"> <em>parallel</em> iterative deepening search for optimals solutions to the 15-puzzle</a>, which is the 4x4 big-brother of the 8-puzzle. It only uses <em>potential</em> parallel as a parallelism construct <strong>(|| a b c d )</strong> which says there are no partial order constraints on the computations <em>a</em> <em>b</em> <em>c</em> <em>d</em>, but it also uses speculation and asynchronously aborts tasks that won\'t find solutions. Its a lot of ideas in a pretty small bit of code.</p>\n\n<p>PARLANSE runs on multicore PCs. A big PARLANSE program (we\'ve built many with 1 million+ lines or more) will have thousands of these partial orders, some of which call functions that contain others.\nSo far we\'ve had good results with up to 8 CPUs, and modest payoff with up to 16, and we\'re still tuning the system. (We think a real problem with larger numbers of cores on current PCs is memory bandwidth: 16 cores pounding a memory subsystem creates a huge bandwidth demand).</p>\n\n<p>Most other languages don\'t expose the parallelism so it is hard to find, and the runtime systems pay a high price for scheduling computation grains by using general-purpose scheduling primitives. We think that\'s a recipe for disaster or at least poor performance because of Amhdahl\'s law: if the number of machine instructions to schedule a grain is large compared to the work, you can\'t be efficient. OTOH, if you insist on computation grains with many machine instructions to keep the scheduling costs relatively low, you can\'t find computation grains that are independent and so you don\'t have any useful parallelism to schedule. So the key idea behind PARLANSE is to minimize the cost of scheduling grains, so that grains can be small, so that there can be many of them found in real code. The insight into this tradeoff came from the abject failure of the pure dataflow paradigm, that did everything in parallel with tiny parallel chunks (e.g., the add operator).</p>\n\n<p>We\'ve been working on this on and off for a decade. Its hard to get this right. I don\'t see how folks that haven\'t been building parallel langauges and using/tuning them for this time frame have any serious chance of building effective parallel systems. </p>\n'}, {'answer_id': 1344990, 'author': 'Steve Rowe', 'author_id': 40744, 'author_profile': 'https://Stackoverflow.com/users/40744', 'pm_score': 1, 'selected': False, 'text': '<p>I really like the model <a href="http://www.clojure.org" rel="nofollow noreferrer">Clojure</a> has chosen. Clojure uses a combination of immutable data structures and software transactional memory.</p>\n\n<p>Immutable data structures are ones that never change. New versions of the structures can be created with modified data, but if you have a "pointer" to a data structure, it will never change out from under you. This is good because you can access that data without worrying about concurrency problems.</p>\n\n<p>Software transactional memory is discussed elsewhere in these answers but suffice it to say that it is a mechanism whereby multiple threads can all act upon some data and if they collide, one of the threads is rolled back to try again. This allows for much faster speed when the risk of collision is present but unlikely.</p>\n\n<p>There is a <a href="http://clojure.blip.tv/file/812787" rel="nofollow noreferrer">video</a> from author Rich Hickey that goes into a lot more detail.</p>\n'}, {'answer_id': 1345078, 'author': 'SingleNegationElimination', 'author_id': 65696, 'author_profile': 'https://Stackoverflow.com/users/65696', 'pm_score': 1, 'selected': False, 'text': '<p>A worthwhile path might be <a href="http://en.wikipedia.org/wiki/OpenCL" rel="nofollow noreferrer">OpenCL</a>, which provides a means of distributing certain kinds of compute loads across heterogeneous compute resources, IE the same code will run on a multicore CPU and also commodity GPU\'s. ATI has recently released exactly such a <a href="http://ati.amd.com/technology/streamcomputing/opencl.html" rel="nofollow noreferrer">toolchain</a>. NVidia\'s <a href="http://www.nvidia.com/object/cuda_home.html" rel="nofollow noreferrer">CUDA</a> toolchain is similar, although somewhat more restricted. It also appears that Nvidia has an OpenCL sdk <a href="http://www.nvidia.com/object/cuda_opencl.html" rel="nofollow noreferrer">in the works</a></p>\n\n<p>It should be noted that this probably won\'t help much where the workloads are not of a data-parallel nature, for instance it won\'t help much with typical transaction processing. OpenCL is mainly oriented toward the kinds of computing that are math intensive, such as scientific/engineering simulation or financial modeling.</p>\n'}, {'answer_id': 2893087, 'author': 'J D', 'author_id': 13924, 'author_profile': 'https://Stackoverflow.com/users/13924', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n <p>If you were writing a new application from scratch today, and wanted it to scale to all the cores you could throw at it tomorrow, what parallel programming model/system/language/library would you choose?</p>\n</blockquote>\n\n<p>Perhaps the most widely applicable today is Cilk-style task queues (now available in .NET 4). They are great for problems that can be solved using divide and conquer with predictable complexity for subtasks (such as parallel <code>map</code> and <code>reduce</code> over arrays where the complexity of the function arguments is known as well as algorithms like quicksort) and that covers many real problems.</p>\n\n<p>Moreover, this only applies to shared-memory architectures like today's multicores. While I do not believe this basic architecture will disappear anytime soon I do believe it must be combined with distributed parallelism at some point. This will either be in the form of a cluster of multicores on a manycore CPU with message passing between multicores, or in the form of a hierarchy of cores with predictable communication times between them. These will require substantially different programming models to obtain maximum efficiency and I do not believe much is known about them.</p>\n"}, {'answer_id': 5943908, 'author': 'Aater Suleman', 'author_id': 745944, 'author_profile': 'https://Stackoverflow.com/users/745944', 'pm_score': 1, 'selected': False, 'text': '<p>There are three parts to parallel programming IMO: identify the parallelism and specify the parallelism. Identify=Breaking down the algorithm into concurrent chunks of work, specify=doing the actual coding/debugging. Identify is independent of which framework you will use to specify the parallelism and I don\'t think a framework can help there much. It comes with good understanding of your app, target platform, common parallel programming trade-offs (hardware latencies etc), and MOST importantly experience. Specify however can be discussed and this is what I try to answer below: </p>\n\n<p>I have tried many frameworks (at school and work). Since you asked about multicores, which are all shared memory, I will stick with three shared memory frameworks I have used. </p>\n\n<p>Pthreads (Its no really a framework, but definitely applicable):</p>\n\n<p>Pro: \n-Pthreads is extremely general. To me, pthreads are like the assembly of parallel programming. You can code any paradigm in pthreads. \n-Its flexible so you can make it as high performance as you want. There are no inherent limitations to slow you down. You can write your own constructs and primitives and get as much speed as possible.</p>\n\n<p>Con: \n-Requires you to do all the plumbing like managing work-queues, task distribution, yourself. \n-The actual syntax is ugly and your app often has a lot of extra code which makes code hard to write and then hard to read. </p>\n\n<p>OpenMP:</p>\n\n<p>Pros:\n-The code looks clean, plumbing and task-splitting is mostly down under the hood\n-Semi-flexible. It gives you several interesting options for work-scheduling </p>\n\n<p>Cons:\n-Meant for simple for-loop like parallelism. (The newer Intel verion does support tasks too but the tasks are the same as Cilk). \n-Underlying structures may or may not be well-written for performance. GNUs implementation is just ok. Intel\'s ICC worked better for me but I would rather write some stuff myself for higher performance. </p>\n\n<p>Cilk, Intel TBB, Apple GCD:</p>\n\n<p>Pros: \n-Provably optimal underlying algorithms for task-level parallelism \n-Decent control of serial/parallel tasks\n-TBB also has a pipeline parallelism framework which I used (it isn\'t the best to be frank)\n-Eliminates the task of writing a lot of code for task-based systems which can be a big plus if you are short-handed </p>\n\n<p>Cons: \n-Less control of underlying structures\' performance. I know the Intel TBB has very poorly-performing underlying data structures, e.g., the work queue was bad (in 2008 when I saw it). \n-The code looks awful sometimes with all the keywords and buzzwords they want you to use\n-Requires reading a lot of references to understand their "flexible" APIs</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/79999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171236/'] |
80,021 | <p>I recently started using Eclipse at work for my Java servlet projects. I've been using jEdit for years, which is a uber-powerful text editor. It has syntax highlighting, but it doesn't have any language-specific features like code completion and intelligent refactoring. I'm finding that's hindering my productivity. I <em>desperately</em> want to like Eclipse. I really do. But I keep running into problem after problem. </p>
<ol>
<li>Now that Eclipse can use an ant script to build, instead of just creating its own build environment from an ant script then ignoring any changes to it, I found some online guides and set it up. It doesn't seem ready for prime time, though. My ant script builds fine from the command line, but I get all these build errors because I need to tell Eclipse all this stuff the build.xml already has in it, like the CLASSPATH, and where external jars are.</li>
<li>When I leave Eclipse running for too long, or sometimes after my laptop wakes up from hibernate, the UI starts breaking. For instance, the tabs on the editor pane disappear, so I can only edit one file at a time, and it doesn't say which one it is.</li>
<li>We have faced several instances where classes weren't rebuilt that should have been, leading to inaccurate line numbers in debugging walkthroughs and other unpredictable behavior (this isn't just me; the two other developers trying it out with me are seeing the same thing).</li>
<li>I find it a huge hassle that the workspace is in a different place than my source code. I have other files I need to edit (xml files, etc), and for each directory I want to edit files in, I need to set up a special entry, and it doesn't even default to where my source code is when setting that up.</li>
</ol>
<p>Do others face these same issues?</p>
<p>Are there better alternatives? </p>
| [{'answer_id': 80041, 'author': 'sblundy', 'author_id': 4893, 'author_profile': 'https://Stackoverflow.com/users/4893', 'pm_score': 3, 'selected': False, 'text': '<p>I love <a href="http://www.intellij.com" rel="nofollow noreferrer">IntelliJ</a>, but it\'s commercial. Eclipse feels like a buggy, half-hearted knockoff compared to it. To the point that IntelliJ\'s worth the cost.</p>\n'}, {'answer_id': 80046, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 4, 'selected': True, 'text': '<p>Try <a href="http://www.netbeans.org/" rel="noreferrer">NetBeans</a></p>\n\n<blockquote>\n <p>A free, open-source Integrated\n Development Environment for software\n developers. You get all the tools you\n need to create professional desktop,\n enterprise, web, and mobile\n applications with the Java language,\n C/C++, and Ruby.</p>\n</blockquote>\n'}, {'answer_id': 80057, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 0, 'selected': False, 'text': "<p>Partial, hopefully helpful answer to</p>\n\n<blockquote>\n <p>4<code></code>. I find it a huge hassle that the workspace is in a different place than my source code. I have other files I need to edit (xml files, etc), and for each directory I want to edit files in, I need to set up a special entry, and it doesn't even default to where my source code is when setting that up.</p>\n</blockquote>\n\n<p>... you can configure the location of both your workspace and your source code, if you want.</p>\n"}, {'answer_id': 80063, 'author': 'kooshmoose', 'author_id': 7436, 'author_profile': 'https://Stackoverflow.com/users/7436', 'pm_score': 0, 'selected': False, 'text': "<p>Most of my time in Eclipse has been spent doing ColdFusion so I can't speak to ANT scripts or compilation. I too noticed that odd things would be more likely to happen if Eclipse was left running for an excessive amount of time. Aside from that, most other buggy-ness could be resolved by making sure that my JRE was the latest version.</p>\n"}, {'answer_id': 80282, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Eclipse can be quite a change, especially coming from something like just a text editor, or Visual Studio</p>\n\n<ol>\n<li><p>try to let Eclipse build the project itself, without the help of ant. Leave ant to a handwritten build.xml file to build the project from the command line outside of eclipse, e.g., on yer build/release machine.</p></li>\n<li><p>low on memory?</p></li>\n<li><p>are you going back and forth between building the project w/ant and then having Eclipse trying to build the project too? i.e., are the builds "fighting" with each other? see 1.</p></li>\n<li><p>yes, one of the things that you would need to get used to... accept, rather than fight, the "eclipse way"; you have to put your working source files somewhere, then why not in Eclipse\'s workspace folder?</p></li>\n</ol>\n\n<p>hope that helps/makes sense</p>\n'}, {'answer_id': 80549, 'author': 'Daniel Schneller', 'author_id': 1252368, 'author_profile': 'https://Stackoverflow.com/users/1252368', 'pm_score': 4, 'selected': False, 'text': '<p>Eclipse works best if you leave the project folder structure to its management. We are working with 15 developers on a project of several thousand classes and even more XML and .properties files.</p>\n\n<p>I agree there are problems with ANT integration, so for production and nightly builds I recommend an external build system based on ANT scripts started from a shell.</p>\n\n<p>However while working in Eclipse make sure you have the automatic build feature on (it should be by default, but checking does not hurt). This should free you from any concerns regarding what to build and when. Sometimes (very rarely for me) there are problems when I have to switch of the automatic build, clean all projects and trigger a manual build via the menu. From time to time I have to trigger the build multiple times (not the cleaning!), but once everything has been built again, turning the auto-build on works great again.</p>\n\n<p>As for long running instances: My machine keeps logged in basically all the time (day and night) and there are at least two Eclipse instances running at all times. I have not seen any problems with these sessions, even when they remain open for literally weeks.</p>\n\n<p>Most of the problems I have seen in the 5 years I have been using Eclipse originated from people installing too many plugins - the only stuff I have added is Checkstyle, the "implementors plugin" and some proprietary stuff for the application framework we are using.</p>\n\n<p>Maybe you can try using a rather clean Eclipse installation the "usual way" for a while (i. e. with the sources imported to the workspace folder).</p>\n\n<p>Regarding NetBeans: I use it from time to time as well, but I think it is a matter of taste and I like Eclipse better. This may be different for you.</p>\n'}, {'answer_id': 80607, 'author': 'Jeroen van Bergen', 'author_id': 15155, 'author_profile': 'https://Stackoverflow.com/users/15155', 'pm_score': 1, 'selected': False, 'text': "<p>Like some other people already have suggested: there are more good Java IDEs besides Eclipse. The strong point of Eclipse is the plug-in system. There's a wealth of functionality available and some of it is indeed very good. That said: I do not use Eclipse, but NetBeans at the moment. NetBeans feels less clunky, is more responsive and has a cleaner feel. </p>\n\n<p>When my main job was Java programming I've used IntelliJ a lot. IMHO IntelliJ beats both NetBeans and Eclipse as far as coding is concerned. It's faster, has better refactoring possibilities, better search, quick navigation and the list goes on.</p>\n\n<p>To a large extent, picking an IDE is a matter of taste, as well as experience. A lot of people feel more happy with the devil they know...</p>\n"}, {'answer_id': 82189, 'author': 'Nerdfest', 'author_id': 7855, 'author_profile': 'https://Stackoverflow.com/users/7855', 'pm_score': 0, 'selected': False, 'text': "<p>As someone else has mentioned, try NetBeans, It's similar to Eclipse in that it is a platform that supports an IDE, and is plug-in based. Its build system is also already based around Ant, allowing you to tap in at various extension points. In general, I've found it a bit more stable than Eclipse as well, but YMMV.</p>\n"}, {'answer_id': 82227, 'author': 'deterb', 'author_id': 15585, 'author_profile': 'https://Stackoverflow.com/users/15585', 'pm_score': 1, 'selected': False, 'text': "<p>For issue number 1, you can setup custom builders for eclipse. To do so, right click on the Project and select Properties. On the left there is a item called Builders, select that.</p>\n\n<p>Based off of what you are saying, you will want to remove the Java builder and replace it with a new Ant Builder. This can be done by clicking New and selecting Ant Builder. This will bring up a some configuration to fill out.</p>\n\n<p>In the configuration, the two most important parts are the Build File in the Main tab and the Targets tab.</p>\n\n<p>For issue 4, I would recommend having your project try to be independent of its location on disc. That way everything is in the same tree. Otherwise, the solution would be to setup external directories. From what it sounds like, not everything is in the same 'source tree', which brings up source control issues.</p>\n"}, {'answer_id': 86405, 'author': 'Scott Stanchfield', 'author_id': 12541, 'author_profile': 'https://Stackoverflow.com/users/12541', 'pm_score': 0, 'selected': False, 'text': '<p>We have eclipse manage things the way it wants, and use ant4eclipse (a set of ant tasks) for continuous builds. Works great!</p>\n'}, {'answer_id': 1570139, 'author': 'Eelco', 'author_id': 445367, 'author_profile': 'https://Stackoverflow.com/users/445367', 'pm_score': 0, 'selected': False, 'text': "<p>Eclipse is a great tool. Hardly ever had problems with it in the many years that I've used it. It always amazes me how so many people can have problems with it. Then again, I'm using it as a fairly basic editor. I'm either lucky or my lack of problems stems from the fact that I'm not expecting it to be much more than a smart editor.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14924/'] |
80,031 | <p>I have a asp:menu object which I set up to use a <em>SiteMapDataSource</em> but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the <code>web.sitemap</code>. Here's the code for the <em>sitemapdatasource</em> and the menu. The Web.sitemap file is sitting in the root directory of the website.</p>
<pre><code><div>
<asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1">
</asp:Menu>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" />
</div>
</code></pre>
<p>And this is the Web.sitemap looks like so:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
</code></pre>
<p>
</p>
| [{'answer_id': 80060, 'author': 'Encoder', 'author_id': 14629, 'author_profile': 'https://Stackoverflow.com/users/14629', 'pm_score': 3, 'selected': True, 'text': '<p>I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removing it and it worked.</p>\n\n<p>Try removing the path from the SiteMapDataSource and ensure that web.sitemap is in the root directory and see if that fixes it.</p>\n'}, {'answer_id': 80061, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': '<p>You need to specify in web.config to use XmlSiteMapProvider and provide it with correct path to .sitemap file.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4298/'] |
80,042 | <p>Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?</p>
| [{'answer_id': 80071, 'author': 'Dave Cheney', 'author_id': 6449, 'author_profile': 'https://Stackoverflow.com/users/6449', 'pm_score': 3, 'selected': True, 'text': '<p>Hows\' this ?</p>\n\n<pre>\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport java.net.InetSocketAddress;\n\n\npublic class Server {\n\n public static void main(String[] args) throws IOException {\n DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));\n byte[] message = new byte[512];\n DatagramPacket packet = new DatagramPacket(message, message.length);\n socket.receive(packet);\n System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));\n }\n}\n</pre>\n\n<pre>\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport java.net.InetSocketAddress;\n\n\npublic class Client {\n\n public static void main(String[] args) throws IOException {\n DatagramSocket socket = new DatagramSocket();\n socket.connect(new InetSocketAddress(5000));\n byte[] message = "Oh Hai!".getBytes();\n DatagramPacket packet = new DatagramPacket(message, message.length);\n socket.send(packet);\n }\n}\n</pre>\n'}, {'answer_id': 80139, 'author': 'Dave Cheney', 'author_id': 6449, 'author_profile': 'https://Stackoverflow.com/users/6449', 'pm_score': 0, 'selected': False, 'text': '<p>@none</p>\n\n<p>The DatagramSocket classes sure need a polish up, DatagramChannel is slightly better for clients, but confusing for server programming. For example:</p>\n\n<pre>\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\n\npublic class Client {\n\n public static void main(String[] args) throws IOException {\n DatagramChannel channel = DatagramChannel.open();\n ByteBuffer buffer = ByteBuffer.wrap("Oh Hai!".getBytes());\n channel.send(buffer, new InetSocketAddress("localhost", 5000));\n }\n}\n</pre>\n\n<p>Bring on <a href="http://jcp.org/en/jsr/detail?id=203" rel="nofollow noreferrer" title="JSR-203">JSR-203</a> I say</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,062 | <p>My friends and I are starting a game like Pokemon and we wanted to know how will we add monsters to the game? We're using VisualBasic because my friend's brother said it would be easier.</p>
<p>So far we can put pictures of the monsters on the screen and you can click to attack and stuff.</p>
<p>Right now when we want to add a monster we have to make a new window. This will take us a long time to make all the windows for each type of monster. Is there a tool or something to make this go faster? How do game companies do this?</p>
| [{'answer_id': 80096, 'author': 'Chris Bunch', 'author_id': 422, 'author_profile': 'https://Stackoverflow.com/users/422', 'pm_score': 1, 'selected': False, 'text': '<p>I\'d suggest making a list of all the attributes you would need for each monster and store all of that in a database like <a href="http://www.mysql.com/" rel="nofollow noreferrer">MySQL</a>. This way you don\'t need to make windows for each monster, only each time a monster appears (in which case you\'d just get the necessary info from the database).</p>\n\n<p>If you\'re not familiar with any database, check out the <a href="http://dev.mysql.com/doc/refman/5.0/en/tutorial.html" rel="nofollow noreferrer">MySQL tutorial</a> to get up and going.</p>\n'}, {'answer_id': 80097, 'author': 'dreamlax', 'author_id': 10320, 'author_profile': 'https://Stackoverflow.com/users/10320', 'pm_score': 0, 'selected': False, 'text': "<p>Once you have created your artwork, I would load it dynamically from the hard disk rather than compile it into one big EXE. You can use the PictureBox control's LoadPicture method.</p>\n"}, {'answer_id': 80100, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You need to learn about data, data structures and loops. Your monsters should consist of data, and maybe some code, then your monster display screen will display and operate a monster based upon this data and code.</p>\n\n<p>Copy and pasting widgets will not work out for you. Learn to abstract data and logic from widgets.</p>\n\n<p>Stop using VB right now and go play with <a href="http://scratch.mit.edu" rel="nofollow noreferrer">http://scratch.mit.edu</a> it is much more suitable.</p>\n'}, {'answer_id': 80102, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 0, 'selected': False, 'text': "<p>What do you mean by, 'when we want to add a monster'? Do you mean you have an individual window for each monster, which is shown when that monster appears? To build on what sit said; design, design, design. Ad Hoc design methods do not scale beyond the smallest of programs.</p>\n"}, {'answer_id': 80104, 'author': 'metao', 'author_id': 11484, 'author_profile': 'https://Stackoverflow.com/users/11484', 'pm_score': 3, 'selected': True, 'text': '<p>I think the best solution would be to make a generic window which can take a few parameters which describe the monster. </p>\n\n<p>Im not entirely up-to-date with VB, but in an OO language we would have a Monster base class, and inheritance to create a Pikachu. The base class would define basic things a monster has (like a picture and a name and a type) and things a monster could do (like attack, run away etc). You could even use a second level, and have base classes for each type (like ElectricMonster which inherits from Monster, and Pikachu inherits from ElectricMonster).</p>\n\n<p>It then becomes really easy to pass a Monster object to a window, and have the window know how to pull out all the relevant information.</p>\n'}, {'answer_id': 80252, 'author': 'user15039', 'author_id': 15039, 'author_profile': 'https://Stackoverflow.com/users/15039', 'pm_score': 0, 'selected': False, 'text': '<p>You have to have your monster data stored in files or a database and load them from a generic window. For example you have a picture of pikachu and one of bulbasaur stored in your hard disk. Then you make a window with a blank picture, when you show the window you tell the picture object to load the picture you need.</p>\n'}, {'answer_id': 111880, 'author': 'Beerly Able', 'author_id': 20044, 'author_profile': 'https://Stackoverflow.com/users/20044', 'pm_score': 1, 'selected': False, 'text': '<p>I think the biggest problem will be creating all the different angles (for when the characters turn, etc.). Can you develop 3d models of the characters based on different frames from the tv show / card game?</p>\n'}, {'answer_id': 150773, 'author': 'Rory Becker', 'author_id': 11356, 'author_profile': 'https://Stackoverflow.com/users/11356', 'pm_score': 1, 'selected': False, 'text': '<p>I would suggest that you should try extract the various attributes that a monster might possess. Think Top-Trumps...</p>\n\n<p>Then you can create a single Monster class with each attribute represented by a Property/Field.</p>\n\n<p>Something like </p>\n\n<pre><code>Class Monster\n Public Name as String \n Public Filename as String \' Location of graphics file on disk\n Public Strength as Integer \n Public Speed as Integer \n Public Sub New(Name as String, Filename as String, Strength as Integer, Speed as Integer)\n Me.Name = Name\n Me.Filename = Filename\n Me.Strength = Strength\n Me.Speed = Speed\n End Sub \nEnd Class\n</code></pre>\n\n<p>Then you\'ll be able to create monsters like this.</p>\n\n<pre><code>Dim Monster1 as New Monster("monster1", "C:\\Graphic1.jpg", 50, 10) \nDim Monster2 as New Monster("monster2", "C:\\Graphic2.jpg", 1, 100) \nDim Monster3 as New Monster("monster3", "C:\\Graphic3.jpg", 60, 17) \n</code></pre>\n\n<p>but you\'ve not needed to create a new "Window" each time.</p>\n\n<p>Equally you will be able to get you "Monster" data from elsewhere... like a database for example.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,067 | <p>Which is the best mocking library for C# 3.0/ ASP.NET MVC? Why?</p>
| [{'answer_id': 80070, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://github.com/Moq/moq4" rel="nofollow noreferrer">Moq</a></p>\n\n<p>It\'s amazing, fully supports the new language features of C# 3.0 and it\'s very easy to get going with. I would highly recommend it.</p>\n'}, {'answer_id': 80074, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 3, 'selected': False, 'text': '<p>Very subjective question. What do you mean by "best"? Maybe you should provide some more context on your situation.</p>\n\n<p><a href="http://www.ayende.com/projects/rhino-mocks.aspx" rel="noreferrer">RhinoMocks</a> is one of the most popular, as to whether it\'s the best for you, who knows?</p>\n'}, {'answer_id': 80076, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 0, 'selected': False, 'text': "<p>I'm going through that process now, weighing them up for use by my team, and I have to say Moq as well, it seems to have the least of a learning curve, and some nice features, I love the use of Moq generics to specify a Mock class</p>\n"}, {'answer_id': 80354, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 0, 'selected': False, 'text': '<p>there\'s also this other post about this topic:</p>\n\n<p><a href="https://stackoverflow.com/questions/10098/best-mock-framework-that-can-do-both-webforms-and-mvc">Best mock framework that can do both WebForms and MVC?</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11034/'] |
80,084 | <p>In JavaScript, the "this" operator can refer to different things under different scenarios. </p>
<p>Typically in a method within a JavaScript "object", it refers to the current object.</p>
<p>But when used as a callback, it becomes a reference to the calling object.</p>
<p>I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.</p>
<p>Can someone clarify usage and best practices regarding how to get around this problem?</p>
<pre><code> function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
</code></pre>
| [{'answer_id': 80095, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 0, 'selected': False, 'text': '<p>I believe this may be due to how the idea of [closures](<a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Closure_(computer_science)</a> work in Javascript.</p>\n\n<p>I am just getting to grips with closures myself. Have a read of the linked wikipedia article.</p>\n\n<p>Here\'s <a href="http://www.javascriptkit.com/javatutors/closures.shtml" rel="nofollow noreferrer">another article</a> with more information.</p>\n\n<p>Anyone out there able to confirm this?</p>\n'}, {'answer_id': 80119, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': "<p>As soon as callback methods are called from other context I'm usually using something that I'm call callback context:</p>\n\n<pre><code>var ctx = function CallbackContext()\n{\n_callbackSender\n...\n}\n\nfunction DoCallback(_sender, delegate, callbackFunc)\n{\n ctx = _callbackSender = _sender;\n delegate();\n}\n\nfunction TestObject()\n{\n test = function()\n {\n DoCallback(otherFunc, callbackHandler);\n }\n\n callbackHandler = function()\n{\n ctx._callbackSender;\n //or this = ctx._callbacjHandler;\n}\n}\n</code></pre>\n"}, {'answer_id': 80127, 'author': 'Ricky', 'author_id': 653, 'author_profile': 'https://Stackoverflow.com/users/653', 'pm_score': 5, 'selected': True, 'text': "<p>In JavaScript, <code>this</code> always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, <code>this</code> will refer to the node that fired the event. But if you have an object and call a function on it like:</p>\n\n<pre><code>myObject.myFunction();\n</code></pre>\n\n<p>Then <code>this</code> inside <code>myFunction</code> will refer to <code>myObject</code>. Does it make sense?</p>\n\n<p>To get around it you need to use closures. You can change your code as follows:</p>\n\n<pre><code>function TestObject() {\n TestObject.prototype.firstMethod = function(){\n this.callback();\n YAHOO.util.Connect.asyncRequest(method, uri, callBack);\n } \n\n var that = this;\n TestObject.prototype.callBack = function(o){\n that.secondMethod();\n }\n\n TestObject.prototype.secondMethod = function() {\n alert('test');\n }\n}\n</code></pre>\n"}, {'answer_id': 80159, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 2, 'selected': False, 'text': "<p><code>this</code> corresponds to the context for the function call. For functions not called as part of an object (no <code>.</code> operator), this is the global context (<code>window</code> in web pages). For functions called as object methods (via the . operator), it's the object.</p>\n\n<p>But, you can make it whatever you want. All functions have .call() and .apply() methods that can be used to invoke them with a custom context. So if i set up an object Chile like so:</p>\n\n<pre><code>var Chile = { name: 'booga', stuff: function() { console.log(this.name); } };\n</code></pre>\n\n<p>...and invoke Chile.stuff(), it'll produce the obvious result:</p>\n\n<pre><code>booga\n</code></pre>\n\n<p>But if i want, i can take and <em>really screw with it</em>:</p>\n\n<pre><code>Chile.stuff.apply({ name: 'supercalifragilistic' });\n</code></pre>\n\n<p>This is actually quite useful...</p>\n"}, {'answer_id': 80177, 'author': 'jeannicolas', 'author_id': 14981, 'author_profile': 'https://Stackoverflow.com/users/14981', 'pm_score': 0, 'selected': False, 'text': "<p>You can also use Function.Apply(<em>thisArg</em>, <em>argsArray</em>)... Where thisArg determines the value of <em>this</em> inside your function...the second parameter is an optional arguments array that you can also pass to your function. </p>\n\n<p>If you don't plan on using the second argument, don't pass anything to it. Internet Explorer will throw a TypeError at you if you pass <em>null</em> (or anything that is not an array) to function.apply()'s second argument...</p>\n\n<p>With the example code you gave it would look something like:</p>\n\n<pre><code>YAHOO.util.Connect.asyncRequest(method, uri, callBack.Apply(this));\n</code></pre>\n"}, {'answer_id': 80478, 'author': 'Alan Storm', 'author_id': 4668, 'author_profile': 'https://Stackoverflow.com/users/4668', 'pm_score': 6, 'selected': False, 'text': '<p>Quick advice on best practices before I babble on about the magic <em>this</em> variable. If you want Object-oriented programming (OOP) in Javascript that closely mirrors more traditional/classical inheritance patterns, pick a framework, learn its quirks, and don\'t try to get clever. If you want to get clever, learn javascript as a functional language, and avoid thinking about things like classes.</p>\n\n<p>Which brings up one of the most important things to keep in mind about Javascript, and to repeat to yourself when it doesn\'t make sense. Javascript does not have classes. If something looks like a class, it\'s a clever trick. Javascript has <strong>objects</strong> (no derisive quotes needed) and <strong>functions</strong>. (that\'s not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)</p>\n\n<p>The <em>this</em> variable is attached to functions. Whenever you invoke a function, <em>this</em> is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.</p>\n\n<p>There are four ways to invoke functions in javascript. You can invoke the function as a <em>method</em>, as a <em>function</em>, as a <em>constructor</em>, and with <em>apply</em>.</p>\n\n<h2>As a Method</h2>\n\n<p>A method is a function that\'s attached to an object</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function(){\n alert(this);\n}\n</code></pre>\n\n<p>When invoked as a method, <em>this</em> will be bound to the object the function/method is a part of. In this example, this will be bound to foo.</p>\n\n<h2>As A Function</h2>\n\n<p>If you have a stand alone function, the <em>this</em> variable will be bound to the "global" object, almost always the <em>window</em> object in the context of a browser.</p>\n\n<pre><code> var foo = function(){\n alert(this);\n }\n foo();\n</code></pre>\n\n<p><strong>This may be what\'s tripping you up</strong>, but don\'t feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that\'s why you\'re seeing what appears to be inconsistent behaviour.</p>\n\n<p>Many people get around the problem by doing something like, um, this</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function (){\n var that=this;\n function bar(){\n alert(that);\n }\n}\n</code></pre>\n\n<p>You define a variable <em>that</em> which points to <em>this</em>. Closure (a topic all it\'s own) keeps <code>that</code> around, so if you call bar as a callback, it still has a reference.</p>\n\n<h2>As a Constructor</h2>\n\n<p>You can also invoke a function as a constructor. Based on the naming convention you\'re using (<code>TestObject</code>) this also <strong>may be what you\'re doing and is what\'s tripping you up</strong>.</p>\n\n<p>You invoke a function as a Constructor with the <code>new</code> keyword.</p>\n\n<pre><code>function Foo(){\n this.confusing = \'hell yeah\';\n}\nvar myObject = new Foo();\n</code></pre>\n\n<p>When invoked as a constructor, a new Object will be created, and <em>this</em> will be bound to that object. Again, if you have inner functions and they\'re used as callbacks, you\'ll be invoking them as functions, and <em>this</em> will be bound to the global object. Use that <code>var that = this;</code> trick/pattern.</p>\n\n<p>Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes.</p>\n\n<h2>With the Apply Method.</h2>\n\n<p>Finally, every function has a method (yes, functions are objects in Javascript) named <code>apply</code>. Apply lets you determine what the value of <em>this</em> will be, and also lets you pass in an array of arguments. Here\'s a useless example.</p>\n\n<pre><code>function foo(a,b){\n alert(a);\n alert(b);\n alert(this);\n}\nvar args = [\'ah\',\'be\'];\nfoo.apply(\'omg\',args);\n</code></pre>\n'}, {'answer_id': 81646, 'author': 'ujh', 'author_id': 4936, 'author_profile': 'https://Stackoverflow.com/users/4936', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re using Prototype you can use <a href="http://www.prototypejs.org/api/function/bind" rel="nofollow noreferrer">bind()</a> and <a href="http://www.prototypejs.org/api/function/bindAsEventListener" rel="nofollow noreferrer">bindAsEventListener()</a> to get around that problem.</p>\n'}, {'answer_id': 83730, 'author': 'Chase Seibert', 'author_id': 7679, 'author_profile': 'https://Stackoverflow.com/users/7679', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using a javascript framework, there may be a handy method for dealing with this. In Prototype, for example, you can call a method and scope it to a particular "this" object:</p>\n\n<pre><code>var myObject = new TestObject();\nmyObject.firstMethod.bind(myObject);\n</code></pre>\n\n<p>Note: bind() returns a function, so you can also use it to pre-scope callbacks inside your class:</p>\n\n<pre><code>callBack.bind(this);\n</code></pre>\n\n<p><a href="http://www.prototypejs.org/api/function/bind" rel="nofollow noreferrer">http://www.prototypejs.org/api/function/bind</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,088 | <p>Desinging web application and for reporting iam using crystal reports.sometimes the crystal reports gives runtimes error. What can i do to make my report faster. Retrieving around 1MB of data. It is the month end sales report. what is the best method to solve this issue.</p>
| [{'answer_id': 80109, 'author': 'pro', 'author_id': 352728, 'author_profile': 'https://Stackoverflow.com/users/352728', 'pm_score': 0, 'selected': False, 'text': '<p>1Mb sounds like far too much data for a report -\nI would try to filter it down more on the server</p>\n'}, {'answer_id': 80145, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>You haven't noted what DB platform you are on, but if it's MSSQL based you may want to try using the embedded SQL Reporting Services Reporting. We found functionality wise it can't do everything crystal can, but it was easy to use, free, and didn`t have some of the annoying bugs that we had with crystal.</p>\n"}, {'answer_id': 80185, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I would be fascinated to hear exactly what you think CR can do that SSRS can\'t. Include only capabilities that cannot be trivially achieved by alternate strategies. Exclude "capabilities" that only work in carefully contrived vendor demos.</p>\n'}, {'answer_id': 80264, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I'm not that knowledgeable at CR, so this is tough for me (I'm a SSRS fan). So you're basically asking me to attack the thing I would normally recommend. Maybe a tough order but here goes.</p>\n\n<p>The feedback I've gotten from others (but who are much smarter than me :-) is that various formatting options/functions are better right now in crystal. One example that I've had to deal with myself in SSRS is manipulating dates - there are (i'm told) many more functions for manipulating dates in CR. Fixing this may be trivial for some, but not everybody and not me.</p>\n\n<p>What else - export to word is, I believe, available in CR, not in SSRS. Also, I believe combining dataset results is at least somewhat easier in CR. These might be better in the newly released 2008 version/</p>\n\n<p>Again, keep in mind this is based more on what I've been told when I complain occasionally about SSRS - I still really like it however.</p>\n"}, {'answer_id': 87526, 'author': 'jbcedge', 'author_id': 14752, 'author_profile': 'https://Stackoverflow.com/users/14752', 'pm_score': 0, 'selected': False, 'text': '<p>The reason why i used crystal report is because i had to print the report into LG Matrix printer that is basically i had to export the report in text format. I really dont know how it is possible to do in SSRS but i find it easier in crystal reports. That is the main reason i have to switch back to crystal. If anyone can suggest me the alternative option then i may try that for my application. I want to do client side reporting more than sever side. </p>\n'}, {'answer_id': 106132, 'author': 'Horcrux7', 'author_id': 12631, 'author_profile': 'https://Stackoverflow.com/users/12631', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <strong><a href="http://www.inetsoftware.de/products/crystal-clear" rel="nofollow noreferrer">i-net Clear Reports</a></strong> (used to be i-net Crystal-Clear). It can read Crystal Reports report files. That way, you do not need to redesign your reports. A report of 1 MB is not a problem. We have reports with 100MB and more. It has also a txt output format.</p>\n\n<p>Client-side reporting is also possible but of course this is a little more complicated.</p>\n'}, {'answer_id': 106167, 'author': 'WACM161', 'author_id': 12255, 'author_profile': 'https://Stackoverflow.com/users/12255', 'pm_score': 0, 'selected': False, 'text': '<p>First thing I would do is make sure your queries are running out side of your reporting tool correctly and quickly.\nI would also look at the indexes on your tables and tune the query, maybe create a view to contain the data or some of it to help speed up the process</p>\n'}, {'answer_id': 5285508, 'author': 'David Thielen', 'author_id': 509627, 'author_profile': 'https://Stackoverflow.com/users/509627', 'pm_score': 0, 'selected': False, 'text': '<p>You didn\'t provide any specifics but <a href="http://www.sql-reports.net/2011/02/how-to-turbo-charge-your-report-speed.html" rel="nofollow">How to Turbo Charge your Report Speed</a> has a number of general suggestions to improve your speed. (Disclaimer - I wrote the blog entry.)</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14752/'] |
80,091 | <p>How do I do a diff of two strings or arrays in Ruby?</p>
| [{'answer_id': 80111, 'author': 'Brian Mitchell', 'author_id': 13716, 'author_profile': 'https://Stackoverflow.com/users/13716', 'pm_score': 5, 'selected': True, 'text': '<p>diff.rb is what you want, which is available at <del><a href="http://users.cybercity.dk/~dsl8950/ruby/diff.html" rel="nofollow noreferrer">http://users.cybercity.dk/~dsl8950/ruby/diff.html</a></del> via internet archive: </p>\n\n<p><a href="http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html" rel="nofollow noreferrer">http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html</a></p>\n'}, {'answer_id': 80117, 'author': 'Chris Bunch', 'author_id': 422, 'author_profile': 'https://Stackoverflow.com/users/422', 'pm_score': 5, 'selected': False, 'text': "<p>For arrays, use the minus operator. For example:</p>\n\n<pre><code>>> foo = [1, 2, 3]\n=> [1, 2, 3]\n>> goo = [2, 3, 4]\n=> [2, 3, 4]\n>> foo - goo\n=> [1]\n</code></pre>\n\n<p>Here the last line removes everything from foo that is also in goo, leaving just the element 1. I don't know how to do this for two strings, but until somebody who knows posts about it, you could just convert each string to an array, use the minus operator, and then convert the result back.</p>\n"}, {'answer_id': 416136, 'author': 'da01', 'author_id': 52001, 'author_profile': 'https://Stackoverflow.com/users/52001', 'pm_score': 4, 'selected': False, 'text': '<p>For strings, I would first try out the Ruby Gem that @sam-saffron mentioned below. It\'s easier to install: \n<a href="http://github.com/pvande/differ/tree/master" rel="noreferrer">http://github.com/pvande/differ/tree/master</a></p>\n\n<pre><code>gem install differ\n\nirb\nrequire \'differ\'\n\none = "one two three"\ntwo = "one two 3"\n\nDiffer.format = :color\nputs Differ.diff_by_word(one, two).to_s\n\nDiffer.format = :html\nputs Differ.diff_by_word(one, two).to_s\n</code></pre>\n'}, {'answer_id': 419013, 'author': 'Grant Hutchins', 'author_id': 6304, 'author_profile': 'https://Stackoverflow.com/users/6304', 'pm_score': 3, 'selected': False, 'text': '<p>There is also <code>diff-lcs</code> which is available as a gem. <strike>It hasn\'t been updated since 2004 but</strike> we have been using it without any problem.</p>\n\n<p><strong>Edit:</strong> A new version was released in 2011. Looks like it\'s back in active development.</p>\n\n<p><a href="http://rubygems.org/gems/diff-lcs" rel="nofollow noreferrer">http://rubygems.org/gems/diff-lcs</a></p>\n'}, {'answer_id': 739161, 'author': 'Brian Armstrong', 'author_id': 76486, 'author_profile': 'https://Stackoverflow.com/users/76486', 'pm_score': 3, 'selected': False, 'text': "<p>The HTMLDiff that @da01 mentions above worked for me. </p>\n\n<pre><code>script/plugin install git://github.com/myobie/htmldiff.git\n\n# bottom of environment.rb\nrequire 'htmldiff'\n\n# in model\nclass Page < ActiveRecord::Base\n extend HTMLDiff\nend\n\n# in view\n<h1>Revisions for <%= @page.name %></h1>\n<ul>\n<% @page.revisions.each do |revision| %>\n <li>\n <b>Revised <%= distance_of_time_in_words_to_now revision.created_at %> ago</b><BR>\n <%= Page.diff(\n revision.changes['description'][0],\n revision.changes['description'][1]\n ) %>\n <BR><BR>\n </li>\n<% end %>\n\n# in style.css\nins.diffmod, ins.diffins { background: #d4fdd5; text-decoration: none; }\ndel.diffmod, del.diffdel { color: #ff9999; }\n</code></pre>\n\n<p>Looks pretty good. By the way I used this with the <code>acts_as_audited</code> plugin.</p>\n"}, {'answer_id': 1210782, 'author': 'Sam Saffron', 'author_id': 17174, 'author_profile': 'https://Stackoverflow.com/users/17174', 'pm_score': 2, 'selected': False, 'text': '<p>I just found a new project that seems pretty flexible: </p>\n\n<p><a href="http://github.com/pvande/differ/tree/master" rel="nofollow noreferrer">http://github.com/pvande/differ/tree/master</a> </p>\n\n<p>Trying it out and will try to post some sort of report. </p>\n'}, {'answer_id': 1511882, 'author': 'Daniel Cukier', 'author_id': 105514, 'author_profile': 'https://Stackoverflow.com/users/105514', 'pm_score': 2, 'selected': False, 'text': '<p>I had the same doubt and the solution I found is not 100% ruby, but is the best for me.\nThe problem with diff.rb is that it doesn\'t have a pretty formatter, to show the diffs in a humanized way. So I used diff from the OS with this code:</p>\n\n<pre><code> def diff str1, str2\n system "diff #{file_for str1} #{file_for str2}"\n end\n\n private\n def file_for text\n exp = Tempfile.new("bk", "/tmp").open\n exp.write(text)\n exp.close\n exp.path\n end\n</code></pre>\n'}, {'answer_id': 3146315, 'author': 'samg', 'author_id': 211136, 'author_profile': 'https://Stackoverflow.com/users/211136', 'pm_score': 5, 'selected': False, 'text': '<p>I got frustrated with the lack of a good library for this in ruby, so I wrote <a href="http://github.com/samg/diffy" rel="noreferrer">http://github.com/samg/diffy</a>. It uses <code>diff</code> under the covers, and focuses on being convenient, and providing pretty output options.</p>\n'}, {'answer_id': 6610781, 'author': 'grosser', 'author_id': 110333, 'author_profile': 'https://Stackoverflow.com/users/110333', 'pm_score': 1, 'selected': False, 'text': '<p>Maybe Array.diff via monkey-patch helps...</p>\n\n<p><a href="http://grosser.it/2011/07/07/ruby-array-diffother-difference-between-2-arrays/" rel="nofollow">http://grosser.it/2011/07/07/ruby-array-diffother-difference-between-2-arrays/</a></p>\n'}, {'answer_id': 9133162, 'author': 'russthegibbon', 'author_id': 1129925, 'author_profile': 'https://Stackoverflow.com/users/1129925', 'pm_score': 2, 'selected': False, 'text': "<p>Just for the benefit of Windows people: diffy looks brilliant but I belive it will only work on *nix (correct me if I'm wrong). Certainly it didn't work on my machine.</p>\n\n<p>Differ worked a treat for me (Windows 7 x64, Ruby 1.8.7).</p>\n"}, {'answer_id': 45572385, 'author': 'dimus', 'author_id': 23080, 'author_profile': 'https://Stackoverflow.com/users/23080', 'pm_score': 1, 'selected': False, 'text': '<p>To get character by character resolution I added a new function to <a href="https://rubygems.org/gems/damerau-levenshtein" rel="nofollow noreferrer">damerau-levenshtein gem</a></p>\n\n<pre><code>require "damerau-levenshtein"\ndiffer = DamerauLevenshtein::Differ.new\ndiffer.run "Something", "Smothing"\n# returns ["S<ins>o</ins>m<subst>e</subst>thing", \n# "S<del>o</del>m<subst>o</subst>thing"]\n</code></pre>\n\n<p>or with parsing:</p>\n\n<pre><code>require "damerau-levenshtein"\nrequire "nokogiri"\n\ndiffer = DamerauLevenshtein::Differ.new\nres = differ.run("Something", "Smothing!")\nnodes = Nokogiri::XML("<root>#{res.first}</root>")\n\nmarkup = nodes.root.children.map do |n|\n case n.name\n when "text"\n n.text\n when "del"\n "~~#{n.children.first.text}~~"\n when "ins"\n "*#{n.children.first.text}*"\n when "subst"\n "**#{n.children.first.text}**"\n end\nend.join("")\n\nputs markup\n</code></pre>\n'}, {'answer_id': 51544818, 'author': 'Steve', 'author_id': 6621187, 'author_profile': 'https://Stackoverflow.com/users/6621187', 'pm_score': 3, 'selected': False, 'text': "<pre><code>t=s2.chars; s1.chars.map{|c| c == t.shift ? c : '^'}.join\n</code></pre>\n\n<p>This simple line gives a <code>^</code> in the positions that don't match. That's often enough and it's copy/paste-able. </p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5004/'] |
80,101 | <p>I am currently programming a scheduling application which loosely based on iCalendar standard. Does anyone knows in which property can I store the event creator's information? By browsing through the iCalendar RFC 2445, I find this property: <a href="http://www.kanzaki.com/docs/ical/organizer.html" rel="nofollow noreferrer">Organizer</a>. can I store the event creator's information in the property even if he/she is the only person involved in the event? or there is already a field to store the event creator's information???!</p>
| [{'answer_id': 80124, 'author': 'Dave Cheney', 'author_id': 6449, 'author_profile': 'https://Stackoverflow.com/users/6449', 'pm_score': 3, 'selected': False, 'text': '<p><code>ORGANIZER;CN="Sally Example":mailto:[email protected]</code></p>\n\n<p>Looks like the answer</p>\n'}, {'answer_id': 99838, 'author': 'Jeffrey04', 'author_id': 5742, 'author_profile': 'https://Stackoverflow.com/users/5742', 'pm_score': 4, 'selected': True, 'text': "<p>Some notes from the rfc2445</p>\n\n<p>Conformance: This property MUST be specified in an iCalendar object\n that specifies a group scheduled calendar entity. This property MUST\n be specified in an iCalendar object that specifies the publication of\n a calendar user's busy time. This property <strong>MUST NOT be specified</strong> in\n an iCalendar object that specifies only a time zone definition or\n that <strong>defines calendar entities that are not group scheduled entities,\n but are entities only on a single user's calendar</strong>.</p>\n"}, {'answer_id': 15266752, 'author': 'simonpa71', 'author_id': 2006608, 'author_profile': 'https://Stackoverflow.com/users/2006608', 'pm_score': 1, 'selected': False, 'text': '<p>I am researching a similar application, concerned with event tracking and handling, and came to the same conclusions as Jeffrey04.</p>\n\n<p>Specifically, to represent warning or alarm, it would seem appropriate to use the VJOURNAL component, as the event is in the past, and maybe continues through the present, but is certainly not a meeting. VJOURNAL also does not occupy space on the calendar.\nIMHO the best field for representing the originator is <strong>X-WR-RELCALID</strong>, which is not RFC5545, but seems to fit the idea of a creator UID. I will link this to a vCard UID.</p>\n\n<p>I cannot understand why the idea of an event creator was unimportant for the writers of iCal specs. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5742/'] |
80,105 | <p>Java is one of my programming languages of choice. I always run into the problem though of distributing my application to end-users.</p>
<p>Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.</p>
<p>What's the best way to distribute a Java application? What if the Java application needs to install artifacts to the user's computer? Are there any good Java installation/packaging systems out there?</p>
| [{'answer_id': 80128, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 1, 'selected': False, 'text': "<p>For simple Java apps I like to use Jar's. It is very simple to distribute one file that a user can just click on (Windows), or</p>\n\n<pre><code>java -jar jarname.jar\n</code></pre>\n\n<p>IMHO, jar is the way to go when simplicity is a main requirement.</p>\n"}, {'answer_id': 80129, 'author': 'zurk', 'author_id': 14907, 'author_profile': 'https://Stackoverflow.com/users/14907', 'pm_score': 2, 'selected': False, 'text': '<p>executable files are best but they are platform limited i.e. use gcj : <a href="http://gcc.gnu.org/java/" rel="nofollow noreferrer">http://gcc.gnu.org/java/</a> for linux to produce executables and use launch4j : <a href="http://launch4j.sourceforge.net/" rel="nofollow noreferrer">http://launch4j.sourceforge.net/</a> to produce windows executables.\nTo package on linux you can use any rpm or deb packager. For win32 try <a href="http://en.wikipedia.org/wiki/Nullsoft_Scriptable_Install_System" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Nullsoft_Scriptable_Install_System</a> </p>\n'}, {'answer_id': 80147, 'author': 'qualidafial', 'author_id': 13253, 'author_profile': 'https://Stackoverflow.com/users/13253', 'pm_score': 0, 'selected': False, 'text': '<p>The best answer depends on the platform. For deployment on Windows, I have had good results using a combination of <a href="http://one-jar.sourceforge.net/" rel="nofollow noreferrer">one-jar</a> and <a href="http://launch4j.sourceforge.net/" rel="nofollow noreferrer">launch4j</a>. It did take a little while to set up my build environment properly (ant scripts, mostly) but now it\'s fairly painless.</p>\n'}, {'answer_id': 80157, 'author': 'Ry4an Brase', 'author_id': 8992, 'author_profile': 'https://Stackoverflow.com/users/8992', 'pm_score': 2, 'selected': False, 'text': "<p>If it's a real GUI-having end user application you should ignore the lanaguage in which you wrote the program (Java) and use a native installer for each of your chosen platforms. Mac folks want a .dmg and on windows a .msi or a .exe installer is the way to go. On Windows I prefer NSIS from NullSoft only because it's less objectionable than InstallShield or InstallAnywhere. On OSX you can count on the JVM already being there. On Windows you'll need to check and install it for them if necessary. Linux people won't run Java GUI applications, and the few that will, know what to do with an executable .jar.</p>\n"}, {'answer_id': 80521, 'author': 'Petr Macek', 'author_id': 15045, 'author_profile': 'https://Stackoverflow.com/users/15045', 'pm_score': 0, 'selected': False, 'text': '<p>Well from my point of view the superior distribution mechanism is to use something like <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a>, or <a href="http://en.wikipedia.org/wiki/Webstart" rel="nofollow noreferrer">WebStart</a> technology. You just deploy the version to the server and it gets automatically to the clients when the version is released. \nAlso the Eclipse RCP platform contains UpdateManager that does what WebStart do, but also much more.</p>\n\n<p>Since I am using Maven2 for building, the deployment is just a piece of cake: copy the built jar to the location on the server, update the jnlp file if needed and you are done.</p>\n'}, {'answer_id': 80595, 'author': 'rustyshelf', 'author_id': 6044, 'author_profile': 'https://Stackoverflow.com/users/6044', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.advancedinstaller.com/" rel="noreferrer">advanced installer</a> makes it easy to package java apps as windows executables, and it\'s quite flexible in the way you can set it up. I\'ve found that for distributing java applications to windows clients, this is the easiest way to go.</p>\n'}, {'answer_id': 80597, 'author': 'Noel Grandin', 'author_id': 6591, 'author_profile': 'https://Stackoverflow.com/users/6591', 'pm_score': 8, 'selected': True, 'text': '<p>There are a variety of solutions, depending on your distribution requirements.</p>\n\n<ol>\n<li><p>Just use a jar. This assumes that the user has the the correct java version installed, otherwise the user will get "class-file format version" exceptions. This is fine for internal distribution inside a company.</p></li>\n<li><p>Use launch4j and an installer like NSIS. This gives you a lot more control, although the user can still do stupid stuff like un-installing the java runtime. This is probably the most popular approach, and what I currently use.</p></li>\n<li><p>Use Webstart. This also assumes that the user has the correct java version installed, but it\'s a lot easier to get going. My experience is that this is fine for tightly controlled intranet environments, but becomes a pain with larger deployments because it has some many weird failures. It may get better with the new plug-in technology in Java 1.7.</p></li>\n<li><p>Use a native-code compiler like Excelsior JET and distribute as a executable, or wrap it up in an installer. Expensive, and it generally ties you to a slightly older version of java, and there is some pain with dynamic class-loading, but its very effective for large-scale deployment where you need to minimise your support hassles.</p></li>\n</ol>\n'}, {'answer_id': 80910, 'author': 'Mario Ortegón', 'author_id': 2309, 'author_profile': 'https://Stackoverflow.com/users/2309', 'pm_score': 1, 'selected': False, 'text': "<p>I develop eclipse RCP applications. Normally to start an eclipse application an executable launcher is included. I include the java virtual machine inside the application folder in a /jre sub directory to ensure that the right java version will be used.</p>\n\n<p>Then we package with Inno Setup for installation on the user's machine.</p>\n"}, {'answer_id': 81010, 'author': 'Rejeev Divakaran', 'author_id': 10980, 'author_profile': 'https://Stackoverflow.com/users/10980', 'pm_score': -1, 'selected': False, 'text': '<p>I would zip the jar file along with other dependent jars, configuration files and documentation along with a run.bat/run.sh. End user should be able unzip it to any location and edit the run.bat if required (It should run without editing in most of the cases).\nAn installer may be useful if you want to create entries in start menu, desktop, system tray etc.</p>\n\n<p>As a user I prefer unzip and run kind of installation (no start menu entries please). However People outside IT industry may have different preferences. So if the application is largely targeted for developers zip-run.bat route and applications for general public may be installed using a installer.</p>\n'}, {'answer_id': 101628, 'author': 'coobird', 'author_id': 17172, 'author_profile': 'https://Stackoverflow.com/users/17172', 'pm_score': 2, 'selected': False, 'text': '<p>Although I haven\'t used <a href="http://nsis.sourceforge.net/" rel="nofollow noreferrer" title="NSIS">NSIS</a> (Nullsoft Scriptable Installer System) myself, there are install scripts that will check whether or not the required JRE is installed on the target system.</p>\n\n<p>Many sample scripts are available from the <a href="http://nsis.sourceforge.net/Category:Code_Examples" rel="nofollow noreferrer" title="Code Examples">Code Examples</a> and <a href="http://nsis.sourceforge.net/Category:Real_World_Installers" rel="nofollow noreferrer" title="Real World Installers">Real World Installers</a> pages, such as:</p>\n\n<ul>\n<li><a href="http://nsis.sourceforge.net/Java_Launcher_with_automatic_JRE_installation" rel="nofollow noreferrer" title="Java Launcher with automatic JRE installation">Java Launcher with automatic JRE installation</a></li>\n<li><a href="http://nsis.sourceforge.net/Simple_Java_Runtime_Download_Script" rel="nofollow noreferrer" title="Simple Java Runtime Download Script">Simple Java Runtime Download Script</a></li>\n</ul>\n\n<p>(Please note that I haven\'t actually used any of the scripts, so please don\'t take it as an endorsement.)</p>\n'}, {'answer_id': 111942, 'author': 'stian', 'author_id': 17542, 'author_profile': 'https://Stackoverflow.com/users/17542', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://jsmooth.sourceforge.net/" rel="noreferrer">JSmooth</a> is a simple program that takes your jar and wraps it up in a standard windows executable file. It comes with a simple GUI that allows you to configure the required JVM, bundle it with the application or provide an option to download it if it\'s not already installed. You can send the exe file as is or zip it with possible dependencies (or let the program download the extra dependencies from the net on startup). It\'s also free, as in beer and speech, which may (or may not) be a good thing.</p>\n'}, {'answer_id': 126935, 'author': 'Tom', 'author_id': 20979, 'author_profile': 'https://Stackoverflow.com/users/20979', 'pm_score': 0, 'selected': False, 'text': '<p>installanywhere is good but expensive one - i have not found (as) good free one</p>\n'}, {'answer_id': 142140, 'author': 'David Carlson', 'author_id': 4901, 'author_profile': 'https://Stackoverflow.com/users/4901', 'pm_score': 2, 'selected': False, 'text': '<p>I needed a way to package my project and its dependencies into a single jar file.</p>\n\n<p>I found what I needed using the Maven2 Assembly plugin: <a href="http://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html#jar-with-dependencies" rel="nofollow noreferrer">Maven2 Assembly plugin</a></p>\n\n<p>This appears to duplicate the functionality of <a href="http://one-jar.sourceforge.net/" rel="nofollow noreferrer">one-jar</a>, but requires no additional configuration to get it going.</p>\n'}, {'answer_id': 455034, 'author': 'Daniel Lopez', 'author_id': 56395, 'author_profile': 'https://Stackoverflow.com/users/56395', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on how sophisticated your target users are. In most cases you want to isolate them from the fact that you are running a Java-based app. Give them with a native installer that does the right thing (create start menu entries, launchers, register with add/remove programs, etc.) and already bundles a Java runtime (so the user does not need to know or care about it). I would like to suggest our cross platform installation tool, <a href="http://bitrock.com" rel="nofollow noreferrer">BitRock InstallBuilder</a>. Although it is not Java-based, it is commonly used to package Java applications. It can be easily integrated with Ant and you can build Windows installers from Unix/Linux/Mac and the other way around. Because the generated installers are native, they do not require a self-extraction step or a JRE to be already present in the target system, which means smaller installers and saves you some headaches. I also would like to mention we have free licenses for open source projects</p>\n'}, {'answer_id': 844999, 'author': 'Jonik', 'author_id': 56285, 'author_profile': 'https://Stackoverflow.com/users/56285', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n <p>What\'s the best way to distribute a\n Java application? What if the Java\n application needs to install artifacts\n to the user\'s computer? Are there any\n good Java installation/packaging\n systems out there?</p>\n</blockquote>\n\n<p>In my experience (from <a href="https://stackoverflow.com/questions/759855/what-are-good-installanywhere-replacements-for-installing-a-java-ee-application/786307#786307">evaluating a number of options</a>), <a href="http://www.ej-technologies.com/products/install4j/overview.html" rel="nofollow noreferrer">install4j</a> is a good solution. It creates native installers for any platform, and is specifically geared towards installing Java apps. For details, see "<a href="http://www.ej-technologies.com/products/install4j/features.html" rel="nofollow noreferrer">Features</a>" on its website.</p>\n\n<p>install4j is a commercial tool, though. Especially if your needs are relatively simple (just distribute an application and install some artifacts), many other good options exist, including free ones (like <a href="http://izpack.org/" rel="nofollow noreferrer">izPack</a> or the already mentioned <a href="http://launch4j.sourceforge.net/" rel="nofollow noreferrer">Lauch4j</a>). But you asked for the <em>best</em> way, and to my current knowledge install4j is the one, especially for distributing larger or more complicated Java (EE) apps.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14204/'] |
80,112 | <p>I've never really understand why a web service implementer would choose one over the other. Is XML-RPC generally found in older systems? Any help in understanding this would be greatly appreciated.</p>
| [{'answer_id': 80136, 'author': 'Dexter', 'author_id': 10717, 'author_profile': 'https://Stackoverflow.com/users/10717', 'pm_score': 3, 'selected': False, 'text': '<p>Kate Rhodes has a great essay on the differences at <a href="http://weblog.masukomi.org/2006/11/21/xml-rpc-vs-soap" rel="noreferrer">http://weblog.masukomi.org/2006/11/21/xml-rpc-vs-soap</a></p>\n'}, {'answer_id': 80156, 'author': 'bmdhacks', 'author_id': 14032, 'author_profile': 'https://Stackoverflow.com/users/14032', 'pm_score': 4, 'selected': False, 'text': '<p>Just to add to the other answers, I would encourage you to look at actual textual representations of SOAP and XML-RPC calls, perhaps by capturing one with Ethereal. The whole, "XML-RPC is simpler" argument doesn\'t make much sense until you see how incredibly verbose a SOAP call is. Many of the fairly popular web sites out there shy away from SOAP as their API due to just the amount of bandwidth it would consume if people started using it extensively.</p>\n'}, {'answer_id': 88893, 'author': 'Christopher Mahan', 'author_id': 479, 'author_profile': 'https://Stackoverflow.com/users/479', 'pm_score': 8, 'selected': True, 'text': "<p>Differences?</p>\n\n<p>SOAP is more powerful, and is much preferred by software tool vendors (MSFT .NET, Java Enterprise edition, that sort of things).</p>\n\n<p>SOAP was for a long time (2001-2007ish) seen as the protocol of choice for SOA. xml-rpc not so much. REST is the new SOA darling, although it's not a protocol.</p>\n\n<p>SOAP is more verbose, but more capable. </p>\n\n<p>SOAP is not supported in some of the older stuff. For example, no SOAP libs for classic ASP (that I could find).</p>\n\n<p>SOAP is not well supported in python. XML-RPC has great support in python, in the standard library.</p>\n\n<p>SOAP supports document-level transfer, whereas xml-rpc is more about values transfer, although it can transfer structures such as structs, lists, etc. </p>\n\n<p>xm-rpc is really about program to program language agnostic transfer. It primarily goes over http/https. SOAP messages can go over email as well.</p>\n\n<p>xml-rpc is more unixy. It lets you do things simply, and when you know what you're doing, it's very fast to deploy quality web services, even when using terminal text editors. Doing SOAP that way is a zoo; you really need a good IDE to make it feasible.</p>\n\n<p>Knowing SOAP, though, will look much better on your resume/CV if you're vying for a Fortune 500 IT job.</p>\n\n<p>xml-rpc has some issues with non-ascii character sets. </p>\n\n<p>XML-RPC does not support named parameters. They must be in correct order. Not sure about SOAP, but think so.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4916/'] |
80,120 | <p>Our team is setting up nightly and continuous integration builds. We own Team Foundation Server and could use Team Foundation Build. I'm more familiar with CC.Net and lean that way but management sees all the money spent on TFS and wants to use it.</p>
<p>Some things I like better about CC.Net is the flexibility of notifications as well as the ease of implementing custom scripts.</p>
<p>If you have experience with both products, which do you prefer and why?</p>
| [{'answer_id': 80192, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 2, 'selected': False, 'text': '<p>We\'ve been using CruiseControl.net since June \'07 and it\'s worked great for us. Best part, it integrates to SVN easily which is a far superior source control provider.</p>\n\n<p>So our setup is:</p>\n\n<ul>\n<li><a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">Cruise Control.Net</a></li>\n<li><a href="http://subversion.tigris.org/" rel="nofollow noreferrer">SVN</a></li>\n<li><a href="http://trac.edgewall.org/" rel="nofollow noreferrer">Trac</a> - for bug reports and project management (integrates perfectly with SVN)</li>\n<li>nunit - for unit testing</li>\n</ul>\n\n<p>We\'ve had some major parallel development going and the branching and merging experience was spectacular. If you have the choice I\'d go with the setup above!</p>\n'}, {'answer_id': 80223, 'author': 'Nick Monkman', 'author_id': 14391, 'author_profile': 'https://Stackoverflow.com/users/14391', 'pm_score': 6, 'selected': True, 'text': "<p>I've used both. I guess it depends on what your organization values.</p>\n\n<p>Since you are familiar with CC Net, I won't speak much to that. You already know what makes it cool.</p>\n\n<p><strong>Here's what I like about Team Foundation Build:</strong></p>\n\n<ul>\n<li>Build Agents. It's very simple to turn any box into a build machine and run a build on it. MSFT got this one right.</li>\n<li>Reporting. All relevant build results (test included) are stored in a SQL database and reported on via SQL Server Reporting Services. This is an immensely powerful tool for charting build and test results over time. CC Net doesn't have this built in.</li>\n<li>You can do similar customizations via MSBUILD. It's basically the same as using NAnt with CC Net</li>\n</ul>\n\n<p><strong>Here's what drives me up the wall about Team Foundation Build:</strong></p>\n\n<ul>\n<li>To build C++/CLI projects (or run unit tests...?) the build agent must have VSTS Dev or Team Suite installed. This, friends, is just batsh*t crazy.</li>\n<li>It must be connected to the TFS Mothership</li>\n</ul>\n\n<p>If you're in a big org with lots of bosses who have huge budgets and love reports (and don't get me wrong, this has huge value) OR you need to scale up to a multi-machine build farm, I'd prefer Team Foundation Build. </p>\n\n<p>If you're a leaner shop, stick with CC Net and grow your own reporting solutions. That's what we did.</p>\n\n<p>Until we got acquired. And got TFS :P</p>\n"}, {'answer_id': 80516, 'author': 'Martin Woodward', 'author_id': 6438, 'author_profile': 'https://Stackoverflow.com/users/6438', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m assuming that as you own TFS you\'ll be using it for version control. In that case I would lean towards Team Foundation Build. That said, I pretty much agree with <a href="https://stackoverflow.com/questions/80120/cruise-control-net-vs-team-foundation-build#80223">Nick</a>.</p>\n\n<p>I wrote the <a href="http://www.codeplex.com/TFSCCNetPlugin/" rel="nofollow noreferrer">CruiseControl.NET integration for TFS</a>. It works fine and gives you the same build capabilities that you are used to. To me, CC.NET\'s main advantage is that it is completely extensible and has integrations with all the major SCM and build systems under the sun. The main reason I wrote the CC.NET integration to TFS it is that in TFS2005 the build system did not have out-the-box CI support. However the TFS2008 version is much improved and the team continue to very actively improve it for future releases of TFS.</p>\n\n<p>The main reason for switching to TFS Build would be so that it automatically reports the build information back into TFS which helps complete the software development picture in terms of reporting. It also integrates nicely with the work item tracking side of TFS and inside the IDE (both in Visual Studio and Eclipse).</p>\n\n<p>That said, if you have large investments in Nant scripts that do more than just compile and test your code or you already have a home-brewed reporting solution you might want to stick with what you have.</p>\n'}, {'answer_id': 80765, 'author': 'granth', 'author_id': 11210, 'author_profile': 'https://Stackoverflow.com/users/11210', 'pm_score': 3, 'selected': False, 'text': '<p>The real value in Team Foundation Build is that it associates changesets and work items with builds.</p>\n\n<p>This enables a couple of useful scenarios:</p>\n\n<ul>\n<li>You can look at a work item and find out what build it is included in</li>\n<li>You can look at a build and see which code changes (and work items) it includes</li>\n</ul>\n\n<p>Then of course there\'s the reports built on top of this information. But even these links by themselves are useful to non-management types.</p>\n\n<p>Have a look at www.tfsbuild.com for "recipes" on different Team Build configurations.</p>\n'}, {'answer_id': 799059, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>SVN is an OK tool far superior is not true, SVN vs. TFS is similar to a Ford pickup vs a Mercedes 500, it gets the job done but it isnt pretty nor is it comfortable, the merging has a lot to be desired. I prefer the TFS merging tool as it seems like the branching dev is right there working with you, that is how smart it is. Our internal SVN seemed to get corrupted a lot, this is the reason we ditched it and went to TFS and have not looked back. The shelving of changesets is wonderful for an agile development shop, currently have 270+ engineers on TFS with no issues or problems, SVN simply was not capable of handling that kind of load without someone having issues.</p>\n\n<p>I prefer CC.NET simply because of tools we have developed in house to extend the functionality in reporting and administration. TFS build is very closely integrated however and we anticipate a switch when we upgrade to SQL 2008</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1321/'] |
80,141 | <p>What algorithms and processes are involved in storing revision changes like stackoverflow and wikipedia do?</p>
<p>Is only one copy of the message kept? And if so is it only the latest copy? Then only changes to go back to the previous version(s) are stored from there? (This would make for a faster display of the main message).
Or are complete messages stored? And if so is the compare done between these on each display?</p>
<p>What algorithms are best used to determine the exact changes in the message? How is this data stored in a database?</p>
<p>If anyone knows exactly what wikipedia or stackoverlfow does I'd love to know.</p>
| [{'answer_id': 80151, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 1, 'selected': False, 'text': '<p>Usually messages are stored as complete snapshots. Previous versions are disabled, and the most recent is displayed. There may be optimizations used like caching which version is the most recent.</p>\n'}, {'answer_id': 80179, 'author': 'Thomas', 'author_id': 14637, 'author_profile': 'https://Stackoverflow.com/users/14637', 'pm_score': 2, 'selected': True, 'text': '<p>The <a href="http://en.wikipedia.org/wiki/Diff#Algorithm" rel="nofollow noreferrer">longest common substring algorithm</a> can be used to detect differences between versions, but it is limited. For example, it does not detect the moving around of text as such, but it would see this as unrelated removals and insertions.</p>\n\n<p>I suppose that websites normally store the latest copy in full, and apply reverse diffs from there. This is also the way <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a> works, but <a href="http://en.wikipedia.org/wiki/Subversion_(software)" rel="nofollow noreferrer">Subversion</a> uses forward diffs, which results in slower checkouts.</p>\n\n<p>To store this in a database, one could maintain a main table with the latest versions, and have a separate table with the reverse differences. This table would have rows in the format <code>(article_id, revision_id, differences)</code>.</p>\n'}, {'answer_id': 80196, 'author': 'mattlant', 'author_id': 14642, 'author_profile': 'https://Stackoverflow.com/users/14642', 'pm_score': 0, 'selected': False, 'text': '<p>Typical revision changes are stored using a delta algorithm, so the only data stored are the changes in each revision in relation to the original. I am unsure of wikipedia or stackoverflow how they have it implemented.</p>\n'}, {'answer_id': 80849, 'author': 'Davy Landman', 'author_id': 11098, 'author_profile': 'https://Stackoverflow.com/users/11098', 'pm_score': 0, 'selected': False, 'text': '<p>I would use the following technique:</p>\n\n<ul>\n<li>Store the current message as complete text. </li>\n<li>Store the history using the delta algorithm.</li>\n</ul>\n\n<p>This will keep your performance good with regular display, while keeping the storage to a minimum for the history.</p>\n'}, {'answer_id': 81844, 'author': 'Erik Johansson', 'author_id': 15307, 'author_profile': 'https://Stackoverflow.com/users/15307', 'pm_score': 2, 'selected': False, 'text': '<p>Mediawiki (the sotware for wikipedia) stores full text for all revision see the <a href="http://www.mediawiki.org/wiki/Image:Mediawiki-database-schema.png" rel="nofollow noreferrer">database schema</a>. Each entry in the <a href="http://www.mediawiki.org/wiki/Text_table" rel="nofollow noreferrer">text table</a> in Mediawiki has flags that tells if the content has been e.g. gziped, using a standard compression is often the sanest option.</p>\n\n<p>I can\'t tell you how to do the diffs algorithmically, but what ever algorithm you use you should do it from two full versions of the text. That is fetch the complete version of old and new object from database then do the diff. This makes it possible to easily change the diffing algorithm. </p>\n\n<p><a href="http://git.or.cz/" rel="nofollow noreferrer">Git</a> is a great example of a Unix application that can do very cheap (storage and speedwise) delta storage. There are wikis that can use git e.g. <a href="http://ikiwiki.info/" rel="nofollow noreferrer">ikiwiki</a>, but I\'m guessing you want to do it with a database.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3153/'] |
80,152 | <p>What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?</p>
<p>Query 1:</p>
<pre><code>SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
</code></pre>
<p>Query 2:</p>
<pre><code>SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
</code></pre>
| [{'answer_id': 80169, 'author': 'Encoder', 'author_id': 14629, 'author_profile': 'https://Stackoverflow.com/users/14629', 'pm_score': -1, 'selected': False, 'text': "<p>I agree, it's sounding a bit too much like Homework!</p>\n\n<p>If it isn't homework then I guess the simplest answer is readability.</p>\n\n<p>As stated before, both queries will produce the same execution plan. If this is the case then the only thing you need to worry about it maintainability.</p>\n"}, {'answer_id': 80172, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': '<p>Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those.</p>\n'}, {'answer_id': 80180, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Nope. I'm just sharing a large, overwhelmed database with some coworkers and am trying to come up with some ways to get more processor bang for our buck. I've been looking around online but haven't found a good explanation for some questions like this.</p>\n\n<p>Sorry for sounding homework-y. I guess I spent too many years as a TA.</p>\n"}, {'answer_id': 80219, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Actually, I think query 2's more readable. Think about when you get to say 5,6, or 7 tables when you hit the where clause in query one. Following the joins could get messy.</p>\n\n<p>As for performance, I have no idea. I bet if you go to the MySQL website, there would be info there - probably examples of joins.</p>\n\n<p>Professionally, I've only worked on one project. But it was a big one, and they always followed query 2's format. This was using Microsoft SQL Server though.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,175 | <p>This is somewhat similar to <a href="https://stackoverflow.com/questions/25653/hide-a-column-in-aspnet-dynamic-data">this question</a>.</p>
<p>However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.</p>
<p>My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.</p>
<p>I would like to replicate this behaviour for other (shorter) columns.</p>
<p>Is this possible?</p>
| [{'answer_id': 81806, 'author': 'Mark Pattison', 'author_id': 15519, 'author_profile': 'https://Stackoverflow.com/users/15519', 'pm_score': 4, 'selected': True, 'text': '<p>You can create a custom page for the particular table you want to change. There\'s an example <a href="http://davidhayden.com/blog/dave/archive/2007/12/30/ASPNETDynamicDataWebsitesCustomizingPagesValidation.aspx" rel="nofollow noreferrer">here</a>.</p>\n\n<p>Within your custom page, you can then set <code>AutoGenerateColumns="false"</code> within the <code>asp:GridView</code> control, and then define exactly the columns you want, like this:</p>\n\n<pre><code><Columns>\n ...\n <asp:DynamicField DataField="Product" HeaderText="Product" />\n <asp:DynamicField DataField="Colour" HeaderText="Colour" />\n</Columns>\n</code></pre>\n'}, {'answer_id': 2527099, 'author': 'Irwin', 'author_id': 27483, 'author_profile': 'https://Stackoverflow.com/users/27483', 'pm_score': 2, 'selected': False, 'text': '<p>I think this solution is a really useful one, because it allow you to use the attribute model to specify which columns go where:\n<a href="http://csharpbits.notaclue.net/2008/10/dynamic-data-hiding-columns-in-selected.html" rel="nofollow noreferrer">http://csharpbits.notaclue.net/2008/10/dynamic-data-hiding-columns-in-selected.html</a></p>\n'}, {'answer_id': 33539874, 'author': 'iamtonyzhou', 'author_id': 1027127, 'author_profile': 'https://Stackoverflow.com/users/1027127', 'pm_score': 0, 'selected': False, 'text': '<p>if u r using bootstrap u can set like this</p>\n\n<pre><code><asp:DynamicField DataField="Id" ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden" FooterStyle-CssClass="hidden"/>\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364/'] |
80,182 | <p>I get the concept of creating a business object or entity to represent something like a Person. I can then serialize the Person using a DTO and send it down to the client. If the client changes the object, it can have an IsDirty flag on there so when it gets sent back to the server I know to update it.</p>
<p>But what if I have an Order object? This has the main header informaton, customer, supplier, required date, etc. Then it has OrderItems which is a List< OrderItem>, being the items to be ordered. I want to be able to use this business object on my UI. So I have some textboxes hooked up to the location, supplier, required date, etc and a grid hooked up to OrderItems. Since OrderItems is a List I can easily add and delete records to it. But how do I track this, especially the deleted items. I don't want the deleted items to be visible in my grid and I shouldn't be able to iterate over them if I used foreach, because they have been deleted. But I still need to track the fact there was a deletion. How do I track the changes. I think I need to use a unit of work? But then the code seems to become quite complex. So then I wonder why not simply use DataTables and get the change tracking for free? But then I read how business objects are the way to go.</p>
<p>I’ve found various examples on simple Person examples, bnut not header-detail examples like Orders.</p>
<p>BTW using C# 3.5 for this.</p>
| [{'answer_id': 80266, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': -1, 'selected': False, 'text': '<p>The data objects don\'t track changes. The change tracking occurs on the DataContext and objects that you\'ve retrieved through the DataContext. So in order to track changes you need to do the following:</p>\n\n<pre><code>public class FooDataContext : DataContext\n{\n public Table<Order> Orders; \n}\n\npublic class Order\n{\n [DbColumn(Identity = true)]\n [Column(DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]\n public int Id { get; set; }\n\n [DbColumn(Default = "(getutcdate())")]\n [Column(DbType = "DateTime", CanBeNull = false, IsDbGenerated = true)]\n public DateTime DateCreated { get; set; }\n\n [Column(DbType = "varchar(50)", CanBeNull = false, IsDbGenerated = false)]\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>Now in your codebehind you can do something like:</p>\n\n<pre><code>public void UpdateOrder(int id, string name)\n{\n FooDataContext db = new FooDataContext();\n Order order = db.Orders.Where(o=>o.Id == id).FirstOrDefault();\n\n if (order == null) return;\n\n order.Name = name;\n\n db.SubmitChanges();\n}\n</code></pre>\n\n<p>I wouldn\'t recommend directly using the data context in the code behind, but this is a good way to get started with Linq To SQL. I would recommend putting all your database interactions in an external project and call from the GUI to the classes that encapsulate this behavior.</p>\n\n<p>I would recommend creating a Linq To Sql (dbml) file if you\'re new to Linq To Sql.</p>\n\n<p>Right click on your project in solution explorer, and select Add New Item. Select Linq To SQL file, and it will then let you connect to your database and select the tables.</p>\n\n<p>You can then look at the generated code, and get some great ideas on how Linq To Sql works and what you can do with it.</p>\n\n<p>Use that as a guideline on working with Linq to SQL and that will take you far...</p>\n'}, {'answer_id': 80277, 'author': 'Ilya Tchivilev', 'author_id': 15029, 'author_profile': 'https://Stackoverflow.com/users/15029', 'pm_score': 3, 'selected': False, 'text': '<p>Firstly, you can use an existing framework that addresses these issues, like CSLA.NET. The author of this framework has tackled these very issues. Go to <a href="http://www.rockfordlhotka.net/cslanet/" rel="nofollow noreferrer">http://www.rockfordlhotka.net/cslanet/</a> for this. Even if you don\'t use the full framework, the concepts are still applicable.</p>\n\n<p>If you wanted to roll your own, what I\'ve done in the past was to instead of using List for my collections, I\'ve used a custom type derived from BindingList. Inhereting from BindingList allows you to override the behaviour of add/remove item. So you can for example have another internal collection of "delteted" items. Every time the overriden Remove method is called on your collection, put the item into the "deleted" collection, and then call the base implementation of the Remove method. You can do the same for added items or changed items.</p>\n'}, {'answer_id': 80337, 'author': 'Aaron Jensen', 'author_id': 11229, 'author_profile': 'https://Stackoverflow.com/users/11229', 'pm_score': 2, 'selected': False, 'text': '<p>You\'re spot on about needing a unit of work, but don\'t write one. Use NHibernate or some other ORM. That is what they\'re made for. They have Unit of Works built in. </p>\n\n<p>Business objects are indeed "the way to go" for most applications. You\'re diving into a deep area and there will be much learning to do. Look into DDD.</p>\n\n<p>I\'d also strongly advise against code like that in your code-behind. Look into the MVP pattern.</p>\n\n<p>I\'d also (while I was bothering to learn lots of new, highly critical things) look into SOLID.</p>\n\n<p>You may want to check out JP Boodhoo\'s nothing but .net course as it covers a lot of these things.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11355/'] |
80,186 | <p>I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).</p>
<p>Anyone used it before and would mind giving a quick snippet of code and a brief description?</p>
| [{'answer_id': 80201, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 5, 'selected': False, 'text': '<p>X-Sendfile is an HTTP header, so you want something like this:</p>\n\n<pre><code>header("X-Sendfile: $filename");\n</code></pre>\n\n<p>Your web server picks it up if correctly configured. Here\'s some more details:</p>\n\n<p><a href="http://www.jasny.net/articles/how-i-php-x-sendfile/" rel="noreferrer">http://www.jasny.net/articles/how-i-php-x-sendfile/</a></p>\n'}, {'answer_id': 80422, 'author': 'Garrett Albright', 'author_id': 11023, 'author_profile': 'https://Stackoverflow.com/users/11023', 'pm_score': 2, 'selected': False, 'text': '<p>If tweaking the web server configuration is not an option, consider PHP\'s standard <a href="http://us3.php.net/manual/en/function.readfile.php" rel="nofollow noreferrer">readfile() function</a>. It won\'t be quite as fast as sendfiling, but it will be more widely compatible. Also note that when doing this, you should also send a Content-Type header at the very least.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,195 | <p>I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?</p>
<p>This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls. </p>
<p>We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up. </p>
<p>We have started looking at </p>
<ul>
<li>DRDB over GFS (GFS for distributed
lock capability)</li>
<li>Gluster (needs
client pieces, no native CIFS
support?)</li>
<li>Windows DFS (doc says only
replicates after file closes?)</li>
</ul>
<p>We are looking for a "black box" that serves up data.</p>
<p>We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.</p>
<p>Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions.</p>
| [{'answer_id': 80211, 'author': 'David Ackerman', 'author_id': 2504, 'author_profile': 'https://Stackoverflow.com/users/2504', 'pm_score': 0, 'selected': False, 'text': '<p>Are you looking for an "enterprise" solution or a "home" solution? It is hard to tell from your question, because 2TB is very small for an enterprise and a little on the high end for a home user (especially two servers). Could you clarify the need so we can discuss tradeoffs?</p>\n'}, {'answer_id': 80212, 'author': 'Sev', 'author_id': 83819, 'author_profile': 'https://Stackoverflow.com/users/83819', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend <strong>NAS Storage. (Network Attached Storage).</strong></p>\n\n<p>HP has some nice ones you can choose from.</p>\n\n<p><a href="http://h18006.www1.hp.com/storage/aiostorage.html" rel="nofollow noreferrer">http://h18006.www1.hp.com/storage/aiostorage.html</a></p>\n\n<p>as well as Clustered versions:</p>\n\n<p><a href="http://h18006.www1.hp.com/storage/software/clusteredfs/index.html?jumpid=reg_R1002_USEN" rel="nofollow noreferrer">http://h18006.www1.hp.com/storage/software/clusteredfs/index.html?jumpid=reg_R1002_USEN</a></p>\n'}, {'answer_id': 80218, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 2, 'selected': False, 'text': '<p>These days 2TB fits in one machine, so you\'ve got options, from simple to complex. These all presume linux servers:</p>\n\n<ul>\n<li>You can get poor-man\'s HA by setting up two machines and doing a periodic rsync from the main one to the backup.</li>\n<li>You can use <a href="http://www.drbd.org" rel="nofollow noreferrer">DRBD</a> to mirror one from the other at the block level. This has the disadvantage of being somewhat difficult to expand in the future.</li>\n<li>You can use <a href="http://oss.oracle.com/projects/ocfs2/" rel="nofollow noreferrer">OCFS2</a> to cluster the disks instead, for future expandability.</li>\n</ul>\n\n<p>There are also plenty of commercial solutions, but 2TB is a bit small for most of them these days.</p>\n\n<p>You haven\'t mentioned your application yet, but if hot failover isn\'t necessary, and all you really want is something that will stand up to losing a disk or two, find a NAS that support RAID-5, at least 4 drives, and hotswap and you should be good to go.</p>\n'}, {'answer_id': 80270, 'author': 'bmdhacks', 'author_id': 14032, 'author_profile': 'https://Stackoverflow.com/users/14032', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s two ways to go at this. The first is to just go buy a SAN or a NAS from Dell or HP and throw money at the problem. Modern storage hardware just makes all of this easy to do, saving your expertise for more core problems.</p>\n\n<p>If you want to roll your own, take a look at using Linux with DRBD.</p>\n\n<p><a href="http://www.drbd.org/" rel="nofollow noreferrer"><a href="http://www.drbd.org/" rel="nofollow noreferrer">http://www.drbd.org/</a></a></p>\n\n<p>DRBD allows you to create networked block devices. Think RAID 1 across two servers instead of just two disks. DRBD deployments are usually done using Heartbeat for failover in case one system dies.</p>\n\n<p>I\'m not sure about load balancing, but you might investigate and see if LVS can be used to load balance across your DRBD hosts:</p>\n\n<p><a href="http://www.linuxvirtualserver.org/" rel="nofollow noreferrer"><a href="http://www.linuxvirtualserver.org/" rel="nofollow noreferrer">http://www.linuxvirtualserver.org/</a></a></p>\n\n<p>To conclude, let me just reiterate that you\'re probably going to save yourself a lot of time in the long run just forking out the money for a NAS.</p>\n'}, {'answer_id': 80473, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I assume from the body of your question is you're a business user? I purchased a 6TB RAID 5 unit from Silicon Mechanics and have it NAS attached and my engineer installed NFS on our servers. Backups performed via rsync to another large capacity NAS.</p>\n"}, {'answer_id': 80520, 'author': 'pro', 'author_id': 352728, 'author_profile': 'https://Stackoverflow.com/users/352728', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at Amazon Simple Storage Service (Amazon S3)</p>\n\n<p><a href="http://www.amazon.com/S3-AWS-home-page-Money/b/ref=sc_fe_l_2?ie=UTF8&node=16427261&no=3435361&me=A36L942TSJ2AJA" rel="nofollow noreferrer">http://www.amazon.com/S3-AWS-home-page-Money/b/ref=sc_fe_l_2?ie=UTF8&node=16427261&no=3435361&me=A36L942TSJ2AJA</a></p>\n\n<p>--\nThis may be of interest re. High Availability</p>\n\n<p>Dear AWS Customer:</p>\n\n<p>Many of you have asked us to let you know ahead of time about features and services that are currently under development so that you can better plan for how that functionality might integrate with your applications. To that end, we are excited to share some early details with you about a new offering we have under development here at AWS -- a content delivery service.</p>\n\n<p>This new service will provide you a high performance method of distributing content to end users, giving your customers low latency and high data transfer rates when they access your objects. The initial release will help developers and businesses who need to deliver popular, publicly readable content over HTTP connections. Our goal is to create a content delivery service that:</p>\n\n<p>Lets developers and businesses get started easily - there are no minimum fees and no commitments. You will only pay for what you actually use. \nIs simple and easy to use - a single, simple API call is all that is needed to get started delivering your content. \nWorks seamlessly with Amazon S3 - this gives you durable storage for the original, definitive versions of your files while making the content delivery service easier to use. \nHas a global presence - we use a global network of edge locations on three continents to deliver your content from the most appropriate location.</p>\n\n<p>You\'ll start by storing the original version of your objects in Amazon S3, making sure they are publicly readable. Then, you\'ll make a simple API call to register your bucket with the new content delivery service. This API call will return a new domain name for you to include in your web pages or application. When clients request an object using this domain name, they will be automatically routed to the nearest edge location for high performance delivery of your content. It\'s that simple.</p>\n\n<p>We\'re currently working with a small group of private beta customers, and expect to have this service widely available before the end of the year. If you\'d like to be notified when we launch, please let us know by clicking here.</p>\n\n<p>Sincerely,</p>\n\n<p>The Amazon Web Services Team </p>\n'}, {'answer_id': 85518, 'author': 'ben', 'author_id': 7561, 'author_profile': 'https://Stackoverflow.com/users/7561', 'pm_score': 0, 'selected': False, 'text': '<p>Your best bet maybe to work with experts who do this sort of thing for a living. These guys are actually in our office complex...I\'ve had a chance to work with them on a similar project I was lead on.</p>\n\n<p><a href="http://www.deltasquare.com/About" rel="nofollow noreferrer">http://www.deltasquare.com/About</a></p>\n'}, {'answer_id': 85606, 'author': 'Tony Dodd', 'author_id': 16465, 'author_profile': 'https://Stackoverflow.com/users/16465', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve recently deployed hanfs using DRBD as the backend, in my situation, I\'m running active/standby mode, but I\'ve tested it successfully using OCFS2 in primary/primary mode too. There unfortunately isn\'t much documentation out there on how best to achieve this, most that exists is barely useful at best. If you do go along the drbd route, I highly recommend joining the drbd mailing list, and reading all of the documentation. Here\'s my ha/drbd setup and script I wrote to handle ha\'s failures:</p>\n\n<hr>\n\n<p>DRBD8 is required - this is provided by drbd8-utils and drbd8-source. Once these are installed (I believe they\'re provided by backports), you can use module-assistant to install it - m-a a-i drbd8. Either depmod -a or reboot at this point, if you depmod -a, you\'ll need to modprobe drbd.</p>\n\n<p>You\'ll require a backend partition to use for drbd, do not make this partition LVM, or you\'ll hit all sorts of problems. Do not put LVM on the drbd device or you\'ll hit all sorts of problems.</p>\n\n<p>Hanfs1:</p>\n\n<pre><code>\n/etc/drbd.conf\n\nglobal {\n usage-count no;\n}\ncommon {\n protocol C;\n disk { on-io-error detach; }\n}\nresource export {\n syncer {\n rate 125M;\n }\n on hanfs2 {\n address 172.20.1.218:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n on hanfs1 {\n address 172.20.1.219:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n}</code></pre>\n\n<p>Hanfs2\'s /etc/drbd.conf:</p>\n\n<p><pre><code>\nglobal {\n usage-count no;\n}\ncommon {\n protocol C;\n disk { on-io-error detach; }\n}\nresource export {\n syncer {\n rate 125M;\n }\n on hanfs2 {\n address 172.20.1.218:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n on hanfs1 {\n address 172.20.1.219:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n}</pre></code></p>\n\n<p>Once configured, we need to bring up drbd next.</p>\n\n<pre>\ndrbdadm create-md export\ndrbdadm attach export\ndrbdadm connect export\n</pre>\n\n<p>We must now perform an initial synchronization of data - obviously, if this is a brand new drbd cluster, it doesn\'t matter which node you choose.</p>\n\n<p></p>\n\n<p>Once done, you\'ll need to mkfs.yourchoiceoffilesystem on your drbd device - the device in our config above is /dev/drbd1. <a href="http://www.drbd.org/users-guide/p-work.html" rel="noreferrer">http://www.drbd.org/users-guide/p-work.html</a> is a useful document to read while working with drbd.</p>\n\n<p>Heartbeat</p>\n\n<p>Install heartbeat2. (Pretty simple, apt-get install heartbeat2).</p>\n\n<p>/etc/ha.d/ha.cf on each machine should consist of:</p>\n\n<p>hanfs1:\n<pre><code>\nlogfacility local0\nkeepalive 2\nwarntime 10\ndeadtime 30\ninitdead 120</p>\n\n<p>ucast eth1 172.20.1.218</p>\n\n<p>auto_failback no</p>\n\n<p>node hanfs1\nnode hanfs2\n</pre></code></p>\n\n<p>hanfs2:</p>\n\n<p><pre><code>\nlogfacility local0\nkeepalive 2\nwarntime 10\ndeadtime 30\ninitdead 120</p>\n\n<p>ucast eth1 172.20.1.219</p>\n\n<p>auto_failback no</p>\n\n<p>node hanfs1\nnode hanfs2\n</pre></code></p>\n\n<p>/etc/ha.d/haresources should be the same on both ha boxes:</p>\n\n<pre>\nhanfs1 IPaddr::172.20.1.230/24/eth1\nhanfs1 HeartBeatWrapper</pre>\n\n<p>I wrote a wrapper script to deal with the idiosyncracies caused by nfs and drbd in a failover scenario. This script should exist within /etc/ha.d/resources.d/ on each machine.</p>\n\n<p><pre><code></p>\n\n<h1>!/bin/bash</h1>\n\n<h1>heartbeat fails hard.</h1>\n\n<h1>so this is a wrapper</h1>\n\n<h1>to get around that stupidity</h1>\n\n<h1>I\'m just wrapping the heartbeat scripts, except for in the case of umount</h1>\n\n<h1>as they work, mostly</h1>\n\n<p>if [[ -e /tmp/heartbeatwrapper ]]; then\n runningpid=$(cat /tmp/heartbeatwrapper)\n if [[ -z $(ps --no-heading -p $runningpid) ]]; then\n echo "PID found, but process seems dead. Continuing."\n else<br>\n echo "PID found, process is alive, exiting."<br>\n exit 7<br>\n fi<br>\nfi </p>\n\n<p>echo $$ > /tmp/heartbeatwrapper</p>\n\n<p>if [[ x$1 == "xstop" ]]; then</p>\n\n<p>/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1</p>\n\n<h1>NFS init script isn\'t LSB compatible, exit codes are 0 no matter what happens.</h1>\n\n<h1>Thanks guys, you really make my day with this bullshit.</h1>\n\n<h1>Because of the above, we just have to hope that nfs actually catches the signal</h1>\n\n<h1>to exit, and manages to shut down its connections.</h1>\n\n<h1>If it doesn\'t, we\'ll kill it later, then term any other nfs stuff afterwards.</h1>\n\n<h1>I found this to be an interesting insight into just how badly NFS is written.</h1>\n\n<p>sleep 1</p>\n\n<pre><code>#we don\'t want to shutdown nfs first!\n#The lock files might go away, which would be bad.\n\n#The above seems to not matter much, the only thing I\'ve determined\n#is that if you have anything mounted synchronously, it\'s going to break\n#no matter what I do. Basically, sync == screwed; in NFSv3 terms. \n#End result of failing over while a client that\'s synchronous is that \n#the client hangs waiting for its nfs server to come back - thing doesn\'t\n#even bother to time out, or attempt a reconnect. \n#async works as expected - it insta-reconnects as soon as a connection seems\n#to be unstable, and continues to write data. In all tests, md5sums have \n#remained the same with/without failover during transfer. \n\n#So, we first unmount /export - this prevents drbd from having a shit-fit\n#when we attempt to turn this node secondary. \n\n#That\'s a lie too, to some degree. LVM is entirely to blame for why DRBD\n#was refusing to unmount. Don\'t get me wrong, having /export mounted doesn\'t\n#help either, but still. \n#fix a usecase where one or other are unmounted already, which causes us to terminate early.\n\nif [[ "$(grep -o /varlibnfs/rpc_pipefs /etc/mtab)" ]]; then \n for ((test=1; test <= 10; test++)); do \n umount /export/varlibnfs/rpc_pipefs >/dev/null 2>&1 \n if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then \n break \n fi \n if [[ $? -ne 0 ]]; then \n #try again, harder this time \n umount -l /var/lib/nfs/rpc_pipefs >/dev/null 2>&1 \n if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then \n break \n fi \n fi \n done \n if [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n echo "Problem unmounting rpc_pipefs" \n exit 1 \n fi \nfi \n\nif [[ "$(grep -o /dev/drbd1 /etc/mtab)" ]]; then \n for ((test=1; test <= 10; test++)); do \n umount /export >/dev/null 2>&1 \n if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then \n break \n fi \n if [[ $? -ne 0 ]]; then \n #try again, harder this time \n umount -l /export >/dev/null 2>&1 \n if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then \n break \n fi \n fi \n done \n if [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n echo "Problem unmount /export" \n exit 1 \n fi \nfi \n\n\n#now, it\'s important that we shut down nfs. it can\'t write to /export anymore, so that\'s fine.\n#if we leave it running at this point, then drbd will screwup when trying to go to secondary. \n#See contradictory comment above for why this doesn\'t matter anymore. These comments are left in\n#entirely to remind me of the pain this caused me to resolve. A bit like why churches have Jesus\n#nailed onto a cross instead of chilling in a hammock. \n\npidof nfsd | xargs kill -9 >/dev/null 2>&1\n\nsleep 1 \n\nif [[ -n $(ps aux | grep nfs | grep -v grep) ]]; then\n echo "nfs still running, trying to kill again" \n pidof nfsd | xargs kill -9 >/dev/null 2>&1 \nfi \n\nsleep 1\n\n/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1\n\nsleep 1\n\n#next we need to tear down drbd - easy with the heartbeat scripts\n#it takes input as resourcename start|stop|status \n#First, we\'ll check to see if it\'s stopped \n\n/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1\nif [[ $? -eq 2 ]]; then \n echo "resource is already stopped for some reason..." \nelse \n for ((i=1; i <= 10; i++)); do \n /etc/ha.d/resource.d/drbddisk export stop >/dev/null 2>&1\n if [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Secondary" ]] || [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Unknown" ]]; then \n echo "Successfully stopped DRBD" \n break \n else \n echo "Failed to stop drbd for some reason" \n cat /proc/drbd \n if [[ $i -eq 10 ]]; then \n exit 50 \n fi \n fi \n done \nfi \n\nrm -f /tmp/heartbeatwrapper \nexit 0 \n</code></pre>\n\n<p>elif [[ x$1 == "xstart" ]]; then</p>\n\n<pre><code>#start up drbd first\n/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then \n echo "Something seems to have broken. Let\'s check possibilities..."\n testvar=$(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) \n if [[ $testvar == "Primary/Unknown" ]] || [[ $testvar == "Primary/Secondary" ]]\n then \n echo "All is fine, we are already the Primary for some reason" \n elif [[ $testvar == "Secondary/Unknown" ]] || [[ $testvar == "Secondary/Secondary" ]]\n then \n echo "Trying to assume Primary again" \n /etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1 \n if [[ $? -ne 0 ]]; then \n echo "I give up, something\'s seriously broken here, and I can\'t help you to fix it."\n rm -f /tmp/heartbeatwrapper \n exit 127 \n fi \n fi \nfi \n\nsleep 1 \n\n#now we remount our partitions \n\nfor ((test=1; test <= 10; test++)); do \n mount /dev/drbd1 /export >/tmp/mountoutput \n if [[ -n $(grep -o export /etc/mtab) ]]; then \n break \n fi \ndone \n\nif [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n exit 125 \nfi \n\n\n#I\'m really unsure at this point of the side-effects of not having rpc_pipefs mounted. \n#The issue here, is that it cannot be mounted without nfs running, and we don\'t really want to start\n#nfs up at this point, lest it ruin everything. \n#For now, I\'m leaving mine unmounted, it doesn\'t seem to cause any problems. \n\n#Now we start up nfs.\n\n/etc/init.d/nfs-kernel-server start >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo "There\'s not really that much that I can do to debug nfs issues."\n echo "probably your configuration is broken. I\'m terminating here."\n rm -f /tmp/heartbeatwrapper\n exit 129\nfi\n\n#And that\'s it, done.\n\nrm -f /tmp/heartbeatwrapper\nexit 0\n</code></pre>\n\n<p>elif [[ "x$1" == "xstatus" ]]; then</p>\n\n<pre><code>#Lets check to make sure nothing is broken.\n\n#DRBD first\n/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo "stopped"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\n#mounted?\ngrep -q drbd /etc/mtab >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo "stopped"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\n#nfs running?\n/etc/init.d/nfs-kernel-server status >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo "stopped"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\necho "running"\nrm -f /tmp/heartbeatwrapper\nexit 0\n</code></pre>\n\n<p>fi\n</pre></code></p>\n\n<p>With all of the above done, you\'ll then just want to configure /etc/exports</p>\n\n<pre>/export 172.20.1.0/255.255.255.0(rw,sync,fsid=1,no_root_squash)</pre>\n\n<p>Then it\'s just a case of starting up heartbeat on both machines and issuing hb_takeover on one of them. You can test that it\'s working by making sure the one you issued the takeover on is primary - check /proc/drbd, that the device is mounted correctly, and that you can access nfs. </p>\n\n<p>--</p>\n\n<p>Best of luck man. Setting it up from the ground up was, for me, an extremely painful experience.</p>\n'}, {'answer_id': 764265, 'author': 'McGovernTheory', 'author_id': 85095, 'author_profile': 'https://Stackoverflow.com/users/85095', 'pm_score': 0, 'selected': False, 'text': '<p>May I suggest you visit the F5 site and check out <a href="http://www.f5.com/solutions/virtualization/file/" rel="nofollow noreferrer">http://www.f5.com/solutions/virtualization/file/</a></p>\n'}, {'answer_id': 2167246, 'author': 'fish.ada94', 'author_id': 262384, 'author_profile': 'https://Stackoverflow.com/users/262384', 'pm_score': 0, 'selected': False, 'text': '<p>You can look at Mirror File System. It does the file replication on file system level.\nThe same file on both primary and backup systems are live file.</p>\n\n<p><a href="http://www.linux-ha.org/RelatedTechnologies/Filesystems" rel="nofollow noreferrer">http://www.linux-ha.org/RelatedTechnologies/Filesystems</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15020/'] |
80,202 | <p>I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p></p>
<p>Now I want to insert an element in to the text so that it will become:</p>
<p><p>Hello <span id=span1>new</span> world!</p></p>
<p>I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".</p>
| [{'answer_id': 80228, 'author': 'Sev', 'author_id': 83819, 'author_profile': 'https://Stackoverflow.com/users/83819', 'pm_score': 0, 'selected': False, 'text': '<p>Include the class definition that\'s defined in CSS on your JavaScript version of the <code><span></code> tag as well.</p>\n\n<pre class="lang-html prettyprint-override"><code><span class="class_defined_in_css">\n</code></pre>\n\n<p>(where this <code><span></code> tag would be part of your JavaScript code.)</p>\n'}, {'answer_id': 80231, 'author': 'dreamlax', 'author_id': 10320, 'author_profile': 'https://Stackoverflow.com/users/10320', 'pm_score': 0, 'selected': False, 'text': '<p>Why not give the paragraph an id and then use Javascript to add the word, or remove it, if necessary? Surely it will retain the same formatting as the paragraph when you insert the word "new", or change the contents of the paragraph entirely.</p>\n'}, {'answer_id': 80251, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 1, 'selected': False, 'text': '<p>Well, I don\'t know how married you are to using a <span> tag, but why not do this?</p>\n\n<pre><code><p style="display: inline">Hello <p id="myIdValue" style="display: inline">new</p> World</p>\n</code></pre>\n\n<p>That way the inserted html retains the same styling as the outer, and you can still have a handle to it, etc. Granted, you will have to add the inline CSS style, but it would work.</p>\n'}, {'answer_id': 80262, 'author': 'Prestaul', 'author_id': 5628, 'author_profile': 'https://Stackoverflow.com/users/5628', 'pm_score': 1, 'selected': False, 'text': '<p>The only way to do this is to either modify the other spans to include a class name and only apply the styles to spans with that class, or override the styles set for all spans for your new span.</p>\n\n<p>So if you\'ve done:</p>\n\n<pre><code>span {\n display: block;\n margin: 10px;\n padding: 10px;\n}\n</code></pre>\n\n<p>You could override with:</p>\n\n<pre><code><span style="display: inline; margin: 0; padding: 0;">New Span</span>\n</code></pre>\n'}, {'answer_id': 80408, 'author': 'Prestaul', 'author_id': 5628, 'author_profile': 'https://Stackoverflow.com/users/5628', 'pm_score': 2, 'selected': True, 'text': '<p>Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:</p>\n\n<pre><code>span#yourSpan {\n /* defaults */\n position: static;\n display: inline;\n margin: 0;\n padding: 0;\n background: transparent;\n border: none;\n\n /* inherit from parent node */\n font: inherit;\n color: inherit;\n text-decoration: inherit;\n line-height: inherit;\n letter-spacing: inherit;\n text-transform: inherit;\n white-space: inherit;\n word-spacing: inherit;\n}\n</code></pre>\n\n<p>This should be sufficient, although you may need to add !important if you are not using an id:</p>\n\n<pre><code><span class="hello-node">hello</span>\n\nspan.hello-node {\n /* defaults */\n position: static !important;\n display: inline !important;\n ...\n}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15023/'] |
80,215 | <p>Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.</p>
| [{'answer_id': 80596, 'author': 'Birger', 'author_id': 11485, 'author_profile': 'https://Stackoverflow.com/users/11485', 'pm_score': 3, 'selected': True, 'text': '<p>As far as I know that is not possible. It is not an open source database, so writing drivers for it is really hard.</p>\n'}, {'answer_id': 275524, 'author': 'Joshua Turner', 'author_id': 820, 'author_profile': 'https://Stackoverflow.com/users/820', 'pm_score': 2, 'selected': False, 'text': '<p>If you download one of the trial versions, you can get/install the odbc client and connect that way.</p>\n\n<p>In our version of pervasive (older version) on the server where the database is installed, you can also find this client install.</p>\n'}, {'answer_id': 718654, 'author': 'Luke Chadwick', 'author_id': 65903, 'author_profile': 'https://Stackoverflow.com/users/65903', 'pm_score': 0, 'selected': False, 'text': "<p>This depends a lot on the version of Btrieve. I've been working with btrieve for a long time and have found that the best API for the old 6.15 version was in pascal. That having been said there was definately a C api around as well.</p>\n\n<p>Pervasive have recently released a 6.15 ultimate patch. Using this and the C api should allow you to work effectively with older btrieve databases. It is possible for instance to build new modules for python using C. </p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/310574/'] |
80,216 | <p>Application frameworks such as DotNetNuke, Eclipse, Websphere and so forth are available today which offer customizable frameworks that can be used as dashboard applications. Do you use these or do you and your peers keep writing amazing, modular, maintainable dashboard frameworks which you support yourselves?</p>
<p>Are there any good web based, OS independent frameworks out there that you suggest using to build your own enterprise class infrastructure around?</p>
| [{'answer_id': 80238, 'author': 'Sten Vesterli', 'author_id': 9363, 'author_profile': 'https://Stackoverflow.com/users/9363', 'pm_score': 2, 'selected': True, 'text': '<p>The one I use is Oracle Application Development Framework. It\'s a complete, fully supported framework, and Oracle use it themselves to build their own enterprise applications. It comes with a lot of JSF components that are very easy to bind to the underlying data objects.\nI\'d recommend this for all Java applications that need database data. </p>\n\n<p>You find a discussion of it on the Oracle Wiki: \n<a href="http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent" rel="nofollow noreferrer">http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent</a></p>\n'}, {'answer_id': 80239, 'author': 'ahockley', 'author_id': 8209, 'author_profile': 'https://Stackoverflow.com/users/8209', 'pm_score': 1, 'selected': False, 'text': "<p>There's no one right answer. Look at the business need... if you're doing fairly typical things, then starting from an established framework is a good place to start. If you feel you may need some custom components or widgets, look for a framework that's extensible using the knowledge and skills that you have in-house.</p>\n\n<p>Unless your line of business is to build application frameworks or dashboards, one should look very hard before building a whole new framework or dashboard.</p>\n"}, {'answer_id': 80241, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 0, 'selected': False, 'text': '<p>At work, we try to create from scratch as little as possible. We use Frameworks a lot (maybe not always end to end frameworks). We have used Dot Net Nuke a lot. Another framework we use a lot is CSLA.</p>\n'}, {'answer_id': 80244, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': '<p>I personally use DotNetNuke quite extensively for both personal and business related ventures. However DNN does not meet one of your requirements as it is a .NET solution so it is windows dependent.</p>\n\n<p>I have found that using DotNetNuke has greatly reduced our time to delivery, and we can focus on our core needs rather than the implementation of the common pieces.</p>\n'}, {'answer_id': 80279, 'author': 'decibel', 'author_id': 11116, 'author_profile': 'https://Stackoverflow.com/users/11116', 'pm_score': 0, 'selected': False, 'text': "<p>Be careful to consider how scalable the framework is. There are several frameworks out there that like to hammer your database because they think it's nothing but a glorified file system... those frameworks don't scale well at all.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10644/'] |
80,234 | <p>I attempted to open a C#/VB form in designer mode, and instead of the form, I got an ugly error message saying "The path is not of a legal form". This form used to work! What happened?</p>
<hr>
<p><em>Thanks to all who have answered. This question is a problem I hit a while back, and I struggled with it for a long time, until I found the answer, which I posted below in order to help other people who might have hit this problem.<br>
Thanks!</em></p>
| [{'answer_id': 80245, 'author': 'Shaul Behr', 'author_id': 7850, 'author_profile': 'https://Stackoverflow.com/users/7850', 'pm_score': 3, 'selected': True, 'text': '<p>I don\'t know what this error message means, but it seems to be associated with third-party controls on the form. Anyway, the solution is almost as absurd as the problem:</p>\n\n<ol>\n<li>Close the designer/error message.</li>\n<li>Open the form code.</li>\n<li>Right-click on the form code and select "View Designer".</li>\n</ol>\n\n<p>Presto! The designer opens!</p>\n'}, {'answer_id': 80249, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 2, 'selected': False, 'text': '<p>Debugging design mode would help. From <a href="http://blog.lab49.com/archives/244" rel="nofollow noreferrer">here</a>:</p>\n\n<ol>\n<li>List item</li>\n<li>In visual studio, select the project you want to debug.</li>\n<li>Right click -> Properties.</li>\n<li>Select the debugging tab.</li>\n<li>Change the debug mode to Program.</li>\n<li>Set the “Start Application” to be your visual studio IDE (C:\\Program Files\\Microsoft Visual Studio .NET 2003\\Common7\\IDE\\devenv.exe)</li>\n<li>Set your solution file in the “command line argument field”.</li>\n<li>Apply -> OK</li>\n<li>Select the project you want to debug as the startup project.</li>\n<li>Run.</li>\n<li>Set a break point in the place you want to start debug (for example, your control constructor)</li>\n</ol>\n'}, {'answer_id': 80269, 'author': 'David Ackerman', 'author_id': 2504, 'author_profile': 'https://Stackoverflow.com/users/2504', 'pm_score': 0, 'selected': False, 'text': '<p>By path, it might be referring to a path to a file or folder. There could be a malformed path that you are trying to reference, i.e. forward slash instead of backslash. Also, what changed since the error came up? Did you move any files around? Did you save any previously unsaved code? Update from a version control system?</p>\n'}, {'answer_id': 4010738, 'author': 'Michel', 'author_id': 485887, 'author_profile': 'https://Stackoverflow.com/users/485887', 'pm_score': 1, 'selected': False, 'text': '<p>This problem happened with me, and I found out it is because of bad reference. You have to review the assemblies that your application references.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7850/'] |
80,243 | <p>I have mixed feelings about TDD. While I believe in testing I have a issues with the idea of the test driving my development effort.</p>
<p>When you code to satisfy some tests written for an interface for requirements you have right now, you might shift your focus from building maintainable code, from clean design and from sound architecture.</p>
<p>I have a problem with driven not with testing. Any thoughts?</p>
| [{'answer_id': 80274, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 1, 'selected': False, 'text': '<p>It\'s always a balance:<br>\n - too much TDD and you end up with code that works, but is a pain to work on.<br>\n - too much \'maintable code, clean design, and sound architecture\' and you end up with <a href="http://www.joelonsoftware.com/articles/fog0000000018.html" rel="nofollow noreferrer">Architecture Astronauts</a> that have talked themselves into coding paralysis</p>\n\n<p>Moderation in all things.</p>\n'}, {'answer_id': 80311, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 5, 'selected': False, 'text': '<p>No.</p>\n\n<p>If done right, Test Driven Development IS your design tool.</p>\n\n<p>I hope you forgive me for linking to <a href="http://jonlimjap.net/2016/09/01/when-tdd-goes-red/" rel="nofollow noreferrer">my own blog entry, wherein I discuss the pitfalls of Test Driven Development that went wrong</a> simply because developers treated their tests as, merely, tests.</p>\n\n<p>In a previous project, devs used a highly damaging singleton pattern that enforced dependencies throughout the project, which just broke the whole thing when requirements were changed:</p>\n\n<blockquote>\n <p>TDD was treated as a task, when it\n should have been treated as an an\n approach. [...]</p>\n \n <p>There was a failure to recognize\n that TDD is not about tests, it’s\n about design. The rampant case of\n singleton abuse in the unit tests made\n this obvious: instead of the test\n writers thinking “WTF are these\n singleton = value; statements doing in\n my tests?”, the test writers just\n propagated the singleton into the\n tests. 330 times.</p>\n \n <p>The unfortunate consequence is that\n the build server-enforced testing was\n made to pass, whatever it took. </p>\n</blockquote>\n\n<p>Test Driven Development, done right, should make developers highly aware of design pitfalls like tight coupling, violations of DRY (don\'t repeat yourself), violations of SRP (Single Responsibility Principle), etc.</p>\n\n<p>If you write passing code for your tests for the sake of passing your tests, you have already failed: you should treat <em>hard to write</em> tests as signposts that make you ask: why is this done this way? Why can\'t I test this code without depending on some other code? Why can\'t I reuse this code? Why is this code breaking when used by itself? </p>\n\n<p>Besides if your design is <em>truly</em> clean, and your code <em>truly</em> maintainable why is it not trivial to write a test for it?</p>\n'}, {'answer_id': 80391, 'author': 'Tom Carr', 'author_id': 14954, 'author_profile': 'https://Stackoverflow.com/users/14954', 'pm_score': 2, 'selected': False, 'text': "<p>There are three steps to complete software:</p>\n\n<ol>\n<li>Make it work </li>\n<li>Make it right </li>\n<li>Make it fast</li>\n</ol>\n\n<p>Tests get you #1. Your code is not done just because the tests have passed. Preferably you have some concept of project structure (Utilities, commonly accessed objects, layers, framework) before you start writing your tests/code. After you've written your code to make the tests pass, you need to re-evaluate it to see which parts can be refactored out to the different aspects of your application. Yuo can do this confidently, because you know that as long as your tests are still passing, you code is still functional (or at least meeting the requirements).</p>\n\n<p>At the start of a project, give thought to the structure. As the project goes on continue to evaluate and re-evaluate your code to keep the design in place or change the design if it stops making sense. All of these items must be taken into account when you estimate, or you will end up with spagetti code, TDD or not.</p>\n"}, {'answer_id': 80406, 'author': 'user15074', 'author_id': 15074, 'author_profile': 'https://Stackoverflow.com/users/15074', 'pm_score': 2, 'selected': False, 'text': '<p>I completely agree with pjz. There is no one right way to design software. If you take TDD to an extreme, without any forethought except the next unit test, you may make things harder on yourself. Ditto for the person who sets out on a grand software project by spending months on diagrams and documentation, but no code.</p>\n\n<p><strong>Moderate.</strong> If feel the urge to draw up a quick diagram that helps you visualize the structure of your code, go for it. If you need two pages, it might be time to start writing some code. And if you want to do that before you write your tests, so what. The goal is working, quality software, not absolute conformity to any particular software development doctrine. Do what works for you and your team. Find areas where improvements can be made. Iterate.</p>\n'}, {'answer_id': 80495, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 1, 'selected': False, 'text': "<p>I'm relatively new to TDD and unit testing, but in the two side projects I've used it on, I've found it to be a design <em>aide</em> rather than alternative to design. The abilty to test and verify components / sub-components independently has made it easier for me to make rapid changes and try out new design ideas.</p>\n\n<p>The difference I've experienced with TDD is reliability. The process of working out component interfacing on smaller levels of component at the begining of the design process, rather than later, is that I've got components I can trust will work <em>earlier</em>, so I can stop worrying about the little pieces and instead get to work on the tough problems. </p>\n\n<p>And when I inevitably need to come back and maintain the little pieces, I can spend <em>less</em> time doing so, so I can get back to the work I want to be doing.</p>\n"}, {'answer_id': 80529, 'author': 'user15122', 'author_id': 15122, 'author_profile': 'https://Stackoverflow.com/users/15122', 'pm_score': 1, 'selected': False, 'text': "<p>For the most part I agree that TDD does provide a sort of design tool. The most important part of that to me is the way that it builds in the ability to make more changes (you know, when you have that flash of insight moment where you can add functionality by deleting code) with greatly reduced risk.</p>\n\n<p>That said, some of the more algorithmic work I've contracted on lately has suffered a bit under TDD without a careful balance of design thought. The statement above about safer refactoring was still a great benefit, but for some algorithms TDD is (although still useful) not sufficient to get you to an ideal solution. Take sorting as a simple example. TDD could easily lead you to a suboptimal (N^2) algorithm (and scads of passing tests that allow you to refactor to a quick sort) like a bubble sort. TDD is a tool, a very good tool, but like many things needs to be used appropriately for the context of the problem being solved.</p>\n"}, {'answer_id': 80666, 'author': 'Bjorn Reppen', 'author_id': 1324220, 'author_profile': 'https://Stackoverflow.com/users/1324220', 'pm_score': 2, 'selected': False, 'text': '<p>I completely agree with you on that subject. In <em>practice</em> I think TDD often has some very negative effects on the code base (crappy design, procedural code, no encapsulation, production code littered with test code, interfaces everywhere, hard to refactor production code because everything is tightly coupled to many tests etc.).</p>\n\n<p><a href="http://en.wikipedia.org/wiki/Jim_Coplien" rel="nofollow noreferrer">Jim Coplien</a> has given talks on exactly this topic for a while now:</p>\n\n<blockquote>\n <p>Recent studies (Siniaalto and\n Abrahamsson) of TDD show that it may\n have no benefits over traditional\n test-last development and that in some\n cases has deteriorated the code and\n that it has other alarming (their\n word) effects. The one that worries me\n the most is that it deteriorates the\n architecture. \n --<a href="http://www.artima.com/weblogs/viewpost.jsp?thread=6771" rel="nofollow noreferrer">Jim\'s blog</a></p>\n</blockquote>\n\n<p>There is also a <a href="http://www.infoq.com/interviews/coplien-martin-tdd" rel="nofollow noreferrer">discussion over on InfoQ</a> between Robert C. Martin and James Coplien where they touch on this subject.</p>\n'}, {'answer_id': 80758, 'author': 'Peter Evjan', 'author_id': 3397, 'author_profile': 'https://Stackoverflow.com/users/3397', 'pm_score': 4, 'selected': False, 'text': '<p>There\'s always a risk of overdoing either the TDD design or the upfront design. So the answer is that it depends. I prefer starting with a user story/acceptance test which is the base of the requirement that my tests will aid in producing. Only after I\'ve established that, I start writing detailed unit tests TDD-style. If the only design and thinking you do is through TDD, then you risk too much of a bottom up approach, which might give you units and classes that are excellent in isolation, but when you try to integrate them into the user story fulfilling task you might be surprised by having done it all wrong. For more inspiration on this, look att <a href="http://blog.daveastels.com/files/BDD_Intro.pdf" rel="noreferrer">BDD</a>.</p>\n\n<p><a href="http://www.infoq.com/interviews/coplien-martin-tdd" rel="noreferrer">A great "debate" about this has been recorded</a> between Robert C. Martin and James Coplien, where the former is a TDD advocate and the latter has stated that it ruins the design of a system. This is what Robert said about TDD and design:</p>\n\n<blockquote>\n <p>"There has been a feeling in the Agile\n community since about \'99 that\n architecture is irrelevant, we don\'t\n need to do architecture, all we need\n to do is write a lots of tests and do\n lots of stories and do quick\n iterations and the code will assemble\n itself magically, and this has always\n been horse shit. I even think most of\n the original Agile proponents would\n agree that was a silliness."</p>\n</blockquote>\n\n<p>James Coplien states that merely driving your design from TDD has a great risk:</p>\n\n<blockquote>\n <p>"One of the things we see a lot, in a\n lot of projects, is that projects go\n south on about their 3rd sprint and\n they crash and burn because they\n cannot go any further, because they\n have cornered themselves\n architecturally. And you can\'t\n refactor your way out of this because\n the refactoring has to be across class\n categories, across class hierarchies,\n and you no longer can have any\n assurances about having the same\n functionality."</p>\n</blockquote>\n\n<p>Also he gives a great example of how a bank account probably would look if you test drove it as compared to using your upfront knowledge to drive the architecture:</p>\n\n<blockquote>\n <p>"I remember when I was talking with\n Kent once, about in the early days\n when he was proposing TDD, and this\n was in the sense of YAGNI and doing\n the simplest thing that could possibly\n work, and he says: \'Ok. Let\'s make a\n bank account, a savings account.\'\n What\'s a savings account? It\'s a\n number and you can add to the number\n and you can subtract from the number.\n So what a saving account is, is a\n calculator. Let\'s make a calculator,\n and we can show that you can add to\n the balance and subtract from the\n balance. That\'s the simplest thing\n that could possibly work, everything\n else is an evolution of that.</p>\n \n <p>If you do a real banking system, a\n savings account is not even an object\n and you are not going to refactor your\n way to the right architecture from\n that one. What a savings account is,\n is a process that does an iteration\n over an audit trail of database\n transactions, of deposits and interest\n gatherings and other shifts of the\n money. It\'s not like the savings\n account is some money sitting on the\n shelf on a bank somewhere, even though\n that is the user perspective, and\n you\'ve just got to know that there are\n these relatively intricate structures\n in the foundations of a banking system\n to support the tax people and the\n actuaries and all these other folks,\n that you can\'t get to in an\n incremental way. Well, you can,\n because of course the banking industry\n has come to this after 40 years. You\n want to give yourself 40 years? It\'s\n not agile."</p>\n</blockquote>\n\n<p>The interesting thing here is that both the TDD proponent and the TDD antagonist are saying that you need design up front. </p>\n\n<p>If you have the time, watch the video. It\'s a great discussion between two highly influential experts, and it\'s only 22 minutes long.</p>\n'}, {'answer_id': 80829, 'author': 'Robert Gould', 'author_id': 15124, 'author_profile': 'https://Stackoverflow.com/users/15124', 'pm_score': 2, 'selected': False, 'text': "<p>My way to think about it is, write what you want your code to look like first.\nOnce you have a sample of your target code (that right now does nothing) see if you can place a test scaffolding onto it. \nIf you can't do that, figure out why you can't. \nMost of the time it's because you made a poor design decision (99%), however if that's not the case (1%) try the following:</p>\n\n<ul>\n<li>determine what the crazy requirements are that you need to abide to that wont let you test your code. One you understand the issues redesign your API.</li>\n<li>if someone else decided this requirements discuss about it him/her. They probably had a good reason for the requirement and once you know their reason you'll be able to perfect your design and make it testable. If not now you can both rework the requirement and you'll both be the better for it.</li>\n</ul>\n\n<p>After you have your target code and the test scaffolding. Implement the code. Now you even have the advantage of knowing how well your progressing as you pass your own test (Its a great motivator!)</p>\n\n<p>The only case where testing may be superfluous, from personal experience, is when you are making an early prototype because at that point you still don't understand the problem well enough to design or test your code accurately.</p>\n"}, {'answer_id': 35225587, 'author': 'Cope', 'author_id': 2464041, 'author_profile': 'https://Stackoverflow.com/users/2464041', 'pm_score': 2, 'selected': False, 'text': '<p>There are many informal opinions here, including the popular opinion (from Jon Limjap) that bad results come from doing it wrong, and claims that seem unsupported by little more than personal experience. The preponderance empirical evidence and published results point in an opposite direction from that experience.</p>\n\n<p>The <em>theory</em> is that a method that requires you to write tests before the code will lead to thinking about design at the level of individual code fragments — i.e., programming-in-the-small. Since procedures are all you can test (you still test an object one method at a time, and you simply can\'t test classes in most languages), your design focus goes to the individual methods and how they compose. That leads, in theory, to a bottom-up procedural design and, in turn, to bad coupling and cohesion among objects.</p>\n\n<p>The broad empirical data substantiate the theory. Siniaalto and Abrahamsson, (<em>Comparative Case Study on the Effect of Test-Driven Development on Program Design and Test Coverage</em>), ESEM 2007, found that "Our\xa0results indicate that the cohesion may be worse (even though Beck claims that TDD produces highly cohesive systems).\xa0In our second study we noticed that the complexity measures were better with TDD, but the dependency management metrics were clearly worse." Janzen and Saledian (<em>Does Test-Driven Development Really Improve Software Design Quality?</em> IEEE Software 25(2), March/April 2008, pp. 77 - 84) found that “[T]he results didn\'t support claims for lower coupling and increased cohesion with TDD”.</p>\n\n<p>A literature review will uncover other publications furthering these cases.</p>\n\n<p>Even my dear friend Uncle Bob writes: "One of the more insidious and persistent myths of agile development is that up-front architecture and design are bad; that you should never spend time up front making architectural decisions. That instead you should evolve your architecture and design from nothing, one test-case at a time. Pardon me, but that’s Horse Shit." ("The Scatology of Agile Architecture," \n<a href="http://blog.objectmentor.com/articles/2009/04/25/the-scatology-of-agile-architecture" rel="nofollow">http://blog.objectmentor.com/articles/2009/04/25/the-scatology-of-agile-architecture</a>)</p>\n\n<p><strong>However</strong>, it\'s worth noting that the broader failure is that people think it\'s a testing technique rather than a design technique. Osherov points out a host of approaches that are often casually equated with TDD. I can\'t be sure what\'s meant by the posters here. See: <a href="http://weblogs.asp.net/rosherove/archive/2007/10/08/the-various-meanings-of-tdd.aspx" rel="nofollow">http://weblogs.asp.net/rosherove/archive/2007/10/08/the-various-meanings-of-tdd.aspx</a>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13615/'] |
80,247 | <p>How can I get all implementations of an interface through reflection in C#?</p>
| [{'answer_id': 80325, 'author': 'Alex Duggleby', 'author_id': 5790, 'author_profile': 'https://Stackoverflow.com/users/5790', 'pm_score': 1, 'selected': False, 'text': '<p>Do you mean all interfaces a Type implements?</p>\n\n<p>Like this:</p>\n\n<pre><code>ObjX foo = new ObjX();\nType tFoo = foo.GetType();\nType[] tFooInterfaces = tFoo.GetInterfaces();\nforeach(Type tInterface in tFooInterfaces)\n{\n // do something with it\n}\n</code></pre>\n\n<p>Hope tha helpts.</p>\n'}, {'answer_id': 80343, 'author': 'Anton', 'author_id': 6464, 'author_profile': 'https://Stackoverflow.com/users/6464', 'pm_score': 3, 'selected': False, 'text': '<p>Have a look at <code>Assembly.GetTypes()</code> method. It returns all the types that can be found in an assembly. All you have to do is to iterate through every returned type and check if it implements necessary interface.</p>\n\n<p>On of the way to do so is using <code>Type.IsAssignableFrom</code> method.</p>\n\n<p>Here is the example. <code>myInterface</code> is the interface, implementations of which you are searching for.</p>\n\n<pre><code>Assembly myAssembly;\nType myInterface;\nforeach (Type type in myAssembly.GetTypes())\n{\n if (myInterface.IsAssignableFrom(type))\n Console.WriteLine(type.FullName);\n}\n</code></pre>\n\n<p>I do believe that it is not a very efficient way to solve your problem, but at least, it is a good place to start.</p>\n'}, {'answer_id': 80375, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Assembly assembly = Assembly.GetExecutingAssembly();\nList<Type> types = assembly.GetTypes();\nList<Type> childTypes = new List<Type>();\nforeach (Type type in Types) {\n foreach (Type interfaceType in type.GetInterfaces()) {\n if (interfaceType.Equals(typeof([yourinterfacetype)) {\n childTypes.Add(type)\n break;\n }\n }\n}\n</code></pre>\n\n<p>Maybe something like that....</p>\n'}, {'answer_id': 80467, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 6, 'selected': False, 'text': '<p>The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.</p>\n\n<pre><code>/// <summary>\n/// Returns all types in the current AppDomain implementing the interface or inheriting the type. \n/// </summary>\npublic static IEnumerable<Type> TypesImplementingInterface(Type desiredType)\n{\n return AppDomain\n .CurrentDomain\n .GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => desiredType.IsAssignableFrom(type));\n}\n</code></pre>\n\n<p>It is used like this;</p>\n\n<pre><code>var disposableTypes = TypesImplementingInterface(typeof(IDisposable));\n</code></pre>\n\n<p>You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions.</p>\n\n<pre><code>public static bool IsRealClass(Type testType)\n{\n return testType.IsAbstract == false\n && testType.IsGenericTypeDefinition == false\n && testType.IsInterface == false;\n}\n</code></pre>\n'}, {'answer_id': 81707, 'author': 'Hallgrim', 'author_id': 15454, 'author_profile': 'https://Stackoverflow.com/users/15454', 'pm_score': 1, 'selected': False, 'text': '<p>You have to loop over all assemblies that you are interested in. From the assembly you can get all the types it defines. Note that when you do AppDomain.CurrentDomain.Assemblies you only get the assemblies that are loaded. Assemblies are not loaded until they are needed, so that means that you have to explicitly load the assemblies before you start searching.</p>\n'}, {'answer_id': 17267339, 'author': 'Sam', 'author_id': 238753, 'author_profile': 'https://Stackoverflow.com/users/238753', 'pm_score': 2, 'selected': False, 'text': '<p>Here are some <a href="http://msdn.microsoft.com/en-us/library/system.type.aspx" rel="nofollow noreferrer"><code>Type</code></a> extension methods that may be useful for this, as suggested by <a href="https://stackoverflow.com/users/35047/simon-farrow">Simon Farrow</a>. This code is just a restructuring of the accepted answer.</p>\n\n<h3>Code</h3>\n\n<pre><code>/// <summary>\n/// Returns all types in <paramref name="assembliesToSearch"/> that directly or indirectly implement or inherit from the given type. \n/// </summary>\npublic static IEnumerable<Type> GetImplementors(this Type abstractType, params Assembly[] assembliesToSearch)\n{\n var typesInAssemblies = assembliesToSearch.SelectMany(assembly => assembly.GetTypes());\n return typesInAssemblies.Where(abstractType.IsAssignableFrom);\n}\n\n/// <summary>\n/// Returns the results of <see cref="GetImplementors"/> that match <see cref="IsInstantiable"/>.\n/// </summary>\npublic static IEnumerable<Type> GetInstantiableImplementors(this Type abstractType, params Assembly[] assembliesToSearch)\n{\n var implementors = abstractType.GetImplementors(assembliesToSearch);\n return implementors.Where(IsInstantiable);\n}\n\n/// <summary>\n/// Determines whether <paramref name="type"/> is a concrete, non-open-generic type.\n/// </summary>\npublic static bool IsInstantiable(this Type type)\n{\n return !(type.IsAbstract || type.IsGenericTypeDefinition || type.IsInterface);\n}\n</code></pre>\n\n<h3>Examples</h3>\n\n<p>To get the instantiable implementors in the calling assembly:</p>\n\n<pre><code>var callingAssembly = Assembly.GetCallingAssembly();\nvar httpModules = typeof(IHttpModule).GetInstantiableImplementors(callingAssembly);\n</code></pre>\n\n<p>To get the implementors in the current AppDomain:</p>\n\n<pre><code>var appDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();\nvar httpModules = typeof(IHttpModule).GetImplementors(appDomainAssemblies);\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,258 | <p>What is the order of topics to explain to a .NET developer or user group to get them started and interested with alt.net tools and practices.</p>
<ul>
<li>ORM</li>
<li>IoC</li>
<li>TDD</li>
<li>DDD</li>
<li>DSL</li>
<li>CI</li>
<li>MVC - MVP</li>
<li>Version Control (I think this is the one they get the fastest)</li>
<li>Agile</li>
<li>Etc, etc...</li>
</ul>
| [{'answer_id': 80358, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 3, 'selected': False, 'text': '<p>ALT.NET is more of an attitude than a set of tools and practices. </p>\n\n<p>I don\'t know that you can "get someone started with ALT.NET," per se.</p>\n\n<hr>\n\n<p>To me it is an attitude born of experience, not something you can put on like a coat. But that is <em>my</em> opinion, subject to change.</p>\n'}, {'answer_id': 80363, 'author': 'Jeremy McGee', 'author_id': 3546, 'author_profile': 'https://Stackoverflow.com/users/3546', 'pm_score': 3, 'selected': True, 'text': "<p>The essential principles to drive home are:</p>\n\n<ul>\n<li>Microsoft tools are a good place to start, but it's possible to write better software faster by using other companion products</li>\n<li>Change is good, so always think about ways that code can be changed and verified quickly</li>\n<li>If it isn't tested, it's not production quality</li>\n</ul>\n\n<p>Then, after version control (!), I'd start with continuous integration, and show how getting immediate feedback on the quality of a build can help improve quality from the first moment. Doing CI first doesn't change the codebase.</p>\n\n<p>Then I'd introduce automated end-to-end testing of the application with FitNesse, Watin or somesuch. This should then illustrate how refactoring code isn't something to be afraid of if you have good testing tools that will verify that the code still works.</p>\n\n<p>Then I'd do gentle refactoring to break out business logic and domain objects from the UI (if they're not there already) and introduce unit testing. This further shows how refactoring is a good thing.</p>\n\n<p>As we aim to get some sort of seperation of concerns, design patterns (such as IoC) will naturally start to become apparent. It's also going to be obvious that we can replace the data layer with ORM.</p>\n\n<p>As we refactor, I'd also show how test-driven development can actually speed creation of better code. This is probably easiest shown for the first time with new development, as otherwise it's quite a culture shock!</p>\n"}, {'answer_id': 86210, 'author': 'Yitzchok', 'author_id': 5723, 'author_profile': 'https://Stackoverflow.com/users/5723', 'pm_score': 0, 'selected': False, 'text': "<p>I don't mean becoming an <em>ALT.NETter</em> just in a way of letting them know that the stuff are out there but in a way that they can understand it and feel that it can help them.</p>\n"}, {'answer_id': 86450, 'author': 'Pragmatic Agilist', 'author_id': 15971, 'author_profile': 'https://Stackoverflow.com/users/15971', 'pm_score': 2, 'selected': False, 'text': "<p>I think it depends on the individual or group. Almost all shops have some exposure to one of these concepts. From there, I would introduce new concepts only as fast as you think the developer or team can absorb them. It's quite depressing to see teams start rejecting some of the important principles and concepts because they are over-loaded. And try not to <em>assume</em> someone understands the principles behind using CI, IoC, or mocking frameworks. </p>\n"}, {'answer_id': 86737, 'author': 'Yitzchok', 'author_id': 5723, 'author_profile': 'https://Stackoverflow.com/users/5723', 'pm_score': 0, 'selected': False, 'text': "<p>I think a lot of people don't know about Generics, delegates, Linq and Lambda expressions.<br>\nIf you will tell then all at about the same time then they will just drop everything. </p>\n\n<p>Like you wouldn't teach a beginner programmer whats a DSL but you can let him know about SVN.</p>\n"}, {'answer_id': 344435, 'author': 'Mike Henry', 'author_id': 14934, 'author_profile': 'https://Stackoverflow.com/users/14934', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="http://altnetpodcast.com/" rel="nofollow noreferrer">Alt.NET Podcast</a> may be a good place to get some ideas. They have podcasts on continuous improvement, agile, DI/IoC, ORM, OOP w/ Ruby, etc. (in that order).</p>\n'}, {'answer_id': 2008199, 'author': 'Lee Warner', 'author_id': 135148, 'author_profile': 'https://Stackoverflow.com/users/135148', 'pm_score': 0, 'selected': False, 'text': "<p>For me it was a colleague who championed IoC/DI and TDD. He also got me going to .net user groups so I could see that he wasn't just a one-off crazy guy who loved using new and strange technologies for the sake of using them.</p>\n"}, {'answer_id': 46253974, 'author': 'ryanwebjackson', 'author_id': 2125723, 'author_profile': 'https://Stackoverflow.com/users/2125723', 'pm_score': 0, 'selected': False, 'text': "<p>I would build a Web application using Nancy with C# (or Boo, Iron*, other language) using SharpDevelop (there is a book on this) or Rider (JetBrains' C# IDE). I view Alt.NET as non-Microsoft .net development, specifically focused on open source, and sometimes out-of-the-box thinking. There is a conference .NET Fringe in Portland Oregon every year now, that caters to this attitude toward development. </p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5723/'] |
80,278 | <p>I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:</p>
<pre><code><cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
</code></pre>
<p>where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.</p>
<p>If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.</p>
<p>Lawrence</p>
<p>Using CF 8.01, Dreamweaver 8</p>
<hr>
<p>Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.</p>
<p>I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution.</p>
| [{'answer_id': 80298, 'author': 'convex hull', 'author_id': 10747, 'author_profile': 'https://Stackoverflow.com/users/10747', 'pm_score': 0, 'selected': False, 'text': "<p>Maybe the layout area doesn't have the right <strong>style</strong>. I think you may have to give the map_canvas a</p>\n\n<pre><code>position: absolute\n</code></pre>\n\n<p>or </p>\n\n<pre><code>position: relative\n</code></pre>\n\n<p>That's just a hunch.</p>\n"}, {'answer_id': 82887, 'author': 'Adam Tuttle', 'author_id': 751, 'author_profile': 'https://Stackoverflow.com/users/751', 'pm_score': 0, 'selected': False, 'text': '<p>CFLayoutArea is a new AJAX tag added with ColdFusion version 8. (In addition to tags like CFWindow, CFDiv, etc.)</p>\n\n<p>Within the AJAX-loaded content of any of these new tags, external JavaScript must be included from the containing page. In your case, that would be the page that includes the <cflayout> tag.</p>\n\n<p>Try something like this:</p>\n\n<p>in index.cfm (or whatever your containing file is):</p>\n\n<pre><code><script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx" type="text/javascript">\n function getMap(lat,lng){ \n if (GBrowserIsCompatible()) { \n var map = new GMap2(document.getElementById("map_canvas"));\n var pt= new GLatLng(lat,lng);\n map.setCenter(pt, 18,G_HYBRID_MAP); \n map.addOverlay(new GMarker(pt));\n } \n }\n</script>\n<cflayout>...</cflayout>\n</code></pre>\n\n<p>map.cfm (content of your map CFLayout tab):</p>\n\n<pre><code><cfif structKeyExists(url, "lat")>\n <cfset variables.lat = url.lat />\n <cfset variables.lng = url.lng />\n</cfif> \n<head></head> \n<cfoutput>\n <body onLoad="getMap(#variables.lat#,#variables.lng#)" onUnload="GUnload()">\n Map:<br>\n <div id="map_canvas" style="width: 500px; height: 300px"/>\n </body>\n</cfoutput>\n</code></pre>\n'}, {'answer_id': 100406, 'author': 'lawrencem49', 'author_id': 15007, 'author_profile': 'https://Stackoverflow.com/users/15007', 'pm_score': 2, 'selected': True, 'text': '<p>Success! (sort of...)</p>\n\n<p>Finally got it working, but not in the way Adam suggested:</p>\n\n<pre><code><script src= "http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx" type="text/javascript"></script>\n<script type="text/javascript">\n getMap=function(lat,lng){ \n if (GBrowserIsCompatible()){\n var map = new GMap2(document.getElementById("map_canvas"));\n var pt = new GLatLng(lat,lng);\n map.setCenter(pt, 18,G_HYBRID_MAP); \n map.addOverlay(new GMarker(pt)); \n } \n }\n</script> \n\n <cflayout name="testlayout" type="border">\n <cflayoutarea name="left" position="left" size="250"/>\n <cflayoutarea name="center" position="center"> \n <!--- sample hard-coded co-ordinates --->\n <body onLoad="getMap(22.280161,114.185096)">\n Map:<br />\n <div id="map_canvas" style="width:500px; height: 300px"/>\n </body>\n </cflayoutarea> \n<!--- <cflayoutarea name="center" position="center" source="map_content.cfm?lat=22.280161&lng=114.185096"/> --->\n</cflayout> \n</code></pre>\n\n<p>The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam\'s exmaple), it results in an undefined map, ie a map object is created but with nothing in it.</p>\n\n<p>So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container? </p>\n'}, {'answer_id': 101544, 'author': 'Adam Tuttle', 'author_id': 751, 'author_profile': 'https://Stackoverflow.com/users/751', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n <p>So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container?</p>\n</blockquote>\n\n<p>It should be possible reference an element loaded via AJAX -- just not until the element is on screen (so not on page load). It looks like getMap() triggers everything. (Is that right?)</p>\n\n<p>Try this: Take exactly what you have as your inline-content for the map tab, and make it the content of map_content.cfm; <strong>then</strong> instead of using body onload to fire the event, write it inline, after the div is defined:</p>\n\n<pre><code><body>\n Map:<br />\n <div id="map_canvas" style="width:500px; height: 300px"/>\n <script type="text/javascript">\n getMap(22.280161,114.185096);\n </script>\n</body>\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15007/'] |
80,284 | <p>Are there any good tools to generate JavaScript? I remember in .NET, there was Script# - don't know its status today. </p>
<p>Anyone have experience with any tools? </p>
| [{'answer_id': 80309, 'author': 'gizmo', 'author_id': 9396, 'author_profile': 'https://Stackoverflow.com/users/9396', 'pm_score': 0, 'selected': False, 'text': '<p>There is currently a lot of tools to generate JavaScript, like GWT.</p>\n\n<p>But giving you a good answer really depends on what is your originator language and what king of JavaScript functionnality you want to use.</p>\n'}, {'answer_id': 80310, 'author': 'Eric Schoonover', 'author_id': 3957, 'author_profile': 'https://Stackoverflow.com/users/3957', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://projects.nikhilk.net/ScriptSharp/" rel="nofollow noreferrer">Latest version of Script#</a> was posted less than a month ago. Nikhil continues to actively work on that project and it\'s a very good tool for generating JavaScript code from C#. It is actively used in a couple of different internal Microsoft projects.</p>\n\n<p>Some of the benefits of Script# are:</p>\n\n<ul>\n<li>Intellisense</li>\n<li>Build errors at compile time</li>\n<li>Refactoring support</li>\n<li>Documentation support</li>\n<li>FxCop code analysis</li>\n<li>MSBuild support</li>\n</ul>\n'}, {'answer_id': 80314, 'author': 'dmazzoni', 'author_id': 7193, 'author_profile': 'https://Stackoverflow.com/users/7193', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">Google Web Toolkit</a> is one option. Write Java code, debug it with a standard Java debugger, then press the "Compile" button and turn it into highly-optimized JavaScript. It generates completely separate JavaScript for each major browser family (IE, Firefox, Safari, etc.).</p>\n\n<p>Very mature, very powerful, and easy to embed into an existing site. One downside is that the UIs it creates are ugly nested tables.</p>\n'}, {'answer_id': 80329, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 2, 'selected': False, 'text': '<p>I use my keyboard, a text editor and my brain to generate JavaScript.</p>\n\n<p>:P</p>\n'}, {'answer_id': 80359, 'author': 'BCS', 'author_id': 1343, 'author_profile': 'https://Stackoverflow.com/users/1343', 'pm_score': 0, 'selected': False, 'text': "<p>I've used D templates (think C++ without the pain and you'll be 50% there) to generate a AJAX based Object proxy.</p>\n"}, {'answer_id': 80618, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 2, 'selected': False, 'text': '<p>As others have said, <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">GWT</a> is a very good option. To summarize some good points:</p>\n\n<ul>\n<li><strong>fast, very portable code</strong> using deferred binding; only loads the code that works on the user\'s browser, and only loads functions that are actually called; also, they\'re compressed</li>\n<li><strong>reliability</strong>; very few known issues</li>\n<li><strong>easier debugging</strong> using a Java-based IDE; you can also look directly at un-obfuscated javascript if you want to, but it seems (based on some reports I\'ve seen & personal experience) that you basically never need this</li>\n<li><strong>good library support</strong> including a nice inline javascript interface, the ability to use existing Java libraries, and special support for ajax / rpc calls</li>\n<li><strong>extensible & stylistically flexible</strong>; you can fine-tune all styles with your own css rules, and extend the Widget base with your own Java subclasses</li>\n</ul>\n\n<p>So I humbly disagree with dominic that the results are ugly since it is up to the coder to \'prettify\' the basic functionality with their own css rules and other decorations. It would be the same mistake to call HTML \'ugly\' - if you don\'t try hard, it isn\'t pretty, but the power and flexibility is in the hands of the coder.</p>\n\n<p>Oh, and it\'s open source, too.</p>\n'}, {'answer_id': 86591, 'author': 'tomdemuyt', 'author_id': 7602, 'author_profile': 'https://Stackoverflow.com/users/7602', 'pm_score': 0, 'selected': False, 'text': '<p>Try <a href="http://haxe.org/" rel="nofollow noreferrer">Haxe</a>. </p>\n\n<p>It can target JavaScript, ActionScript and Neko bytecode. The language is close to Java.</p>\n'}, {'answer_id': 5927317, 'author': 'Maciek Sawicki', 'author_id': 201306, 'author_profile': 'https://Stackoverflow.com/users/201306', 'pm_score': 1, 'selected': False, 'text': '<p>Nice list: <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS" rel="nofollow">https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS</a></p>\n'}, {'answer_id': 17924363, 'author': 'OlliP', 'author_id': 1537246, 'author_profile': 'https://Stackoverflow.com/users/1537246', 'pm_score': 0, 'selected': False, 'text': '<p>Kotlin can generate JavaScript out of Kotlin code. For Kotlin see <a href="http://kotlin.jetbrains.org/" rel="nofollow">http://kotlin.jetbrains.org/</a> and also <a href="http://devnet.jetbrains.com/thread/447468?tstart=0" rel="nofollow">http://devnet.jetbrains.com/thread/447468?tstart=0</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9087/'] |
80,287 | <p>I can get easily see what projects and dlls a single project references from within a Visual Studio .NET project.</p>
<p>Is there any application or use of reflection that can build me a full dependency tree that I can use to plot a graphical chart of dependencies?</p>
| [{'answer_id': 80303, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 3, 'selected': True, 'text': '<p>In addition to NDepend, you can also try this addin for <a href="http://www.codeplex.com/reflectoraddins/Wiki/View.aspx?title=Graph&referringTitle=Home" rel="nofollow noreferrer">Reflector</a> for showing assembly dependency graph.</p>\n'}, {'answer_id': 308289, 'author': 'Patrick from NDepend team', 'author_id': 27194, 'author_profile': 'https://Stackoverflow.com/users/27194', 'pm_score': 3, 'selected': False, 'text': '<p>NDepend comes with an interactive dependency graph coupled with a dependency matrix. You can <a href="http://www.ndepend.com/NDependDownload.aspx" rel="noreferrer">download and use the free trial edition</a> of NDepend for a while.</p>\n\n<p><a href="http://www.ndepend.com/Doc_VS_Arch.aspx" rel="noreferrer">More on NDepend Dependency Graph</a>\n<img src="https://i.stack.imgur.com/D3cYI.png" alt="enter image description here"></p>\n\n<p><a href="http://www.ndepend.com/Doc_Matrix.aspx" rel="noreferrer">More on NDepend Dependency Matrix</a>:\n<img src="https://i.stack.imgur.com/zVHhe.png" alt="enter image description here"></p>\n\n<p><em>Disclaimer: I am part of the tool team</em></p>\n'}, {'answer_id': 2293365, 'author': 'Esther Fan - MSFT', 'author_id': 275715, 'author_profile': 'https://Stackoverflow.com/users/275715', 'pm_score': 2, 'selected': False, 'text': '<p>You can create a dependency graph of projects and assemblies in Visual Studio 2010 Ultimate by using Architecture Explorer to browse your solution, select projects and the relationships that you want to visualize, and then create a dependency graph from your selection.</p>\n\n<p>For more info, see the following topics:</p>\n\n<p><strong>How to: Generate Graph Documents from Code</strong>: <a href="http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource</a></p>\n\n<p><strong>How to: Find Code Using Architecture Explorer</strong>: <a href="http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx</a></p>\n\n<p><strong>RC download</strong>: <a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a</a>.</p>\n\n<p><strong>Visual Studio 2010 Architectural Discovery & Modeling Tools</strong> forum: <a href="http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads</a></p>\n'}, {'answer_id': 2295631, 'author': 'Chris Chedgey - Structure101', 'author_id': 181065, 'author_profile': 'https://Stackoverflow.com/users/181065', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.headwaysoftware.com/products/structure101/index.php" rel="nofollow noreferrer">Structure101</a> can do that. You can browse a model by assembly and/or namespace, and clicking on any dependency at any level give you all the code-level references that cause the dependency. The .NET version is in beta, but it\'s been available for other languages for years, so it\'s very mature. Here\'s an example screen shot. \n<a href="http://www.headwaysoftware.com/images/assemblies.jpg" rel="nofollow noreferrer">alt text http://www.headwaysoftware.com/images/assemblies.jpg</a></p>\n'}, {'answer_id': 10472374, 'author': 'Danny Tuppeny', 'author_id': 25124, 'author_profile': 'https://Stackoverflow.com/users/25124', 'pm_score': 3, 'selected': False, 'text': '<p>I needed something similar, but didn\'t want to pay for (or install) a tool to do it. I <a href="https://blog.dantup.com/2012/05/free-dependency-graph-generation-using-powershell-and-yuml/" rel="nofollow noreferrer">created a quick PowerShell script that goes through the project references</a> and spits them out in a <a href="https://yuml.me/" rel="nofollow noreferrer">yuml.me</a> friendly-format instead:</p>\n<pre><code>Function Get-ProjectReferences ($rootFolder)\n{\n $projectFiles = Get-ChildItem $rootFolder -Filter *.csproj -Recurse\n $ns = @{ defaultNamespace = "http://schemas.microsoft.com/developer/msbuild/2003" }\n\n $projectFiles | ForEach-Object {\n $projectFile = $_ | Select-Object -ExpandProperty FullName\n $projectName = $_ | Select-Object -ExpandProperty BaseName\n $projectXml = [xml](Get-Content $projectFile)\n \n $projectReferences = $projectXml | Select-Xml \'//defaultNamespace:ProjectReference/defaultNamespace:Name\' -Namespace $ns | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty "#text"\n \n $projectReferences | ForEach-Object {\n "[" + $projectName + "] -> [" + $_ + "]"\n }\n }\n}\n\nGet-ProjectReferences "C:\\Users\\DanTup\\Documents\\MyProject" | Out-File "C:\\Users\\DanTup\\Documents\\MyProject\\References.txt"\n</code></pre>\n<p><a href="https://i.stack.imgur.com/PH5br.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PH5br.png" alt="Sample Graph" /></a><br />\n<sub>(source: <a href="https://yuml.me/4f30e632" rel="nofollow noreferrer">yuml.me</a>)</sub></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302/'] |
80,291 | <p>In Sql Server 2000/2005, I have a few NT user groups that need to be granted access to hundreds of stored procedures.</p>
<p>Is there a nice easy way to do that?</p>
| [{'answer_id': 80340, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 2, 'selected': False, 'text': '<ul>\n<li>Create a role in sql server.</li>\n<li>Write a\nscript that grants that role\npermission to use those sprocs.</li>\n<li>Add those NT user groups to that role.</li>\n</ul>\n'}, {'answer_id': 83079, 'author': 'Paul G', 'author_id': 162, 'author_profile': 'https://Stackoverflow.com/users/162', 'pm_score': 2, 'selected': True, 'text': "<p>Here's a script that I use for granting permissions to lots of procedures:</p>\n\n<pre><code>DECLARE @DB sysname ; set @DB = DB_NAME()\nDECLARE @U sysname ; set @U = QUOTENAME('UserID')\n\nDECLARE @ID integer,\n @LAST_ID integer,\n @NAME varchar(1000),\n @SQL varchar(4000)\n\nSET @LAST_ID = 0\n\nWHILE @LAST_ID IS NOT NULL\nBEGIN\n SELECT @ID = MIN(id)\n FROM dbo.sysobjects\n WHERE id > @LAST_ID AND type = 'P' AND category = 0\n\n SET @LAST_ID = @ID\n\n -- We have a record so go get the name\n IF @ID IS NOT NULL\n BEGIN\n SELECT @NAME = name\n FROM dbo.sysobjects\n WHERE id = @ID\n\n -- Build the DCL to do the GRANT\n SET @SQL = 'GRANT EXECUTE ON ' + @NAME + ' TO ' + @U\n\n -- Run the SQL Statement you just generated\n EXEC master.dbo.xp_execresultset @SQL, @DB\n\n END \nEND\n</code></pre>\n\n<p>You can modify the select to get to a more specific group of stored procs.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3276/'] |
80,292 | <p>I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the <code>num_rows()</code> method from the <code>mysqli_statement</code> class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the <code>num_rows()</code> method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:</p>
<pre><code>$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
</code></pre>
<p>The expected result is:</p>
<pre><code>1name
</code></pre>
<p>And the actual result is:</p>
<pre><code>0name
</code></pre>
<p>Can anyone tell me why this is?</p>
| [{'answer_id': 80382, 'author': 'Cetra', 'author_id': 15087, 'author_profile': 'https://Stackoverflow.com/users/15087', 'pm_score': -1, 'selected': False, 'text': '<p>It doesn\'t look like you\'ve declared $name.</p>\n\n<p>Also, try removing bind_result() and fetch() so it reads something like this:</p>\n\n<pre><code>$statement->execute();\n\n$statement->store_result();\n\nprintf("Number of rows: %d.\\n", $statement->num_rows);\n</code></pre>\n'}, {'answer_id': 80400, 'author': 'Nathan Strong', 'author_id': 9780, 'author_profile': 'https://Stackoverflow.com/users/9780', 'pm_score': 4, 'selected': True, 'text': '<p>I wonder if num_rows() is reporting relative to the current resultset. Try capturing num_rows() prior to fetching the data. e.g.</p>\n\n<pre><code>if($statement->prepare($query))\n{\n $statement->execute();\n $statement->store_result();\n echo $statement->num_rows();\n $statement->bind_result($name);\n $statement->fetch();\n echo $name; \n}\n</code></pre>\n\n<p>Does that have any effect?</p>\n'}, {'answer_id': 624630, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p><code>num_rows</code> is not a method, it's a property.</p>\n"}, {'answer_id': 66500988, 'author': 'Dharman', 'author_id': 1839439, 'author_profile': 'https://Stackoverflow.com/users/1839439', 'pm_score': 0, 'selected': False, 'text': "<p>In order to be able to use <code>mysqli_stmt::num_rows(),</code> you need to fetch all rows into PHP. There are two ways to fetch everything: buffering using <code>store_result()</code> or manual fetching of all rows using <code>fetch()</code>.</p>\n<p>In your case, you have started manual fetching by calling <code>fetch()</code> once. You can't call <code>store_result()</code> when another fetch process is ongoing. The call to <code>store_result()</code> fails with an error*.</p>\n<pre><code>$statement->fetch();\n$statement->store_result(); // produces error. See $mysqli->error;\necho $statement->num_rows();\n</code></pre>\n<p>The easiest solution is to swap the order in which you call these two methods.</p>\n<pre><code>$statement->store_result();\n$statement->fetch(); // This will initiate fetching from PHP buffer instead of MySQL buffer\necho $statement->num_rows(); // This will tell you the total number of rows fetched to PHP\n</code></pre>\n<p><sub>* Due to a bug in PHP, this error will not trigger an exception in the exception error reporting mode. The error message can only be seen with <code>mysqli_error()</code> function or its corresponding property.</sub></p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3831/'] |
80,305 | <p>We are developing a Visual Basic 6.0 project. We have written a library, which we were testing using vbunit and vbmock. But soon found that the tests were not maintainable. So, we decided to write tests using MBunit. Now, we want to know the test coverage. How can we do it?
thanks</p>
| [{'answer_id': 80324, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': 0, 'selected': False, 'text': '<p>Look into NCover</p>\n'}, {'answer_id': 1556464, 'author': 'Ira Baxter', 'author_id': 120163, 'author_profile': 'https://Stackoverflow.com/users/120163', 'pm_score': 2, 'selected': False, 'text': '<p>The only VB6 test coverage tool I know is <a href="http://www.aivosto.com/vbwatch.html" rel="nofollow noreferrer">http://www.aivosto.com/vbwatch.html</a> Aivisto seems to have a generally good reputation for their VB tools.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9087/'] |
80,307 | <p>I've read in a couple of places that the desktop wallpaper can be set to an HTML document. Has anyone had any success changing it programmatically? </p>
<p>The following snippet of VB6 helps me set things up for BMPs but when I try to use it for HTML, I get a nice blue background and nothing else.</p>
<pre><code>Dim reg As New StdRegistry
Public Function CurrentWallpaper() As String
CurrentWallpaper = reg.ValueEx(HKEY_CURRENT_USER, "Control Panel\Desktop", "Wallpaper", REG_SZ, "")
End Function
Public Sub SetWallpaper(cFilename As Variant)
reg.ClassKey = HKEY_CURRENT_USER
reg.SectionKey = "Control Panel\Desktop"
reg.ValueKey = "Wallpaper"
reg.ValueType = REG_SZ
reg.Default = ""
reg.Value = cFilename
End Sub
Public Sub RefreshDesktop()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
End Sub
</code></pre>
<p>Perhaps there's some other setting that's required. Any ideas?</p>
| [{'answer_id': 80334, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 2, 'selected': False, 'text': '<p>I think you need to make sure "Active Desktop" is turned on.</p>\n\n<p>You might try setting <code>HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\ForceActiveDesktopOn</code> to <code>1</code> (found <a href="http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/93205.mspx?mfr=true" rel="nofollow noreferrer">here</a>).</p>\n\n<p>I haven\'t tried it, so no guarantees.</p>\n'}, {'answer_id': 83921, 'author': 'bugmagnet', 'author_id': 426, 'author_profile': 'https://Stackoverflow.com/users/426', 'pm_score': 0, 'selected': False, 'text': '<p>Getting closer: <a href="http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w2rkbook/gp.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w2rkbook/gp.mspx?mfr=true</a>\n<hr />\nBut it turns out that I was getting sidetracked in Policy space. What I really wanted was to set the desktop in the userspace and let the Policy settings stand. Some helpful stuff was found here: <a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/912569.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/coding4fun/archive/2006/10/31/912569.aspx</a>. </p>\n\n<p>This isn\'t the final solution, however. The control of HTML desktops is still out of reach.\n<hr />\nSeems that HTML settings are stored in HKCU\\Software\\Microsoft\\Internet Explorer\\Desktop\\General. However, just storing them here doesn\'t seem to be enough. I still need to find the mechanism that lets Windows know which set of registry values to use.</p>\n'}, {'answer_id': 84359, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I recomend only BMP format. Do not use ActiveDesctop, because you PC will work slowly after that.</p>\n'}, {'answer_id': 84489, 'author': 'Matt', 'author_id': 2338, 'author_profile': 'https://Stackoverflow.com/users/2338', 'pm_score': 2, 'selected': True, 'text': '<p>I\'m not sure if there\'s an official API for this, but if you have your heart set on it you could use Sysinternal\'s <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">Process Monitor</a> and see what registry keys get touched when you set an HTML desktop background via the UI. Then you\'d just need to repeat those edits in your code. However, an API call would be far preferable in terms of backward/forward compatibility.</p>\n'}, {'answer_id': 89333, 'author': 'bugmagnet', 'author_id': 426, 'author_profile': 'https://Stackoverflow.com/users/426', 'pm_score': 2, 'selected': False, 'text': '<p>Okay, I\'ve discovered the answer to my question, thanks to egl1044 on <a href="http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Windows/XP/Q_23739345.html" rel="nofollow noreferrer">Experts Exchange</a>. Essentially, one must talk to the IActiveDesktop object. A good implementation of that, in VB6, can be found at <a href="http://www.vbforums.com/showthread.php?t=367342" rel="nofollow noreferrer">VB6 - JPEGs as wallpapers (without conversion)</a>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426/'] |
80,313 | <p>How do I preview a url using ajax? I have seen this done with search engine plug ins and would like to learn how to do this. Specifically, I would like to be able to mouse over a link and see the preview of the webpage using ajax.</p>
| [{'answer_id': 80346, 'author': 'Patrick McKenzie', 'author_id': 15046, 'author_profile': 'https://Stackoverflow.com/users/15046', 'pm_score': 3, 'selected': True, 'text': '<p>There\'s the <strong>easy</strong> solution, the <strong>hard</strong> solution, and the <strong>use-a-library</strong> solution.</p>\n\n<p><strong>use-a-library</strong> : I prefer always doing the use-a-library solution unless you have a darn good reason otherwise. One possible site which wraps the "hard solution" as a service for you: <a href="http://thumbnails.iwebtool.com/demo/" rel="nofollow noreferrer">http://thumbnails.iwebtool.com/demo/</a></p>\n\n<p><strong>easy</strong>: The easy solution is to just load the target webpage as a downscaled AJAXy window. You can use many of the Lightbox-class plugins for this task, particularly the ones which allow you to target arbitrary HTTP content for the Lightbox window. <a href="http://www.orangoo.com/labs/GreyBox/" rel="nofollow noreferrer">GreyBox</a> is my favorite of those which I have used before. <a href="http://particletree.com/features/lightbox-gone-wild/" rel="nofollow noreferrer">Lightbox Gone Wild</a> is also nice.</p>\n\n<p><strong>hard</strong>: Then there is the hard solution: you need to render the web page server side, cache the rendering as an image, and then serve up that image using Lightbox-esque Javascript (which is trivial next to the other requirements). How you would go about doing this is outside the scope of this box. Why would you do it this way? The preview generates MUCH faster for the client, and it hermetically seals the client\'s session away from things which might bust it in the target website -- poorly behaving Javascript and/or malware can cause Really Bad Things when you open them, even in an AJAXy window-within-a-window.</p>\n'}, {'answer_id': 80355, 'author': 'Christopher Mahan', 'author_id': 479, 'author_profile': 'https://Stackoverflow.com/users/479', 'pm_score': 0, 'selected': False, 'text': '<p>I think I know what he\'s driving at. What happens is that he wants a windows to appear on hover over a hyperlink (javascript), and for that windows to display a snapshot image of the website being referenced by the hyperlink.</p>\n\n<p>The ajax part connects to the server where you are hosting your site, asynchronously, and hits a page that goes and fetches an image of the site to display in a img tag.</p>\n\n<p>Now, how does one generate the image of the site? I would suggest that this is done in advance (for example as the content is being created) and that already-generated image is recalled. </p>\n\n<p>How to generate the images to begin with? I think that would be another question: "How to generate snapshot images of websites?"</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15059/'] |
80,319 | <p>I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.</p>
<p>What would be the best approach?</p>
| [{'answer_id': 80366, 'author': 'Mladen Mihajlovic', 'author_id': 11421, 'author_profile': 'https://Stackoverflow.com/users/11421', 'pm_score': 2, 'selected': False, 'text': "<p>Something like this?</p>\n\n<pre><code>$vals = explode(':', $duration);\n\nif ( $vals[0] == 0 )\n $result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';\nelse\n $result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';\n</code></pre>\n"}, {'answer_id': 80380, 'author': 'paan', 'author_id': 2976, 'author_profile': 'https://Stackoverflow.com/users/2976', 'pm_score': 3, 'selected': True, 'text': "<p>try using split </p>\n\n<pre><code>list($hh,$mm,$ss)= split(':',$duration);\n</code></pre>\n"}, {'answer_id': 80389, 'author': 'Mladen Mihajlovic', 'author_id': 11421, 'author_profile': 'https://Stackoverflow.com/users/11421', 'pm_score': 1, 'selected': False, 'text': '<p>One little change could be:</p>\n\n<pre><code>$vals = explode(\':\', $duration);\n\nif ( $vals[0] == 0 )\n $result = "{$vals[1]} minutes, {$vals[2]} seconds";\nelse\n $result = "{$vals[0]} hours, {$vals[1]} minutes, {$vals[2]} seconds";\n</code></pre>\n'}, {'answer_id': 80395, 'author': 'Garrett Albright', 'author_id': 11023, 'author_profile': 'https://Stackoverflow.com/users/11023', 'pm_score': -1, 'selected': False, 'text': '<p>explode() is for pansies. This is a job for <a href="http://regular-expressions.info" rel="nofollow noreferrer">regular expressions</a>!</p>\n\n<pre><code><?php\npreg_match(\'/^(\\d\\d):(\\d\\d):(\\d\\d)$/\', $video_duration, $parts);\nif ($parts[1] !== \'00\') {\n echo("{$parts[1]} hours, {$parts[2]} minutes, {$parts[3]} seconds");\n}\nelse {\n echo("{$parts[2]} minutes, {$parts[3]} seconds");\n}\n</code></pre>\n\n<p>Totally untested, but something like that ought to work. Note that this code assumes that the hour fragment will <em>always</em> be two digits (eg, a three-hour video would be <code>03:00:00</code> instead of <code>3:00:00</code>).</p>\n\n<p><strong>EDIT:</strong> In retrospect, using regular expressions for this is probably a case of over-engineering; explode() will do the job just as well and probably even be faster in this case. But it was the first method to come to mind when I read the question.</p>\n'}, {'answer_id': 80442, 'author': 'Nathan Strong', 'author_id': 9780, 'author_profile': 'https://Stackoverflow.com/users/9780', 'pm_score': 1, 'selected': False, 'text': '<p>Pretty simple:</p>\n\n<pre><code>list( $h, $m, $s) = explode(\':\', $hms);\necho ($h ? "$h hours, " : "").($m ? "$m minutes, " : "").(($h || $m) ? "and " : "")."$s seconds";\n</code></pre>\n\n<p>This will only display the hours or minutes if there are any, and inserts an "and" before the seconds if there are hours, minutes, or both to display. If you wanted to get really fancy, you could add some code to display "hour" vs. "hours" as appropriate, ditto for minutes and seconds.</p>\n'}, {'answer_id': 80459, 'author': 'Steve Obbayi', 'author_id': 11190, 'author_profile': 'https://Stackoverflow.com/users/11190', 'pm_score': 0, 'selected': False, 'text': '<p>Heres a different way, with different functions which is more open and a more step by step for newbies. it also handles the 1 hour and many hours... you could try use the same logic to handle the 0 minutes and 0 seconds.</p>\n\n<pre><code><?php\n// your time\n$var = "00:00:00";\n\nif(substr($var, 0, 2) == 0){\n $myTime = substr_replace(substr_replace($var, \'\', 0, 3), \' Minutes, \', 2, 1);\n}\nelseif(substr($var, 1, 1) == 1){\n$myTime = substr_replace(substr_replace($var, \' Hour, \', 2, 1), \' Minutes, \', 11, 1); \n }\nelse{\n$myTime = substr_replace(substr_replace($var, \' Hours, \', 2, 1), \' Minutes, \', 12, 1);\n}\n// work with your variable\necho $myTime .\' Seconds\';\n\n?>\n</code></pre>\n'}, {'answer_id': 80704, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>If you really want to use a built-in function, perhaps for robustness, you can try </p>\n\n<pre><code> date_default_timezone_set('UTC'); \n $date = strtotime($hms,0); \n</code></pre>\n\n<p>and use any of the date formatting functions (<code>date()</code>, <code>strftime()</code>, etc) to format the time in any way you wish. Or you can use the output of <code>strptime($hms,'%T')</code>. Either may be overkill for the simple scenario you have.</p>\n"}, {'answer_id': 80776, 'author': 'Curtis Lassam', 'author_id': 9337, 'author_profile': 'https://Stackoverflow.com/users/9337', 'pm_score': -1, 'selected': False, 'text': '<p>Converting 00:00:00 to hours, minutes, and seconds in PHP is really easy.</p>\n\n<p>$hours = 0; \n$minutes = 0;\n$seconds = 0; </p>\n'}, {'answer_id': 80981, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I'll reply with a different approach of the problem. My approach is to store the lengths in seconds. Then depending the needs, it's easy to render these seconds as hh:mm:ss by using :</p>\n\n<p><code>print gmdate($seconds >= 3600 ? 'H:i:s' : 'i:s', $seconds);</code> (for your question)</p>\n\n<p>or to search on the length in a database:</p>\n\n<p><code>SELECT * FROM videos WHERE length > 300;</code> for example, to search for video with a length higher than 5 minutes.</p>\n"}, {'answer_id': 83497, 'author': 'enobrev', 'author_id': 14651, 'author_profile': 'https://Stackoverflow.com/users/14651', 'pm_score': 1, 'selected': False, 'text': "<p>Why bother with regex or explodes when php handles time just fine?</p>\n\n<pre><code>$sTime = '04:20:00';\n$oTime = new DateTime($sTime);\n$aOutput = array();\nif ($oTime->format('G') > 0) {\n $aOutput[] = $oTime->format('G') . ' hours';\n}\n$aOutput[] = $oTime->format('i') . ' minutes';\n$aOutput[] = $oTime->format('s') . ' seconds';\necho implode(', ', $aOutput);\n</code></pre>\n\n<p>The benefit is that you can reformat the time however you like (including am/pm, adjustments for timezone, addition / subtraction, etc).</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,320 | <p>Poppler is a classic example of something without documentation that you would prefer be documented. This question is language agnostic, just asking about the general idea..
In short, how do you make a PDF viewer control with poppler?<br>
From what I can tell, you'd need to use poppler to render it to some surface, which sounds good up until you ask yourself how the user would select text and such. Does poppler offer a window for its various bindings, or do you have to code it all yourself?</p>
| [{'answer_id': 80373, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 2, 'selected': True, 'text': '<p>You have to code it all yourself -- Poppler only handles the PDF part, you have to write the GUI. Look at the code to <a href="http://www.gnome.org/projects/evince/" rel="nofollow noreferrer">Evince</a> for a good example. </p>\n'}, {'answer_id': 1722023, 'author': 'BastiBen', 'author_id': 195347, 'author_profile': 'https://Stackoverflow.com/users/195347', 'pm_score': 1, 'selected': False, 'text': '<p>The poppler release downloads now contain a Qt4 wrapper and some examples that you can take a look at.</p>\n'}, {'answer_id': 12053665, 'author': 'CantGetANick', 'author_id': 228589, 'author_profile': 'https://Stackoverflow.com/users/228589', 'pm_score': 0, 'selected': False, 'text': '<p>If you are making a app in GLib, then there is good documentation here. <a href="http://developer.gnome.org/poppler/unstable/index.html" rel="nofollow">http://developer.gnome.org/poppler/unstable/index.html</a></p>\n\n<p>If you can compile this documentations by doxygen, Just checkout the code. :) </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14278/'] |
80,323 | <p>I've been looking into report definition customization extensions (RDCE) in SQL2K8 recently and I've been at a loss to find much documentation or even chatter on the internet about it.</p>
<p>MSDN has a brief overview: <a href="http://msdn.microsoft.com/en-us/library/cc281022.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc281022.aspx</a></p>
<p>And the sample report from this book <a href="https://rads.stackoverflow.com/amzn/click/com/0976635313" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Applied-Microsoft-Server-Reporting-Services/dp/0976635313/ref=pd_bbs_sr_2?ie=UTF8&s=books&qid=1221629676&sr=8-2</a> is something, but I was wondering if anyone had real experience with this and how it worked out for them. And if anyone has other references worth looking at I'd appreciate it.</p>
| [{'answer_id': 80373, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 2, 'selected': True, 'text': '<p>You have to code it all yourself -- Poppler only handles the PDF part, you have to write the GUI. Look at the code to <a href="http://www.gnome.org/projects/evince/" rel="nofollow noreferrer">Evince</a> for a good example. </p>\n'}, {'answer_id': 1722023, 'author': 'BastiBen', 'author_id': 195347, 'author_profile': 'https://Stackoverflow.com/users/195347', 'pm_score': 1, 'selected': False, 'text': '<p>The poppler release downloads now contain a Qt4 wrapper and some examples that you can take a look at.</p>\n'}, {'answer_id': 12053665, 'author': 'CantGetANick', 'author_id': 228589, 'author_profile': 'https://Stackoverflow.com/users/228589', 'pm_score': 0, 'selected': False, 'text': '<p>If you are making a app in GLib, then there is good documentation here. <a href="http://developer.gnome.org/poppler/unstable/index.html" rel="nofollow">http://developer.gnome.org/poppler/unstable/index.html</a></p>\n\n<p>If you can compile this documentations by doxygen, Just checkout the code. :) </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15050/'] |
80,341 | <p>Okay, so this probably sounds terribly nefarious, but I need such capabilities for my senior project. Essentially I'm tasked with writing something that will cut down outbound spam on a zombified pc through a system of packet interception and evaluation. We have a number of algorithms we'll use on the captured messages, but it's the actual capture -- full on interception rather than just sniffing -- that has me a bit stumped.</p>
<p>The app is being designed for windows, so I can't use IP tables. I could use the winpcap libraries, but I don't want to reinvent the wheel if I don't have to. Ettercap seemed a good option, but a test run on vista using the unofficial binaries resulted in nothing but crashes.</p>
<p>So, any suggestions?</p>
<p>Update: Great suggestions. Ended up scaling back the project a bit, but still received an A. I'm thinking Adam Mintz's answer is probably best, though we used WinPcap and Wireshark for the application.</p>
| [{'answer_id': 80398, 'author': 'Ilkka', 'author_id': 15064, 'author_profile': 'https://Stackoverflow.com/users/15064', 'pm_score': 0, 'selected': False, 'text': '<p>One would think <a href="http://www.wireshark.org/" rel="nofollow noreferrer">Wireshark</a> would solve your problem -- no hassle install and pretty easy to use.</p>\n\n<p>Edit: Ah, I see now the interception requirement vs. just sniffing.. in this case Wireshark alone won\'t cut it. Probably whatever\'s the equivalent of iptables on windows would.</p>\n'}, {'answer_id': 80402, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 3, 'selected': True, 'text': '<p>Sounds like you need to write a <a href="http://en.wikipedia.org/wiki/Layered_Service_Provider" rel="nofollow noreferrer">Winsock LSP</a>.</p>\n\n<blockquote>\n <p>Once in the stack, a Layered Service Provider can intercept and modify inbound and outbound Internet traffic. It allows processing all the TCP/IP traffic taking place between the Internet and the applications that are accessing the Internet.</p>\n</blockquote>\n'}, {'answer_id': 80421, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="http://monkey.org/~dugsong/dsniff/" rel="nofollow noreferrer">DSNIFF</a> package has the mailsnarf utility. It can grab POP3 too. There are all sorts of other wonderful sniffing utilities there. Make sure you have the legal right before using these tools (the legal right to intercept other peoples traffic). I beleive the documentation has more information on the legality. According to the web page there are Windows and Mac OS X ports too.</p>\n\n<p>It would not be too hard to analyze the text output of the program.</p>\n'}, {'answer_id': 80426, 'author': 'Gopherkhan', 'author_id': 13825, 'author_profile': 'https://Stackoverflow.com/users/13825', 'pm_score': 0, 'selected': False, 'text': "<p>Ilkka: I was looking at Wireshark, but from what I could tell, that didn't handle the interception aspect -- only the sniffing and logging. The thing the professor's looking for is to prevent the spams from getting out onto the network.</p>\n\n<p>Adam: I'll definitely look into Winsock. I haven't checked that out yet. Only thing is the app's due in about 2 months, so if there are any OS apps that build off the WinSock SPI, I might want to tie into those. Know of any off the top of your head? </p>\n"}, {'answer_id': 80432, 'author': 'Gopherkhan', 'author_id': 13825, 'author_profile': 'https://Stackoverflow.com/users/13825', 'pm_score': 0, 'selected': False, 'text': "<p>Thanks, CDV. I'll look into that as well. Good call about the legality check. I've actually been trying to use gnu public license projects so far.</p>\n"}, {'answer_id': 80461, 'author': 'Jim In Texas', 'author_id': 15079, 'author_profile': 'https://Stackoverflow.com/users/15079', 'pm_score': 0, 'selected': False, 'text': '<p>I agree that Wireshark might be all you need. If you want to write your own filter application and can use Vista, then check out the <a href="http://www.microsoft.com/whdc/device/network/WFP.mspx" rel="nofollow noreferrer">Windows Filtering Platform</a>. </p>\n'}, {'answer_id': 82017, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.tcpdump.org/" rel="nofollow noreferrer">tcpdump</a> if you need command line or something more visual like <a href="http://www.wireshark.org/" rel="nofollow noreferrer">wireshark</a></p>\n\n<p>If you want to write something on your own use <a href="http://www.tcpdump.org/" rel="nofollow noreferrer">libpcap</a>.</p>\n'}, {'answer_id': 87083, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 0, 'selected': False, 'text': "<p>Use Snort, stripped down, if this is a long-term thing. It's built to watch for particular packets flying by, examining payload where needed, recording data and launching alerts.</p>\n\n<p>It's intended for intrusion detection, but it makes a surprisingly good network monitor for particular things over long term use.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13825/'] |
80,347 | <p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow noreferrer">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
| [{'answer_id': 80362, 'author': 'Aaron Jensen', 'author_id': 11229, 'author_profile': 'https://Stackoverflow.com/users/11229', 'pm_score': 2, 'selected': False, 'text': '<p>These may be a bit heavy for you depending on your needs but:\n<a href="http://www.nservicebus.com/" rel="nofollow noreferrer">http://www.nservicebus.com/</a>\n<a href="http://blog.phatboyg.com/masstransit/" rel="nofollow noreferrer">http://blog.phatboyg.com/masstransit/</a></p>\n'}, {'answer_id': 80864, 'author': 'pobk', 'author_id': 7829, 'author_profile': 'https://Stackoverflow.com/users/7829', 'pm_score': 0, 'selected': False, 'text': '<p>Again, my be overkill, but the <a href="http://ose.sf.net" rel="nofollow noreferrer">OSE</a> library allows thins kind of thing.</p>\n'}, {'answer_id': 467248, 'author': 'Tracker1', 'author_id': 43906, 'author_profile': 'https://Stackoverflow.com/users/43906', 'pm_score': 1, 'selected': False, 'text': '<p>Note, if you have events for message notification, there are many options for dependancy injection / inversion of control. See <a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring.Net</a> and <a href="http://www.castleproject.org/container/" rel="nofollow noreferrer">Castle Windsor</a> as two popular frameworks.</p>\n'}, {'answer_id': 29311041, 'author': 'Keith Barrows', 'author_id': 86555, 'author_profile': 'https://Stackoverflow.com/users/86555', 'pm_score': 0, 'selected': False, 'text': '<p>Looks like there are several offerings on NuGet: <a href="https://www.nuget.org/packages?q=pubsub" rel="nofollow">https://www.nuget.org/packages?q=pubsub</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,348 | <p>In C++0x I would like to write a function like this:</p>
<pre><code>template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
</code></pre>
<p>I first tried to use a for loop on <code>int i</code> and then do:</p>
<pre><code>get<i>(my_tuple);
</code></pre>
<p>And then store some value in the result. However, <code>get</code> only works on <code>constexpr</code>.</p>
<p>If I could get the variables out of the <code>tuple</code> and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without <code>get</code>. Any ideas on how to do that? Or does anyone have another way of modifying this <code>tuple</code>?</p>
| [{'answer_id': 80573, 'author': 'Adam Mitz', 'author_id': 2574, 'author_profile': 'https://Stackoverflow.com/users/2574', 'pm_score': 3, 'selected': True, 'text': '<p>Since the "i" in</p>\n\n<pre><code>get<i>(tup)\n</code></pre>\n\n<p>needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.</p>\n'}, {'answer_id': 80687, 'author': 'Daniel James', 'author_id': 2434, 'author_profile': 'https://Stackoverflow.com/users/2434', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.boost.org/doc/libs/release/libs/fusion/doc/html/index.html" rel="nofollow noreferrer">Boost.Fusion</a> is worth a look. It can \'iterate\' over <code>std::pair</code>, <code>boost::tuple</code>, some other containers and its own tuple types, although I don\'t think it supports <code>std::tuple</code> yet.</p>\n'}, {'answer_id': 103372, 'author': 'Timmie Smith', 'author_id': 8405, 'author_profile': 'https://Stackoverflow.com/users/8405', 'pm_score': 0, 'selected': False, 'text': '<p>Take a look at section 6.1.3.4 of TR1, <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf" rel="nofollow noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf</a></p>\n\n<p>get is defined for both const and non-const qualified tuples and returns the appropriate reference type. If you change your function declaration to the following:</p>\n\n<pre><code>template \nvoid fun(typename std::tuple& my_tuple) {\n //Put things into the tuple\n}</code></pre>\n\n<p>Then the argument to your function is a non-const tuple and get will allow you to make the necessary assignments once you\'ve written the iteration using the information provided in previous responses.</p>\n'}, {'answer_id': 103401, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<p>AFAICT, C++ tuples basically need to be handled with recursion; there don't seem to be any real ways of packing/unpacking tuples <em>except</em> using the typesystem's only variadic template handling.</p>\n"}, {'answer_id': 1611301, 'author': 'David', 'author_id': 193481, 'author_profile': 'https://Stackoverflow.com/users/193481', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at my answer here for an example of template recursion to unwind tuple arguments to a function call.</p>\n\n<p><a href="https://stackoverflow.com/questions/687490/c0x-how-do-i-expand-a-tuple-into-variadic-template-function-arguments">How do I expand a tuple into variadic template function's arguments?</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,351 | <p>I have tried:</p>
<ol>
<li>Xdebug and Eclipse. Eclipse launches a web browser, but the browser tries to access a non-existent file in Eclipse's .app bundle.</li>
<li>Xdebug and NetBeans. It does a little bit better; a browser opens a page in /tmp which says "Launching. Please wait…" but nothing happens beyond that.</li>
<li>Xdebug and debugclient, the CLI tool which comes with Xdebug. MacPorts (which I used to install PHP and Xdebug) doesn't seem to install this by itself, and when I try compiling it by hand, I get told "you have strange libedit". Installing libedit via MacPorts doesn't solve that.</li>
<li>Zend's debugger (the precise name escapes me right now) and Eclipse. I can't recall what the problem was, as this was some time ago, but it didn't work.</li>
</ol>
<p>With regards to Xdebug, at least, I'm fairly confident I've installed it correctly. It shows up with both a phpinfo() in a PHP file and a <code>php -i</code> in the CLI.</p>
<p>If anyone has managed to get PHP debugging working in some way or other on the Mac, I'd appreciate it if you could share with me how. Littering code with <code>var_dump($foo);die();</code> gets old quick. Bonus points if it can be done <em>without</em> using some bloatware editor like Eclipse, or that expensive proprietary thing Zend wants to sell me.</p>
<p>My server is connecting to PHP via FastCGI, if that makes a diff.</p>
| [{'answer_id': 84513, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 0, 'selected': False, 'text': "<p>I guess I don't get bonus points, but Zend Studio works for me on my Mac connecting to Apache running in VMware.</p>\n"}, {'answer_id': 84901, 'author': 'Brian Benzinger', 'author_id': 8096, 'author_profile': 'https://Stackoverflow.com/users/8096', 'pm_score': 5, 'selected': True, 'text': '<p>You may want to look into <a href="http://www.bluestatic.org/software/macgdbp/" rel="noreferrer">MacGDBp</a>. It\'s new, free, and the UI looks great. It utilizes the Xdebug PHP extension as well. You can find instructions in the <a href="http://www.bluestatic.org/software/macgdbp/help.php" rel="noreferrer">help</a> section, which includes Xdebug configurations, and there\'s also a nice overview of the app from the guys at Particletree here: <a href="http://particletree.com/notebook/silence-the-echo-with-macgdbp/" rel="noreferrer">Silence The Echo with MacGDBp</a>.</p>\n'}, {'answer_id': 131855, 'author': 'phatduckk', 'author_id': 3896, 'author_profile': 'https://Stackoverflow.com/users/3896', 'pm_score': 0, 'selected': False, 'text': '<p>I debug PHP CLI scripts and web probject (thru apache etc) using Eclipse & ZendDebugger all the time. </p>\n\n<p>I answered a similar question over at the following link:\n<a href="https://stackoverflow.com/questions/127761/php-debugging-with-aptana-studio-and-xdebug-or-zend-debugger-on-os-x#131722">click here</a></p>\n\n<p>Hopefully that\'s what you\'re looking for.</p>\n'}, {'answer_id': 426452, 'author': 'Luke Dennis', 'author_id': 24010, 'author_profile': 'https://Stackoverflow.com/users/24010', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s how I did it:</p>\n\n<p>1 - Copy the latest version of xdebug.so from <a href="http://aspn.activestate.com/ASPN/Downloads/Komodo/RemoteDebugging" rel="noreferrer">http://aspn.activestate.com/ASPN/Downloads/Komodo/RemoteDebugging</a> to /usr/libexec.</p>\n\n<p>2 - Add the following to the global php.ini:</p>\n\n<pre><code>zend_extension="/usr/libexec/xdebug.so"\nxdebug.remote_enable=1\nxdebug.remote_host=localhost\nxdebug.remote_port=9000\nxdebug.remote_autostart=1\n</code></pre>\n\n<p>3 - Restart Apache and run <a href="http://www.bluestatic.org/software/macgdbp/help.php" rel="noreferrer">MacGDBp</a>.</p>\n'}, {'answer_id': 3765605, 'author': 'David', 'author_id': 57246, 'author_profile': 'https://Stackoverflow.com/users/57246', 'pm_score': 1, 'selected': False, 'text': "<p>I use Komodo 5 --- debugging works wonderfully, not only with PHP, but also with Ruby and Python.\nI mostly use it to debug PHP scripts that are running on a remote server but you can do local stuff as well. It's not free, but assuming your own time is worth something, you will have gotten your money back within a few hours!</p>\n"}, {'answer_id': 12918754, 'author': 'Henrique B.', 'author_id': 406428, 'author_profile': 'https://Stackoverflow.com/users/406428', 'pm_score': 2, 'selected': False, 'text': '<p>Just wanted to update this thread to let you know there\'s a new app out here <a href="http://codebugapp.com/" rel="nofollow">http://codebugapp.com/</a> it\'s commercial, but it\'s Xdebug client for OSX</p>\n'}, {'answer_id': 38305526, 'author': 'Arif Dewi', 'author_id': 2668045, 'author_profile': 'https://Stackoverflow.com/users/2668045', 'pm_score': 1, 'selected': False, 'text': '<h3>There is a way how to do it using</h3>\n\n<ul>\n<li><a href="https://www.jetbrains.com/phpstorm/" rel="nofollow">PhpStorm</a> </li>\n<li><p>Homebrew<br>\nruby -e "$(curl -fsSL <a href="https://raw.githubusercontent.com/Homebrew/install/master/install" rel="nofollow">https://raw.githubusercontent.com/Homebrew/install/master/install</a>)"</p></li>\n<li><p>Php + Xdebug</p></li>\n</ul>\n\n<p>1) Install php and debug </p>\n\n<pre><code>brew install php70 \nbrew install php70-xdebug\n</code></pre>\n\n<ul>\n<li><p>In PhpStorm - check Preferences => Language and Frameworks => PHP<br>\nPhp language level: 7<br>\nInterpreter: PHP 7.0.8 + XDebug (or choose from [...])</p></li>\n<li><p>Check debug config: \nPreferences => Language and Frameworks => PHP => Debug => Xdebug section<br>\nAll checkboxes should be checked and set Debug port to: 9001</p></li>\n</ul>\n\n<p>2) run server in your app\'s directory: </p>\n\n<pre><code>php -S localhost:8080\n</code></pre>\n\n<p>3) Add localhost:8080 to PhpStorm Preferences => Language and Frameworks => PHP => Servers:<br>\nName: Localhost:8080<br>\nHost: localhost<br>\nPort: 8080<br>\nDebugger: Xdebug </p>\n\n<p>4) Update php.ini:<br>\nPhp => Interpreter => […] => Configuration file - Open in Editor<br>\nAdd this section: (check zend_extention path through the cli) </p>\n\n<pre><code>[Xdebug]\nzend_extension=/usr/lib/php/extensions/no-debug-non-zts-20121212/xdebug.so\nxdebug.remote_enable=1\nxdebug.remote_host=localhost\nxdebug.remote_port=9001 (same as in Debug preferences)\n</code></pre>\n\n<p>5) Add Debug Configuration:\nRun => Edit Configuration => add - Php Web Application</p>\n\n<ul>\n<li>Choose Localhost:8080 server</li>\n</ul>\n\n<p>6) Click Start Listening for Php Debug Connections<br>\n7) Set up breakpoints<br>\n7) Click on Debug (Green bug)</p>\n'}, {'answer_id': 39327220, 'author': 'Aurovrata', 'author_id': 3596672, 'author_profile': 'https://Stackoverflow.com/users/3596672', 'pm_score': 0, 'selected': False, 'text': '<p>If you are using MAMP, please note that it has 2 php.ini files that need to be updated. It took me hours to figure this one out. The two files are in the following folders for MAMP 4, </p>\n\n<pre><code>/Applications/MAMP/bin/php/php5.6.25/conf/php.ini\n/Applications/MAMP/conf/php5.6.25/php.ini\n</code></pre>\n\n<p>if you\'re using php7 then you\'ll need to update those files instead. Scroll to the bottom of the files and make sure you have the following entries,</p>\n\n<pre><code>[xdebug]\nzend_extension="/Applications/MAMP/bin/php/php5.6.25/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so"\nxdebug.default_enable=1\nxdebug.remote_enable=1\nxdebug.remote_host=localhost\nxdebug.remote_port=9000\nxdebug.remote_autostart=1\n</code></pre>\n\n<p>Then make sure you restart your server else the new settings won\'t be loaded. To make sure Xdebug is working properly, open your MAMP Start page, and click onthe phpinfo tab. Search for xdebug in the listing, you should see the <a href="http://www.codeforest.net/wp-content/uploads/2013/04/phpinfo.png" rel="nofollow">Xdebug section</a> that shows that the extension is loaded and enabled, else something is wrong with the above configurations.</p>\n\n<p>Next you can launch MacGDBp and it will connect to port 9000 and allow you to debug your files. </p>\n\n<p>NOTE: If you are developing on Wordpress, then make sure you skip the \'AJAX\' debugging sessions. These are regular as the Dashboard will ping the server for changes. If you enable the \'break on the first line\' in MacGDBp settings, you will see the ajax sessions breaking on the line <code>define (\'DOING_AJAX\')....</code> which you can skip. Once you have then fire your event for debugging your code.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11023/'] |
80,357 | <p>Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.</p>
| [{'answer_id': 80387, 'author': 'Jean', 'author_id': 7898, 'author_profile': 'https://Stackoverflow.com/users/7898', 'pm_score': 11, 'selected': True, 'text': '<p>Using <a href="http://ruby-doc.org/core-1.9.3/String.html#method-i-scan" rel="noreferrer"><code>scan</code></a> should do the trick:</p>\n\n<pre><code>string.scan(/regex/)\n</code></pre>\n'}, {'answer_id': 35964234, 'author': 'sudo bangbang', 'author_id': 3951782, 'author_profile': 'https://Stackoverflow.com/users/3951782', 'pm_score': 6, 'selected': False, 'text': '<p>To find all the matching strings, use String\'s <a href="http://ruby-doc.org/core-2.2.0/String.html#method-i-scan" rel="noreferrer"><code>scan</code></a> method.</p>\n\n<pre><code>str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"\nstr.scan(/\\d+/)\n#=> ["54", "3", "1", "7", "3", "36", "0"]\n</code></pre>\n\n<p>If you want, <a href="http://ruby-doc.org/core-1.9.3/MatchData.html" rel="noreferrer"><code>MatchData</code></a>, which is the type of the object returned by the Regexp <code>match</code> method, use:</p>\n\n<pre><code>str.to_enum(:scan, /\\d+/).map { Regexp.last_match }\n#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]\n</code></pre>\n\n<p>The benefit of using <code>MatchData</code> is that you can use methods like <code>offset</code>:</p>\n\n<pre><code>match_datas = str.to_enum(:scan, /\\d+/).map { Regexp.last_match }\nmatch_datas[0].offset(0)\n#=> [2, 4]\nmatch_datas[1].offset(0)\n#=> [7, 8]\n</code></pre>\n\n<p>See these questions if you\'d like to know more:</p>\n\n<ul>\n<li>"<a href="https://stackoverflow.com/questions/6804557/how-do-i-get-the-match-data-for-all-occurrences-of-a-ruby-regular-expression-in?lq=1">How do I get the match data for all occurrences of a Ruby regular expression in a string?</a>"</li>\n<li>"<a href="https://stackoverflow.com/questions/19596382/ruby-regular-expression-matching-enumerator-with-named-capture-support?lq=1">Ruby regular expression matching enumerator with named capture support</a>"</li>\n<li>"<a href="https://stackoverflow.com/questions/17185943/how-to-find-out-the-starting-point-for-each-match-in-ruby?lq=1">How to find out the starting point for each match in ruby</a>"</li>\n</ul>\n\n<p>Reading about special variables <code>$&</code>, <code>$\'</code>, <code>$1</code>, <code>$2</code> in Ruby will be helpful too.</p>\n'}, {'answer_id': 36751235, 'author': 'MVP', 'author_id': 6231595, 'author_profile': 'https://Stackoverflow.com/users/6231595', 'pm_score': 4, 'selected': False, 'text': '<p>if you have a regexp with groups:</p>\n\n<pre><code>str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"\nre=/(\\d+)[m-t]/\n</code></pre>\n\n<p>you can use String\'s <code>scan</code> method to find matching groups:</p>\n\n<pre><code>str.scan re\n#> [["54"], ["1"], ["3"]]\n</code></pre>\n\n<p>To find the matching pattern:</p>\n\n<pre><code>str.to_enum(:scan,re).map {$&}\n#> ["54m", "1t", "3r"]\n</code></pre>\n'}, {'answer_id': 60586543, 'author': 'Datt', 'author_id': 1398515, 'author_profile': 'https://Stackoverflow.com/users/1398515', 'pm_score': 3, 'selected': False, 'text': '<p>You can use <code>string.scan(your_regex).flatten</code>. If your regex contains groups, it will return in a single plain array. </p>\n\n<pre><code>string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"\nyour_regex = /(\\d+)[m-t]/\nstring.scan(your_regex).flatten\n=> ["54", "1", "3"]\n</code></pre>\n\n<p>Regex can be a named group as well.</p>\n\n<pre><code>string = \'group_photo.jpg\'\nregex = /\\A(?<name>.*)\\.(?<ext>.*)\\z/\nstring.scan(regex).flatten\n</code></pre>\n\n<p>You can also use <code>gsub</code>, it\'s just one more way if you want MatchData.</p>\n\n<pre><code>str.gsub(/\\d/).map{ Regexp.last_match }\n</code></pre>\n'}, {'answer_id': 72266342, 'author': 'Victor', 'author_id': 7644846, 'author_profile': 'https://Stackoverflow.com/users/7644846', 'pm_score': 0, 'selected': False, 'text': '<p>If you have capture groups <code>()</code> inside the regex for other purposes, the proposed solutions with <code>String#scan</code> and <code>String#match</code> are problematic:</p>\n<ol>\n<li><code>String#scan</code> only get what is inside the <a href="https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html" rel="nofollow noreferrer">capture groups</a>;</li>\n<li><code>String#match</code> only get the first match, rejecting all the others;</li>\n<li><code>String#matches</code> (proposed function) get all the matches.</li>\n</ol>\n<p>On this case, we need a solution to match the regex without considering the capture groups.</p>\n<h1><code>String#matches</code></h1>\n<p>With the <a href="https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html" rel="nofollow noreferrer">Refinements</a> you can monkey patch the <code>String</code> class, implement the <code>String#matches</code> and this method will be available inside the scope of the class that is using the refinement. It is an incredible way to Monkey Patch classes on Ruby.</p>\n<h3>Setup</h3>\n<ul>\n<li><code>/lib/refinements/string_matches.rb</code></li>\n</ul>\n<pre class="lang-rb prettyprint-override"><code># This module add a String refinement to enable multiple String#match()s\n# 1. `String#scan` only get what is inside the capture groups (inside the parens)\n# 2. `String#match` only get the first match\n# 3. `String#matches` (proposed function) get all the matches\nmodule StringMatches\n refine String do\n def matches(regex)\n scan(/(?<matching>#{regex})/).flatten\n end\n end\nend\n\n</code></pre>\n<p>Used: <a href="https://ruby-doc.org/core-2.4.3/Regexp.html" rel="nofollow noreferrer">named capture groups</a></p>\n<h3>Usage</h3>\n<ul>\n<li><code>rails c</code></li>\n</ul>\n<pre class="lang-rb prettyprint-override"><code>> require \'refinements/string_matches\'\n\n> using StringMatches\n\n> \'function(1, 2, 3) + function(4, 5, 6)\'.matches(/function\\((\\d), (\\d), (\\d)\\)/)\n=> ["function(1, 2, 3)", "function(4, 5, 6)"]\n\n> \'function(1, 2, 3) + function(4, 5, 6)\'.scan(/function\\((\\d), (\\d), (\\d)\\)/)\n=> [["1", "2", "3"], ["4", "5", "6"]]\n\n> \'function(1, 2, 3) + function(4, 5, 6)\'.match(/function\\((\\d), (\\d), (\\d)\\)/)[0]\n=> "function(1, 2, 3)"\n</code></pre>\n'}, {'answer_id': 73542998, 'author': 'some_guy', 'author_id': 4019925, 'author_profile': 'https://Stackoverflow.com/users/4019925', 'pm_score': -1, 'selected': False, 'text': "<h1>Return an array of <code>MatchData</code> objects</h1>\n<p><code>#scan</code> is very limited--only returns a simple array of strings!</p>\n<p>Far more powerful/flexible for us to get an array of <code>MatchData</code> objects.</p>\n<p>I'll provide two approaches (using same logic), one using a PORO and one using a monkey patch:</p>\n<h2>PORO:</h2>\n<pre><code>class MatchAll\n def initialize(string, pattern)\n raise ArgumentError, 'must pass a String' unless string.is_a?(String)\n\n raise ArgumentError, 'must pass a Regexp pattern' unless pattern.is_a?(Regexp)\n\n @string = string\n @pattern = pattern\n @matches = []\n end\n\n def match_all\n recursive_match\n end\n\n private\n\n def recursive_match(prev_match = nil)\n index = prev_match.nil? ? 0 : prev_match.offset(0)[1]\n\n matching_item = @string.match(@pattern, index)\n return @matches unless matching_item.present?\n\n @matches << matching_item\n recursive_match(matching_item)\n end\nend\n</code></pre>\n<p><strong>USAGE:</strong></p>\n<pre><code>test_string = 'a green frog jumped on a green lilypad'\n\nMatchAll.new(test_string, /green/).match_all\n=> [#<MatchData "green", #<MatchData "green"]\n</code></pre>\n<hr />\n<h2>Monkey patch</h2>\n<p>I don't typically condone monkey-patching, but in this case:</p>\n<ul>\n<li>we're doing it the right way by "quarantining" our patch into its own module</li>\n<li>I prefer this approach because <code>'string'.match_all(/pattern/)</code> is more intuitive (and looks a lot nicer) than <code>MatchAll.new('string', /pattern/).match_all</code></li>\n</ul>\n<pre><code>module RubyCoreExtensions\n module String\n module MatchAll\n def match_all(pattern)\n raise ArgumentError, 'must pass a Regexp pattern' unless pattern.is_a?(Regexp)\n\n recursive_match(pattern)\n end\n\n private\n\n def recursive_match(pattern, matches = [], prev_match = nil)\n index = prev_match.nil? ? 0 : prev_match.offset(0)[1]\n\n matching_item = self.match(pattern, index)\n return matches unless matching_item.present?\n\n matches << matching_item\n recursive_match(pattern, matches, matching_item)\n end\n end\n end\nend\n\n</code></pre>\n<p>I recommend creating a new file and putting the patch (assuming you're using Rails) there <code>/lib/ruby_core_extensions/string/match_all.rb</code></p>\n<p>To use our patch we need to make it available:</p>\n<pre><code># within application.rb\nrequire './lib/ruby_core_extensions/string/match_all.rb'\n</code></pre>\n<p>Then be sure to include it in the <code>String</code> class (you could put this wherever you want; but for example, right under the require statement we just wrote above. After you <code>include</code> it once, it will be available everywhere, even outside the class where you included it).</p>\n<pre><code>String.include RubyCoreExtensions::String::MatchAll\n</code></pre>\n<p><strong>USAGE: And now when you use <code>#match_all</code> you get results like:</strong></p>\n<pre><code>test_string = 'hello foo, what foo are you going to foo today?'\n\ntest_string.match_all /foo/\n=> [#<MatchData "foo", #<MatchData "foo", #<MatchData "foo"]\n\ntest_string.match_all /hello/\n=> [#<MatchData "hello"]\n\ntest_string.match_all /none/\n=> []\n</code></pre>\n<hr />\n<p>I find this particularly useful when I want to match multiple occurrences, and then get useful information about each occurrence, such as which index the occurrence starts and ends (e.g. <code>match.offset(0) => [first_index, last_index]</code>)</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422/'] |
80,388 | <p>I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates.</p>
<p>The "progressAnimation" is defined as a resource in the user control.</p>
<p>I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error:</p>
<blockquote>
<p>'System.Windows.Style' value cannot be assigned to property 'Style'
of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Style
cannot specify a TargetName. Remove TargetName 'progressWheel'.</p>
</blockquote>
<p>ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want.</p>
<p>I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code.</p>
| [{'answer_id': 80455, 'author': 'Jobi Joy', 'author_id': 8091, 'author_profile': 'https://Stackoverflow.com/users/8091', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend to use RoutedEvent instead of your IsBusy property. Just fire OnBusyStarted and OnBusyStopped event and use Event trigger on the appropriate elements.</p>\n'}, {'answer_id': 80794, 'author': 'Jobi Joy', 'author_id': 8091, 'author_profile': 'https://Stackoverflow.com/users/8091', 'pm_score': 1, 'selected': False, 'text': '<p>You can subscribe to the PropertyChanged event of the DataObject class and make a RoutedEvent fire from Usercontrol level. </p>\n\n<p>For RoutedEvent to work we need to have the class derived from DependancyObject</p>\n'}, {'answer_id': 81175, 'author': 'ligaz', 'author_id': 6409, 'author_profile': 'https://Stackoverflow.com/users/6409', 'pm_score': 0, 'selected': False, 'text': '<p>You can use Trigger.EnterAction to start an animation when a property is changed.</p>\n\n<pre><code><Trigger Property="IsBusy" Value="true">\n <Trigger.EnterActions>\n <BeginStoryboard x:Name="BeginBusy" Storyboard="{StaticResource MyStoryboard}" />\n </Trigger.EnterActions>\n <Trigger.ExitActions>\n <StopStoryboard BeginStoryboardName="BeginBusy" />\n </Trigger.ExitActions>\n</Trigger>\n</code></pre>\n'}, {'answer_id': 1735810, 'author': 'Dabblernl', 'author_id': 108493, 'author_profile': 'https://Stackoverflow.com/users/108493', 'pm_score': 7, 'selected': True, 'text': '<p>What you want is possible by declaring the animation on the progressWheel itself:\nThe XAML:</p>\n\n<pre><code><UserControl x:Class="TriggerSpike.UserControl1"\nxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\nxmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\nHeight="300" Width="300">\n<UserControl.Resources>\n <DoubleAnimation x:Key="SearchAnimation" Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:4"/>\n <DoubleAnimation x:Key="StopSearchAnimation" Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:4"/>\n</UserControl.Resources>\n<StackPanel>\n <TextBlock Name="progressWheel" TextAlignment="Center" Opacity="0">\n <TextBlock.Style>\n <Style>\n <Style.Triggers>\n <DataTrigger Binding="{Binding IsBusy}" Value="True">\n <DataTrigger.EnterActions>\n <BeginStoryboard>\n <Storyboard>\n <StaticResource ResourceKey="SearchAnimation"/>\n </Storyboard>\n </BeginStoryboard>\n </DataTrigger.EnterActions>\n <DataTrigger.ExitActions>\n <BeginStoryboard>\n <Storyboard>\n <StaticResource ResourceKey="StopSearchAnimation"/> \n </Storyboard>\n </BeginStoryboard>\n </DataTrigger.ExitActions>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n Searching\n </TextBlock>\n <Label Content="Here your search query"/>\n <TextBox Text="{Binding SearchClause}"/>\n <Button Click="Button_Click">Search!</Button>\n <TextBlock Text="{Binding Result}"/>\n</StackPanel>\n</code></pre>\n\n<p></p>\n\n<p>Code behind:</p>\n\n<pre><code> using System.Windows;\nusing System.Windows.Controls;\n\nnamespace TriggerSpike\n{\n public partial class UserControl1 : UserControl\n {\n private MyViewModel myModel;\n\n public UserControl1()\n {\n myModel=new MyViewModel();\n DataContext = myModel;\n InitializeComponent();\n }\n\n private void Button_Click(object sender, RoutedEventArgs e)\n {\n myModel.Search(myModel.SearchClause);\n }\n }\n}\n</code></pre>\n\n<p>The viewmodel:</p>\n\n<pre><code> using System.ComponentModel;\nusing System.Threading;\nusing System.Windows;\n\nnamespace TriggerSpike\n{\n class MyViewModel:DependencyObject\n {\n\n public string SearchClause{ get;set;}\n\n public bool IsBusy\n {\n get { return (bool)GetValue(IsBusyProperty); }\n set { SetValue(IsBusyProperty, value); }\n }\n\n public static readonly DependencyProperty IsBusyProperty =\n DependencyProperty.Register("IsBusy", typeof(bool), typeof(MyViewModel), new UIPropertyMetadata(false));\n\n\n\n public string Result\n {\n get { return (string)GetValue(ResultProperty); }\n set { SetValue(ResultProperty, value); }\n }\n\n public static readonly DependencyProperty ResultProperty =\n DependencyProperty.Register("Result", typeof(string), typeof(MyViewModel), new UIPropertyMetadata(string.Empty));\n\n public void Search(string search_clause)\n {\n Result = string.Empty;\n SearchClause = search_clause;\n var worker = new BackgroundWorker();\n worker.DoWork += worker_DoWork;\n worker.RunWorkerCompleted += worker_RunWorkerCompleted;\n IsBusy = true;\n worker.RunWorkerAsync();\n }\n\n void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n IsBusy=false;\n Result = "Sorry, no results found for: " + SearchClause;\n }\n\n void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n Thread.Sleep(5000);\n }\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n'}, {'answer_id': 24774823, 'author': 'Ian Griffiths', 'author_id': 497397, 'author_profile': 'https://Stackoverflow.com/users/497397', 'pm_score': 4, 'selected': False, 'text': '<p>Although the answer that proposes attaching the animation directly to the element to be animated solves this problem in simple cases, this isn\'t really workable when you have a complex animation that needs to target multiple elements. (You can attach an animation to each element of course, but it gets pretty horrible to manage.)</p>\n\n<p>So there\'s an alternative way to solve this that lets you use a <code>DataTrigger</code> to run an animation that targets named elements.</p>\n\n<p>There are three places you can attach triggers in WPF: elements, styles, and templates. However, the first two options don\'t work here. The first is ruled out because WPF doesn\'t support the use of a <code>DataTrigger</code> directly on an element. (There\'s no particularly good reason for this, as far as I know. As far as I remember, when I asked people on the WPF team about this many years ago, they said they\'d have liked to have supported it but didn\'t have time to make it work.) And styles are out because, as the error message you\'ve reported says, you can\'t target named elements in an animation associated with a style.</p>\n\n<p>So that leaves templates. And you can use either control or data templates for this.</p>\n\n<pre><code><ContentControl>\n <ContentControl.Template>\n <ControlTemplate TargetType="ContentControl">\n <ControlTemplate.Resources>\n <Storyboard x:Key="myAnimation">\n\n <!-- Your animation goes here... -->\n\n </Storyboard>\n </ControlTemplate.Resources>\n <ControlTemplate.Triggers>\n <DataTrigger\n Binding="{Binding MyProperty}"\n Value="DesiredValue">\n <DataTrigger.EnterActions>\n <BeginStoryboard\n x:Name="beginAnimation"\n Storyboard="{StaticResource myAnimation}" />\n </DataTrigger.EnterActions>\n <DataTrigger.ExitActions>\n <StopStoryboard\n BeginStoryboardName="beginAnimation" />\n </DataTrigger.ExitActions>\n </DataTrigger>\n </ControlTemplate.Triggers>\n\n <!-- Content to be animated goes here -->\n\n </ControlTemplate>\n </ContentControl.Template>\n<ContentControl>\n</code></pre>\n\n<p>With this construction, WPF is happy to let the animation refer to named elements inside the template. (I\'ve left both the animation and the template content empty here - obviously you\'d populate that with your actual animation nd content.)</p>\n\n<p>The reason this works in a template but not a style is that when you apply a template, the named elements it defines will always be present, and so it\'s safe for animations defined within that template\'s scope to refer to those elements. This is not generally the case with a style, because styles can be applied to multiple different elements, each of which may have quite different visual trees. (It\'s a little frustrating that it prevents you from doing this even in scenarios when you can be certain that the required elements will be there, but perhaps there\'s something that makes it very difficult for the animation to be bound to the named elements at the right time. I know there are quite a lot of optimizations in WPF to enable elements of a style to be reused efficiently, so perhaps one of those is what makes this difficult to support.)</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199387/'] |
80,394 | <p>I am having trouble deciding on whether to classify my application as 'real time' or 'near real time', or perhaps even something else.</p>
<p>The software receives data immediately as it is generated from the source, then based on certain rules, raises an alert when certain conditions are met. It takes the approach of checking the last 30 seconds of data every 30 seconds to see whether the criteria for a rule has been met.</p>
<p>Is that real time? What are the thresholds for the definitions of real time vs. near real-time?</p>
<p><strong>EDIT</strong></p>
<p>I think this is a duplicate of <a href="https://stackoverflow.com/questions/51135/define-realtime-on-the-web-for-business">Define realtime on the web for business</a>.</p>
<p>Please decide if the above thread is insufficient to answer your question.</p>
| [{'answer_id': 80409, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': -1, 'selected': False, 'text': '<p>I am in agreement with John, in your scenario you are looking at least 30 seconds of delay, I would say that it is nearly real time.</p>\n'}, {'answer_id': 80410, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': -1, 'selected': False, 'text': "<p>I would say the definition of real time would depend on the context. As with the music example real time would need to be milliseconds, but possibly with your example real time could be within 30 seconds or so. It's all relative.</p>\n"}, {'answer_id': 80414, 'author': 'Per Hornshøj-Schierbeck', 'author_id': 11619, 'author_profile': 'https://Stackoverflow.com/users/11619', 'pm_score': -1, 'selected': False, 'text': '<p>I think you need to look at the specific solution or part of the solution in where you need the response to be real-time. A real time response is one which is perceived by the receiver (the application or basically the end-user) as being real-time.</p>\n'}, {'answer_id': 80416, 'author': 'paxdiablo', 'author_id': 14860, 'author_profile': 'https://Stackoverflow.com/users/14860', 'pm_score': 2, 'selected': False, 'text': '<p>Well, that could be more of a marketing question than a technical one.</p>\n\n<p>Real-time, in terms of embedded hardware, involves a known fixed maximum time for handling incoming information (interrupts and the like).</p>\n\n<p>You can certainly claim 30 seconds delay as real-time especially if the delivery of said information is longer than that.</p>\n\n<p>For example, if your "alert" is an email that could spend 10 minutes in a mail server or a red cross on a monitor that the users only check every half hour, 30 seconds is more than adequate for real-time.</p>\n'}, {'answer_id': 80419, 'author': 'Tom Carr', 'author_id': 14954, 'author_profile': 'https://Stackoverflow.com/users/14954', 'pm_score': -1, 'selected': False, 'text': "<p>Real Time deals with microseconds...mainly around robotics. Think 'move arm 30 microseconds; weld 1000 microseconds;', like in automobile assembly.</p>\n\n<p>Is your 30 seconds based on a Thread sleep or a timer in a non-real time OS? If so, then you have a potential varience. Will you consider it a failure if you're outside that variance (30.01 seconds)? If not, then it's not real time.</p>\n"}, {'answer_id': 80433, 'author': 'moobaa', 'author_id': 3569, 'author_profile': 'https://Stackoverflow.com/users/3569', 'pm_score': 2, 'selected': False, 'text': '<p>I think one aspect that defines real-time is that the process is <em>deterministic</em> - that is, the application\'s response time is totally predictable based on the inputs.</p>\n\n<p>Thus, painting with very broad brush-strokes, any app sitting on top of Windows can only be "near-real-time", at best. Doubly so if your app is running on some sort of sandbox platform (Java, .NET) where you don\'t have absolute control over platform functions (eg, garbage collection).</p>\n\n<p>My personal rule is that "real-time" doesn\'t belong on a desktop PC; that\'s the realm of PLCs (and yes, they may be running OSes like QNX, VxWorx or even RTLinux).</p>\n'}, {'answer_id': 80435, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Real-time = Guaranteed maximum time for resolution. It could be picoseconds or minutes depending on the application\'s requirements</p>\n\n<p>This is StackOverflow\'s biggest problem: unqualified people answer LOTS of questions with answers that "sound right" and get voted up, people who care whether the answer is actually correct don\'t spew nonsense fast enough to earn rep to fix the wrong answers. Posting anonymously due to expected knee-jerk reactions.</p>\n'}, {'answer_id': 80436, 'author': 'Rob Gray', 'author_id': 5691, 'author_profile': 'https://Stackoverflow.com/users/5691', 'pm_score': 0, 'selected': False, 'text': '<p>I believe the answer is that realtime systems are subjective, in that "real time" is just timeliness contraints imposed by the requirements. Though clearly something that takes 2 hours to respond to a request is not real time, a 30 second delay might be fast enough to qualify as real time. </p>\n\n<p>I work on what I consider real time systems, where when an event happens in the sytem it is immediately propogated to devices on the system, such that the delay in knowing about an update on a device is product of the network latency and the time take to update its in-memory data.</p>\n\n<p>I personally wouldn\'t classify something with that polls for updates every 30 seconds as realtime. We have a web app as part of the afore mentioned system that does just that, it refreshes every 30 seconds, so the user is presented with data that is at most 30 seconds old. Contrast this with the win forms equalivent that is updated as soon as the event occurs. </p>\n\n<p>Again, "real time" is bounded by your definition of a timely response.</p>\n'}, {'answer_id': 80574, 'author': 'Noel Grandin', 'author_id': 6591, 'author_profile': 'https://Stackoverflow.com/users/6591', 'pm_score': 3, 'selected': False, 'text': '<p>The phrase "real-time" covers a fairly large patch of ground.</p>\n\n<p>The vague definition is "software that acts within a bounded response time".</p>\n\n<p>Where the boundary is hard e.g. in a car\'s injection control system, the software is said to be "hard real-time".</p>\n\n<p>Where the boundary is soft e.g. in a music-playback system, where variations of up to 50ms are tolerable, the system is said to be "soft real-time".</p>\n\n<p>So yes, for some definition of real-time, your system is real-time.</p>\n\n<p>But you\'re probably going to get laughed at if you call it real-time around anybody else who actually works on real-time systems, because 30 seconds is pretty huge.</p>\n'}, {'answer_id': 80805, 'author': 'Bob Nadler', 'author_id': 2514, 'author_profile': 'https://Stackoverflow.com/users/2514', 'pm_score': 1, 'selected': False, 'text': '<p>Another way to define "real-time" is by evaluating the capabilities of the many <a href="http://www.google.com/search?q=RTOS" rel="nofollow noreferrer">RTOS</a>s (real-time operating systems). e.g QNX\'s definition is <a href="http://www.qnx.com/products/neutrino_rtos/realtime.html" rel="nofollow noreferrer">here</a>. Notice that they conform to the <a href="http://en.wikipedia.org/wiki/POSIX" rel="nofollow noreferrer">POSIX</a> PSE52 Realtime Controller 1003.13-2003 System product standard. Most embedded operating systems will provide similar functionality.</p>\n'}, {'answer_id': 81279, 'author': 'YermoungDer', 'author_id': 15293, 'author_profile': 'https://Stackoverflow.com/users/15293', 'pm_score': 3, 'selected': False, 'text': "<p>Real-time is getting a required response to an event completed within the time period specified or <em>your system fails</em>.</p>\n\n<p>People are used to thinking this must mean 'small number of milliseconds/microseconds' but that isn't necessarily true - it depends on your system.</p>\n\n<p>If your system will <em>fail</em> if it doesn't complete it's required response within 30 seconds then it's 'real-time'.</p>\n\n<p>For some systems, a <em>fail</em> could be catastrophic, e.g. causing multiple fatalities - this is described as <em>safety critical</em>, e.g. shutting down a nuclear power plant.</p>\n"}, {'answer_id': 563104, 'author': 'Stephen Friederichs', 'author_id': 39492, 'author_profile': 'https://Stackoverflow.com/users/39492', 'pm_score': 1, 'selected': False, 'text': "<p>Definition of 'hard' real-time from my controls friends - Late information is wrong information. If it needs to be there every 1s and it gets there in 1.1s, it's useless for calculations. </p>\n"}, {'answer_id': 4107919, 'author': 'E. Douglas Jensen', 'author_id': 498523, 'author_profile': 'https://Stackoverflow.com/users/498523', 'pm_score': 1, 'selected': False, 'text': '<p>I provide a lengthy discourse on this on my web site real-time.org. The home page has a temporary link to a briefing. The briefing discusses how and why people don\'t understand what "real-time" (and "hard" and "soft" and "predictable" etc.) means. It provides some precise and general definitions. I have heard from people who don\'t agree with my explanation of this topic, but none of them have come forward with anything remotely as precise and general as mine. "Pull up a chair, let\'s talk" as Larry King says.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1693/'] |
80,415 | <p>I have a string which starts with <code>//#...</code> goes upto the newline characater. I have figured out the regex for the which is this <code>..#([^\n]*)</code>.</p>
<p>My question is how do you remove this line from a file if the following condition matches</p>
| [{'answer_id': 80444, 'author': 'EricSchaefer', 'author_id': 8976, 'author_profile': 'https://Stackoverflow.com/users/8976', 'pm_score': 0, 'selected': False, 'text': "<p>Read the file line by line and only write those lines to a new file that don't match the regex.\nYou cannot just remove a line.</p>\n"}, {'answer_id': 80445, 'author': 'baudtack', 'author_id': 10738, 'author_profile': 'https://Stackoverflow.com/users/10738', 'pm_score': 0, 'selected': False, 'text': "<p>Does it start at the begining of a line or can it appear anywhere? If the former s/old/new is what you want. If the latter, I'll have to figure that out. I suspect that back referances could be used somehow.</p>\n"}, {'answer_id': 80498, 'author': 'bmb', 'author_id': 5298, 'author_profile': 'https://Stackoverflow.com/users/5298', 'pm_score': 0, 'selected': False, 'text': "<p>I don't think your regex is correct.</p>\n\n<p>First you need to start with ^ or else it will match this pattern anywhere on the line.</p>\n\n<p>Second, the <code>..</code> should be <code>\\/\\/</code> or else it will match any two characters.</p>\n\n<p><code>^\\/\\/#[^\\n]*</code> is probably what you want.</p>\n\n<p>Then do what EricSchaefer says and read the file line by line only writing lines that don't match.</p>\n\n<p>--<br>\nbmb</p>\n"}, {'answer_id': 80703, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 0, 'selected': False, 'text': "<p>Try the following:</p>\n\n<pre><code>perl -ne 'print unless m{^//#}' input.txt > output.txt\n</code></pre>\n\n<p>If you are using windows you need double quotes instead of single quotes.</p>\n\n<p>You can do the same with grep</p>\n\n<pre><code>grep -v -e '^//#' input.txt > output.txt\n</code></pre>\n"}, {'answer_id': 80711, 'author': 'David Precious', 'author_id': 4040, 'author_profile': 'https://Stackoverflow.com/users/4040', 'pm_score': 0, 'selected': False, 'text': '<p>Iterate over each line in the file, and skip the line if it matches the pattern:</p>\n\n<pre>\nmy $fh = new FileHandle \'filename\'\n or die "Failed to open file - $!";\n\nwhile (my $line = $fh->getline) {\n next if $line =~ m{^//#};\n print $line;\n}\nclose $fh;\n</pre>\n\n<p>This will print all lines from the file, except the line that starts with \'//#\'.</p>\n'}, {'answer_id': 80791, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 1, 'selected': False, 'text': "<p>You really don't need perl for this.</p>\n\n<pre><code>sed '/^\\/\\/#/d' inputfile > outputfile\n</code></pre>\n\n<p>I <3 sed.</p>\n"}, {'answer_id': 80853, 'author': 'kixx', 'author_id': 11260, 'author_profile': 'https://Stackoverflow.com/users/11260', 'pm_score': 3, 'selected': False, 'text': '<p>To filter out all the lines in a file that match a certain regex:</p>\n\n<pre><code>perl -n -i.orig -e \'print unless /^#/\' file1 file2 file3\n</code></pre>\n\n<p>The \'.orig\' after the -i switch creates a backup of the file with the given extension (.orig). You can skip it if you don\'t need a backup (just use -i).</p>\n\n<p>The -n switch causes perl to execute your instructions (-e \' ... \') for each line in the file. The line is stored in $_ (which is also the default argument for many instructions, in this case: print and regex matching).</p>\n\n<p>Finally, the argument to the -e switch says "print the line unless it matches a # character at the start of the line.</p>\n\n<p>PS. There is also a -p switch which behaves like -n, except the lines are always printed (good for searching and replacing)</p>\n'}, {'answer_id': 80948, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 6, 'selected': True, 'text': '<p>Your regex is badly chosen on several points:</p>\n\n<ol>\n<li><p>Instead of matching two slashes specifically, you use <code>..</code> to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match <em>almost</em> anything, as we’ll see in #3.)</p>\n\n<p>Within a slash-delimited regex literal, <code>//</code>, you can match slashes simply by protecting them with backslashes, eg. <code>/\\/\\//</code>. The nicer variant, however, is to use the longer form of regex literal, <code>m//</code>, where you can choose the delimiter, eg. <code>m!!</code>. Since you use something other than slashes for delimitation, you can then write them without escaping them: <code>m!//!</code>. See <a href="http://p3rl.org/op#Quote-and-Quote-like-Operators" rel="noreferrer">perldoc perlop</a>.</p></li>\n<li><p>It’s not anchored to the start of the string so it will match anywhere. Use the <code>^</code> start-of-string assertion in front.</p></li>\n<li><p>You wrote <code>[^\\n]</code> to match “any character except newline” when there is a much simpler way to write that, which is just the <code>.</code> wildcard. It does exactly that – match any character except newline.</p></li>\n<li><p>You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous.</p></li>\n</ol>\n\n<p>Altogether, that makes it <code>m!^//#.*!</code>. But putting an uncaptured <code>.*</code> (or anything with a <code>*</code> quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the <code>*</code> is happy to match nothing at all.</p>\n\n<p>So that leaves you with <code>m!^//#!</code>.</p>\n\n<p>As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily:</p>\n\n<pre><code>perl -ni.bak -e\'print unless m!^//#!\' somefile.txt\n</code></pre>\n\n<p>Here, the <code>-n</code> switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The <code>-i</code> switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The <code>.bak</code> parameter to the <code>-i</code> option tells perl to keep a backup of the original file in a file named after the original file name with <code>.bak</code> appended. For all of these bits, see <a href="http://p3rl.org/run" rel="noreferrer">perldoc perlrun</a>.</p>\n\n<p>If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with <a href="http://p3rl.org/IO::AtomicFile" rel="noreferrer">IO::AtomicFile</a>, another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed.</p>\n'}, {'answer_id': 81383, 'author': 'arclight', 'author_id': 13366, 'author_profile': 'https://Stackoverflow.com/users/13366', 'pm_score': 2, 'selected': False, 'text': '<p>As others have pointed out, if the end goal is only to remove lines starting with <code>//#</code>, for performance reasons you are probably better off using <code>grep</code> or <code>sed</code>:</p>\n\n<pre><code>grep -v \'^\\/\\/#\' filename.txt > filename.stripped.txt\n\nsed \'/^\\/\\/#/d\' filename.txt > filename.stripped.txt\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sed -i \'/^\\/\\/#/d\' filename.txt\n</code></pre>\n\n<p>if you prefer in-place editing.</p>\n\n<p>Note that in perl your regex would be</p>\n\n<pre><code>m{^//#}\n</code></pre>\n\n<p>which matches two slashes followed by a # at the start of the string.</p>\n\n<p>Note that you avoid "backslashitis" by using the match operator <code>m{pattern}</code> instead of the more familiar <code>/pattern/</code>. Train yourself on this syntax early since it\'s a simple way to avoid excessive escaping. You could write <code>m{^//#}</code> just as effectively as <code>m%^//#%</code> or <code>m#^//\\##</code>, depending on what you want to match. Strive for clarity - regular expressions are hard enough to decipher without a prickly forest of avoidable backslashes killing readability. Seriously, <code>m/^\\/\\/#/</code> looks like an alligator with a chipped tooth and a filling or a tiny ASCII painting of the Alps.</p>\n\n<p>One problem that might come up in your script is if the entire file is slurped up into a string, newlines and all. To defend against that case, use the /m (multiline) modifier on the regex:</p>\n\n<pre><code>m{^//#}m\n</code></pre>\n\n<p>This allows ^ to match at the beginning of the string <em>and</em> after a newline. You would think there was a way to strip or match the lines matching <code>m{^//#.*$}</code> using the regex modifiers <code>/g</code>, <code>/m</code>, and <code>/s</code> in the case where you\'ve slurped the file into a string but you don\'t want to make a copy of it (begging the question of why it was slurped into a string in the first place.) It <em>should</em> be possible, but it\'s late and I\'m not seeing the answer. However, one \'simple\' way of doing it is:</p>\n\n<pre><code>my $cooked = join qq{\\n}, (grep { ! m{^//} } (split m{\\n}, $raw));\n</code></pre>\n\n<p>even though that creates a copy instead of an in-place edit on the original string <code>$raw</code>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13046/'] |
80,424 | <p>I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.</p>
<p>I found this via Google (which I've customized a little):</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This works great, except for a few occasions where account_id is ambiguous so I adapted it to:</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?</p>
<p>When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.</p>
<p>(I'm using Rails v2.1)</p>
| [{'answer_id': 80440, 'author': 'Jean', 'author_id': 7898, 'author_profile': 'https://Stackoverflow.com/users/7898', 'pm_score': 4, 'selected': True, 'text': '<p>You don\'t tell us which version of rails you are using [edit - it is on rails 2.1 thus following advice is fully operational], but I would recommand you use the following form instead of overloading find yourself : </p>\n\n<pre><code>account.contacts.find(...) \n</code></pre>\n\n<p>this will automatically wrap the find in a scope where the user clause is included (since you have the account_id I assume you have the account somewhere close)</p>\n\n<p>I suggest you check the following resources on scopes</p>\n\n<ul>\n<li><a href="http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality" rel="nofollow noreferrer">http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality</a>\n(this is not edge anymore :) )</li>\n<li><a href="http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know" rel="nofollow noreferrer">http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know</a></li>\n</ul>\n'}, {'answer_id': 80610, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>to give a specific answer to your problem, I\'d suggest moving the above mentioned method into a module to be included by the models in question; so you\'d have </p>\n\n<pre><code>class Contact\n include NarrowFind\n ...\nend\n</code></pre>\n\n<p>PS. watch out for sql escaping of the account_id, you should probably use the <code>:conditions=>[".... =?", $account_id]</code> syntax.</p>\n'}, {'answer_id': 83010, 'author': 'Nathan de Vries', 'author_id': 11109, 'author_profile': 'https://Stackoverflow.com/users/11109', 'pm_score': 3, 'selected': False, 'text': "<p>Jean's advice is sound. Assuming your models look like this:</p>\n\n<pre><code>class Contact < ActiveRecord::Base\n belongs_to :account\nend\n\nclass Account < ActiveRecord::Base\n has_many :contacts\nend\n</code></pre>\n\n<p>You should be using the <code>contacts</code> association of the current account to ensure that you're only getting <code>Contact</code> records scoped to that account, like so:</p>\n\n<pre><code>@account.contacts\n</code></pre>\n\n<p>If you would like to add further conditions to your contacts query, you can specify them using find:</p>\n\n<pre><code>@account.contacts.find(:conditions => { :activated => true })\n</code></pre>\n\n<p>And if you find yourself constantly querying for activated users, you can refactor it into a named scope:</p>\n\n<pre><code>class Contact < ActiveRecord::Base\n belongs_to :account\n named_scope :activated, :conditions => { :activated => true }\nend\n</code></pre>\n\n<p>Which you would then use like this:</p>\n\n<pre><code>@account.contacts.activated\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14530/'] |
80,427 | <p>Code I have:</p>
<pre><code>cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
</code></pre>
<p>This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.</p>
| [{'answer_id': 80457, 'author': 'jan.vdbergh', 'author_id': 9540, 'author_profile': 'https://Stackoverflow.com/users/9540', 'pm_score': 5, 'selected': True, 'text': '<p>I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:</p>\n\n<pre><code>For iter = 1 To Len(cell_val) \n If Asc(Mid(cell_val, iter, 1)) > 127 Then\n addlog "Export contains ascii character > 127"\n End If\nNext\n</code></pre>\n'}, {'answer_id': 80460, 'author': 'Per Hornshøj-Schierbeck', 'author_id': 11619, 'author_profile': 'https://Stackoverflow.com/users/11619', 'pm_score': 0, 'selected': False, 'text': "<p>Did you debug it? ;) Are you sure the cell_val is not empty? Also you don't need the 'Step 1' in the For loop since it's default. Also what do you expect to acomplish with your code? It logs if any ascii values are above 127? But that's it - there is no branching depending on the result?</p>\n"}, {'answer_id': 80462, 'author': 'Scott Evernden', 'author_id': 11397, 'author_profile': 'https://Stackoverflow.com/users/11397', 'pm_score': 0, 'selected': False, 'text': '<p>Try AscW()</p>\n'}, {'answer_id': 80472, 'author': 'paxdiablo', 'author_id': 14860, 'author_profile': 'https://Stackoverflow.com/users/14860', 'pm_score': 0, 'selected': False, 'text': "<p>VB/VBA strings are based from one rather than zero so you need to use:</p>\n\n<pre><code>For iter = 1 To Len(cell_val)\n</code></pre>\n\n<p>I've also left off the <code>step 1</code> since that's the default.</p>\n"}, {'answer_id': 80489, 'author': 'vzczc', 'author_id': 224, 'author_profile': 'https://Stackoverflow.com/users/224', 'pm_score': 2, 'selected': False, 'text': '<p>Your example should be modfied so it does not have external dependencies, it now depends on Nz and addLog.</p>\n\n<p>Anyway, the problem here seems to be that you are looping from 0 to len()-1. In VBA this would be 1 to n.</p>\n\n<pre><code> Dim cell_val As String\n cell_val = "øabcdæøå~!#%&/()"\n Dim iter As Long\n For iter = 1 To Len(cell_val)\n If Asc(Mid(cell_val, iter, 1)) > 127 Then\n \'addlog "Export contains ascii character > 127"\n Debug.Print iter, "Export contains ascii character > 127"\n End If\n Next iter\n</code></pre>\n'}, {'answer_id': 80530, 'author': 'bfabry', 'author_id': 924607, 'author_profile': 'https://Stackoverflow.com/users/924607', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>Did you debug it? ;) Are you sure the\n cell_val is not empty? Also you don't\n need the 'Step 1' in the For loop\n since it's default. Also what do you\n expect to acomplish with your code? It\n logs if any ascii values are above\n 127? But that's it - there is no\n branching depending on the result?</p>\n</blockquote>\n\n<p>I didn't debug it, I have no idea how to use vba or any of the tools that go along with it.\nYes I am sure cell_val is not empty.\nThe code was representative, I was ensuring the branch condition works before writing the branch itself.</p>\n\n<blockquote>\n <p>I believe your problem is that in VBA string indexes start at 1 and not at 0.</p>\n</blockquote>\n\n<p>Ah, the exact kind of thing that goes along with vba that I was bound to miss, thank you.</p>\n"}, {'answer_id': 80531, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 2, 'selected': False, 'text': '<p>With VBA, VB6 you can just declare a byte array and assign a string value to it and it will be converted for you. Then you can just iterate through it like a regular array.</p>\n\n<p>e.g.</p>\n\n<pre><code>Dim b() as byte\nDim iter As Long\nb = CStr(Nz(fld.value, ""))\n\nFor iter = 0 To UBound(b)\n if b(iter) > 127 then\n addlog "Export contains ascii character > 127"\n end if\nnext\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/924607/'] |
80,447 | <p>What are futures? It's something to do with lazy evaluation.</p>
| [{'answer_id': 80464, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 2, 'selected': False, 'text': '<p>A Future encapsulates a deferred calculation, and is commonly used to shoehorn lazy evaluation into a non-lazy language. The first time a future is evaluated, the code required to evaluate it is run, and the future is replaced with the result. </p>\n\n<p>Since the future is replaced, subsequent evaluations do not execute the code again, and simply yield the result.</p>\n'}, {'answer_id': 80469, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 3, 'selected': False, 'text': '<p>When you create a future, a new background thread is started that begins calculating the real value. If you request the value of the future, it will block until the thread has finished calculating. This is very useful for when you need to generate some values in parallel and don\'t want to manually keep track of it all.</p>\n\n<p>See <a href="http://moonbase.rydia.net/software/lazy.rb/" rel="noreferrer">lazy.rb</a> for Ruby, or <a href="http://www.bluishcoder.co.nz/2006/07/scala-futures-and-lazy-evaluation.html" rel="noreferrer">Scala, futures, and lazy evaluation</a>.</p>\n\n<p>They can probably be implemented in any language with threads, though it would obviously be more difficult in a low-level language like C than in a high-level functional language.</p>\n'}, {'answer_id': 80519, 'author': 'Motti', 'author_id': 3848, 'author_profile': 'https://Stackoverflow.com/users/3848', 'pm_score': 3, 'selected': False, 'text': '<p>There is a <a href="http://en.wikipedia.org/wiki/Future_%28programming%29" rel="nofollow noreferrer">Wikipedia article</a> about futures. In short, it\'s a way to use a value that is not yet known. The value can then be calculated on demand (lazy evaluation) and, optionally, concurrently with the main calculation.</p>\n\n<p>C++ example follows.</p>\n\n<hr>\n\n<p>Say you want to calculate the sum of two numbers. You can either have the typical eager implementation:</p>\n\n<pre><code>int add(int i, int j) { return i + j; }\n// first calculate both Nth_prime results then pass them to add\nint sum = add(Nth_prime(4), Nth_prime(2)); \n</code></pre>\n\n<p>or you can use the futures way using C++11\'s <code>std::async</code>, which returns an <code>std::future</code>. In this case, the <code>add</code> function will only block if it tries to use a value that hasn\'t yet been computed (one can also create a purely lazy alternative).</p>\n\n<pre><code>int add(future<int> i, future<int> j) { return i.get() + j.get(); }\nint sum = add(async(launch::async, [](){ return Nth_prime(4); }),\n async(launch::async, [](){ return Nth_prime(2); }));\n</code></pre>\n'}, {'answer_id': 80635, 'author': 'Robert Gould', 'author_id': 15124, 'author_profile': 'https://Stackoverflow.com/users/15124', 'pm_score': 3, 'selected': False, 'text': "<p>Everyone mentions futures for the purpose of lazy calculation. However another use that isn't as advertised is the use of Futures for IO in general. Especially they're useful for loading files and waiting on network data</p>\n"}, {'answer_id': 80729, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Future_(programming)" rel="nofollow noreferrer">The Wiki Article</a> gives a good overview of Futures. The concept is generally used in concurrent systems, for scheduling computations over values that may or may not have been computed yet, and further, whose computation may or may not already be in progress.</p>\n\n<p>From the article:</p>\n\n<blockquote>\n <p>A future is associated with a\n specific thread that computes its\n value. This computation may be started\n either eagerly when the future is\n created, or lazily when its value is\n first needed.</p>\n</blockquote>\n\n<p>Not mentioned in the article, futures are a <a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming" rel="nofollow noreferrer">Monad</a>, and so it is possible to project functions on future values into the monad to have them applied to the future value when it becomes available, yielding another future which in turn represents the result of that function.</p>\n'}, {'answer_id': 1287691, 'author': 'scope_creep', 'author_id': 89521, 'author_profile': 'https://Stackoverflow.com/users/89521', 'pm_score': 0, 'selected': False, 'text': "<p>Futures are also used in certain design patterns, particularly for real time patterns, for example, the ActiveObject pattern, which seperates method invocation from method execution. The future is setup to wait for the completed execution. I tend to see it when you need to move from a multithreaded enviroment to communicate with a single threaded environment. There may be instances where a piece of hardware doesn't have kernel support for threading, and futures are used in this instance. At first glance it not obvious how you would communicate, and surprisingly futures make it fairly simple. I've got a bit of c# code. I'll dig it out and post it. </p>\n"}, {'answer_id': 5548588, 'author': 'Felix', 'author_id': 238100, 'author_profile': 'https://Stackoverflow.com/users/238100', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://vigtig.it/blog/?p=73#more-73" rel="nofollow">This blog post</a> gives a <strong>very thorough</strong> explanation together with an example of how you could implement a future yourself. I really recommend it :)</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
80,452 | <p>Microsoft WPF? Adobe AIR/Flex? Adobe Flash? Curl programming language?</p>
<p>How does AJAX fit in?</p>
<p>Given a server written in C++ .NET.</p>
| [{'answer_id': 80466, 'author': 'Davide Vosti', 'author_id': 1812, 'author_profile': 'https://Stackoverflow.com/users/1812', 'pm_score': 0, 'selected': False, 'text': '<p>Using WPF you can build desktop and then almost 1:1 port it to silverlight and target the web</p>\n'}, {'answer_id': 80474, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': '<p>What about Silverlight?</p>\n\n<p>Also XAML based solutions with MVP pattern applied could be very good, when UI layer could be rendered based on front-end type and has no strong relationships with business model.</p>\n\n<p>Cheers!</p>\n'}, {'answer_id': 80491, 'author': 'Robert Gould', 'author_id': 15124, 'author_profile': 'https://Stackoverflow.com/users/15124', 'pm_score': 0, 'selected': False, 'text': "<p>I remember seeing a free C++ library that gave you a Web-base UI. \nDidn't try it, and can't remember it's name but that could the trick if you want C++.</p>\n\n<p>Or perhaps I'd go with Adobe's Air or Google's Gear stuff.\nif you want something you can do over a weekend.</p>\n"}, {'answer_id': 80513, 'author': 'Jobi Joy', 'author_id': 8091, 'author_profile': 'https://Stackoverflow.com/users/8091', 'pm_score': 0, 'selected': False, 'text': '<p>Consider developing the app in Silverlight and having either of the bellow 2 methods to make the same Silverlight App running in Desktop too. I admit that both of these are just silly tricks but it helps if your app doesnt have much layer dependancies.</p>\n<ol>\n<li><a href="https://jobijoy.blogspot.com/2008/09/desklighter-handy-tool-for-silverlight.html" rel="nofollow noreferrer">http://jobijoy.blogspot.com/2008/09/desklighter-handy-tool-for-silverlight.html</a></li>\n<li><a href="https://web.archive.org/web/20210125001349/http://geekswithblogs.net/lbugnion/archive/2008/04/24/silverlight-running-standalone-full-trust-applications.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/lbugnion/archive/2008/04/24/silverlight-running-standalone-full-trust-applications.aspx</a></li>\n</ol>\n<p>There is another technology which is going to come from Microsoft called <a href="https://www.microsoft.com/en-us/mesh?rtc=1" rel="nofollow noreferrer">Live Mesh</a> also going to support both Offline and Online silverlight application.</p>\n'}, {'answer_id': 80989, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>We\'ve created an application which does 3D visualization in a browser or as a standalone application.</p>\n\n<p>The application is written in JavaScript (for app logic) and C++ (for 3D rendering) and uses the Qt library from <a href="http://www.trolltech.com" rel="nofollow noreferrer">http://www.trolltech.com</a>.</p>\n\n<p>When running in a browser, the application is wrapped in a thin layer as an ActiveX control (for IE) and as a Netscape browser plugin (for Firefox, Mozilla, Netscape, Opera). Qt does the plugin wrapping more or less automatically.</p>\n'}, {'answer_id': 81005, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 0, 'selected': False, 'text': "<p>Your two main choice are Silverlight / WPF & Flex / Air.</p>\n\n<p>If you're familiar with the .NET framework use the first, if you're more familiar with Flash / ECMA script, use the later.</p>\n\n<p>Use the best tool for the job. If both tools are the same, use the one that you are more highly trained in, or could pick up the easiest.</p>\n"}, {'answer_id': 81070, 'author': 'James Strachan', 'author_id': 2068211, 'author_profile': 'https://Stackoverflow.com/users/2068211', 'pm_score': 2, 'selected': True, 'text': '<p>The answer does depend really on what your application actually does and your platform requirements. </p>\n\n<p>If its a regular web application like gmail and you want it to work on lots of browsers and platforms; then I\'d recommend a combination of HTML, CSS and <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">GWT</a> as this means your application code is all Java, its very easy to refactor modularise and maintain, there\'s a ton of Java programmers out there and the IDEs for Java are awesome (IntelliJ or eclipse etc).</p>\n\n<p>You can then use browser plugins like Siverlight or Flex if and when they make sense (e.g. like <a href="http://finance.google.com/finance" rel="nofollow noreferrer">Google finance</a> uses Flash for interactive graphs).</p>\n\n<p>If your application is highly graphical like a Visio type of thing or needs to embed Microsoft Office or something; you might wanna look at Silverlight/Flex/AIR particularly if you can kinda dictate the browser versions and platforms for an internal application.</p>\n\n<p>Though with client side there\'s no clear single answer (just look at the comments on this thread :) there are many options (Java Applets/Swing/JavaFX, Ajax, GWT, Air/Flex, Silverlight/.Net etc) which all have strengths and weaknesses. My recommendation for the communication between the client and your C++ server would be to expose your C++ application as a set of RESTful resources - then at any point in time you can easily write other kinds of clients in any language technology or framework.</p>\n'}, {'answer_id': 123660, 'author': 'David', 'author_id': 21328, 'author_profile': 'https://Stackoverflow.com/users/21328', 'pm_score': 0, 'selected': False, 'text': '<p>Create a DHTML/Ajax app and use <a href="http://gears.google.com/" rel="nofollow noreferrer">Google Gears</a> to persist data so it can still function when off-line.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15112/'] |
80,470 | <p>I'm trying to find out what the performance of a large directory structure would be if deep directories were to be accessed on a shared, nfs filesystem. The structure would be excessively large, with 4 levels of nested directories, each level containing 1024 directories. (1024 at root, 1024 in a given subdirectory, and so on).</p>
<p>This filesystem would be on a network repository that users would be accessing for their personal information. The data would be replicated on multiple servers and load-balanced, but still, each machine would have a decent load at all times.</p>
<p>If the 4th level contained the information that the users were looking for, how bad would the performance be? If all were accessing different subdirectories? Could this be resolved by caching inode information, or no? </p>
<p>I've been searching on this for a while, but I'm primarily finding information on large files rather than large directory structures. </p>
| [{'answer_id': 80488, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 0, 'selected': False, 'text': "<p>The answer here is going to be highly dependent on your operating system, can you provide more information? I have found that file open times under Linux have been reasonable up to directory sizes in the small tens of thousands, but I have not tried any tests with directory structures as large as yours (you do know that 1024 to the fourth power is 1,099,511,627,776 right? And that that's something like 180 times the population of the earth, right?)</p>\n"}, {'answer_id': 80496, 'author': 'Tom Carr', 'author_id': 14954, 'author_profile': 'https://Stackoverflow.com/users/14954', 'pm_score': 0, 'selected': False, 'text': "<p>Seems like you'd just want to write an test app to generate 1024 folders, iterated 8 levels down, with each folder containing some number (100 - 1000?) of files 1KB in size and then randomly find and access the files. </p>\n\n<p>Track the access times over multiple passes and see if it's acceptable to your requirements.</p>\n"}, {'answer_id': 85076, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 2, 'selected': True, 'text': "<p>I did that at my work once. Don't remember the exact numbers offhand, but I think it was 8 levels deep, 10 subdirectories in each level (user id 87654321 maps to directory 8/7/6/5/4/3/2/1/. Turned out that was not such a great idea, started running into problems with filesystem inode number limits, iirc (10^10 = 10000000000 directories, not good). Switched to more subdirectories per level and many less levels; problems went away. Your situation sounds more manageable, but still, check that your filesystem would support the kinds of file and directory counts that you're anticipating.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13825/'] |
80,476 | <p>I need to concatenate two <code>String</code> arrays in Java.</p>
<pre><code>void f(String[] first, String[] second) {
String[] both = ???
}
</code></pre>
<p>Which is the easiest way to do this?</p>
| [{'answer_id': 80503, 'author': 'jeannicolas', 'author_id': 14981, 'author_profile': 'https://Stackoverflow.com/users/14981', 'pm_score': 10, 'selected': False, 'text': '<p>Here\'s a simple method that will concatenate two arrays and return the result:</p>\n\n<pre><code>public <T> T[] concatenate(T[] a, T[] b) {\n int aLen = a.length;\n int bLen = b.length;\n\n @SuppressWarnings("unchecked")\n T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);\n System.arraycopy(a, 0, c, 0, aLen);\n System.arraycopy(b, 0, c, aLen, bLen);\n\n return c;\n}\n</code></pre>\n\n<p>Note that it will not work with primitive data types, only with object types.</p>\n\n<p>The following slightly more complicated version works with both object and primitive arrays. It does this by using <code>T</code> instead of <code>T[]</code> as the argument type.</p>\n\n<p>It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.</p>\n\n<pre><code>public static <T> T concatenate(T a, T b) {\n if (!a.getClass().isArray() || !b.getClass().isArray()) {\n throw new IllegalArgumentException();\n }\n\n Class<?> resCompType;\n Class<?> aCompType = a.getClass().getComponentType();\n Class<?> bCompType = b.getClass().getComponentType();\n\n if (aCompType.isAssignableFrom(bCompType)) {\n resCompType = aCompType;\n } else if (bCompType.isAssignableFrom(aCompType)) {\n resCompType = bCompType;\n } else {\n throw new IllegalArgumentException();\n }\n\n int aLen = Array.getLength(a);\n int bLen = Array.getLength(b);\n\n @SuppressWarnings("unchecked")\n T result = (T) Array.newInstance(resCompType, aLen + bLen);\n System.arraycopy(a, 0, result, 0, aLen);\n System.arraycopy(b, 0, result, aLen, bLen); \n\n return result;\n}\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));\nAssert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));\n</code></pre>\n'}, {'answer_id': 80559, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 10, 'selected': False, 'text': '<p>I found a one-line solution from the good old Apache Commons Lang library.<br> <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#addAll%28T%5B%5D,%20T...%29" rel="noreferrer"><code>ArrayUtils.addAll(T[], T...)</code></a></p>\n\n<p>Code:</p>\n\n<pre><code>String[] both = ArrayUtils.addAll(first, second);\n</code></pre>\n'}, {'answer_id': 80621, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://functionaljava.org" rel="noreferrer">Functional Java</a> library has an array wrapper class that equips arrays with handy methods like concatenation.</p>\n\n<pre><code>import static fj.data.Array.array;\n</code></pre>\n\n<p>...and then</p>\n\n<pre><code>Array<String> both = array(first).append(array(second));\n</code></pre>\n\n<p>To get the unwrapped array back out, call</p>\n\n<pre><code>String[] s = both.array();\n</code></pre>\n'}, {'answer_id': 80977, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Using only Javas own API:</p>\n\n<pre><code>\nString[] join(String[]... arrays) {\n // calculate size of target array\n int size = 0;\n for (String[] array : arrays) {\n size += array.length;\n }\n\n // create list of appropriate size\n java.util.List list = new java.util.ArrayList(size);\n\n // add arrays\n for (String[] array : arrays) {\n list.addAll(java.util.Arrays.asList(array));\n }\n\n // create and return final array\n return list.toArray(new String[size]);\n}\n</code></pre>\n\n<p>Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).</p>\n'}, {'answer_id': 85216, 'author': 'volley', 'author_id': 13905, 'author_profile': 'https://Stackoverflow.com/users/13905', 'pm_score': 4, 'selected': False, 'text': '<p>Here\'s an adaptation of silvertab\'s solution, with generics retrofitted:</p>\n\n<pre><code>static <T> T[] concat(T[] a, T[] b) {\n final int alen = a.length;\n final int blen = b.length;\n final T[] result = (T[]) java.lang.reflect.Array.\n newInstance(a.getClass().getComponentType(), alen + blen);\n System.arraycopy(a, 0, result, 0, alen);\n System.arraycopy(b, 0, result, alen, blen);\n return result;\n}\n</code></pre>\n\n<p>NOTE: See <a href="https://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java/784842#784842">Joachim\'s answer</a> for a Java 6 solution. Not only does it eliminate the warning; it\'s also shorter, more efficient and easier to read!</p>\n'}, {'answer_id': 85266, 'author': 'volley', 'author_id': 13905, 'author_profile': 'https://Stackoverflow.com/users/13905', 'pm_score': 5, 'selected': False, 'text': "<p>I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):</p>\n\n<pre><code>private static <T> T[] concatOrReturnSame(T[] a, T[] b) {\n final int alen = a.length;\n final int blen = b.length;\n if (alen == 0) {\n return b;\n }\n if (blen == 0) {\n return a;\n }\n final T[] result = (T[]) java.lang.reflect.Array.\n newInstance(a.getClass().getComponentType(), alen + blen);\n System.arraycopy(a, 0, result, 0, alen);\n System.arraycopy(b, 0, result, alen, blen);\n return result;\n}\n</code></pre>\n\n<p>Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!</p>\n"}, {'answer_id': 96892, 'author': 'Fabian Steeg', 'author_id': 18154, 'author_profile': 'https://Stackoverflow.com/users/18154', 'pm_score': 6, 'selected': False, 'text': '<p>Using the Java API:</p>\n\n<pre><code>String[] f(String[] first, String[] second) {\n List<String> both = new ArrayList<String>(first.length + second.length);\n Collections.addAll(both, first);\n Collections.addAll(both, second);\n return both.toArray(new String[both.size()]);\n}\n</code></pre>\n'}, {'answer_id': 135237, 'author': 'Bob Cross', 'author_id': 5812, 'author_profile': 'https://Stackoverflow.com/users/5812', 'pm_score': 2, 'selected': False, 'text': "<p>If you'd like to work with ArrayLists in the solution, you can try this:</p>\n\n<pre><code>public final String [] f(final String [] first, final String [] second) {\n // Assuming non-null for brevity.\n final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));\n resultList.addAll(new ArrayList<String>(Arrays.asList(second)));\n return resultList.toArray(new String [resultList.size()]);\n}\n</code></pre>\n"}, {'answer_id': 707558, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I tested below code and worked ok</p>\n\n<p>Also I\'m using library: org.apache.commons.lang.ArrayUtils</p>\n\n<pre><code>public void testConcatArrayString(){\n String[] a = null;\n String[] b = null;\n String[] c = null;\n a = new String[] {"1","2","3","4","5"};\n b = new String[] {"A","B","C","D","E"};\n\n c = (String[]) ArrayUtils.addAll(a, b);\n if(c!=null){\n for(int i=0; i<c.length; i++){\n System.out.println("c[" + (i+1) + "] = " + c[i]);\n }\n }\n}\n</code></pre>\n\n<p>Regards</p>\n'}, {'answer_id': 784813, 'author': 'glue', 'author_id': 94685, 'author_profile': 'https://Stackoverflow.com/users/94685', 'pm_score': 3, 'selected': False, 'text': '<p>This works, but you need to insert your own error checking.</p>\n\n<pre><code>public class StringConcatenate {\n\n public static void main(String[] args){\n\n // Create two arrays to concatenate and one array to hold both\n String[] arr1 = new String[]{"s","t","r","i","n","g"};\n String[] arr2 = new String[]{"s","t","r","i","n","g"};\n String[] arrBoth = new String[arr1.length+arr2.length];\n\n // Copy elements from first array into first part of new array\n for(int i = 0; i < arr1.length; i++){\n arrBoth[i] = arr1[i];\n }\n\n // Copy elements from second array into last part of new array\n for(int j = arr1.length;j < arrBoth.length;j++){\n arrBoth[j] = arr2[j-arr1.length];\n }\n\n // Print result\n for(int k = 0; k < arrBoth.length; k++){\n System.out.print(arrBoth[k]);\n }\n\n // Additional line to make your terminal look better at completion!\n System.out.println();\n }\n}\n</code></pre>\n\n<p>\nIt\'s probably not the most efficient, but it doesn\'t rely on anything other than Java\'s own API.</p>\n'}, {'answer_id': 784842, 'author': 'Joachim Sauer', 'author_id': 40342, 'author_profile': 'https://Stackoverflow.com/users/40342', 'pm_score': 9, 'selected': False, 'text': '<p>It\'s possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28T[],%20int%29" rel="noreferrer"><code>Arrays.copyOf()</code></a></p>\n\n<p>Both versions avoid creating any intermediary <code>List</code> objects and use <code>System.arraycopy()</code> to ensure that copying large arrays is as fast as possible.</p>\n\n<p>For two arrays it looks like this:</p>\n\n<pre><code>public static <T> T[] concat(T[] first, T[] second) {\n T[] result = Arrays.copyOf(first, first.length + second.length);\n System.arraycopy(second, 0, result, first.length, second.length);\n return result;\n}\n</code></pre>\n\n<p>And for a arbitrary number of arrays (>= 1) it looks like this:</p>\n\n<pre><code>public static <T> T[] concatAll(T[] first, T[]... rest) {\n int totalLength = first.length;\n for (T[] array : rest) {\n totalLength += array.length;\n }\n T[] result = Arrays.copyOf(first, totalLength);\n int offset = first.length;\n for (T[] array : rest) {\n System.arraycopy(array, 0, result, offset, array.length);\n offset += array.length;\n }\n return result;\n}\n</code></pre>\n'}, {'answer_id': 786450, 'author': 'MetroidFan2002', 'author_id': 8026, 'author_profile': 'https://Stackoverflow.com/users/8026', 'pm_score': 2, 'selected': False, 'text': '<p>An easy, but inefficient, way to do this (generics not included):</p>\n\n<pre><code>ArrayList baseArray = new ArrayList(Arrays.asList(array1));\nbaseArray.addAll(Arrays.asList(array2));\nString concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);\n</code></pre>\n'}, {'answer_id': 1012285, 'author': 'Damo', 'author_id': 2955, 'author_profile': 'https://Stackoverflow.com/users/2955', 'pm_score': 3, 'selected': False, 'text': '<p>A simple variation allowing the joining of more than one array:</p>\n\n<pre><code>public static String[] join(String[]...arrays) {\n\n final List<String> output = new ArrayList<String>();\n\n for(String[] array : arrays) {\n output.addAll(Arrays.asList(array));\n }\n\n return output.toArray(new String[output.size()]);\n}\n</code></pre>\n'}, {'answer_id': 1012309, 'author': 'Damo', 'author_id': 2955, 'author_profile': 'https://Stackoverflow.com/users/2955', 'pm_score': 2, 'selected': False, 'text': '<p>A type independent variation (UPDATED - thanks to Volley for instantiating T):</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic static <T> T[] join(T[]...arrays) {\n\n final List<T> output = new ArrayList<T>();\n\n for(T[] array : arrays) {\n output.addAll(Arrays.asList(array));\n }\n\n return output.toArray((T[])Array.newInstance(\n arrays[0].getClass().getComponentType(), output.size()));\n}\n</code></pre>\n'}, {'answer_id': 4552278, 'author': 'Sujay', 'author_id': 556856, 'author_profile': 'https://Stackoverflow.com/users/556856', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public String[] concat(String[]... arrays)\n{\n int length = 0;\n for (String[] array : arrays) {\n length += array.length;\n }\n String[] result = new String[length];\n int destPos = 0;\n for (String[] array : arrays) {\n System.arraycopy(array, 0, result, destPos, array.length);\n destPos += array.length;\n }\n return result;\n}\n</code></pre>\n'}, {'answer_id': 4574691, 'author': 'Doug', 'author_id': 543770, 'author_profile': 'https://Stackoverflow.com/users/543770', 'pm_score': 2, 'selected': False, 'text': "<p>Another one based on SilverTab's suggestion, but made to support x number of arguments and not require Java 6. It is also not generic, but I'm sure it could be made generic.</p>\n\n<pre><code>private byte[] concat(byte[]... args)\n{\n int fulllength = 0;\n for (byte[] arrItem : args)\n {\n fulllength += arrItem.length;\n }\n byte[] retArray = new byte[fulllength];\n int start = 0;\n for (byte[] arrItem : args)\n {\n System.arraycopy(arrItem, 0, retArray, start, arrItem.length);\n start += arrItem.length;\n }\n return retArray;\n}\n</code></pre>\n"}, {'answer_id': 5247896, 'author': 'KARASZI István', 'author_id': 221213, 'author_profile': 'https://Stackoverflow.com/users/221213', 'pm_score': 8, 'selected': False, 'text': '<p>Or with the beloved <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ObjectArrays.html#concat(T%5B%5D,%20T%5B%5D,%20java.lang.Class)" rel="noreferrer">Guava</a>:</p>\n\n<pre><code>String[] both = ObjectArrays.concat(first, second, String.class);\n</code></pre>\n\n<p>Also, there are versions for primitive arrays:</p>\n\n<ul>\n<li><code>Booleans.concat(first, second)</code></li>\n<li><code>Bytes.concat(first, second)</code></li>\n<li><code>Chars.concat(first, second)</code></li>\n<li><code>Doubles.concat(first, second)</code></li>\n<li><code>Shorts.concat(first, second)</code></li>\n<li><code>Ints.concat(first, second)</code></li>\n<li><code>Longs.concat(first, second)</code></li>\n<li><code>Floats.concat(first, second)</code></li>\n</ul>\n'}, {'answer_id': 5497557, 'author': 'Adham', 'author_id': 671613, 'author_profile': 'https://Stackoverflow.com/users/671613', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Object[] obj = {"hi","there"};\nObject[] obj2 ={"im","fine","what abt u"};\nObject[] obj3 = new Object[obj.length+obj2.length];\n\nfor(int i =0;i<obj3.length;i++)\n obj3[i] = (i<obj.length)?obj[i]:obj2[i-obj.length];\n</code></pre>\n'}, {'answer_id': 6295624, 'author': 'candrews', 'author_id': 791247, 'author_profile': 'https://Stackoverflow.com/users/791247', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s my slightly improved version of Joachim Sauer\'s concatAll. It can work on Java 5 or 6, using Java 6\'s System.arraycopy if it\'s available at runtime. This method (IMHO) is perfect for Android, as it work on Android <9 (which doesn\'t have System.arraycopy) but will use the faster method if possible.</p>\n\n<pre><code> public static <T> T[] concatAll(T[] first, T[]... rest) {\n int totalLength = first.length;\n for (T[] array : rest) {\n totalLength += array.length;\n }\n T[] result;\n try {\n Method arraysCopyOf = Arrays.class.getMethod("copyOf", Object[].class, int.class);\n result = (T[]) arraysCopyOf.invoke(null, first, totalLength);\n } catch (Exception e){\n //Java 6 / Android >= 9 way didn\'t work, so use the "traditional" approach\n result = (T[]) java.lang.reflect.Array.newInstance(first.getClass().getComponentType(), totalLength);\n System.arraycopy(first, 0, result, 0, first.length);\n }\n int offset = first.length;\n for (T[] array : rest) {\n System.arraycopy(array, 0, result, offset, array.length);\n offset += array.length;\n }\n return result;\n }\n</code></pre>\n'}, {'answer_id': 6301908, 'author': 'Muhammad Haris Altaf', 'author_id': 789261, 'author_profile': 'https://Stackoverflow.com/users/789261', 'pm_score': 0, 'selected': False, 'text': '<p>The easiest way i could find is as following :</p>\n\n<pre>\n<code>\nList allFiltersList = Arrays.asList(regularFilters);\nallFiltersList.addAll(Arrays.asList(preFiltersArray));\nFilter[] mergedFilterArray = (Filter[]) allFiltersList.toArray();\n</code>\n</pre>\n'}, {'answer_id': 6318217, 'author': 'Oritm', 'author_id': 574736, 'author_profile': 'https://Stackoverflow.com/users/574736', 'pm_score': 3, 'selected': False, 'text': '<p>This is a converted function for a String array:</p>\n\n<pre><code>public String[] mergeArrays(String[] mainArray, String[] addArray) {\n String[] finalArray = new String[mainArray.length + addArray.length];\n System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);\n System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);\n\n return finalArray;\n}\n</code></pre>\n'}, {'answer_id': 6691787, 'author': 'Jeroen', 'author_id': 844342, 'author_profile': 'https://Stackoverflow.com/users/844342', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Import java.util.*;\n\nString array1[] = {"bla","bla"};\nString array2[] = {"bla","bla"};\n\nArrayList<String> tempArray = new ArrayList<String>(Arrays.asList(array1));\ntempArray.addAll(Arrays.asList(array2));\nString array3[] = films.toArray(new String[1]); // size will be overwritten if needed\n</code></pre>\n\n<p>You could replace String by a Type/Class of your liking</p>\n\n<p>Im sure this can be made shorter and better, but it works and im to lazy to sort it out further...</p>\n'}, {'answer_id': 6777237, 'author': 'Sushim ', 'author_id': 856097, 'author_profile': 'https://Stackoverflow.com/users/856097', 'pm_score': 0, 'selected': False, 'text': '<p><strong>You can try this</strong></p>\n\n<pre><code> public static Object[] addTwoArray(Object[] objArr1, Object[] objArr2){\n int arr1Length = objArr1!=null && objArr1.length>0?objArr1.length:0;\n int arr2Length = objArr2!=null && objArr2.length>0?objArr2.length:0;\n Object[] resutlentArray = new Object[arr1Length+arr2Length]; \n for(int i=0,j=0;i<resutlentArray.length;i++){\n if(i+1<=arr1Length){\n resutlentArray[i]=objArr1[i];\n }else{\n resutlentArray[i]=objArr2[j];\n j++;\n }\n }\n\n return resutlentArray;\n}\n</code></pre>\n\n<p>U can type cast your array !!!</p>\n'}, {'answer_id': 7724875, 'author': 'francois', 'author_id': 989332, 'author_profile': 'https://Stackoverflow.com/users/989332', 'pm_score': 5, 'selected': False, 'text': '<p>A solution <strong>100% old java</strong> and <strong>without</strong> <code>System.arraycopy</code> (not available in GWT client for example):</p>\n\n<pre><code>static String[] concat(String[]... arrays) {\n int length = 0;\n for (String[] array : arrays) {\n length += array.length;\n }\n String[] result = new String[length];\n int pos = 0;\n for (String[] array : arrays) {\n for (String element : array) {\n result[pos] = element;\n pos++;\n }\n }\n return result;\n}\n</code></pre>\n'}, {'answer_id': 7733971, 'author': 'Ephraim', 'author_id': 432499, 'author_profile': 'https://Stackoverflow.com/users/432499', 'pm_score': 3, 'selected': False, 'text': '<p>How about simply </p>\n\n<pre><code>public static class Array {\n\n public static <T> T[] concat(T[]... arrays) {\n ArrayList<T> al = new ArrayList<T>();\n for (T[] one : arrays)\n Collections.addAll(al, one);\n return (T[]) al.toArray(arrays[0].clone());\n }\n}\n</code></pre>\n\n<p>And just do <code>Array.concat(arr1, arr2)</code>. As long as <code>arr1</code> and <code>arr2</code> are of the same type, this will give you another array of the same type containing both arrays. </p>\n'}, {'answer_id': 8728568, 'author': 'hpgisler', 'author_id': 757684, 'author_profile': 'https://Stackoverflow.com/users/757684', 'pm_score': 3, 'selected': False, 'text': '<p>Here a possible implementation in working code of the pseudo code solution written by silvertab. </p>\n\n<p>Thanks silvertab!</p>\n\n<pre class="lang-java prettyprint-override"><code>public class Array {\n\n public static <T> T[] concat(T[] a, T[] b, ArrayBuilderI<T> builder) {\n T[] c = builder.build(a.length + b.length);\n System.arraycopy(a, 0, c, 0, a.length);\n System.arraycopy(b, 0, c, a.length, b.length);\n return c;\n }\n}\n</code></pre>\n\n<p>Following next is the builder interface. </p>\n\n<p>Note: A builder is necessary because in java it is not possible to do </p>\n\n<p><code>new T[size]</code> </p>\n\n<p>due to generic type erasure:</p>\n\n<pre class="lang-java prettyprint-override"><code>public interface ArrayBuilderI<T> {\n\n public T[] build(int size);\n}\n</code></pre>\n\n<p>Here a concrete builder implementing the interface, building a <code>Integer</code> array:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class IntegerArrayBuilder implements ArrayBuilderI<Integer> {\n\n @Override\n public Integer[] build(int size) {\n return new Integer[size];\n }\n}\n</code></pre>\n\n<p>And finally the application / test:</p>\n\n<pre class="lang-java prettyprint-override"><code>@Test\npublic class ArrayTest {\n\n public void array_concatenation() {\n Integer a[] = new Integer[]{0,1};\n Integer b[] = new Integer[]{2,3};\n Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());\n assertEquals(4, c.length);\n assertEquals(0, (int)c[0]);\n assertEquals(1, (int)c[1]);\n assertEquals(2, (int)c[2]);\n assertEquals(3, (int)c[3]);\n }\n}\n</code></pre>\n'}, {'answer_id': 9512746, 'author': 'Jerome', 'author_id': 811865, 'author_profile': 'https://Stackoverflow.com/users/811865', 'pm_score': -1, 'selected': False, 'text': '<p>In Haskell you can do something like that <code>[a, b, c] ++ [d, e]</code> to get <code>[a, b, c, d, e]</code>. These are Haskell lists concatenated but that\'d very nice to see a similar operator in Java for arrays. Don\'t you think so ? That\'s elegant, simple, generic and it\'s not that difficult to implement.</p>\n\n<p>If you want to, I suggest you to have a look at Alexander Hristov\'s work in his <a href="http://www.ahristov.com/tutoriales/java-compiler/duplicating-lexer.html" rel="nofollow">Hacking the OpenJDK compiler</a>. He explains how to modify javac source to create a new operator. His example consists in defining a \'**\' operator where <code>i ** j = Math.pow(i, j)</code>. One could take that example to implement an operator that concatenates two arrays of same type.<br></p>\n\n<p>Once you do that, you are bound to your customized javac to compile your code but the generated bytecode will be understood by any JVM. <br><br>Of course, you can implement your own array concatenatation method at your source level, there are many examples on how to do it in the other answers !<br>\n<br>\nThere are so many useful operators that could be added, this one would be one of them.</p>\n'}, {'answer_id': 10056834, 'author': 'filosofem', 'author_id': 1319411, 'author_profile': 'https://Stackoverflow.com/users/1319411', 'pm_score': -1, 'selected': False, 'text': '<p>Look at this elegant solution (if you need other type than char, change it):</p>\n\n<pre><code>private static void concatArrays(char[] destination, char[]... sources) {\n int currPos = 0;\n for (char[] source : sources) {\n int length = source.length;\n System.arraycopy(source, 0, destination, currPos, length);\n currPos += length;\n }\n}\n</code></pre>\n\n<p>You can concatenate a every count of arrays.</p>\n'}, {'answer_id': 10382513, 'author': 'user462990', 'author_id': 462990, 'author_profile': 'https://Stackoverflow.com/users/462990', 'pm_score': 2, 'selected': False, 'text': '<p>I found I had to deal with the case where the arrays can be null...</p>\n\n<pre><code>private double[] concat (double[]a,double[]b){\n if (a == null) return b;\n if (b == null) return a;\n double[] r = new double[a.length+b.length];\n System.arraycopy(a, 0, r, 0, a.length);\n System.arraycopy(b, 0, r, a.length, b.length);\n return r;\n\n}\nprivate double[] copyRest (double[]a, int start){\n if (a == null) return null;\n if (start > a.length)return null;\n double[]r = new double[a.length-start];\n System.arraycopy(a,start,r,0,a.length-start); \n return r;\n}\n</code></pre>\n'}, {'answer_id': 11470232, 'author': 'Reto Höhener', 'author_id': 1124509, 'author_profile': 'https://Stackoverflow.com/users/1124509', 'pm_score': 4, 'selected': False, 'text': '<p>Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.</p>\n\n<pre><code>@SuppressWarnings("unchecked")\npublic static <T> T[] concat(T[]... inputArrays) {\n if(inputArrays.length < 2) {\n throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");\n }\n\n for(int i = 0; i < inputArrays.length; i++) {\n if(inputArrays[i] == null) {\n throw new IllegalArgumentException("inputArrays[" + i + "] is null");\n }\n }\n\n int totalLength = 0;\n\n for(T[] array : inputArrays) {\n totalLength += array.length;\n }\n\n T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);\n\n int offset = 0;\n\n for(T[] array : inputArrays) {\n System.arraycopy(array, 0, result, offset, array.length);\n\n offset += array.length;\n }\n\n return result;\n}\n</code></pre>\n'}, {'answer_id': 13112678, 'author': 'doles', 'author_id': 1118233, 'author_profile': 'https://Stackoverflow.com/users/1118233', 'pm_score': 3, 'selected': False, 'text': '<p>Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:</p>\n\n<pre><code>String [] arg1 = new String{"a","b","c"};\nString [] arg2 = new String{"x","y","z"};\n\nArrayList<String> temp = new ArrayList<String>();\ntemp.addAll(Arrays.asList(arg1));\ntemp.addAll(Arrays.asList(arg2));\nString [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);\n</code></pre>\n'}, {'answer_id': 15103456, 'author': 'Earth Engine', 'author_id': 812034, 'author_profile': 'https://Stackoverflow.com/users/812034', 'pm_score': 2, 'selected': False, 'text': "<p>Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a <code>List<T></code> and then calls <code>toArray</code> on it. Some other answers uses <code>ArrayList</code>, and that's fine. But how about implement our own? It is not hard:</p>\n\n<pre><code>private static <T> T[] addAll(final T[] f, final T...o){\n return new AbstractList<T>(){\n\n @Override\n public T get(int i) {\n return i>=f.length ? o[i - f.length] : f[i];\n }\n\n @Override\n public int size() {\n return f.length + o.length;\n }\n\n }.toArray(f);\n}\n</code></pre>\n\n<p>I believe the above is equivalent to solutions that uses <code>System.arraycopy</code>. However I think this one has its own beauty. </p>\n"}, {'answer_id': 17235840, 'author': 'Frimousse', 'author_id': 2509077, 'author_profile': 'https://Stackoverflow.com/users/2509077', 'pm_score': 2, 'selected': False, 'text': '<pre><code>String [] both = new ArrayList<String>(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);\n</code></pre>\n'}, {'answer_id': 18350255, 'author': 'h-rai', 'author_id': 1109689, 'author_profile': 'https://Stackoverflow.com/users/1109689', 'pm_score': 5, 'selected': False, 'text': '<pre><code>ArrayList<String> both = new ArrayList(Arrays.asList(first));\nboth.addAll(Arrays.asList(second));\n\nboth.toArray(new String[0]);\n</code></pre>\n'}, {'answer_id': 19666913, 'author': 'SuperCamp', 'author_id': 2782483, 'author_profile': 'https://Stackoverflow.com/users/2782483', 'pm_score': -1, 'selected': False, 'text': '<p>Should do the trick. This is assuming String[] first and String[] second</p>\n\n<pre><code>List<String> myList = new ArrayList<String>(Arrays.asList(first));\nmyList.addAll(new ArrayList<String>(Arrays.asList(second)));\nString[] both = myList.toArray(new String[myList.size()]);\n</code></pre>\n'}, {'answer_id': 20903551, 'author': 'Ricardo Vallejo', 'author_id': 3144146, 'author_profile': 'https://Stackoverflow.com/users/3144146', 'pm_score': 0, 'selected': False, 'text': '<p>This one works only with int but the idea is generic</p>\n\n<pre><code>public static int[] junta(int[] v, int[] w) {\n\nint[] junta = new int[v.length + w.length];\n\nfor (int i = 0; i < v.length; i++) { \n junta[i] = v[i];\n}\n\nfor (int j = v.length; j < junta.length; j++) {\n junta[j] = w[j - v.length];\n}\n</code></pre>\n'}, {'answer_id': 23188881, 'author': 'Vitalii Fedorenko', 'author_id': 288671, 'author_profile': 'https://Stackoverflow.com/users/288671', 'pm_score': 9, 'selected': False, 'text': '<p>Using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="noreferrer"><code>Stream</code></a> in Java 8:</p>\n\n<pre><code>String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))\n .toArray(String[]::new);\n</code></pre>\n\n<p>Or like this, using <code>flatMap</code>:</p>\n\n<pre><code>String[] both = Stream.of(a, b).flatMap(Stream::of)\n .toArray(String[]::new);\n</code></pre>\n\n<p>To do this for a generic type you have to use reflection:</p>\n\n<pre><code>@SuppressWarnings("unchecked")\nT[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(\n size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));\n</code></pre>\n'}, {'answer_id': 25026341, 'author': 'spacebiker', 'author_id': 1114732, 'author_profile': 'https://Stackoverflow.com/users/1114732', 'pm_score': 2, 'selected': False, 'text': '<p>I think the best solution with generics would be:</p>\n\n<pre><code>/* This for non primitive types */\npublic static <T> T[] concatenate (T[]... elements) {\n\n T[] C = null;\n for (T[] element: elements) {\n if (element==null) continue;\n if (C==null) C = (T[]) Array.newInstance(element.getClass().getComponentType(), element.length);\n else C = resizeArray(C, C.length+element.length);\n\n System.arraycopy(element, 0, C, C.length-element.length, element.length);\n }\n\n return C;\n}\n\n/**\n * as far as i know, primitive types do not accept generics \n * http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types\n * for primitive types we could do something like this:\n * */\npublic static int[] concatenate (int[]... elements){\n int[] C = null;\n for (int[] element: elements) {\n if (element==null) continue;\n if (C==null) C = new int[element.length];\n else C = resizeArray(C, C.length+element.length);\n\n System.arraycopy(element, 0, C, C.length-element.length, element.length);\n }\n return C;\n}\n\nprivate static <T> T resizeArray (T array, int newSize) {\n int oldSize =\n java.lang.reflect.Array.getLength(array);\n Class elementType =\n array.getClass().getComponentType();\n Object newArray =\n java.lang.reflect.Array.newInstance(\n elementType, newSize);\n int preserveLength = Math.min(oldSize, newSize);\n if (preserveLength > 0)\n System.arraycopy(array, 0,\n newArray, 0, preserveLength);\n return (T) newArray;\n}\n</code></pre>\n'}, {'answer_id': 28466684, 'author': 'clément francomme', 'author_id': 4151755, 'author_profile': 'https://Stackoverflow.com/users/4151755', 'pm_score': 2, 'selected': False, 'text': '<p>How about :</p>\n\n<pre><code>public String[] combineArray (String[] ... strings) {\n List<String> tmpList = new ArrayList<String>();\n for (int i = 0; i < strings.length; i++)\n tmpList.addAll(Arrays.asList(strings[i]));\n return tmpList.toArray(new String[tmpList.size()]);\n}\n</code></pre>\n'}, {'answer_id': 33018648, 'author': 'George', 'author_id': 791195, 'author_profile': 'https://Stackoverflow.com/users/791195', 'pm_score': 1, 'selected': False, 'text': '<pre><code>public int[] mergeArrays(int [] a, int [] b) {\n int [] merged = new int[a.length + b.length];\n int i = 0, k = 0, l = a.length;\n int j = a.length > b.length ? a.length : b.length;\n while(i < j) {\n if(k < a.length) {\n merged[k] = a[k];\n k++;\n }\n if((l - a.length) < b.length) {\n merged[l] = b[l - a.length];\n l++;\n }\n i++;\n }\n return merged;\n}\n</code></pre>\n'}, {'answer_id': 33711992, 'author': 'Paul', 'author_id': 4908555, 'author_profile': 'https://Stackoverflow.com/users/4908555', 'pm_score': 4, 'selected': False, 'text': '<p>You could try converting it into a <code>ArrayList</code> and use the <code>addAll</code> method then convert back to an array.</p>\n<pre><code>List list = new ArrayList(Arrays.asList(first));\n list.addAll(Arrays.asList(second));\n String[] both = list.toArray();\n</code></pre>\n'}, {'answer_id': 35315750, 'author': 'Vaseph', 'author_id': 1912860, 'author_profile': 'https://Stackoverflow.com/users/1912860', 'pm_score': 4, 'selected': False, 'text': '<p>Another way with Java8 using Stream</p>\n\n<pre><code> public String[] concatString(String[] a, String[] b){ \n Stream<String> streamA = Arrays.stream(a);\n Stream<String> streamB = Arrays.stream(b);\n return Stream.concat(streamA, streamB).toArray(String[]::new); \n }\n</code></pre>\n'}, {'answer_id': 35644035, 'author': 'Kamil Tomasz Jarmusik', 'author_id': 5642475, 'author_profile': 'https://Stackoverflow.com/users/5642475', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static String[] toArray(String[]... object){\n List<String> list=new ArrayList<>();\n for (String[] i : object) {\n list.addAll(Arrays.asList(i));\n }\n return list.toArray(new String[list.size()]);\n}\n</code></pre>\n'}, {'answer_id': 38448403, 'author': 'obwan02', 'author_id': 6554496, 'author_profile': 'https://Stackoverflow.com/users/6554496', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Object[] mixArray(String[] a, String[] b)\nString[] s1 = a;\nString[] s2 = b;\nObject[] result;\nList<String> input = new ArrayList<String>();\nfor (int i = 0; i < s1.length; i++)\n{\n input.add(s1[i]);\n}\nfor (int i = 0; i < s2.length; i++)\n{\n input.add(s2[i]);\n}\nresult = input.toArray();\nreturn result;\n</code></pre>\n'}, {'answer_id': 39322165, 'author': 'Douglas Held', 'author_id': 399723, 'author_profile': 'https://Stackoverflow.com/users/399723', 'pm_score': 2, 'selected': False, 'text': '<p>Every single answer is copying data and creating a new array. This is not strictly necessary and is definitely NOT what you want to do if your arrays are reasonably large. Java creators already knew that array copies are wasteful and that is why they provided us System.arrayCopy() to do those outside Java when we have to.</p>\n\n<p>Instead of copying your data around, consider leaving it in place and draw from it where it lies. Copying data locations just because the programmer would like to organize them is not always sensible.</p>\n\n<pre><code>// I have arrayA and arrayB; would like to treat them as concatenated\n// but leave my damn bytes where they are!\nObject accessElement ( int index ) {\n if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);\n // is reading from the head part?\n if ( index < arrayA.length )\n return arrayA[ index ];\n // is reading from the tail part?\n if ( index < ( arrayA.length + arrayB.length ) )\n return arrayB[ index - arrayA.length ];\n throw new ArrayIndexOutOfBoundsException(...); // index too large\n}\n</code></pre>\n'}, {'answer_id': 40855217, '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 <a href="https://github.com/landawn/AbacusUtil" rel="nofollow noreferrer">AbacusUtil</a>.</p>\n\n<pre><code>String[] a = {"a", "b", "c"};\nString[] b = {"1", "2", "3"};\nString[] c = N.concat(a, b); // c = ["a", "b", "c", "1", "2", "3"]\n\n// N.concat(...) is null-safety.\na = null;\nc = N.concat(a, b); // c = ["1", "2", "3"]\n</code></pre>\n'}, {'answer_id': 40991067, 'author': 'Yashovardhan99', 'author_id': 7252861, 'author_profile': 'https://Stackoverflow.com/users/7252861', 'pm_score': -1, 'selected': False, 'text': '<pre><code> void f(String[] first, String[] second) {\n String[] both = new String[first.length+second.length];\n for(int i=0;i<first.length;i++)\n both[i] = first[i];\n for(int i=0;i<second.length;i++)\n both[first.length + i] = second[i];\n}\n</code></pre>\n\n<p>This one works without knowledge of any other classes/libraries etc.\nIt works for any data type. Just replace <code>String</code> with anything like <code>int</code>,<code>double</code> or <code>char</code>.\nIt works quite efficiently.</p>\n'}, {'answer_id': 42201601, 'author': 'Raj S. Rusia', 'author_id': 7178104, 'author_profile': 'https://Stackoverflow.com/users/7178104', 'pm_score': 4, 'selected': False, 'text': '<p>If you use this way so you no need to import any third party class.</p>\n\n<p>If you want concatenate <code>String</code></p>\n\n<p><strong>Sample code for concate two String Array</strong></p>\n\n<pre><code>public static String[] combineString(String[] first, String[] second){\n int length = first.length + second.length;\n String[] result = new String[length];\n System.arraycopy(first, 0, result, 0, first.length);\n System.arraycopy(second, 0, result, first.length, second.length);\n return result;\n }\n</code></pre>\n\n<p>If you want concatenate <code>Int</code></p>\n\n<p><strong>Sample code for concate two Integer Array</strong></p>\n\n<pre><code>public static int[] combineInt(int[] a, int[] b){\n int length = a.length + b.length;\n int[] result = new int[length];\n System.arraycopy(a, 0, result, 0, a.length);\n System.arraycopy(b, 0, result, a.length, b.length);\n return result;\n }\n</code></pre>\n\n<p><strong>Here is Main method</strong></p>\n\n<pre><code> public static void main(String[] args) {\n\n String [] first = {"a", "b", "c"};\n String [] second = {"d", "e"};\n\n String [] joined = combineString(first, second);\n System.out.println("concatenated String array : " + Arrays.toString(joined));\n\n int[] array1 = {101,102,103,104};\n int[] array2 = {105,106,107,108};\n int[] concatenateInt = combineInt(array1, array2);\n\n System.out.println("concatenated Int array : " + Arrays.toString(concatenateInt));\n\n }\n } \n</code></pre>\n\n<p>We can use this way also.</p>\n'}, {'answer_id': 46542530, 'author': 'c-chavez', 'author_id': 1042409, 'author_profile': 'https://Stackoverflow.com/users/1042409', 'pm_score': 0, 'selected': False, 'text': '<p>Yet another answer for algorithm lovers:</p>\n\n<pre><code>public static String[] mergeArrays(String[] array1, String[] array2) {\n int totalSize = array1.length + array2.length; // Get total size\n String[] merged = new String[totalSize]; // Create new array\n // Loop over the total size\n for (int i = 0; i < totalSize; i++) {\n if (i < array1.length) // If the current position is less than the length of the first array, take value from first array\n merged[i] = array1[i]; // Position in first array is the current position\n\n else // If current position is equal or greater than the first array, take value from second array.\n merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.\n }\n\n return merged;\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>String[] array1str = new String[]{"a", "b", "c", "d"}; \nString[] array2str = new String[]{"e", "f", "g", "h", "i"};\nString[] listTotalstr = mergeArrays(array1str, array2str);\nSystem.out.println(Arrays.toString(listTotalstr));\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[a, b, c, d, e, f, g, h, i]\n</code></pre>\n'}, {'answer_id': 46972713, 'author': 'Hakim', 'author_id': 4800139, 'author_profile': 'https://Stackoverflow.com/users/4800139', 'pm_score': 0, 'selected': False, 'text': '<p>You can try this method which concatenates multiple arrays:</p>\n\n<pre><code>public static <T> T[] concatMultipleArrays(T[]... arrays)\n{\n int length = 0;\n for (T[] array : arrays)\n {\n length += array.length;\n }\n T[] result = (T[]) Array.newInstance(arrays.getClass().getComponentType(), length) ;\n\n length = 0;\n for (int i = 0; i < arrays.length; i++)\n {\n System.arraycopy(arrays[i], 0, result, length, arrays[i].length);\n length += arrays[i].length;\n }\n\n return result;\n}\n</code></pre>\n'}, {'answer_id': 49772469, 'author': 'rghome', 'author_id': 3800782, 'author_profile': 'https://Stackoverflow.com/users/3800782', 'pm_score': 7, 'selected': False, 'text': '<p>You can append the two arrays in two lines of code.</p>\n\n<pre><code>String[] both = Arrays.copyOf(first, first.length + second.length);\nSystem.arraycopy(second, 0, both, first.length, second.length);\n</code></pre>\n\n<p>This is a fast and efficient solution and will work for primitive types as well as the two methods involved are overloaded.</p>\n\n<p>You should avoid solutions involving ArrayLists, streams, etc as these will need to allocate temporary memory for no useful purpose.</p>\n\n<p>You should avoid <code>for</code> loops for large arrays as these are not efficient. The built in methods use block-copy functions that are extremely fast.</p>\n'}, {'answer_id': 49793485, 'author': 'Basil Battikhi', 'author_id': 2901129, 'author_profile': 'https://Stackoverflow.com/users/2901129', 'pm_score': 0, 'selected': False, 'text': '<p>In Java 8 </p>\n\n<pre><code>public String[] concat(String[] arr1, String[] arr2){\n Stream<String> stream1 = Stream.of(arr1);\n Stream<String> stream2 = Stream.of(arr2);\n Stream<String> stream = Stream.concat(stream1, stream2);\n return Arrays.toString(stream.toArray(String[]::new));\n}\n</code></pre>\n'}, {'answer_id': 52375659, 'author': 'BrownRecluse', 'author_id': 5143356, 'author_profile': 'https://Stackoverflow.com/users/5143356', 'pm_score': 1, 'selected': False, 'text': '<p>Non Java 8 solution:</p>\n\n<pre><code>public static int[] combineArrays(int[] a, int[] b) {\n int[] c = new int[a.length + b.length];\n\n for (int i = 0; i < a.length; i++) {\n c[i] = a[i];\n }\n\n for (int j = 0, k = a.length; j < b.length; j++, k++) {\n c[k] = b[j];\n }\n\n return c;\n }\n</code></pre>\n'}, {'answer_id': 52950353, 'author': 'keisar', 'author_id': 1344070, 'author_profile': 'https://Stackoverflow.com/users/1344070', 'pm_score': 4, 'selected': False, 'text': '<p>Using Java 8+ streams you can write the following function:</p>\n\n<pre><code>private static String[] concatArrays(final String[]... arrays) {\n return Arrays.stream(arrays)\n .flatMap(Arrays::stream)\n .toArray(String[]::new);\n}\n</code></pre>\n'}, {'answer_id': 53025243, 'author': 'avigaild', 'author_id': 10567980, 'author_profile': 'https://Stackoverflow.com/users/10567980', 'pm_score': 3, 'selected': False, 'text': '<p>This should be one-liner.</p>\n\n<pre><code>public String [] concatenate (final String array1[], final String array2[])\n{\n return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);\n}\n</code></pre>\n'}, {'answer_id': 53181401, 'author': 'beaudet', 'author_id': 2730420, 'author_profile': 'https://Stackoverflow.com/users/2730420', 'pm_score': 3, 'selected': False, 'text': '<p>A generic static version that uses the high performing System.arraycopy without requiring a @SuppressWarnings annotation:</p>\n\n<pre><code>public static <T> T[] arrayConcat(T[] a, T[] b) {\n T[] both = Arrays.copyOf(a, a.length + b.length);\n System.arraycopy(b, 0, both, a.length, b.length);\n return both;\n}\n</code></pre>\n'}, {'answer_id': 55320708, 'author': 'ZhekaKozlov', 'author_id': 706317, 'author_profile': 'https://Stackoverflow.com/users/706317', 'pm_score': 2, 'selected': False, 'text': '<p>This is probably the only generic and type-safe way:</p>\n\n<pre><code>public class ArrayConcatenator<T> {\n private final IntFunction<T[]> generator;\n\n private ArrayConcatenator(IntFunction<T[]> generator) {\n this.generator = generator;\n }\n\n public static <T> ArrayConcatenator<T> concat(IntFunction<T[]> generator) {\n return new ArrayConcatenator<>(generator);\n }\n\n public T[] apply(T[] array1, T[] array2) {\n T[] array = generator.apply(array1.length + array2.length);\n System.arraycopy(array1, 0, array, 0, array1.length);\n System.arraycopy(array2, 0, array, array1.length, array2.length);\n return array;\n }\n}\n</code></pre>\n\n<p>And the usage is quite concise:</p>\n\n<pre><code>Integer[] array1 = { 1, 2, 3 };\nDouble[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat(Number[]::new).apply(array1, array2);\n</code></pre>\n\n<p>(requires static import)</p>\n\n<p>Invalid array types are rejected:</p>\n\n<pre><code>concat(String[]::new).apply(array1, array2); // error\nconcat(Integer[]::new).apply(array1, array2); // error\n</code></pre>\n'}, {'answer_id': 58587509, 'author': 'Kaplan', 'author_id': 11199879, 'author_profile': 'https://Stackoverflow.com/users/11199879', 'pm_score': 0, 'selected': False, 'text': '<p><em>concatenates a series of arrays compact, fast and type-safe with lambda</em></p>\n\n<pre><code>@SafeVarargs\npublic static <T> T[] concat( T[]... arrays ) {\n return( Stream.of( arrays ).reduce( ( arr1, arr2 ) -> {\n T[] rslt = Arrays.copyOf( arr1, arr1.length + arr2.length );\n System.arraycopy( arr2, 0, rslt, arr1.length, arr2.length );\n return( rslt );\n } ).orElse( null ) );\n};\n</code></pre>\n\n<p>returns <code>null</code> when called without argument<br /></p>\n\n<p>eg. example with 3 arrays:</p>\n\n<pre><code>String[] a = new String[] { "a", "b", "c", "d" };\nString[] b = new String[] { "e", "f", "g", "h" };\nString[] c = new String[] { "i", "j", "k", "l" };\n\nconcat( a, b, c ); // [a, b, c, d, e, f, g, h, i, j, k, l]\n</code></pre>\n\n<p><br /><em>"…probably the only generic and type-safe way"</em> – adapted:</p>\n\n<pre><code>Number[] array1 = { 1, 2, 3 };\nNumber[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat( array1, array2 ); // [1, 2, 3, 4.0, 5.0, 6.0]\n</code></pre>\n'}, {'answer_id': 60017520, 'author': 'JGFMK', 'author_id': 495157, 'author_profile': 'https://Stackoverflow.com/users/495157', 'pm_score': 0, 'selected': False, 'text': '<p>Just wanted to add, you can use <code>System.arraycopy</code> too:</p>\n\n<pre><code>import static java.lang.System.out;\nimport static java.lang.System.arraycopy;\nimport java.lang.reflect.Array;\nclass Playground {\n @SuppressWarnings("unchecked")\n public static <T>T[] combineArrays(T[] a1, T[] a2) {\n T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);\n arraycopy(a1,0,result,0,a1.length);\n arraycopy(a2,0,result,a1.length,a2.length);\n return result;\n }\n public static void main(String[ ] args) {\n String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";\n String[] months = monthsString.split("(?<=\\\\G.{3})");\n String daysString = "SUNMONTUEWEDTHUFRISAT";\n String[] days = daysString.split("(?<=\\\\G.{3})");\n for (String m : months) {\n out.println(m);\n }\n out.println("===");\n for (String d : days) {\n out.println(d);\n }\n out.println("===");\n String[] results = combineArrays(months, days);\n for (String r : results) {\n out.println(r);\n }\n out.println("===");\n }\n}\n</code></pre>\n'}, {'answer_id': 60188847, 'author': 'Areeha', 'author_id': 6834039, 'author_profile': 'https://Stackoverflow.com/users/6834039', 'pm_score': -1, 'selected': False, 'text': '<p>Here is what worked for me:</p>\n\n<pre><code>String[] data=null;\nString[] data2=null;\nArrayList<String> data1 = new ArrayList<String>();\nfor(int i=0; i<2;i++) {\n data2 = input.readLine().split(",");\n data1.addAll(Arrays.asList(data2));\n data= data1.toArray(new String[data1.size()]);\n }\n</code></pre>\n'}, {'answer_id': 65484015, 'author': 'Oleksandr Tsurika', 'author_id': 1663094, 'author_profile': 'https://Stackoverflow.com/users/1663094', 'pm_score': 0, 'selected': False, 'text': '<p>I use next method to concatenate any number of arrays of the same type using java 8:</p>\n<pre><code>public static <G> G[] concatenate(IntFunction<G[]> generator, G[] ... arrays) {\n int len = arrays.length;\n if (len == 0) {\n return generator.apply(0);\n } else if (len == 1) {\n return arrays[0];\n }\n int pos = 0;\n Stream<G> result = Stream.concat(Arrays.stream(arrays[pos]), Arrays.stream(arrays[++pos]));\n while (pos < len - 1) {\n result = Stream.concat(result, Arrays.stream(arrays[++pos]));\n }\n return result.toArray(generator);\n}\n</code></pre>\n<p>usage:</p>\n<pre><code> concatenate(String[]::new, new String[]{"one"}, new String[]{"two"}, new String[]{"three"}) \n</code></pre>\n<p>or</p>\n<pre><code> concatenate(Integer[]::new, new Integer[]{1}, new Integer[]{2}, new Integer[]{3})\n</code></pre>\n'}, {'answer_id': 65727399, 'author': 'rizesky', 'author_id': 6324746, 'author_profile': 'https://Stackoverflow.com/users/6324746', 'pm_score': 0, 'selected': False, 'text': '<p>I just discovered this question, sorry very late, and saw a lot of answers that were too far away,\nusing certain libraries, using the feature of converting data from an array to a stream and back to an array and so on. But,\nwe can just use a simple loop and the problem is done</p>\n<pre class="lang-java prettyprint-override"><code>public String[] concat(String[] firstArr,String[] secondArr){\n //if both is empty just return\n if(firstArr.length==0 && secondArr.length==0)return new String[0];\n\n String[] res = new String[firstArr.length+secondArr.length];\n int idxFromFirst=0;\n\n //loop over firstArr, idxFromFirst will be used as starting offset for secondArr\n for(int i=0;i<firstArr.length;i++){\n res[i] = firstArr[i];\n idxFromFirst++;\n }\n\n //loop over secondArr, with starting offset idxFromFirst (the offset track from first array)\n for(int i=0;i<secondArr.length;i++){\n res[idxFromFirst+i]=secondArr[i];\n }\n\n return res;\n }\n</code></pre>\n<p>Thats it all, right? he didnt say he care about the order or anything.\nThis should be the easiest way of it.</p>\n'}, {'answer_id': 67960387, 'author': 'Lakshitha Kanchana', 'author_id': 6696702, 'author_profile': 'https://Stackoverflow.com/users/6696702', 'pm_score': 0, 'selected': False, 'text': "<p>I have a simple method. You don't want to waste your time to research complex java functions or libraries. But the return type should be String.</p>\n<pre><code>String[] f(String[] first, String[] second) {\n\n // Variable declaration part\n int len1 = first.length;\n int len2 = second.length;\n int lenNew = len1 + len2;\n String[] both = new String[len1+len2];\n\n // For loop to fill the array "both"\n for (int i=0 ; i<lenNew ; i++){\n if (i<len1) {\n both[i] = first[i];\n } else {\n both[i] = second[i-len1];\n }\n }\n\n return both;\n\n}\n</code></pre>\n<p>So simple...</p>\n"}, {'answer_id': 69157437, 'author': 'Rajesh Patel', 'author_id': 7866838, 'author_profile': 'https://Stackoverflow.com/users/7866838', 'pm_score': 0, 'selected': False, 'text': "<p>Using Java Collections</p>\n<p>Well, Java doesn't provide a helper method to concatenate arrays. However, since Java 5, the Collections utility class has introduced an addAll(Collection<? super T> c, T… elements) method.</p>\n<p>We can create a List object, then call this method twice to add the two arrays to the list. Finally, we convert the resulting List back to an array:</p>\n<pre><code>static <T> T[] concatWithCollection(T[] array1, T[] array2) {\n List<T> resultList = new ArrayList<>(array1.length + array2.length);\n Collections.addAll(resultList, array1);\n Collections.addAll(resultList, array2);\n\n @SuppressWarnings("unchecked")\n //the type cast is safe as the array1 has the type T[]\n T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);\n return resultList.toArray(resultArray);\n}\n</code></pre>\n<p>Test</p>\n<pre><code>@Test\npublic void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {\n String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);\n assertThat(result).isEqualTo(expectedStringArray);\n}\n\n</code></pre>\n"}, {'answer_id': 71449230, 'author': 'mkemper', 'author_id': 14763038, 'author_profile': 'https://Stackoverflow.com/users/14763038', 'pm_score': 0, 'selected': False, 'text': '<p>I see many generic answers with signatures such as public static T[] concat(T[] a, T[] b) {} but these only work on Object arrays, not on primitive arrays, as far as I can work out. The code below works both on Object and primitive arrays, making it more generic...</p>\n<pre><code>public static <T> T concat(T a, T b) {\n //Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});\n //You get a compile error if argument(s) not same type as output. (int[] in example above)\n //You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);\n if (a == null && b == null) return null;\n if (a == null) return b;\n if (b == null) return a;\n final int aLen = Array.getLength(a);\n final int bLen = Array.getLength(b);\n if (aLen == 0) return b;\n if (bLen == 0) return a;\n //From here on we really need to concatenate!\n\n Class componentType = a.getClass().getComponentType();\n final T result = (T)Array.newInstance(componentType, aLen + bLen);\n System.arraycopy(a, 0, result, 0, aLen);\n System.arraycopy(b, 0, result, aLen, bLen);\n return result;\n }\n\n public static void main(String[] args) {\n String[] out1 = concat(new String[]{"aap", "monkey"}, new String[]{"rat"});\n int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});\n }\n</code></pre>\n'}, {'answer_id': 72239759, 'author': 'J.R', 'author_id': 3156682, 'author_profile': 'https://Stackoverflow.com/users/3156682', 'pm_score': 1, 'selected': False, 'text': '<pre><code> /**\n * With Java Streams\n * @param first First Array\n * @param second Second Array\n * @return Merged Array\n */\n String[] mergeArrayOfStrings(String[] first, String[] second) {\n return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);\n }\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2948/'] |
80,486 | <p>I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file. </p>
<p>There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.</p>
<p>I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).</p>
| [{'answer_id': 80600, 'author': 'Martin Woodward', 'author_id': 6438, 'author_profile': 'https://Stackoverflow.com/users/6438', 'pm_score': 5, 'selected': True, 'text': '<p>How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies?</p>\n\n<p>If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.</p>\n\n<pre><code><RunConfigFile>$(SolutionRoot)\\TestRunConfig.testrunconfig</RunConfigFile>\n</code></pre>\n\n<p>This points the build at your .testrunconfig so it can pick up the instructions to run code coverage.</p>\n'}, {'answer_id': 429561, 'author': 'jlo', 'author_id': 48148, 'author_profile': 'https://Stackoverflow.com/users/48148', 'pm_score': 1, 'selected': False, 'text': "<p>You'll need the RunConfigFile entry whether you use the .vsmdi file for Test Lists or just specify the assembly file pattern. In that .testrunconfig file you specify the assemblies you want to apply code coverage to.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5132/'] |
80,493 | <p>In C, using the standard Windows API, what is the best way to read an unformatted disk? Specifically, I have an <a href="http://en.wikipedia.org/wiki/MultiMediaCard" rel="nofollow noreferrer">MMC</a> or <a href="http://en.wikipedia.org/wiki/Secure_Digital_card" rel="nofollow noreferrer">SD card</a> with data, but no file system (not FAT16, not FAT32, just raw data). If there was a simple way to open the entire card for byte by byte binary access, that would be great.</p>
<p>Thanks!</p>
| [{'answer_id': 80533, 'author': 'Kasprzol', 'author_id': 5957, 'author_profile': 'https://Stackoverflow.com/users/5957', 'pm_score': 1, 'selected': False, 'text': '<p>You have to open the device file with <a href="http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx" rel="nofollow noreferrer">CreateFile</a> and then use <a href="http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx" rel="nofollow noreferrer">ReadFile</a>/<a href="http://msdn.microsoft.com/en-us/library/aa365468(VS.85).aspx" rel="nofollow noreferrer">readFileEx</a>. Don\'t forget to close the file with <a href="http://msdn.microsoft.com/en-us/library/ms724211.aspx" rel="nofollow noreferrer">CloseHandle</a></p>\n'}, {'answer_id': 80542, 'author': 'szevvy', 'author_id': 11437, 'author_profile': 'https://Stackoverflow.com/users/11437', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/aa363858.aspx" rel="nofollow noreferrer">CreateFile function reference on MSDN</a></p>\n\n<p>Scroll down to "Physical Disks and Volumes" - note the security restrictions on Vista do not apply for voulmes without a filesystem, so you\'ll be fine even on Vista under the conditions you have given.</p>\n'}, {'answer_id': 81420, 'author': 'Andreas Magnusson', 'author_id': 5811, 'author_profile': 'https://Stackoverflow.com/users/5811', 'pm_score': 3, 'selected': True, 'text': '<p>I would go with</p>\n\n<pre><code>HANDLE drive = CreateFile(_T("\\\\.\\PhysicalDrive0"), GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);\n// error handling\nDWORD br = 0;\nDISK_GEOMETRY dg;\nDeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0, &dg, sizeof(dg), &br, 0);\n//\nLARGE_INTEGER pos;\npos.QuadPart = static_cast<LONGLONG>(sectorToRead) * dg.BytesPerSector;\nSetFilePointerEx(drive, pos, 0, FILE_BEGIN);\nconst bool success = ReadFile(drive, sectorData, dg.BytesPerSector, &br) && br == dg.BytesPerSector;\n//\nCloseHandle(drive);\n</code></pre>\n\n<p>Please note that in order to verify that you\'ve successfully read a sector you must verify that the read byte count corresponds to the number of bytes you wanted to read, i.e. in my experience ReadFile() on a physical disk can return TRUE even when no bytes are read (or maybe I just have a buggy driver).</p>\n\n<p>The problem that remains is to determine your drive number (0 as is used in my example refers to C: which is probably not what you want). I don\'t know how to do that, but if you only have one drive connected which is not formatted, it ought to be possible by calling opening each PhysicalDrive in order and calling DeviceIOControl() with <code>IOCTL_DISK_GET_DRIVE_LAYOUT_EX</code> as a command:</p>\n\n<pre><code>DRIVE_LAYOUT_INFORMATION_EX dl;\nDeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, 0, &dl, sizeof(dl), &br, 0);\nif(dl.PartitionStyle == PARTITION_STYLE_RAW)\n{\n // found correct disk\n}\n</code></pre>\n\n<p>But that\'s just a guess.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3175/'] |
80,515 | <p>I'd like to install some presentation templates, but don't know where to put them...</p>
<p>Thanks a lot</p>
| [{'answer_id': 80524, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 3, 'selected': True, 'text': '<p>Choose Tools > Options > OpenOffice.org > Paths and select the Templates line. There you can click "edit" and see the paths that it uses to search for templates.</p>\n'}, {'answer_id': 80532, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<pre><code>/usr/lib/openoffice/share/template/\n</code></pre>\n\n<p>That's on a Debian Lenny/testing. You can find them by typing</p>\n\n<pre><code>locate .ots\n</code></pre>\n\n<p>in a console (ots being the extension of OOo templates)</p>\n"}, {'answer_id': 677388, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>It is not recommended to place templates in /usr/lib/openoffice/... because the contents of that folder can be altered automatically through the process of Debian package management. For site-wide installation I created the folder "/usr/local/share/templates/ooo2/common", placed templates in there, then added the path to the set of paths mentioned above.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11104/'] |
80,518 | <p>I am working on a legacy project in <code>VC++/Win32/MFC</code>. Recently it became a requirement that the application work on a <strong>tablet pc</strong>, and this ushered in a host of new issues.
I have been able to work with, and around these issues, <strong>but am left with one wherein I could use some expert suggestions.</strong></p>
<p>I have a particular bug that is induced by the "lift" of the stylus off of the active surface. Basically the mouse cursor disappears and then reappears when you "press" it back onto the screen.</p>
<p>It makes sense that this is unaccounted for in the application. you can't <strong>lift</strong> the cursor on a desktop pc. So what I am looking for is a good overview on what happens (in terms of windows messages, etc.) when the lift occurs. Does this translate to just focus changes and mouseover events? My bug seems to also involve cursor changes (may not be lift related though). Certainly the unexpected "lift" is breaking the state of the application's tool processing.</p>
<p><strong>So the tangible questions are:</strong></p>
<ol>
<li>What happens when a stylus "lift" occurs? A press?</li>
<li>What API calls can be used to detect this? Does it just translate into standard messages with flags/values set?</li>
<li>Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc)</li>
<li>What represents correct behavior or best practice for tablet stylus awareness?</li>
</ol>
<p>Thanks for your consideration,
ee</p>
| [{'answer_id': 80566, 'author': 'Kitty', 'author_id': 14345, 'author_profile': 'https://Stackoverflow.com/users/14345', 'pm_score': 2, 'selected': True, 'text': '<p>As a tablet user I can answer a few of your questions.</p>\n\n<p>First:</p>\n\n<blockquote>\n <p>You cannot very easily keep a "keyboard focus" on a window when the stylus has to trail out of the focused window to push a key on the virtual keyboard.</p>\n</blockquote>\n\n<p>Most of the virtual keyboards I\'ve used (The windows tablet input panel and one under ubuntu) allow the program they are typing in to keep "keyboard focus."</p>\n\n<blockquote>\n <p>What happens when a stylus "lift" occurs? A press?</p>\n</blockquote>\n\n<p>Under Windows, the pressure value drops, but outside of that, there is no event. (I don\'t know about linux.)</p>\n\n<blockquote>\n <p>What API calls can be used to detect this? Does it just translate into standard messages with flags/values set?</p>\n</blockquote>\n\n<p>As mentioned above, if you can get the pressure value, you can use that.</p>\n\n<blockquote>\n <p>Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc)</p>\n</blockquote>\n\n<p>When the stylus is placed down elsewhere, the global coordinates of the pointer change, so, you can emulate the sudden pointer move with anything that allows you to change the global pointer values. (The Robot class in Java makes this fairly easy.)</p>\n\n<blockquote>\n <p>What represents correct behavior or best practice for tablet stylus awareness?</p>\n</blockquote>\n\n<p>I\'d recommend you read what Microsoft has to say, the MSDN website has a number of excellent articles. (<a href="http://msdn.microsoft.com/en-us/library/ms704849(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms704849(VS.85).aspx</a>)\nI\'ll point out that the size of the buttons on your applications makes a HUGE difference.</p>\n\n<p>Hope this was of help.</p>\n'}, {'answer_id': 80579, 'author': 'raldi', 'author_id': 7598, 'author_profile': 'https://Stackoverflow.com/users/7598', 'pm_score': 0, 'selected': False, 'text': '<p>As I understand it, there is no "lift" event -- the only event happens when the stylus is brought back to the screen later. Of course, this depends on your specific driver and so on.</p>\n\n<p>Worse, the bug you describe might be reproducible with just a typical mouse. Try moving the mouse as fast as you can -- it will almost certainly jump several pixels at once. Or even dozens or hundreds, if you have the mouse settings configured for the highest pointer speed. One update, the mouse might be at 100,100. The very next update, it could be at 200,300.</p>\n'}, {'answer_id': 80961, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>Under Windows, the pressure value drops, but outside of that, there is no event. (I don\'t know about linux.)</p>\n</blockquote>\n\n<p>Under linux you`ll get "ProximityEvents" </p>\n\n<p>Most likely these events WT_PROXIMITY are avaliable in windows (please refer to: <a href="http://www.wacomeng.com/devsupport/ibmpc/wacomwindevfaq.html" rel="nofollow noreferrer">http://www.wacomeng.com/devsupport/ibmpc/wacomwindevfaq.html</a> )</p>\n'}, {'answer_id': 81112, 'author': 'el2iot2', 'author_id': 8668, 'author_profile': 'https://Stackoverflow.com/users/8668', 'pm_score': 0, 'selected': False, 'text': '<p>@Greg - A clarification, this is a laptop pc with integrated tablet and stylus built in. the device has no dedicated keyboard (it is a virtual one on the touchscreen) and is not a wacom input device. Sorry for the confusion.</p>\n\n<p>It appears that there is an <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=B46D4B83-A821-40BC-AA85-C9EE3D6E9699&displaylang=en#RelatedLinks" rel="nofollow noreferrer">SDK</a> for the Microsoft Windows XP Tablet PC Edition that may have the ability to get special details such as pressure. However, I know that there has to be some level of standard compatibility with existing non-tablet-aware applications. I guess I can try to get Spy++ installed on the tablet and try and filter down to specific messages/events. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8668/'] |
80,541 | <p>The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.</p>
<p>For instance, how would I find out that there are 10 week days in between <code>31/08/2008</code> and <code>13/09/2008</code>?</p>
| [{'answer_id': 80553, 'author': 'erlando', 'author_id': 4192, 'author_profile': 'https://Stackoverflow.com/users/4192', 'pm_score': 0, 'selected': False, 'text': "<p>One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):</p>\n\n<pre><code>$dif_in_seconds = abs(strtotime($a) - strtotime($b));\n$daysbetween = $dif_in_seconds / 86400;\n</code></pre>\n\n<p>ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..</p>\n"}, {'answer_id': 80557, 'author': 'cruizer', 'author_id': 6441, 'author_profile': 'https://Stackoverflow.com/users/6441', 'pm_score': 0, 'selected': False, 'text': "<p>The best way is to iterate through all dates in between the given date range, and get the day of week for each date. If it's a week day, increment a certain counter. At the end of the process you get the number of weekdays.</p>\n\n<p>The PHP functions mktime() and date() (for working with UNIX timestamps) are your friends here.</p>\n"}, {'answer_id': 80578, 'author': 'kobusb', 'author_id': 1620, 'author_profile': 'https://Stackoverflow.com/users/1620', 'pm_score': 3, 'selected': True, 'text': '<pre><code> $datefrom = strtotime($datefrom, 0);\n $dateto = strtotime($dateto, 0);\n\n $difference = $dateto - $datefrom;\n\n $days_difference = floor($difference / 86400);\n $weeks_difference = floor($days_difference / 7); // Complete weeks\n\n $first_day = date("w", $datefrom);\n $days_remainder = floor($days_difference % 7);\n\n $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?\n if ($odd_days > 7) { // Sunday\n $days_remainder--;\n }\n if ($odd_days > 6) { // Saturday\n $days_remainder--;\n }\n\n $datediff = ($weeks_difference * 5) + $days_remainder;\n</code></pre>\n\n<p>From here: <a href="http://www.addedbytes.com/php/php-datediff-function/" rel="nofollow noreferrer">http://www.addedbytes.com/php/php-datediff-function/</a></p>\n'}, {'answer_id': 80627, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 2, 'selected': False, 'text': "<p>If you are creating an invoicing system, you have to think about the bank holidays, Easter, etc. It is not simple to compute it. </p>\n\n<p>The best solution I have ever seen is to pregenerate a table with days and its type to SQL database (row per day = 365 rows per year) and then perform simple count query with proper selection (WHERE clause). </p>\n\n<p>You can find this solution fully described in <em>Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL</em></p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/80541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131/'] |
Subsets and Splits