body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
Extensible Markup Language (XML) is a structured document format that defines human- and machine-readable encoding rules.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:24:15.337", "Id": "8084", "Score": "0", "Tags": null, "Title": null }
8084
<p><a href="https://en.wikipedia.org/wiki/Scala_(programming_language)" rel="nofollow">Scala</a> is a general purpose programming language principally targeting the Java Virtual Machine. Designed to express common programming patterns in a concise, elegant, and type-safe way, it fuses both imperative and functional programming styles. Its key features are:</p> <ul> <li>Static typing</li> <li>Advanced type system with type inference and declaration-site variance</li> <li>Function types (including anonymous) which support <em>lexical closures</em></li> <li>Pattern-matching</li> <li>Implicit parameters and conversions which support the <em>typeclass</em> and <em>enrich-my-library</em> patterns</li> <li>Mixin composition</li> <li>Full interoperability with Java</li> <li>Powerful concurrency constructs</li> <li>Advanced language constructs such as delimited continuations and an experimental macro system</li> </ul> <p>For more information, see the official <a href="http://www.scala-lang.org/node/25" rel="nofollow">Scala Introduction</a> and <a href="http://docs.scala-lang.org" rel="nofollow">Scala Documentation</a>.</p> <p>To search for Scala symbols such as "=>" in Code Review, you can use <a href="http://symbolhound.com/" rel="nofollow">symbolhound search</a>.</p> <p>To search Scala documentation, you can use <a href="http://scalex.org/" rel="nofollow">Scalex</a>.</p> <hr> <h2>See this tag for a comprehensive Scala tutorial:</h2> <p><a href="http://stackoverflow.com/tags/scala/info">Scala Tutorial at SO</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:25:23.920", "Id": "8085", "Score": "0", "Tags": null, "Title": null }
8085
Scala is a general purpose programming language principally targeting the Java Virtual Machine. Designed to express common programming patterns in a concise, elegant, and type-safe way, it fuses both imperative and functional programming styles.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:25:23.920", "Id": "8086", "Score": "0", "Tags": null, "Title": null }
8086
<p>AJAX is a set of techniques that run on the client to create interactive websites. It allows updates to the current page to be made in more or less real-time without having to reload the page from the server.</p> <p><a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow">AJAX on Wikipedia</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:26:37.023", "Id": "8087", "Score": "0", "Tags": null, "Title": null }
8087
AJAX (Asynchronous Javascript And XML) is a popular technique for creating interactive websites, allowing web content to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:26:37.023", "Id": "8088", "Score": "0", "Tags": null, "Title": null }
8088
<p><strong>Strong Programming Features VB.Net</strong></p> <p><strong>VB.Net</strong> has numerous strong programming features that make it endearing to multitude of programmers worldwide.Some of these features are furnished below</p> <ul> <li>Boolean Conditions </li> <li>Automatic Garbage Collection</li> <li>Standard Library</li> <li>Assembly Versioning</li> <li>Properties and Events</li> <li>Delegates and Events Management</li> <li>Easy-to-use Generics</li> <li>Indexers</li> <li>Conditional Compilation</li> <li>Simple Multithreading</li> </ul> <p><strong>Integrated Development Environment (<em>IDE</em>) For VB.Net</strong></p> <p><strong>Microsoft</strong> provides the following development tools for VB.Net programming:</p> <ul> <li><p>Visual Studio 2010 (VS)</p></li> <li><p>Visual Basic 2010 Express (VBE)</p></li> <li><p>Visual Web Developer</p></li> </ul> <p>The last two are <em>free</em>. Using these tools, you can write all kinds of VB.Net programs from simple command-line applications to more complex applications. Visual Basic Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same look and feel. They retain most features of Visual Studio. In this tutorial, we have used Visual Basic 2010 Express and Visual Web Developer.</p> <p>You can download it from <a href="http://www.visualstudio.com/downloads/download-visual-studio-vs" rel="nofollow">here. </a>It gets automatically installed in your machine.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:27:00.190", "Id": "8089", "Score": "0", "Tags": null, "Title": null }
8089
Visual Basic .NET (VB.NET) is an object-oriented computer programming language that can be viewed as an evolution of Microsoft's Visual Basic 6 (VB6) but implemented on the Microsoft .NET Framework.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:27:00.190", "Id": "8090", "Score": "0", "Tags": null, "Title": null }
8090
<p>jQuery UI is an Extension of the jQuery Library.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:32:42.247", "Id": "8091", "Score": "0", "Tags": null, "Title": null }
8091
jQuery UI is the official jQuery user interface library. It provides interactions, widgets, effects, and theming for creating highly interactive web applications.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:32:42.247", "Id": "8092", "Score": "0", "Tags": null, "Title": null }
8092
iOS is an operating system for mobile devices developed by Apple Inc. that is currently used in their iPhone, iPod touch, iPad, and Apple TV (2nd generation) devices. It shares a lot with Mac OS X, but is optimized for touch-based interfaces. Use this tag for questions about iOS-specific code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:33:37.267", "Id": "8094", "Score": "0", "Tags": null, "Title": null }
8094
<p><a href="http://en.wikipedia.org/wiki/Thread_safety" rel="nofollow">From Wikipedia</a>:</p> <blockquote> <p><strong>Thread safety</strong> is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is <strong>thread-safe</strong> if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. There are various strategies for making thread-safe data structures.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:35:12.273", "Id": "8095", "Score": "0", "Tags": null, "Title": null }
8095
A piece of code is thread-safe if it only manipulates data structures in a way that allows consistent execution of this code by multiple threads.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:35:12.273", "Id": "8096", "Score": "0", "Tags": null, "Title": null }
8096
<h1>About Bash</h1> <p>There are a variety of interpreters that receive commands either interactively or as a sequence of commands from a file. The <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="nofollow">Bourne-again shell</a> (Bash) is one such interpreter. Bash implements the standard <a href="http://en.wikipedia.org/wiki/Bourne_shell" rel="nofollow">Bourne Shell</a> (sh), and offers numerous additions.</p> <p>From the Free Software Foundation's <a href="http://www.gnu.org/software/bash/" rel="nofollow">Bash page</a>:</p> <blockquote> <p>Bash is an sh-compatible shell that incorporates useful features from the KornShell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.</p> </blockquote> <p>Read the <a href="http://www.gnu.org/software/bash/manual/" rel="nofollow">Bash manual</a> for technical details.</p> <h1>Books and Resources</h1> <p>Additional reading materials include:</p> <ul> <li><a href="http://www.gnu.org/software/bash/manual/" rel="nofollow">Bash manual</a></li> <li><a href="http://tiswww.case.edu/php/chet/bash/FAQ" rel="nofollow">Bash FAQ</a> by the current primary maintainer, <a href="http://tiswww.case.edu/php/chet/" rel="nofollow">Chet Ramey</a>.</li> <li><a href="http://mywiki.wooledge.org/BashFAQ" rel="nofollow">Bash FAQ</a> by Lhunath</li> <li><a href="http://mywiki.wooledge.org/BashPitfalls" rel="nofollow">Bash pitfalls</a></li> <li><a href="http://wiki.bash-hackers.org/scripting/newbie_traps" rel="nofollow">Bash beginner's mistakes</a></li> <li><a href="http://wiki.bash-hackers.org/doku.php" rel="nofollow">Bash hackers</a></li> <li><a href="http://mywiki.wooledge.org/BashGuide" rel="nofollow">Bash Guide</a> by Lhunath</li> <li><a href="http://tldp.org/LDP/abs/html/" rel="nofollow">Advanced Bash-Scripting Guide</a></li> <li><a href="http://www.tldp.org/LDP/Bash-Beginners-Guide/html/" rel="nofollow">Bash Guide for Beginners</a> by Machtelt Garrels</li> <li><a href="http://learncodethehardway.org/cli/book/" rel="nofollow">The Command Line Crash Course</a> (also a Powershell reference)</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:36:01.320", "Id": "8097", "Score": "0", "Tags": null, "Title": null }
8097
BASH is the GNU Bourne Again SHell, the successor to the classic Unix Bourne sh (shell). It's the default shell for various GNU systems.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:36:01.320", "Id": "8098", "Score": "0", "Tags": null, "Title": null }
8098
<p>API, for code implementing an Application Programming Interface. A program's API defines the proper way for a developer to request services from that program, site and/or service. Do NOT use this tag if the code simply uses an already existing API. This tag is purely for questions which implement one in the question itself.</p> <p>For using existing API, see if a tag is already created <a href="https://codereview.stackexchange.com/tags">here</a>. Keep in mind not every API needs its own tag. Questions about the Stack Exchange API can be tagged with <a href="/questions/tagged/stackexchange" class="post-tag" title="show questions tagged &#39;stackexchange&#39;" rel="tag">stackexchange</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-21T15:36:28.917", "Id": "8099", "Score": "0", "Tags": null, "Title": null }
8099
API, for code implementing (NOT using) an Application Programming Interface. A program's API defines the proper way for a developer to request services from that program, site and/or service.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-21T15:36:28.917", "Id": "8100", "Score": "0", "Tags": null, "Title": null }
8100
<p>HTML5 is a core technology <a href="http://en.wikipedia.org/wiki/Markup_language" rel="nofollow">markup language</a> of the Internet used for structuring and presenting content for the <a href="http://en.wikipedia.org/wiki/World_Wide_Web" rel="nofollow">World Wide Web</a>. As of October 28, 2014 this is the final and complete fifth revision of the HTML standard of the <a href="http://en.wikipedia.org/wiki/World_Wide_Web_Consortium" rel="nofollow">World Wide Web Consortium</a> (W3C). The previous version, HTML 4, was standardized in 1997.</p> <p>On 18 January 2011, the W3C introduced a <a href="http://www.w3.org/html/logo/downloads/HTML5_Logo.svg" rel="nofollow">logo</a> to <a href="http://www.w3.org/html/logo/faq.html" rel="nofollow">represent</a> the use of or interest in HTML5. Unlike other badges previously issued by the W3C, it does not imply validity or conformance to a certain standard. As of 1 April 2011, this logo is official.</p> <blockquote> <p><strong>Note:</strong> <em>"The term "HTML5" is widely used as a buzzword to refer to modern Web technologies, many of which (though by no means all) are developed at the WHATWG, in some cases in conjunction with the W3C and IETF."</em> (WHATWG <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/introduction.html#is-this-html5?" rel="nofollow">Is this HTML5?</a>)</p> </blockquote> <p>Compared to its predecessors (HTML 4.1 and XHTML 1.0) HTML5 introduces new elements, and also some JavaScript features, including:</p> <ul> <li>&lt;<a href="http://dev.w3.org/html5/html-author/#the-video-element" rel="nofollow">video</a>> and &lt;<a href="http://dev.w3.org/html5/html-author/#the-audio-element" rel="nofollow">audio</a>> elements for native media playback.</li> <li>&lt;<a href="http://dev.w3.org/html5/html-author/#canvas" rel="nofollow">canvas</a>> element for procedural drawing.</li> <li>New form elements.</li> <li>New input types and attributes.</li> <li>New semantic structural elements like &lt;<a href="http://dev.w3.org/html5/html-author/#the-header-element" rel="nofollow">header</a>>, &lt;<a href="http://dev.w3.org/html5/html-author/#the-footer-element" rel="nofollow">footer</a>>, &lt;<a href="http://dev.w3.org/html5/html-author/#the-nav-element" rel="nofollow">nav</a>>, &lt;<a href="http://dev.w3.org/html5/html-author/#the-section-element" rel="nofollow">section</a>>, and &lt;<a href="http://dev.w3.org/html5/html-author/#the-article-element" rel="nofollow">article</a>></li> <li>Drag and Drop feature.</li> <li>Local storage API's.</li> <li>An offline web applications API.</li> <li>Device APIs such as Camera API, Location API, etc.</li> <li>3D, Graphics, &amp; Effects.</li> </ul> <p>The <a href="http://www.w3.org/2012/12/html5-cr.html.en" rel="nofollow">HTML5 Definition</a>, with Canvas 2D, has been declared complete in December 2012, and the next round of W3C HTML standardization is now available as the <a href="http://www.w3.org/html/wg/drafts/html/master/Overview.html" rel="nofollow">draft of HTML5.1</a>.</p> <hr> <h2>HTML5 <code>&lt;video&gt;</code> Element</h2> <p>The <code>&lt;video&gt;</code> element specifies video, such as a movie clip or other video streams.</p> <p>Currently, there are 3 supported video formats for the <code>&lt;video&gt;</code> element: MP4, WebM, and Ogg.</p> <p>The <code>&lt;video&gt;</code> element is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.</p> <p><strong>Note:</strong> <em>Internet Explorer 8 and earlier versions, do not support the <code>&lt;video&gt;</code> element.</em></p> <hr> <h2>HTML5 <code>&lt;audio&gt;</code> Element</h2> <p>The <code>&lt;audio&gt;</code> element defines sound, such as music or other audio streams.</p> <p>Currently, there are 3 supported file formats for the <code>&lt;audio&gt;</code> element: MP3, Wav, and Ogg.</p> <p>The <code>&lt;audio&gt;</code> element is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.</p> <p><strong>Note:</strong> <em>Internet Explorer 8 and earlier versions, do not support the <code>&lt;audio&gt;</code> element.</em></p> <hr> <h2>HTML5 <code>&lt;canvas&gt;</code> Element</h2> <p>The HTML5 <code>&lt;canvas&gt;</code> element is used to draw graphics, on the fly, via scripting (usually JavaScript).</p> <p>The <code>&lt;canvas&gt;</code> element is only a container for graphics. You must use a script to actually draw the graphics.</p> <p>Canvas has several methods for drawing paths, boxes, circles, text, and adding images.</p> <p>Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <code>&lt;canvas&gt;</code> element.</p> <p><strong>Note:</strong> <em>Internet Explorer 8 and earlier versions, do not support the <code>&lt;canvas&gt;</code> element.</em></p> <hr> <h1>HTML5 New Form Elements</h1> <p>HTML5 has the following new form elements:</p> <ul> <li><code>&lt;datalist&gt;</code></li> <li><code>&lt;keygen&gt;</code></li> <li><code>&lt;output&gt;</code></li> </ul> <p><strong>Note:</strong> <em>Not all major browsers support all the new form elements. However, you can already start using them; If they are not supported, they will behave as regular text fields.</em></p> <h2>HTML5 <code>&lt;datalist&gt;</code> Element:</h2> <p>The <code>&lt;datalist&gt;</code> element specifies a list of predefined options for an <code>&lt;input&gt;</code> element.</p> <p>The <code>&lt;datalist&gt;</code> element is used to provide an "autocomplete" feature on <code>&lt;input&gt;</code> elements. Users will see a drop-down list of predefined options as they input data.</p> <p>Use the <code>&lt;input&gt;</code> element's list attribute to bind it together with a <code>&lt;datalist&gt;</code> element.</p> <h2>HTML5 <code>&lt;keygen&gt;</code> Element:</h2> <p>The purpose of the <code>&lt;keygen&gt;</code> element is to provide a secure way to authenticate users.</p> <p>The <code>&lt;keygen&gt;</code> element specifies a key-pair generator field in a form.</p> <p>When the form is submitted, two keys are generated, one private and one public.</p> <p>The private key is stored locally, and the public key is sent to the server. The public key could be used to generate a client certificate to authenticate the user in the future.</p> <h2>HTML5 <code>&lt;output&gt;</code> Element:</h2> <p>The <code>&lt;output&gt;</code> element represents the result of a calculation (like one performed by a script).</p> <hr> <h1>HTML5 New Form Attributes</h1> <p>HTML5 has several new attributes for <code>&lt;form&gt;</code> and <code>&lt;input&gt;</code>.</p> <p><strong>New attributes for <code>&lt;form&gt;</code>:</strong></p> <ul> <li>autocomplete</li> <li>novalidate</li> </ul> <p><strong>New attributes for <code>&lt;input&gt;</code>:</strong></p> <ul> <li>autocomplete</li> <li>autofocus</li> <li>form</li> <li>formaction</li> <li>formenctype</li> <li>formmethod</li> <li>formnovalidate</li> <li>formtarget</li> <li>height and width</li> <li>list</li> <li>min and max</li> <li>multiple</li> <li>pattern (regexp)</li> <li>placeholder</li> <li>required</li> <li>step</li> </ul> <h2>1. autocomplete Attribute</h2> <p>The autocomplete attribute specifies whether a form or input field should have autocomplete on or off.</p> <p>When autocomplete is on, the browser automatically complete values based on values that the user has entered before.</p> <p><strong>Tip:</strong> It is possible to have autocomplete "on" for the form, and "off" for specific input fields, or vice versa.</p> <p><strong>Note:</strong> The autocomplete attribute works with and the following types: text, search, url, tel, email, password, datepickers, range, and color.</p> <h2>2. novalidate Attribute</h2> <p>The novalidate attribute is a boolean attribute.</p> <p>When present, it specifies that the form-data (input) should not be validated when submitted.</p> <h2>3. autofocus Attribute</h2> <p>The autofocus attribute is a boolean attribute.</p> <p>When present, it specifies that an <code>&lt;input&gt;</code> element should automatically get focus when the page loads.</p> <h2>4. form Attribute</h2> <p>The form attribute specifies one or more forms an <code>&lt;input&gt;</code> element belongs to.</p> <p><strong>Tip:</strong> To refer to more than one form, use a space-separated list of form ids.</p> <h2>5. formaction Attribute</h2> <p>The formaction attribute specifies the URL of a file that will process the input control when the form is submitted.</p> <p>The formaction attribute overrides the action attribute of the <code>&lt;form&gt;</code> element.</p> <p><strong>Note:</strong> The formaction attribute is used with type="submit" and type="image".</p> <h2>6. formenctype Attribute</h2> <p>The formenctype attribute specifies how the form-data should be encoded when submitting it to the server (only for forms with <code>method="post"</code>)</p> <p>The formenctype attribute overrides the enctype attribute of the <code>&lt;form&gt;</code> element.</p> <p><strong>Note:</strong> The formenctype attribute is used with type="submit" and type="image".</p> <h2>7. formmethod Attribute</h2> <p>The formmethod attribute defines the HTTP method for sending form-data to the action URL.</p> <p>The formmethod attribute overrides the method attribute of the <code>&lt;form&gt;</code> element.</p> <p><strong>Note:</strong> The formmethod attribute can be used with type="submit" and type="image".</p> <h2>8. formnovalidate Attribute</h2> <p>The novalidate attribute is a boolean attribute.</p> <p>When present, it specifies that the <code>&lt;input&gt;</code> element should not be validated when submitted.</p> <p>The formnovalidate attribute overrides the novalidate attribute of the <code>&lt;form&gt;</code> element.</p> <p><strong>Note:</strong> The formnovalidate attribute can be used with type="submit".</p> <h2>9. formtarget Attribute</h2> <p>The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form.</p> <p>The formtarget attribute overrides the target attribute of the <code>&lt;form&gt;</code> element.</p> <p><strong>Note:</strong> The formtarget attribute can be used with type="submit" and type="image".</p> <h2>10. height and width Attributes</h2> <p>The height and width attributes specify the height and width of an <code>&lt;input&gt;</code> element.</p> <p><strong>Note:</strong> The height and width attributes are only used with <code>&lt;input type="image"&gt;</code>.</p> <p><strong>Tip:</strong> Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).</p> <h2>11. list Attribute</h2> <p>The list attribute refers to a <code>&lt;datalist&gt;</code> element that contains pre-defined options for an <code>&lt;input&gt;</code> element.</p> <h2>12. min and max Attributes</h2> <p>The min and max attributes specify the minimum and maximum value for an <code>&lt;input&gt;</code> element.</p> <p><strong>Note:</strong> The min and max attributes works with the following input types: number, range, date, datetime, datetime-local, month, time and week.</p> <h2>13. multiple Attribute</h2> <p>The multiple attribute is a boolean attribute.</p> <p>When present, it specifies that the user is allowed to enter more than one value in the <code>&lt;input&gt;</code> element.</p> <p><strong>Note:</strong> The multiple attribute works with the following input types: email, and file.</p> <h2>14. pattern Attribute</h2> <p>The pattern attribute specifies a regular expression that the <code>&lt;input&gt;</code> element's value is checked against.</p> <p><strong>Note:</strong> The pattern attribute works with the following input types: text, search, url, tel, email, and password.</p> <p><strong>Tip:</strong> Use the global title attribute to describe the pattern to help the user.</p> <h2>15. placeholder Attribute</h2> <p>The placeholder attribute specifies a short hint that describes the expected value of an input field (<em>e.g. a sample value or a short description of the expected format</em>).</p> <p>The hint is displayed in the input field when it is empty, and disappears when the field gets focus.</p> <p><strong>Note:</strong> The placeholder attribute works with the following input types: text, search, url, tel, email, and password.</p> <h2>16. required Attribute</h2> <p>The required attribute is a boolean attribute.</p> <p>When present, it specifies that an input field must be filled out before submitting the form.</p> <p><strong>Note:</strong> The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.</p> <h2>17. step Attribute</h2> <p>The step attribute specifies the legal number intervals for an <code>&lt;input&gt;</code> element.</p> <p><strong>Example:</strong> if step="3", legal numbers could be -3, 0, 3, 6, etc.</p> <p><strong>Tip:</strong> The step attribute can be used together with the max and min attributes to create a range of legal values.</p> <p><strong>Note:</strong> The step attribute works with the following input types: number, range, date, datetime, datetime-local, month, time and week.</p> <hr> <p>There are several HTML5 introduction sites like <a href="http://diveintohtml5.info/" rel="nofollow">Dive into HTML5</a> or <a href="http://www.html5rocks.com" rel="nofollow">HTML5 Rocks</a>. </p> <p>Each feature has varying levels of support in different web browsers. <a href="http://caniuse.com/" rel="nofollow">CanIUse.com</a> and <a href="http://html5test.com/" rel="nofollow">HTML5Test</a> has great cross-browser compatibility information.</p> <p>HTML5 includes the previous standards; therefore, it is backwards compatible with existing content. However, deprecated elements are now classified as obsolete.</p> <p>The W3C has released the specification for HTML5 <a href="http://www.w3.org/TR/html5/" rel="nofollow">here</a>.</p> <p>The WHATWG actively works on HTML5 in what it terms the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/introduction.html#history0" rel="nofollow">HTML Living Standard</a> and the two paths have diverged somewhat.</p> <h2>Resources</h2> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5" rel="nofollow">Mozilla MDN</a></li> <li><a href="http://www.html5rocks.com/en/tutorials/?page=1" rel="nofollow">html5rocks</a></li> <li><a href="http://www.w3schools.com/html/html5_intro.asp" rel="nofollow">HTML5 Introduction</a></li> <li><a href="http://en.wikipedia.org/wiki/Html5" rel="nofollow">HTML5 Wikipedia Article</a></li> <li><a href="http://www.w3.org/TR/html5/" rel="nofollow">W3C HTML5 Documentation</a></li> <li><a href="http://www.w3.org/html/logo/faq.html" rel="nofollow">HTML5 Logo FAQ</a></li> </ul> <h2>Books</h2> <ul> <li><a href="http://diveintohtml5.info/" rel="nofollow">Dive into HTML5</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:37:43.957", "Id": "8101", "Score": "0", "Tags": null, "Title": null }
8101
HTML5 (Hyper Text Markup Language, version 5) is an umbrella term for recent web technologies. It is also the latest iteration of HTML, and became a W3C Recommendation in October 2014, introducing new elements and APIs.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:37:43.957", "Id": "8102", "Score": "0", "Tags": null, "Title": null }
8102
<h1>Definition (Wikipedia):</h1> <blockquote> <p>Windows Forms (WinForms) is the name given to the graphical application programming interface (API) included as a part of Microsoft .NET Framework, providing access to native Microsoft Windows interface elements by wrapping the extant Windows API in managed code.</p> </blockquote> <p><strong>From MSDN:</strong></p> <blockquote> <p>As forms are the base unit of your application, it is essential that you give some thought to their function and design. A form is ultimately a blank slate that you, as a developer, enhance with controls to create a user interface and with code to manipulate data. To that end, Visual Studio provides you with an integrated development environment (IDE) to aid in writing code, as well as a rich control set written with the .NET Framework. By complementing the functionality of these controls with your code, you can easily and quickly develop the solutions you need.</p> </blockquote> <h1>More reading:</h1> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/dd30h2yb(v=vs.110).aspx" rel="nofollow"><strong>MSDN: Windows Forms</strong></a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms229601(v=vs.110).aspx" rel="nofollow"><strong>Getting Started with Windows Forms</strong></a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:38:26.123", "Id": "8103", "Score": "0", "Tags": null, "Title": null }
8103
WinForms is the informal term given to the graphical application programming interface (API) included as a part of Microsoft's .NET Framework, providing access to the native Microsoft Windows interface elements by wrapping the existing Windows API in managed code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:38:26.123", "Id": "8104", "Score": "0", "Tags": null, "Title": null }
8104
<p>ANSI Common Lisp, the programmable programming language.</p> <p>We have a <a href="http://en.wikipedia.org/wiki/Common_Lisp" rel="nofollow">Wikipedia page</a> on Common Lisp, an online version of the <a href="http://www.lispworks.com/documentation/HyperSpec/Front/" rel="nofollow">ANSI Common Lisp standard</a> and a list of recommended <a href="http://common-lisp.net/~dlw/LispSurvey.html" rel="nofollow">Common Lisp implementations</a>. Many Lisp specific mailing lists are archived at <a href="http://dir.gmane.org/index.php?prefix=gmane.lisp" rel="nofollow">Gmane</a>.</p> <h3>Popular Common Lisp implementations</h3> <ul> <li><a href="http://www.sbcl.org/" rel="nofollow">Steel Bank Common Lisp (SBCL)</a>, a high performance Common Lisp compiler</li> <li><a href="http://www.clisp.org/" rel="nofollow">CLISP</a>, a portable implementation that compiles to bytecode</li> <li><a href="http://common-lisp.net/project/armedbear/" rel="nofollow">Armed Bear Common Lisp</a>, an implementation on top of JVM</li> <li><a href="http://ccl.clozure.com/" rel="nofollow">Clozure CL</a></li> </ul> <h3>See also</h3> <ul> <li><a href="http://www.lispworks.com/documentation/common-lisp.html" rel="nofollow">Common Lisp HyperSpec</a></li> <li><a href="http://stackoverflow.com/tags/lisp/info">Lisp</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:39:25.093", "Id": "8105", "Score": "0", "Tags": null, "Title": null }
8105
Common Lisp, or ANSI Common Lisp, is a standardized version of the Lisp programming language intended for production-strength power and libraries.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:39:25.093", "Id": "8106", "Score": "0", "Tags": null, "Title": null }
8106
<p>Since different languages may use different RNGs, a question with this tag must also be tagged with the language being used.</p> <p>All questions pertaining to create random numbers or random distributions: good or bad random number generators (RNGs), how to create specific distributions (gaussian, log-normal) with given parameters from normal random numbers, problems and caveats with given implementations in different languages.</p> <p>Since different languages may use different RNGs, a question with this tag must also be tagged with the language being used.</p> <h2>Frequently-asked questions</h2> <ul> <li>How can I generate N uniformly-distributed random real numbers <strong>that sum to a given value</strong>? <ul> <li><a href="http://stackoverflow.com/questions/5622608/choosing-n-numbers-with-fixed-sum">Language-agnostic</a></li> <li><a href="http://stackoverflow.com/questions/3959021/non-biased-return-a-list-of-n-random-positive-numbers-0-so-that-their-sum">Python</a></li> <li><a href="http://stackoverflow.com/questions/8064629/random-numbers-that-add-to-100-matlab">Matlab</a></li> <li><a href="http://stackoverflow.com/questions/3696612/how-can-i-create-a-specified-amount-of-random-values-that-all-equal-up-to-a-spec">PHP</a></li> <li><a href="http://stackoverflow.com/questions/4959975/random-between-two-numbers-in-javascript">Javascript</a></li> <li>If uniformity is important, beware of <a href="http://stackoverflow.com/a/2640067">this popular algorithm</a> (its output is <strong>not</strong> uniform.)</li> </ul></li> <li>How can I choose N elements, <strong>avoiding duplicates</strong>, from a list (or from the integer range 1..M)? <ul> <li><a href="http://stackoverflow.com/questions/158716/how-do-you-efficiently-generate-a-list-of-k-non-repeating-integers-between-0-and">Language-agnostic</a></li> <li><a href="http://stackoverflow.com/questions/9690009/pick-n-items-at-random">Python</a></li> <li><a href="http://stackoverflow.com/questions/8378752/java-pick-multiple-random-elements-from-a-list-without-repeating">Java</a></li> </ul></li> <li>If I create a new random number generator object for each request, why does it return the same value repeatedly? (Or: only seed the random generator once) <ul> <li><a href="http://stackoverflow.com/questions/5533191/java-random-always-returns-the-same-number-when-i-set-the-seed">Java</a></li> <li><a href="http://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c">C#</a></li> <li><a href="http://stackoverflow.com/questions/6954490/how-often-should-i-call-srand-in-a-c-application">C++</a></li> </ul></li> <li>How do I generate a random integer value within a range? <ul> <li><a href="http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java">Java</a></li> </ul></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:42:13.433", "Id": "8107", "Score": "0", "Tags": null, "Title": null }
8107
This tag is for questions pertaining to random numbers, whether pseudo random or truly random.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:42:13.433", "Id": "8108", "Score": "0", "Tags": null, "Title": null }
8108
<p><a href="http://en.wikipedia.org/wiki/Queue_%28data_structure%29" rel="nofollow">From Wikipedia</a>:</p> <blockquote> <p>In computer science, a <strong>queue</strong> is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as <em>enqueue</em>, and removal of entities from the front terminal position, known as <em>dequeue</em>. This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed. Often a <em>peek</em> or <em>front</em> operation is also entered, returning the value of the front element without dequeuing it. A queue is an example of a linear data structure, or more abstractly a sequential collection.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:43:11.217", "Id": "8109", "Score": "0", "Tags": null, "Title": null }
8109
A queue is an ordered, first-in-first-out (FIFO) data structure. Typical implementations of queues support pushing elements to the back and popping them off the front position.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:43:11.217", "Id": "8110", "Score": "0", "Tags": null, "Title": null }
8110
<p><a href="http://en.wikipedia.org/wiki/Memory_management" rel="nofollow">From Wikipedia</a>:</p> <blockquote> <p><strong>Memory management</strong> is the act of managing computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. This is critical to the computer system.</p> <p>Several methods have been devised that increase the effectiveness of memory management. Virtual memory systems separate the memory addresses used by a process from actual physical addresses, allowing separation of processes and increasing the effectively available amount of RAM using paging or swapping to secondary storage. The quality of the virtual memory manager can have an extensive effect on overall system performance.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:43:26.287", "Id": "8111", "Score": "0", "Tags": null, "Title": null }
8111
Memory management is the act of managing computer memory by allocating portions of memory to programs as well as freeing memory so that it can be re-used.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:43:26.287", "Id": "8112", "Score": "0", "Tags": null, "Title": null }
8112
Locking allows different types of resources to be locked by a transaction.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:45:35.737", "Id": "8114", "Score": "0", "Tags": null, "Title": null }
8114
<p><a href="http://en.wikipedia.org/wiki/Exception_handling" rel="nofollow">From Wikipedia</a>:</p> <blockquote> <p><strong>Exception handling</strong> is the process of responding to the occurrence, during computation, of <em>exceptions</em> – anomalous or exceptional events requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.</p> <p>In general, an exception is <em>handled</em> (resolved) by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an <em>exception handler</em>. If exceptions are <em>continuable</em>, the handler may later resume the execution at the original location using the saved information. For example, a floating point divide by zero exception will typically, by default, allow the program to be resumed, while an out of memory condition might not be resolvable transparently.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:46:27.843", "Id": "8115", "Score": "0", "Tags": null, "Title": null }
8115
An exception is a rarely occurring (exceptional!) condition that requires deviation from the program's normal flow.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:46:27.843", "Id": "8116", "Score": "0", "Tags": null, "Title": null }
8116
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:47:38.603", "Id": "8118", "Score": "0", "Tags": null, "Title": null }
8118
<blockquote> <p>The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. PDO provides a <em>data-access</em> abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. </p> <p>PDO does <em>not</em> provide a <em>database</em> abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.</p> </blockquote> <p>Via <a href="http://us3.php.net/manual/en/intro.pdo.php" rel="nofollow">PHP.net PDO</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:48:13.503", "Id": "8119", "Score": "0", "Tags": null, "Title": null }
8119
PDO is a PHP extension that serves as a data access abstraction layer for accessing databases.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:48:13.503", "Id": "8120", "Score": "0", "Tags": null, "Title": null }
8120
Zend Framework is an open source, object-oriented web application framework implemented in PHP 5 and licensed under the New BSD License.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:49:33.580", "Id": "8122", "Score": "0", "Tags": null, "Title": null }
8122
Historically, Hibernate facilitated the storage and retrieval of Java domain objects via Object/Relational Mapping. Today, Hibernate is a collection of related projects enabling developers to utilize POJO-style domain models in their applications in ways extending well beyond Object/Relational Mapping.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T15:50:11.783", "Id": "8124", "Score": "0", "Tags": null, "Title": null }
8124
Swing is a GUI toolkit packaged with the standard Java SDK since version 1.2.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:07:08.387", "Id": "8126", "Score": "0", "Tags": null, "Title": null }
8126
Scripting is a form of programming generally characterized by low formality, loose typing, and no requirement for explicit compilation. There are numerous scripting languages, and these are used in a wide variety of scenarios - command-line applications, GUIs, server-side applications, extension modules.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:07:44.297", "Id": "8128", "Score": "0", "Tags": null, "Title": null }
8128
<p>Reflection is the process by which a program can perform introspection. This introspection usually involves the ability to observe and modify its own structure and behavior at runtime. From theoretical perspective reflection relates to the fact that program instructions are stored as data. The distinction between program code and data is a matter of how the information is treated. Hence programs can treat their own code as data and observe or modify them. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:08:28.400", "Id": "8129", "Score": "0", "Tags": null, "Title": null }
8129
Reflection is the process by which a program can observe and modify its own structure and behavior at runtime.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:08:28.400", "Id": "8130", "Score": "0", "Tags": null, "Title": null }
8130
<p>See also: <a href="/questions/tagged/floating-point" class="post-tag" title="show questions tagged &#39;floating-point&#39;" rel="tag">floating-point</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:13:54.880", "Id": "8131", "Score": "0", "Tags": null, "Title": null }
8131
Use this tag for questions about using, storing or manipulating integral values of all types and sizes, including concerns about overflow. Not for code that casually happens to use integers.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:13:54.880", "Id": "8132", "Score": "0", "Tags": null, "Title": null }
8132
<p>In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. An enumeration is often predefined with an implied ordering.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:14:37.797", "Id": "8133", "Score": "0", "Tags": null, "Title": null }
8133
A data type consisting of a set of named values called elements, members or enumerators of the type.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:14:37.797", "Id": "8134", "Score": "0", "Tags": null, "Title": null }
8134
<p><strong>The Integrated Development Environment (<em>IDE</em>) for VB 6.0</strong></p> <p>One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE). IDE is a term commonly used in the programming world to describe the interface and environment that we use to create our applications. It is called integrated because we can access virtually all of the development tools that we need from one screen called an interface. The IDE is also commonly referred to as the design environment, or the program.</p> <p>The Visual Basic IDE is made up of a number of components</p> <ul> <li>Menu Bar</li> <li>Tool Bar</li> <li>Project Explorer</li> <li>Properties window</li> <li>Form Layout Window</li> <li>Toolbox</li> <li>Form Designer</li> <li>Object Browser</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:15:48.870", "Id": "8135", "Score": "0", "Tags": null, "Title": null }
8135
Visual Basic 6.0 (VB6) is the "third-generation" event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model. It was also considered a relatively easy programming language to learn and use, because of its graphical development features and BASIC heritage.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:15:48.870", "Id": "8136", "Score": "0", "Tags": null, "Title": null }
8136
<p>In computing, a <em>shell</em> is a user interface for access to an operating system's services. In general, operating system shells use either a <em>command-line interface</em> (CLI) or <em>graphical user interface</em> (GUI), depending on a computer's role and particular operation. It is named a shell because it is the outermost layer around the operating system kernel.</p> <h3>Links</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Shell_(computing)" rel="nofollow noreferrer">Wiki: Shell</a></li> <li><a href="https://en.wikipedia.org/wiki/Command-line_interface" rel="nofollow noreferrer">Wiki: Command-Line Interface</a></li> <li><a href="https://en.wikipedia.org/wiki/Graphical_user_interface" rel="nofollow noreferrer">Wiki: Graphical User Interface</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-21T16:16:29.650", "Id": "8137", "Score": "0", "Tags": null, "Title": null }
8137
<p>The <code>mysqli</code> PHP extension is the successor to the <a href="/questions/tagged/mysql" class="post-tag" title="show questions tagged 'mysql'" rel="tag">mysql</a> PHP extension. The extension's principle features consist of:</p> <ul> <li>An object-oriented interface</li> <li>Support for prepared statements</li> <li>Support for multiple statements</li> <li>Support for transactions</li> <li>Enhanced debugging support</li> <li>Embedded server support</li> </ul> <blockquote> <p>As of PHP version >= 7.0, the <strong>mysql_</strong> extension (deprecated in version 5.5) will be removed and only <strong>mysqli_</strong> will be available</p> </blockquote> <p>In addition to an object-oriented interface, most <code>mysqli</code> features also provide an equivalent procedural interface through functions prefixed <code>mysqli_*()</code></p> <p><code>Mysqli</code>'s prepared statement support makes use of <code>?</code> placeholders bound to variable references for input, and variable references bound to columns when fetching output rows. Please note that, in order to use some aspects of <code>mysqli</code> prepared statements (most notably <a href="http://www.php.net/manual/en/mysqli-stmt.get-result.php" rel="nofollow">mysqli_stmt_get_result</a>), your installation of PHP must use the <a href="http://us3.php.net/manual/en/intro.mysqlnd.php" rel="nofollow">Mysql Native Driver</a> (<code>mysqlnd</code>), which also provides improved performance over the older MySQL Client Library.</p> <ul> <li><a href="http://php.net/manual/en/book.mysqli.php" rel="nofollow">PHP documentation on the MySQLi class</a></li> <li><a href="https://wikis.oracle.com/display/mysql/Converting+to+MySQLi" rel="nofollow">MySQL Tool for conversion MySQL to MySQLi</a> (<a href="https://wikis.oracle.com/display/mysql/Converting+to+MySQLi" rel="nofollow">download</a>)</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:17:02.083", "Id": "8139", "Score": "0", "Tags": null, "Title": null }
8139
The MySQLi extension, or as it is sometimes known, the MySQL Improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The MySQLi extension is included with PHP versions 5 and later.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:17:02.083", "Id": "8140", "Score": "0", "Tags": null, "Title": null }
8140
<p><a href="http://codeigniter.com/" rel="nofollow noreferrer"><img src="https://ellislab.com/_user_guide_src_ci/images/ci_logo_flame.jpg" alt="PHP"></a></p> <p><a href="http://codeigniter.com/" rel="nofollow noreferrer">CodeIgniter</a> is an open-source <a href="http://www.php.net/" rel="nofollow noreferrer">PHP</a> web development framework created by <a href="https://ellislab.com/" rel="nofollow noreferrer">EllisLab Inc</a>. The framework implements the Model-View-Controller design pattern. It is praised for its performance and the quality of its <a href="http://codeigniter.com/user_guide/" rel="nofollow noreferrer">documentation</a>.</p> <p>These are generally regarded as pros of the framework:</p> <ul> <li>Small footprint</li> <li>Performance</li> <li>Easy to learn</li> <li>Great documentation</li> </ul> <p>These are generally regarded as cons of the framework:</p> <ul> <li>No built in ORM</li> <li>Validation in the controller, instead of model</li> <li>CodeIgniter 2.0 doesn't support PHP4</li> </ul> <p>The current version (2.1.3) was released on October 8, 2012.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:18:20.520", "Id": "8141", "Score": "0", "Tags": null, "Title": null }
8141
CodeIgniter is an open-source PHP web development framework created by EllisLab Inc. The framework implements the Model-View-Controller design pattern. It is praised for its performance and the quality of its documentation.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:18:20.520", "Id": "8142", "Score": "0", "Tags": null, "Title": null }
8142
<p>A makefile is usually an input file for the build control language/tool make. The <code>make</code> utility and the corresponding makefile format is <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/make.html" rel="nofollow">standardized by POSIX</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:19:33.420", "Id": "8143", "Score": "0", "Tags": null, "Title": null }
8143
A makefile is usually an input file for the build control language/tool make.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:19:33.420", "Id": "8144", "Score": "0", "Tags": null, "Title": null }
8144
<p>Sorting is the process of applying some order to a collection of items. There are various algorithms for doing this, including <a href="/questions/tagged/mergesort" class="post-tag" title="show questions tagged &#39;mergesort&#39;" rel="tag">mergesort</a> and <a href="/questions/tagged/quick-sort" class="post-tag" title="show questions tagged &#39;quick-sort&#39;" rel="tag">quick-sort</a>.</p> <p>From the <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow">Sorting Algorithms Wikipedia entry</a>:</p> <blockquote> <p>In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions:</p> <ol> <li>The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order);</li> <li>The output is a permutation (reordering) of the input.</li> </ol> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:20:10.470", "Id": "8145", "Score": "0", "Tags": null, "Title": null }
8145
Sorting is the process of applying some order to a collection of items.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:20:10.470", "Id": "8146", "Score": "0", "Tags": null, "Title": null }
8146
<p><a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">From Wikipedia</a>:</p> <blockquote> <p>In software engineering, the <strong>singleton pattern</strong> is a design pattern that restricts the Instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.</p> </blockquote>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:22:45.287", "Id": "8147", "Score": "0", "Tags": null, "Title": null }
8147
The singleton is a design pattern to ensure that exactly one application-wide instance of a particular class exists.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:22:45.287", "Id": "8148", "Score": "0", "Tags": null, "Title": null }
8148
ASP.NET MVC 2 is the second major version of the ASP.NET MVC platform, it has since been outdated by ASP.NET MVC 3.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:23:36.033", "Id": "8150", "Score": "0", "Tags": null, "Title": null }
8150
Quicksort is a sorting algorithm invented by C. A. R. Hoare that has an average-case complexity of O(n log n), worst-case complexity of O(n^2). It is one of the fastest general-purpose sorting algorithms in practice.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:25:26.657", "Id": "8152", "Score": "0", "Tags": null, "Title": null }
8152
Asynchronous programming is simply allowing some portions of code to be executed on separate threads. It makes your applications perform better, be more responsive, and use the resources of the system they are running on to the fullest extent.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:26:49.460", "Id": "8154", "Score": "0", "Tags": null, "Title": null }
8154
<p>OpenGL (or Open Graphics Library) is a cross-language, multi-platform application programming interface (API) specification for 2D and 3D graphics rendering. It is designed to be easy to accelerate with dedicated computer hardware, and hence most implementations give greatly improved performance over traditional software rendering. The API is typically used to interact with a graphics processing unit (GPU), to achieve hardware-accelerated rendering.</p> <p>Silicon Graphics Inc. (SGI) started developing OpenGL circa 1991 and released the first implementation in 1992. The specification is currently at version 4.6 (July 2017). Applications use it extensively in the fields of CAD, virtual reality, scientific and data visualization, flight simulation and video games. OpenGL is now managed by the non-profit technology consortium <a href="https://www.khronos.org/" rel="nofollow noreferrer">Khronos Group</a>.</p> <p><strong>Reference sites:</strong></p> <ul> <li><p><a href="https://www.opengl.org/" rel="nofollow noreferrer">OpenGL.org</a>, the home of OpenGL.</p> </li> <li><p><a href="http://en.wikipedia.org/wiki/OpenGL" rel="nofollow noreferrer">The Wikipedia page</a> on OpenGL.</p> </li> <li><p>Introduction and tutorials at <a href="http://openglbook.com/" rel="nofollow noreferrer">OpenGLBook.com</a>.</p> </li> <li><p><a href="http://ogldev.atspace.co.uk/" rel="nofollow noreferrer">Another collection of tutorials</a> targeting major OSes.</p> </li> </ul> <hr /> <p>Questions including code that uses the OpenGL API should use this tag. This not only applies to the C version of the API, but to any language that has bindings to OpenGL.</p> <p>For questions that also include GLSL shader code, add the <a href="/questions/tagged/glsl" class="post-tag" title="show questions tagged &#39;glsl&#39;" rel="tag">glsl</a> tag as well.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-21T16:28:24.013", "Id": "8155", "Score": "0", "Tags": null, "Title": null }
8155
OpenGL is a graphics standard and API which targets the desktop, workstation and mobile segments. OpenGL is used for applications like CAD software and computer games. It is also cross-platform and with bindings for several programming languages. Use this tag together with the appropriate language tag for code that uses OpenGL libraries; add the 'glsl' tag for questions which include GLSL shader code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-21T16:28:24.013", "Id": "8156", "Score": "0", "Tags": null, "Title": null }
8156
Windows Communication Foundation is a part of the .NET Framework that provides a unified programming model for rapidly building service-oriented applications. This integrates various other(.net\java\MSMQ) technologies. The primary focus on the interoperability of different stacks of communication.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:28:40.317", "Id": "8158", "Score": "0", "Tags": null, "Title": null }
8158
"Don't Repeat Yourself", or DRY, is a software development philosophy which aims at reducing redundancy and code repetition.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:29:49.317", "Id": "8160", "Score": "0", "Tags": null, "Title": null }
8160
An iterator is an object-oriented programming pattern which for the most part functions similarly to a pointer to an object inside a collection with the added ability to traverse through the collection in a defined manner, agnostic of the actual implementation or even object addresses in physical memory. Iterators may be further limited in particular traversal directions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:30:35.820", "Id": "8162", "Score": "0", "Tags": null, "Title": null }
8162
<p>I use this Matlab code:</p> <pre><code>load ~/emailAnalysis/results.txt results=results(size(results,1)-400:size(results,1),:) temp = results(:,3)-1238370000; h=plot(temp,smooth(results(:,1)),':b') set(h,'LineWidth',1) ylim([0 80]) xlim([max(temp)-(86400*7),max(temp)-1]) set(gca,'XGrid','on') ylabel('Emails') hold on i=plot(temp,smooth(results(:,4)),'r') j=plot(temp,smooth(results(:,5)),'-g') k=plot(temp,smooth(results(:,6)),'m') xlim([max(temp)-(86400*7),max(temp)-1]) set(gca,'XTick',[1:86400:(86400*max(temp))+1]) set(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun']) set(j,'LineWidth',2) set(h,'LineWidth',1) set(i,'LineWidth',2) set(k,'LineWidth',2) xlabel('Time') title('Size of inbox over time (seven days)') print -r3000 -djpeg /XXXX/inbox7day.jpeg hold off </code></pre> <p>to generate this graph:</p> <p><img src="https://i.stack.imgur.com/Jmsi8.jpg" alt="graph"></p> <p>from data like:</p> <pre><code>34 2012-01-21 1327152611 5 16 10 32 2012-01-21 1327154411 5 14 9 32 2012-01-21 1327156209 5 14 9 34 2012-01-21 1327158012 5 14 9 34 2012-01-21 1327159808 5 15 9 34 2012-01-21 1327161611 5 15 9 34 2012-01-21 1327163406 5 15 9 33 2012-01-21 1327165211 5 13 9 34 2012-01-21 1327167011 5 13 9 31 2012-01-21 1327168810 4 12 8 </code></pre> <p>but it's a little slow, and also probably not very elegant (it's my first use of Matlab) I'm interested in any tips for best practice, tips for speeding it up, or examples of how I might do the same things in R...</p>
[]
[ { "body": "<pre><code>clear all;\nload('results.txt');\ntime = results(:,3) - 1238370000;\n</code></pre>\n\n<p>There's no need to plot all of the points if you're going to restrict the range to the past week. So I'd suggest you find the index where the time is less than a week ago and limit your plotting to that period to reduce complexity</p>\n\n<pre><code>firstTimeIndex = find(time &gt;= (max(time) - 86400*7), 1);\n</code></pre>\n\n<p>Also note that you can use 'end' instead of 'size(results,1)'</p>\n\n<pre><code>results = results(max(1,firstTimeIndex-1):end, :);\nclf;\nh = plot(time,smooth(results(:,1)),':b');\nhold on;\n</code></pre>\n\n<p>Line properties like linewidth can be specified at the time of plotting</p>\n\n<pre><code>plot(time, smooth(results(:,4)), 'r', 'linewidth', 2);\nplot(time, smooth(results(:,5)), 'g', 'linewidth', 2);\nplot(time, smooth(results(:,6)), 'm', 'linewidth', 2);\nxlabel('Time');\nylabel('Emails');\nxlim([max(time)-(86400*7) max(time)-1]);\nylim([0 80]);\nset(gca,'XGrid','on');\nset(gca,'XTickLabel',['Mon';'Tue';'Wed';'Thu';'Fri';'Sat';'Sun']);\ntitle('Size of inbox over time (seven days)');\n</code></pre>\n\n<p>I'm not sure why you are setting the resolution to 3000 dpi? Maybe you could elaborate on what you're using this for, but if your goal is high resolution and low storage size then you might like to use -dmeta for a metafile on windows, or -deps for an encapsulated postscript on unix</p>\n\n<pre><code>print -djpeg inbox7day.jpeg;\n</code></pre>\n\n<p>I'm not sure what you are trying to achieve with the 'XTick' property, but the vector you're passing in is extremely large (~100 million elements) which is why the code is running so slow. I'm guessing that you don't want 100 million ticks?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T19:13:30.623", "Id": "14125", "Score": "0", "body": "Awesome. Particularly that I hadn't noticed the problem with the xticks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-11T21:24:11.417", "Id": "8892", "ParentId": "8165", "Score": "3" } } ]
{ "AcceptedAnswerId": "8892", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T18:10:53.287", "Id": "8165", "Score": "3", "Tags": [ "performance", "matlab", "r" ], "Title": "Generate graph in Matlab" }
8165
<p>I'm trying to devise a way to calculate the <strong>mean differences</strong> (the absolute average differences between any two values in a set), of sub-arrays (starting from arbitrary indices) in an <code>int</code> array. I'll be placing the bounds of each subarray in to "buckets" of differing mean difference magnitudes.</p> <p>The problem is, I can't find an efficient (better than \$O(n^3)\$) way of doing this. Would anyone mind helping me make the code more efficient (at least better than \$O(n^2)\$)?. </p> <p>The calculations are performed server-side upon user request from my web-app. If making it more efficient isn't possible, would it be advisable to adopt a solution that doesn't involve modifying the computation, such as:</p> <ul> <li>Keep this inefficient implementation and include a disclaimer stating it may take some time to complete</li> <li>Transfer the calculations to several daemon threads which will perform the process on the entire user base and store the results in the database, which will be returned to the users (returned results may not be up-to-date)</li> </ul> <p>I'm currently at a crossroads and am not sure which route I should take.</p> <p><strong>Pseudocode of main function:</strong></p> <blockquote> <pre><code>/*The purpose of the main function is to store the mean differences of sub-arrays in a given array, making the sure the stored sub-arrays are as long as possible*/ for i in dataArray loop through all j (j starting from i + 1) in dataArray get mean difference of values in between indexes i and j get int value of mean difference (bucket) if bucket != (bucket of mean difference of values in between indexes i and j - 1), store i and j in bucket </code></pre> </blockquote> <p><strong>Main function</strong>:</p> <pre><code>public static HashMap&lt;Integer, Stack&lt;HashMap&lt;String, Integer&gt;&gt;&gt; calculateMeanDifferences(ArrayList&lt;Integer&gt; dataArrayList) { //Each key maps to a stack which will hold HashMaps containing the bounding indices of subArrays which have mean differences that round to the key HashMap&lt;Integer, Stack&lt;HashMap&lt;String, Integer&gt;&gt;&gt; meanDifferenceBucketHashMap = new HashMap&lt;Integer, Stack&lt;HashMap&lt;String, Integer&gt;&gt;&gt;(); long size = dataArrayList.size(); Integer previousMeanDifferenceBucket = null; Integer currentMeanDifferenceBucket = null; double currentMeanDifference = 0; //Major loop which starts the mean difference calculations from every index for(int i = 0; i &lt; size; i++) { //Minor loop which calculates the mean differences for sub-arrays of increasing length starting from i. for(int j = i + 2; j &lt; size + 1; j++) { currentMeanDifference = calculateMeanDifference(new ArrayList(dataArrayList.subList(i, j))); currentMeanDifferenceBucket = (int)Math.round(currentMeanDifference); //Ensure longest possible sub-array is recorded (so, for all i and j, if both subList(i,j-1) and subList(i, j) are recorded, they will be in different buckets) if((previousMeanDifferenceBucket != null &amp;&amp; previousMeanDifferenceBucket != currentMeanDifferenceBucket) || j == size) { HashMap&lt;String, Integer&gt; previousSubArrayBoundsHashMap = new HashMap&lt;String, Integer&gt;(); previousSubArrayBoundsHashMap.put("start", i); previousSubArrayBoundsHashMap.put("onePastEnd", j); if(!meanDifferenceBucketHashMap.containsKey(previousMeanDifferenceBucket)) meanDifferenceBucketHashMap.put(previousMeanDifferenceBucket, new Stack&lt;HashMap&lt;String, Integer&gt;&gt;()); else meanDifferenceBucketHashMap.get(previousMeanDifferenceBucket).push(previousSubArrayBoundsHashMap); } previousMeanDifferenceBucket = currentMeanDifferenceBucket; } previousMeanDifferenceBucket = currentMeanDifferenceBucket = null; } return meanDifferenceBucketHashMap; } </code></pre> <p><strong>Sub-function</strong> (not necessary to look over, just know it is \$O(n)\$ for my use case (all values guaranteed to be in the set [0,5])):</p> <pre><code>public static double calculateMeanDifference(ArrayList&lt;Integer&gt; valuesArrayList) { HashMap&lt;Integer, Double&gt; valueCountsHashMap = new HashMap&lt;Integer, Double&gt;(); double size = valuesArrayList.size(); for(int i = 0; i &lt; size; i++) { int currentValue = valuesArrayList.get(i); if(!valueCountsHashMap.containsKey(currentValue)) valueCountsHashMap.put(currentValue, new Double(1)); else valueCountsHashMap.put(currentValue, valueCountsHashMap.get(currentValue)+ 1); } double sum = 0; for(Map.Entry&lt;Integer, Double&gt; valueCountKeyValuePair : valueCountsHashMap.entrySet()) { int currentValue = valueCountKeyValuePair.getKey(); Double currentCount = valueCountKeyValuePair.getValue(); for(Map.Entry&lt;Integer, Double&gt; valueCountKeyValuePair1 : valueCountsHashMap.entrySet()) { int loopValue = valueCountKeyValuePair1.getKey(); Double loopCount = valueCountKeyValuePair1.getValue(); sum += (currentValue != loopValue ? Math.abs(currentValue - loopValue) * loopCount * currentCount : 0); } } return new Double( sum/ (size * (size - 1))); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:32:22.273", "Id": "12746", "Score": "5", "body": "Could you, instead of just posting your code, provide some (links to) hints on the actual math which you are trying to implement, as well as pseudocode of your algorithm? This would make it much easier to see if there are any shortcuts you are missing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:39:06.080", "Id": "12747", "Score": "0", "body": "@TomasLycken: The methodology behind calculating the mean difference average can be found in the first img in my SO post [here](http://stackoverflow.com/questions/8931515/translating-equivalent-formulas-in-to-code-isnt-giving-correct-results/8931761). This isn't of particular interest though, it will always O(N). I'll include pseudocode of what i'm trying to do right now. It'll be up in a couple of minutes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:49:09.980", "Id": "12748", "Score": "1", "body": "Mean difference calculation is O(n^2) surely?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:52:05.433", "Id": "12749", "Score": "0", "body": "@TimGee: Depending on the implementation (see the linked post in my first comment). Using this particular function with random values in the dataArray, it will be O(n^2). For my use case, however, it is O(n), since all the values in the data array are guarenteed to have values in the set [0,5]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:58:57.347", "Id": "12750", "Score": "0", "body": "Ah okay. I think what you might need is an incremental/online calculation for mean difference. I know that's not sufficient for an answer, so I'll just leave that as a comment... ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:01:45.827", "Id": "12751", "Score": "1", "body": "It's still not clear what you are generally trying to achieve and what buckets are exactly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:02:14.787", "Id": "12752", "Score": "0", "body": "Your problem looks very parallelizable: each pass of the outer loop seems to be independent of the others. Might start with that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:12:28.653", "Id": "12753", "Score": "0", "body": "@cyborg: The buckets are simply categories that contain subarrays that have mean differences that round to a given integer. My objective is still unclear? Can you be a bit more specific as to what is unclear?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:46:26.547", "Id": "12754", "Score": "0", "body": "@Kevin I can't speak for cyborg, but here's what gets me confused. In the pseudocode, you talk of \"looping over j\", which to me says that j is a int that varies (as it does in your code) but then \"get mean difference of dataArray(i, j)\". If i is a single number (at a time) and so is j, what is the talk of \"mean\" difference. There's only a single difference. There's a k missing somewhere. Also, in the actual code, why does j start at i+2, not i+1?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:57:57.850", "Id": "12755", "Score": "0", "body": "@user949300: Sorry for the confusion. In the pseudocode, \"get mean difference of dataArray(i, j)\" means \"get the mean difference of the values contained between index i and index j (inclusive). In the actual code, j starts at \"i + 2\" because we want to process sub-arrays with at least two elements (the mean difference of a one element set is useless). The .subList() function takes the beginning index, and one PAST the end index of the selection. So if I wanted a sub-list of size 2 starting from index 0, I would use .subList(0, 2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T03:23:06.177", "Id": "12757", "Score": "0", "body": "If I understand the problem correctly (`sum(abs(v1-v2) for i,v1 in enumerate(a) for v2 in a[i+1:])/(len(a)*(len(a+1))/2)`), this is doable in O(nlogn) time, O(n) auxiliary space with a balanced search tree structure (keeping extra metadata, e.g. sum of elements in the subtrees rooted at each node)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T19:20:35.170", "Id": "12851", "Score": "0", "body": "I don't quite understand what you are trying to do, but rounding the mean of differences to an integer looks quite wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T19:36:22.137", "Id": "13193", "Score": "0", "body": "@toto2: Sorry if it is still confusing. I've gone over the pseudocode several times and think it describes the procedure at least somewhat adequately. Even though I've changed what I'm measuring and no longer need to use the method, I'd still like to make was I was trying to accomplish clear for others who may want to analyze data in a similar way in the future. So, what exactly is it you don't understand? The rounding of the mean differences is done merely to categorize sub-arrays with similar mean differences together" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T20:22:31.047", "Id": "13195", "Score": "0", "body": "Sorry, I just reread your question and I'm still as confused. I think you should start over with a new question if you want help from someone. The problem is not as much the code as not explaining what you are trying to do. It would help to describe what it is that you are trying to do in very general terms and what it is used for. You did try to explain by replying to comments, but it's a mess now." } ]
[ { "body": "<p>Let us have two functions:</p>\n\n<pre><code>aggr_sum(a, i, j) : |a[i]-a[j]| +....+ |a[j-1]-a[j]|\nsum_difference(a,i,j): sum of difference of all elements from a[i]...a[j]\n</code></pre>\n\n<p>You can calculate aggr_sum for all values of i and j in O(n^2) time:</p>\n\n<pre><code>aggr_sum(a, i, j) = aggr_sum(a, i+1, j) + |a[i]-a[j]|\n</code></pre>\n\n<p>Now,</p>\n\n<pre><code>sum_difference(a,i,j) = sum_difference(a,i,j-1)+aggr_sum(a,i,j)\n</code></pre>\n\n<p>Which is also O(n^2)</p>\n\n<p>Then you can divide sum_difference by count to get mean_difference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T01:26:46.730", "Id": "12758", "Score": "0", "body": "I see. This is an attempt at the incremental approach that Tim Gee alluded to in a comment in the original post. However, I don't think that's possibe for the mean difference calculation. Once a new number is added in to the mix, you have to add: `|(new number) - a[i]|` for all i in a to the sum of the previous mean difference calculation; you can't just perform one more calculation and increment the number of elements to divide by" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T01:45:54.513", "Id": "12759", "Score": "0", "body": "@Kevin All I am saying is, when ever you add a new value you can update the calculations in O(n) steps (courtesy aggr_sum function). So even for incremental addition complexity is still O(n^2)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T00:08:27.620", "Id": "8175", "ParentId": "8174", "Score": "1" } }, { "body": "<p>The first optimisation is to avoid using <code>Double</code> and <code>Integer</code> when you really want <code>double</code> and <code>int</code> You can use Trove4j to act as collection of these types. Additionally I wouldn't use double when you mean to use int, e.g. for counts which can only be whole numbers.</p>\n\n<p>I would also avoid counting the combinations twice. e.g. if you have an array of two you compare both a1 - a2 and a2 - a1 which should be the same.</p>\n\n<p>Can you make any assumptions on the range of int values?</p>\n\n<hr>\n\n<p>This example</p>\n\n<pre><code>public static void main(String... args) throws IOException {\n Random rand = new Random(1);\n int size = 100000;\n TIntArrayList valuesArrayList = new TIntArrayList(size);\n for (int i = 0; i &lt; size; i++) {\n valuesArrayList.add(rand.nextInt(size) - rand.nextInt(size));\n }\n long start = System.nanoTime();\n double d = calculateMeanDifference(valuesArrayList);\n long time = System.nanoTime() - start;\n System.out.printf(\"Took %.3f seconds to calculate d=%.3f for size=%,d values%n\", time / 1e9, d, size);\n}\n\npublic static double calculateMeanDifference(TIntArrayList valuesArrayList) {\n final TIntIntHashMap counts = new TIntIntHashMap();\n valuesArrayList.forEach(new TIntProcedure() {\n @Override\n public boolean execute(int value) {\n counts.adjustOrPutValue(value, 1, 1);\n return true;\n }\n });\n\n final int[] uniqueValues = new int[counts.size()], uniqueCounts = new int[counts.size()];\n counts.forEachEntry(new TIntIntProcedure() {\n int i = 0;\n @Override\n public boolean execute(int a, int b) {\n uniqueValues[i] = a;\n uniqueCounts[i++] = b;\n return true;\n }\n });\n long sum = 0;\n for (int i = 1; i &lt; uniqueValues.length; i++) {\n int vi = uniqueValues[i];\n int ci = uniqueCounts[i];\n for (int j = 0; j &lt; i; j++) {\n int counts2 = ci * uniqueCounts[j];\n sum += Math.abs(vi - uniqueValues[j]) * counts2;\n }\n }\n\n return 2.0 * sum / valuesArrayList.size() / (valuesArrayList.size() - 1);\n}\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>Took 12.173 seconds to calculate d=46786.434 for size=100,000 values\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T11:05:11.517", "Id": "12760", "Score": "0", "body": "Thanks for the tips. In actuality, I'll be processing an array of objects from which the values will be retrieved, so I won't be able to use TIntArrayList. And yes, an important assumption can be made for the values processed: they all will have values in the range [0,5]. I'm a bit confused as to why `count` is being increased by the product of every two unique counts processed. In the return statement, what is `count` supposed to represent? In the official formula, the denominator is `N * (N - 1)`, where `N`, in your code, is the summation of all values in `uniqueCounts[]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T11:14:24.790", "Id": "12761", "Score": "0", "body": "Additionally, in your code you loop through the map just to insert unique values and counts in to seperate arrays, then iterate through them. I know in theory iterating through arrays is faster than going over each `Map.entry`, but won't having to iterate through 100,000 elements once (map, nested loop in my code) beat doing it twice (creation of value& count arrays, then nested loop for processing of the arrays) every time? Am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T11:24:21.180", "Id": "12762", "Score": "0", "body": "Ah. I assume your stance is that the avoidance of calculating `|a[i] - a[j]|` when `|a[j] - a[i]|` is already known may offset the extra processing done by your code. I suppose I could use a map of pairs to store and re-use the calculated mini-sums to avoid doing that in my code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T12:35:17.280", "Id": "12763", "Score": "0", "body": "You are right that count is not strictly needed. Since you mutliplying by the values, I don't see how they can be objects. You are performing O(n^2) lookups so iterating to build an array isn't significant. It also simplifies accessing `i < j`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T16:23:20.630", "Id": "12764", "Score": "0", "body": "What I mean to say is that the argument array will actually be an array of Maps, each of which will contain the value of interest. So if `mapArray` is the input array, `mapArray[i].get(\"value\")` for each `i` would give the values we are computing the mean difference for. So, the input parameter can't be of type `TIntArrayList`. In any case, your method is SUPER fast. I'll definately be using it. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T17:23:34.473", "Id": "12765", "Score": "0", "body": "You can copy all the `mapArray[i].get(\"value\")` into a TIntArrayList" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T09:01:30.070", "Id": "8176", "ParentId": "8174", "Score": "7" } }, { "body": "<p>I ended up changing what I wanted to analyze in order decrease the amount of computation required. The solution is scenario-specific and involves analyzing groups of the array elements (represented as numbers in the original question, but are actually Objects containing these values) created on the same day, rather than analyzing all the contiguous subsets of the array.</p>\n\n<p>A solution to the actual problem still hasn't been proposed, so I'll leave it unanswered in hopes that someone will come up with one!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T19:53:05.470", "Id": "8430", "ParentId": "8174", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T23:23:02.017", "Id": "8174", "Score": "8", "Tags": [ "java", "algorithm", "complexity" ], "Title": "Calculating the mean differences of subarrays" }
8174
<p>A prime (or prime number) is a number divisible only by itself and one.<br> The first 5 prime numbers are: 2, 3, 5, 7, 11. </p> <p>Prime numbers are commonly used in hashing and encryption algorithms. Most notably, many encryptions rely on using very large primes.</p> <p>There is no known relationship between primes aside from them being only divisible by themselves and one. Additionally, all primes follow certain rules:</p> <p>For any given prime \$p\$, the following is true \$(p-1)! + 1 \bmod p = 0\$, to name one.</p> <p>Primes can be found using many different algortihms. The most well known are Trial Division and the <a href="/questions/tagged/sieve-of-eratosthenes" class="post-tag" title="show questions tagged &#39;sieve-of-eratosthenes&#39;" rel="tag">sieve-of-eratosthenes</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T23:42:03.870", "Id": "8177", "Score": "0", "Tags": null, "Title": null }
8177
Primes or prime numbers are numbers which are divisible only by themselves and one, starting with 2, 3, 5, 7, 11.... They are commonly used in encryption and hashing algorithms.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T23:42:03.870", "Id": "8178", "Score": "0", "Tags": null, "Title": null }
8178
<p>I find it a bit odd in ASP.NET MVC that the <code>Html</code> helper extensions, like <code>Html.EditorFor</code>, take a <code>Func&lt;T1, TResult&gt;</code> where the <code>T1</code> argument is just the already in scope <code>Model</code> variable, e.g.:</p> <pre><code>@Html.EditorFor(x =&gt; x.Name) </code></pre> <p>If I really wanted <code>Model</code> renamed, I would just assign it once to a variable in the top of the razor view. So, I feel compelled to do the following:</p> <pre><code>@Html.EditorFor(_ =&gt; Model.Name) </code></pre> <p>Does this seem reasonable?</p>
[]
[ { "body": "<p>I think MVC's way of suggesting that it needs a direct member of the <code>Model</code> class.</p>\n\n<p>What (I think) MVC is doing in the <code>x =&gt; x.Name</code> case is analyze the expression and make sure its composed of a single node, which is a property/field of the input parameter (no need to check if the property/field belongs to the Model class, since this is strongly typed in the expression itself)</p>\n\n<p>So, basically MVC takes a reference to a member of the Model class. After doing so, it uses the Name of the member to generate the <code>for</code> attribute of the HTML element and the Value of the member for the current Model instance to do the actual display (using reflection, probably).</p>\n\n<p>Using the second approach it might still be possible, but more indirect, because when parsing the Lambda expression, it should also check that the <code>Model</code> variable is an instance of the Model class, in addition to all the other things it needs to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T10:08:53.310", "Id": "8190", "ParentId": "8181", "Score": "0" } }, { "body": "<p>I'd fail this review if I saw it at my company. Most are probably shown the first approach, doing this will only confuse people that come after you. Now they have to determine if the way you've chosen is actually equivolent to the \"standard\" way. I actually just went through that exercise myself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T16:45:08.390", "Id": "12800", "Score": "0", "body": "Fair enough - not worth making others have to analyze my deviation from the standard pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T13:28:44.933", "Id": "8191", "ParentId": "8181", "Score": "1" } }, { "body": "<p>You don't have to use x as the parameter name for the lambda. You can call it model with a small m for instance.</p>\n\n<pre><code>@Html.EditorFor(model =&gt; model.Name)\n</code></pre>\n\n<p>You aren't renaming it either, you're naming the parameter for the anonymous function the lambda expression represents.</p>\n\n<p>But if you don't like the lambda syntax, there's also overloads taking the property name as a string.</p>\n\n<pre><code>@Html.Editor(\"Name\")\n</code></pre>\n\n<p>I wouldn't presume the metadata information gathered from reflection as mentioned by w0lf will be handled completely if you reference the Model property directly from the lambdas.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T16:12:43.870", "Id": "8196", "ParentId": "8181", "Score": "1" } } ]
{ "AcceptedAnswerId": "8191", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T03:18:50.050", "Id": "8181", "Score": "2", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "ASP.NET MVC Html.XXFor OK to discard lambda argument and just use Model directly?" }
8181
<p><a href="http://jondavidjohn.com/blog/2012/01/imperfect-human-list-card-shuffle-in-python" rel="nofollow">I've got this <code>humanoid_shuffle</code> I wrote in Python</a>. I've been wanting to learn C so as an exercise I ported it to C. As this is my first venture into C and even the ideas of memory management and the like, what are some ways to make this better from a code quality and efficiency perspective?</p> <p>A couple of quick thoughts from a C beginner:</p> <ul> <li>Interesting how it's harder to justify creating multiple new copies of the array to juggle between.</li> <li>Seems like you have to be much more clever and less practical with C (obviously the Python version is much easier to follow).</li> </ul> <p>Thoughts?</p> <p><strong>Python</strong></p> <pre><code>@staticmethod def humanoid_shuffle(items, num_shuffles=6): # how many times items can be pulled from the same list consecutively MAX_STREAK = 10 # divide list roughly in half num_items = len(items) end_range = int(num_items / 2 + random.randint(0, int(.1 * num_items))) first_half = items[:end_range] # list up to 0 - end_range second_half = items[end_range:] # list after end_range - len(items) split_lists = (first_half, second_half) mixed = [] streak = current_item_index = 0 # while both lists still contain items while first_half and second_half: # calc the percentage of remaining total items remaining = (1 - float(len(mixed)) / num_items) # if we happen to generate a random value less than the remaining percentage # which will be continually be decreasing (along with the probability) # or # if MAX_STREAK is exceeded if random.random() &lt; remaining or streak &gt; MAX_STREAK: # switch which list is being used to pull items from current_list_index = 1 ^ current_list_index # reset streak counter streak = 0 # pop the selected list onto the new (shuffled) list mixed.append(split_lists[current_list_index].pop()) # increment streak of how many consecutive times a list has remained selected streak += 1 # add any remaining items mixed.extend(first_half) mixed.extend(second_half) num_shuffles -= 1 # if we still have shuffles to do if num_shuffles: # rinse and repeat mixed = humanoid_shuffle(mixed, num_shuffles) # finally return fully shuffled list return mixed </code></pre> <p><strong>C</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; void shuffle(int *shuffle_array, int length) { int const MAX_STREAK = 10; int end_range; int mixed[length]; int m, f, l; int streak; int *current_ptr; srand(time(NULL)); current_ptr = (rand() % 2) ? &amp;f : &amp;l; end_range = (int)(length / 2 + rand() % (int)(.1 * length)); for(m = 0, f = 0, l = (end_range + 1), streak = 0; m &lt; length &amp;&amp; l &lt; length &amp;&amp; f &lt; end_range + 1; m++, *current_ptr += 1) { float remaining = 1 - m / (float)length; float test = rand() / (float)RAND_MAX; if (test &lt; remaining || streak &gt; MAX_STREAK) { current_ptr = (current_ptr == &amp;f ? &amp;l : &amp;f); streak = 0; } mixed[m] = shuffle_array[*current_ptr]; printf("Dropped from %p --&gt; %d \n", current_ptr, mixed[m]); streak += 1; } // change the pointer to the one that didn't cause the for to exit current_ptr = (current_ptr == &amp;f ? &amp;l : &amp;f); printf("remaing items in %p\n", current_ptr); while(m &lt; length) { mixed[m] = shuffle_array[*current_ptr]; printf("Dropped from %p --&gt; %d \n", current_ptr, mixed[m]); m++; *current_ptr += 1; } memcpy( shuffle_array, mixed, length * sizeof( int ) ); } int main(void) { int i; int array[52] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; int length = sizeof(array) / sizeof(int); printf("\nShuffling...\n\n"); shuffle( array, length ); // for(i = 0; i &lt; length; i++) // { // printf("%d\n", array[i]); // } return 0; } </code></pre>
[]
[ { "body": "<p>Before I do a C review I just want to do a literal translation of your python so you can compare it. Personally I think you can make your C look identical to your python (a small amount of extra work required for memory management and the array like container but otherwise the same).</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;time.h&gt;\n\ntypedef struct Cards\n{\n int* cards;\n int size;\n} Cards;\n\nCards shuffle_n(Cards deck, int num_shuffles)\n{\n /* how many times items can be pulled from the same list consecutively */\n int const MAX_Streak = 10;\n\n /* divide list roughly in half */\n int num_items = deck.size;\n int end_range = num_items / 2 + rand() % (int)(.1 * num_items);\n\n Cards split_lists[2] = { {deck.cards, end_range}, /* # list up to 0 - end_range */\n {deck.cards + end_range, deck.size - end_range} /* list after end_range - len(items) */\n };\n int current_list_index = rand() % 2;\n\n int* mixedData = (int*)malloc(sizeof(int) * deck.size);\n Cards mixed = {mixedData, 0 };\n int streak = 0;\n\n /* # while both lists still contain items */\n while((split_lists[0].size != 0) &amp;&amp; (split_lists[1].size != 0))\n {\n /* calc the percentage of remaining total items */\n int remaining = (1 - ((float)mixed.size) / num_items);\n /* if we happen to generate a random value less than the remaining percentage\n * which will be continually be decreasing (along with the probability)\n * or \n * if MAX_Streak is exceeded \n */\n if ((rand() &lt; remaining) || (streak &gt; MAX_Streak))\n {\n /* switch which list is being used to pull items from */\n current_list_index = !current_list_index;\n /* reset streak counter */\n streak = 0;\n }\n\n /* pop the selected list onto the new (shuffled) list */\n mixed.cards[mixed.size++] = split_lists[current_list_index].cards[--split_lists[current_list_index].size];\n /* increment streak of how many consecutive times a list has remained selected */\n streak += 1;\n }\n\n /* add any remaining items */\n memcpy(&amp;mixed.cards[mixed.size], &amp;split_lists[0].cards, split_lists[0].size * sizeof(int)); mixed.size += split_lists[0].size;\n memcpy(&amp;mixed.cards[mixed.size], &amp;split_lists[1].cards, split_lists[1].size * sizeof(int)); mixed.size += split_lists[1].size;\n\n num_shuffles -= 1;\n /* if we still have shuffles to do */\n if (num_shuffles &gt; 0)\n { /* rinse and repeat */\n Cards result = shuffle_n(mixed, num_shuffles);\n free(mixedData);\n\n mixed = result;\n }\n\n /* # finally return fully shuffled list */\n return mixed;\n}\nCards shuffle(Cards deck) {return shuffle_n(deck, 6);}\n\n\nint main()\n{\n srand(time(NULL));\n int i;\n int array[52] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };\n\n Cards deck = {array, sizeof(array)/sizeof(array[0])};\n\n printf(\"\\nShuffling...\\n\\n\");\n Cards shuffled = shuffle( deck );\n\n for(i = 0; i &lt; shuffled.size; i++)\n {\n printf(\"%d\\n\", shuffled.cards[i]);\n }\n free(shuffled.cards);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T15:37:01.650", "Id": "12796", "Score": "0", "body": "very cool. definitely some stuff I don't understand yet... what about comparing the two c approaches? also is there anything I'm doing in my version that is questionable from a convention standpoint?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T18:12:47.480", "Id": "12803", "Score": "0", "body": "@jondavidjohn: Yes I will do a code review today (going skiing). I just wanted to show that you can write the C very much like the python. My point being once you know a language well you can easily translate to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T19:04:03.873", "Id": "12806", "Score": "0", "body": "Thanks, maybe a few considerations to address when you give it another look, with your version I'd be concerned (as a utility function) the user not knowing to free the `result.cards`, and while I did take joy in the cleverness of my solution, it clearly by a read the morning after, seems overly terse and complicated. Enjoy your skiing!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T09:14:18.237", "Id": "8189", "ParentId": "8182", "Score": "5" } }, { "body": "<h2>Code Review</h2>\n\n<h3>General Comments</h3>\n\n<p>Be careful of identifiers in all caps.<br>\nIt is traditional to reserve all caps for macros (which can cause problems when you get clashes as macros do not respect scope).</p>\n\n<pre><code>int const MAX_STREAK = 10;\n</code></pre>\n\n<p>It is usually best to initialize variables as you declare them</p>\n\n<pre><code>int end_range;\nint mixed[length];\n</code></pre>\n\n<p>Try not to declare multiple variables on a single line (Every coding standard I have seen will hit you on this). There are also some corner cases with pointers that are not so obvious thus best to just avoid them.</p>\n\n<pre><code>int m, f, l;\n</code></pre>\n\n<p>Initialization of the random number generator should be done once in the application. So best to do it just after main() has been entered.</p>\n\n<pre><code>srand(time(NULL));\n</code></pre>\n\n<p>This is an excessive number of identifiers you are initializing in the <code>for(;;)</code>.</p>\n\n<pre><code>for(m = 0, f = 0, l = (end_range + 1), streak = 0; m &lt; length &amp;&amp; l &lt; length &amp;&amp; f &lt; end_range + 1; m++, *current_ptr += 1)\n</code></pre>\n\n<h3>Algorithm Comments</h3>\n\n<p>To be blunt I have a hard time following what you are trying to do. There should definitely be more comments explaining what you are trying to do at each step (the only way I managed to decode it was reading the python version).</p>\n\n<p>One technique you can use to make things easier is to create structures to hold groups of related information (You should have mimicked the python array).</p>\n\n<pre><code>typedef struct Array\n{\n int* data;\n int size;\n // Other structures you want\n} Array;\n</code></pre>\n\n<p>Unfortunately unlike python ther are no built-in us-full generic container types (That's why C++ is very popular (or one of the reasons)). As C++ has a std::vector (a dynamically sized array with push/pop).</p>\n\n<p>In fact I would consider C++ a better bet for a python programmer as it gives you some useful built-in types and allows you to do OO programming like python.</p>\n\n<p>Also as you mention in the comments (to the other questions) the downside (or the beauty depending on how you look at it) is the requirement for memory management. C is very basic and you must do it <strong>all manually</strong>. If you return dynamic allocated memory from a C function you must be very careful to document the requires of the user on what to do with it (this is solved in C++ where memory management is practically automatic).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T02:48:35.520", "Id": "8206", "ParentId": "8182", "Score": "3" } } ]
{ "AcceptedAnswerId": "8206", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T03:22:40.817", "Id": "8182", "Score": "5", "Tags": [ "beginner", "c", "memory-management", "simulation", "shuffle" ], "Title": "Human (imperfect) array (card) shuffle written in C" }
8182
<p>I am looking for feedback on my doubly linked list implementation that I have written in Java. I am looking for specific feedback on the efficiency of my code, as well as my usage of generics. I am pretty new to using generics in Java, and I'm not quite sure that I am using them correctly yet. </p> <p>My node class is pretty basic, but I'd like to revisit my Equals and Hashcode. Am I implementing these correctly? See snippet below: </p> <p>My node class's equals/hashcode:</p> <pre><code>@Override public boolean equals(Object that){ if(this == that) return true; if(!(that instanceof LLNode)) return false; return this.data.equals(((LLNode)that).getData()); } @Override public int hashCode(){ return (this.data == null ? 0 : this.data.hashCode()); } </code></pre> <p>The <code>DoublyLinkedList</code> class, where the linked list is actually implemented can be found <a href="https://github.com/matt-y/DataStructures/blob/master/src/JavaDataStructures/DoublyLinkedList.java" rel="nofollow">here</a>, as there is too much to post here I think. Am I missing any major functionality? Are generics used properly?</p> <p>If possible I'd also like to have my test cases reviewed to see if they are strong enough, and at least somewhat well designed. Those are <a href="https://github.com/matt-y/DataStructures/tree/master/test/JavaDataStructures" rel="nofollow">here</a>.</p> <p>I was unsure of how to test certain things - specifically cases where I am expecting exceptions to be thrown.</p>
[]
[ { "body": "<p>My answer only deals with the \"testing\" part of your question, not the review of the classes themselves.</p>\n\n<p>If I can start with a question - are you expecting <code>LLNode</code> to be used by other classes? Or is it only for use by <code>DoublyLinkedList</code>? If it's the latter, then it's effectively private to <code>DoublyLinkedList</code>, whether you've declared it that way or not. That is, it's not part of your library's API, and I wouldn't bother with separate tests for it.</p>\n\n<p>Your tests for <code>removeAt</code> look like they're only checking that the size of the structure is correct at the end of the test, not that the correct nodes have been removed. They really need some kind of assertion to make sure that the list has the right nodes in it afterwards.</p>\n\n<p>The way you've tested exceptions is fine; although there are other ways of doing it. I suggest you read up on the <code>ExpectedException</code> feature of JUnit, and see whether it's what you want to use.</p>\n\n<p>Now for the controversial stuff - I've been shot down for this point of view before, but this is the voice of experience speaking.</p>\n\n<p>It's hard, on reading your test, to tell what behaviour of the list has been tested, and what hasn't. For example, you have a <code>testRemoveAt</code>; but without reading every line of the test, I can't tell which cases of the <code>removeAt</code> method have been tested - for example, (1) What if the argument is negative? (2) What if the argument is greater than the number of things in the list? (3) What if the argument is valid? (4) What if the list is empty?. I think you've tested (3) and (4), but not (1) and (2), but I'm not sure.</p>\n\n<p>For this reason, I strongly recommend naming your tests after the behaviour that they test, NOT after the method that implements that behaviour. This means you'll have more tests, and smaller ones, but you'll be able to see far more easily which behaviour has and hasn't been tested. Also, in the event of a failure, it will be easier to see what has actually gone wrong. So in this particular case, I would name the tests for <code>removeAt</code> something like -</p>\n\n<pre><code>@Test\npublic void removeAtThrowsException_withNegativeArgument(){\n}\n\n@Test\npublic void removeAtThrowsException_whenListIsEmpty(){\n}\n\n@Test\npublic void removeAtRemovesCorrectNodeFromList_whenArgumentLessThanSizeOfList(){\n} \n\n@Test\npublic void removeAtThrowsException_whenArgumentNotLessThanSizeOfList(){\n}\n</code></pre>\n\n<p>As far as tests for <code>equals</code> go, you probably want quite a few cases. Such as -</p>\n\n<ol>\n<li>What happens if the argument is not a <code>DoublyLinkedList</code>?</li>\n<li>What happens if the argument is a <code>DoublyLinkedList</code> with different elements</li>\n<li>What happens if the argument is a <code>DoublyLinkedList</code> with the same elements in a different order?</li>\n<li>What happens if the argument is a <code>DoublyLinkedList</code> with the same elements in the same order?</li>\n<li>What happens if the argument is a <code>DoublyLinkedList</code> with equal elements (but not the same) in the same order?</li>\n</ol>\n\n<p>Again, I recommend having each of these as a separate test method, with a descriptive name. And the biggest benefit is that you can look at your test method names, and know which cases have and have not been tested, without having to read through the code. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T08:21:31.070", "Id": "8188", "ParentId": "8185", "Score": "4" } }, { "body": "<p>David had some really good points about your tests. I just wanted to add a few more in regard to your list.</p>\n\n<ol>\n<li><p>The <code>Iterable</code> interface is generic and you should bind a type parameter to it, so your client receives a type-safe iterator.</p></li>\n<li><p>If you didn't design this list to be subclassed, you should declare it as <code>final</code>. I really don't forsee any issues in subclassing your list since there's no case of self-use, but it's a good practice if you don't want to commit to maintaining a class hierarchy.</p></li>\n<li><p>As David mentioned, the client should know nothing of your node class. Have your public methods return data and have your iterator deal with data as well. If you return to me the head of the list I can call <code>head.setNext(null)</code> and your list is gone. It's OK to have methods that accept nodes, but they should be private, e.g. <code>private boolean removeNode(LLNode)</code>.</p></li>\n<li><p>In <code>LLNode.equals</code> you test if <code>that</code> is null right after testing if its an instance of <code>LLNode</code>. The instance check will return false if its parameter is null, so the null check isn't necessary.</p></li>\n<li><p>Also in <code>LLNode.equals</code> -- I'm being picky here -- you don't have to call <code>LLNode.getData</code>. You can access another instance's private data from inside its class. If your doing a lot of comparisons, you'll cut method invocation overhead, but that's not going to result in significant savings of any kind. </p></li>\n<li><p>A <code>contains(T data)</code> method would be nice.</p></li>\n<li><p>You could easily extend <code>LLIterator</code> to support reverse iteration by setting <code>currentPos</code> to the size of your list and decrementing the position in next(). </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T19:43:11.087", "Id": "13138", "Score": "0", "body": "Hi, thank you for the feedback, I greatly appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T08:07:25.173", "Id": "8211", "ParentId": "8185", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T05:30:36.700", "Id": "8185", "Score": "3", "Tags": [ "java", "performance", "unit-testing", "linked-list" ], "Title": "Generic Linked List Implementation in Java" }
8185
<p>I have a form that I need to resubmit to the action if a checkbox is TRUE. This is to facilitate chained select boxes with javascript turned off. Ideally I would instanciate the form object at the end only, just before sending it to the view, but as you can see I need it beforehand. </p> <p>The form takes parameters (an array of lists used to populate the select boxes), and these parameters are not yet calculated at the point where I have to first instanciate the form object. Is there a way to instantiate the form and add the parameters later, thus avoiding having to re-instanciate the form at the end when I have the definitive lists?</p> <p>Can anyone see a better way of doing this?</p> <pre><code>public function editcontactdetailsAction() { $auth = Zend_Auth::getInstance(); $id = $auth-&gt;getidentity(); $user = $this-&gt;em-&gt;getRepository('Entities\User') -&gt;findOneByid($id); $town = $user-&gt;getTown(); // initialize list values as null $townlist = array(); $provincelist= array(); $regionlist=array(); $countrylist=array(); //initialize ids as 0 so defaults can be set $townid=0; $provinceid=0; $regionid=0; $countryid=0; //initialize $data variable used to set defaults later $data=null; // HAS town - get corresponding lists for dropdowns if (!is_null($town)) { $townid = $town-&gt;getId(); //get the province $province = $town-&gt;getProvince(); $provinceid = $province-&gt;getId(); //get the region $region = $province-&gt;getRegion(); $regionid = $region-&gt;getId(); //get the country $country = $region-&gt;getCountry(); $countryid = $country-&gt;getId(); $townlist = $this-&gt;em-&gt;getRepository('Entities\Town')-&gt;findActiveTowns($provinceid); $provincelist = $this-&gt;em-&gt;getRepository('Entities\Province')-&gt;findActiveProvinces($regionid); $regionlist = $this-&gt;em-&gt;getRepository('Entities\Region')-&gt;findActiveRegions($countryid); } // even if user NO town, populate the countries list $countrylist = $this-&gt;em-&gt;getRepository('Entities\Country')-&gt;findActiveCountries(); $lists = array($townlist, $provincelist, $regionlist, $countrylist); $form = new Application_Model_FormContactDetails($lists); // //--------------------------------------------------------------- // Has the form been submitted? if ($this-&gt;getRequest()-&gt;isPost()) { //if we dont include the $validformline, the form is not populated with the post data $validform =$form-&gt;isValid($this-&gt;_request-&gt;getPost()); //Is this a request to refresh the regional structure and not a real submit if($form-&gt;getValue('refreshregionalstructure')==1){ //find out up to what the level the user has selected, starting from the bottom $formprovincevalue=$form-&gt;getValue('province'); if(!$formprovincevalue==0){ $townlist = $this-&gt;em-&gt;getRepository('Entities\Town')-&gt;findActiveTowns($formprovincevalue); } } else{ // If the form data is valid, process it if ($form-&gt;isValid($this-&gt;_request-&gt;getPost())) { //save all to db try { // Save the user to the database // Set the flash message $this-&gt;_helper-&gt;flashMessenger-&gt;addMessage(array('success' =&gt; _('The contact details were updated'))); // Redirect the user to the home page $this-&gt;_redirect('/account/index'); } catch (Exception $e) { $this-&gt;em-&gt;close(); $this-&gt;view-&gt;errors = array(array(_('There was a problem editing your contact details.'))); } } else { $this-&gt;view-&gt;errors = $form-&gt;getErrors(); } } } else { //form has not been submitted yet // populate form with user record $data = array('firstname' =&gt; $user-&gt;getFirstname(), 'middlename' =&gt; $user-&gt;getMiddlename(), 'surname' =&gt; $user-&gt;getSurname(), 'address1' =&gt; $user-&gt;getAddress1(), 'address2' =&gt; $user-&gt;getAddress2(),'town'=&gt; $townid, 'province'=&gt; $provinceid,'region'=&gt; $regionid,'country'=&gt; $countryid); } $lists = array($townlist, $provincelist, $regionlist, $countrylist); $form = new Application_Model_FormContactDetails($lists); //if we dont include the $validform line, the form is not populated with the post data $validform =$form-&gt;isValid($this-&gt;_request-&gt;getPost()); if (!is_null($data))$form-&gt;setDefaults($data); $this-&gt;view-&gt;form = $form; } </code></pre>
[]
[ { "body": "<p>I did it like this in the end, I'm not sure if it's the best way and I would welcome comments.</p>\n\n<pre><code>public function editcontactdetailsAction() {\n\n $auth = Zend_Auth::getInstance();\n $id = $auth-&gt;getidentity();\n $user = $this-&gt;em-&gt;getRepository('Entities\\User')\n -&gt;findOneByid($id);\n $town = $user-&gt;getTown();\n\n\n // initialize list values as null\n $townlist = array();\n $provincelist = array();\n $regionlist = array();\n $countrylist = array();\n //initialize ids as 0 so defaults can be set\n $townid = 0;\n $provinceid = 0;\n $regionid = 0;\n $countryid = 0;\n //initialize $data variable used to set defaults later\n $data = null;\n\n // HAS town - get corresponding lists for dropdowns\n if (!is_null($town)) {\n $townid = $town-&gt;getId();\n\n //get the province\n $province = $town-&gt;getProvince();\n $provinceid = $province-&gt;getId();\n\n //get the region\n $region = $province-&gt;getRegion();\n $regionid = $region-&gt;getId();\n\n //get the country\n $country = $region-&gt;getCountry();\n $countryid = $country-&gt;getId();\n\n $townlist = $this-&gt;em-&gt;getRepository('Entities\\Town')-&gt;findActiveTowns($provinceid);\n $provincelist = $this-&gt;em-&gt;getRepository('Entities\\Province')-&gt;findActiveProvinces($regionid);\n $regionlist = $this-&gt;em-&gt;getRepository('Entities\\Region')-&gt;findActiveRegions($countryid);\n }\n\n // even if user NO town, populate the countries list\n $countrylist = $this-&gt;em-&gt;getRepository('Entities\\Country')-&gt;findActiveCountries();\n\n//---------------------------------------------------------------\n // Has the form been submitted?\n if ($this-&gt;getRequest()-&gt;isPost()) {\n\n if ($this-&gt;getRequest()-&gt;getPost('refreshregionalstructure') == 1) {\n //find out up to what the level the user has selected, starting from the bottom\n\n $formprovincevalue = $this-&gt;getRequest()-&gt;getPost('province');\n if (!$formprovincevalue == 0) {\n $townlist = $this-&gt;em-&gt;getRepository('Entities\\Town')-&gt;findActiveTowns($formprovincevalue);\n }\n\n $lists = array($townlist, $provincelist, $regionlist, $countrylist);\n $form = new Application_Model_FormContactDetails($lists);\n //if we dont include the $validform line, the form is not populated with the post data\n $validform = $form-&gt;isValid($this-&gt;_request-&gt;getPost());\n } else {\n $lists = array($townlist, $provincelist, $regionlist, $countrylist);\n $form = new Application_Model_FormContactDetails($lists);\n // If the form data is valid, process it\n if ($form-&gt;isValid($this-&gt;_request-&gt;getPost())) {\n\n\n //save all to db\n try {\n\n // Save the user to the database\n // Set the flash message\n $this-&gt;_helper-&gt;flashMessenger-&gt;addMessage(array('success' =&gt;\n _('The contact details were updated')));\n\n\n // Redirect the user to the home page\n $this-&gt;_redirect('/account/index');\n } catch (Exception $e) {\n $this-&gt;em-&gt;close();\n $this-&gt;view-&gt;errors = array(array(_('There was a problem editing your contact details.')));\n }\n } else {\n $this-&gt;view-&gt;errors = $form-&gt;getErrors();\n }\n }\n } else { //form has not been submitted yet\n // populate form with user record\n $data = array('firstname' =&gt; $user-&gt;getFirstname(), 'middlename' =&gt; $user-&gt;getMiddlename(),\n 'surname' =&gt; $user-&gt;getSurname(), 'address1' =&gt; $user-&gt;getAddress1(),\n 'address2' =&gt; $user-&gt;getAddress2(), 'town' =&gt; $townid,\n 'province' =&gt; $provinceid, 'region' =&gt; $regionid, 'country' =&gt; $countryid);\n\n $lists = array($townlist, $provincelist, $regionlist, $countrylist);\n\n $form = new Application_Model_FormContactDetails($lists);\n //if we dont include the $validform line, the form is not populated with the post data\n $validform = $form-&gt;isValid($this-&gt;_request-&gt;getPost());\n }\n\n if (!is_null($data))\n $form-&gt;setDefaults($data);\n $this-&gt;view-&gt;form = $form;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T08:05:45.963", "Id": "8194", "ParentId": "8193", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T16:46:04.037", "Id": "8193", "Score": "3", "Tags": [ "php", "zend-framework" ], "Title": "Zend form parameters - how to change after instanciated" }
8193
<p>So say I have a method that does a bunch of stuff, and I want to refactor this method to take a different type of parameter:</p> <pre><code>public object A(MyObject a) { // does a bunch of crap with a // then calls another method this.B(a); } </code></pre> <p>Now even method <code>B()</code> does a lot of crap with that same <code>Object a</code>. What if I want an endpoint that takes a <code>SecondObject b</code>. What I just did was basically duplicate all the methods and change the parameter type, but now I'm sitting with basically a bunch of duplicate code here. What's the best way to refactor this so that all my methods can take a different <em>set</em> (not just a different type) of parameters and reduce duplicity?</p> <p>Thanks.</p> <p>Edit:</p> <p>Example,</p> <pre><code>private Chatham.Panda.WCF.DataContracts.IInstrument FillHistoricInstrumentRates( Chatham.Panda.WCF.DataContracts.IInstrument instrument, Chatham.Enumerations.BidMidAsk valuationPrice, DateTime rateCutoffDate, bool loadRates, FillInstrumentRates recursiveDelegate) { if (instrument == null) { throw new ArgumentNullException( "instrument", "RateAcqusitionService.SetInstrumentHistRates's 'instrument' argument is null"); } // Compound Instruments Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument compoundInstrument = instrument as Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument; if (compoundInstrument != null) { foreach (Chatham.Panda.WCF.DataContracts.IInstrument i in compoundInstrument.ChildInstruments) { recursiveDelegate(i); return compoundInstrument; } } // Simple Instruments Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument simpleInstrument = instrument as Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument; if (simpleInstrument != null) { // Set Rates for each Component foreach (Chatham.Panda.WCF.DataContracts.Component component in simpleInstrument.Components) { this.FillHistoricComponentRates( component, valuationPrice, rateCutoffDate, loadRates ); } return instrument; } throw new NotSupportedException( string.Format( "Instrument with type '{0}' currently not supported", instrument.GetType().FullName) ); } </code></pre> <p>Now I want to change this method so that it takes a <code>List&lt;ScheduleRow&gt; rows</code>, as well as some other random properties including within the <code>Chatham.Panda.WCF.DataContracts.IInstrument instrument</code>, instead of passing the whole <code>instrument</code> across the wire, but if I just create another method with all this code in it and different parameters, it won't look TOO much different, and have plenty of duplicate code.</p> <p>Then I'd also be doing things like calling:</p> <pre><code>this.FillHistoricComponentRates( component, valuationPrice, rateCutoffDate, loadRates ); </code></pre> <p>With a list of <code>rows</code> instead of the entire <code>component</code>, which leads to THAT method being changed in the same exact fashion, so on and so on...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T22:43:37.340", "Id": "12813", "Score": "0", "body": "Is simpleInstrument merely a base case of the CompoundInstrument? If so the RecursiveDelegate is not written properly as any recursive method naturally must handle it's base case. And RecursiveDelegate signature would change to pass along those other parameters. If the type & number of parameters is still indeterminate perhaps create a class who's sole purpose is to have a property for every potential parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:15:27.123", "Id": "12893", "Score": "0", "body": "It's hard to say from the example, but I feel like the FillHistoricInstrumentRates method might belong as a method on a common base class of SimpleInterestRateInstrument and CompoundInterestRateInstrument. The common logic can stay in that method, but differences could possibly be addressed by adding protected abstract methods; SimpleInterestRateInstrument and CompoundInterestRateInstrument would need to provide the appropriate implementations for those abstract methods." } ]
[ { "body": "<p>If I understand your question correctly I would refactor your method by implementing the template pattern in an OO or functional way whatever suits you best. Look at this excellent article for more information on the two options <a href=\"http://www.codeproject.com/KB/architecture/TMDPvsLambda.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/architecture/TMDPvsLambda.aspx</a>.</p>\n\n<p>This you'll be able to avoid duplicating your code while still being able to have different behaviors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T14:47:38.303", "Id": "8199", "ParentId": "8198", "Score": "1" } }, { "body": "<p>What you want to probably look at is </p>\n\n<ol>\n<li>Either Method Overloading or<a href=\"http://www.akadia.com/services/dotnet_delegates_and_events.html\" rel=\"nofollow\">Simple Explanation &amp; Example of Delegates</a></li>\n<li>Delegates or Anonymous delegates.. </li>\n<li>Basic OO Concepts - Object Oriented Concepts <a href=\"http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx\" rel=\"nofollow\">Basic OO Concepts</a>\nalso your Method Names should be more descriptive</li>\n<li>Basic Design Patterns in C# <a href=\"http://www.codeproject.com/KB/architecture/DesignPatternExampleCS.aspx\" rel=\"nofollow\">Code Project Site Basic Design Patterns</a></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T15:00:32.520", "Id": "12801", "Score": "0", "body": "I know how to overload methods, but even with the method overload there is duplicate code. That's my main issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T15:11:24.020", "Id": "12802", "Score": "0", "body": "What about Delegates then..?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T14:50:12.540", "Id": "8200", "ParentId": "8198", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T14:28:13.253", "Id": "8198", "Score": "1", "Tags": [ "c#", ".net" ], "Title": "Refactoring different type of param to reduce duplicate code" }
8198
<p>I'd like to refactor the following code:</p> <pre><code>case @request.path when '/' Rack::Response.new do |response| do_stuff end when '/env' then Rack::Response.new(@env.to_html) end </code></pre> <p>And extract <code>Rack::Response.new</code>, something like the following:</p> <pre><code>Rack::Response.new case @request.path when '/' then Proc.new {|response| do_stuff } when '/env' then @env.to_html end </code></pre> <p>But I get</p> <blockquote> <p>stringable or iterable required</p> </blockquote> <p>What's the correct implementation (Ruby 1.9.2)?</p>
[]
[ { "body": "<p>In order to pass a block to a function, you need to prefix it with an ampersand.</p>\n\n<pre><code>block_or_string = case @request.path\n when '/' then Proc.new { |response| do_stuff }\n when '/env' then @end.to_html\nend\n\nresponse = if block_or_string.is_a?(Proc)\n Rack::Response.new(&amp;block_or_string)\nelse\n Rack::Response.new(block_or_string)\nend\n</code></pre>\n\n<p>This is pretty ugly. It might be an improvement to wrap the strings in simple procs.</p>\n\n<pre><code>block = case @request.path\n when '/' then Proc.new { |response| do_stuff }\n when '/env' then Proc.new { @end.to_html }\nend\n\nRack::Response.new(&amp;block)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T16:09:46.923", "Id": "12845", "Score": "1", "body": "However, [Rack::Response.new](http://rack.rubyforge.org/doc/classes/Rack/Response.src/M000176.html) responds differently to a block than to the first argument. It would work if you changed the line to: `when '/env' then Proc.new { rr.write @end.to_html }`, but it's complicated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T07:16:44.710", "Id": "8209", "ParentId": "8203", "Score": "2" } }, { "body": "<p>Essentially, you are wanting Ruby Procs to be first-class. By design, this language prefers other ways to accomplish your objective.</p>\n\n<p>I see Rack::Response.new's first argument is the response body. </p>\n\n<p>Looking at <a href=\"http://rack.rubyforge.org/doc/classes/Rack/Response.html\" rel=\"nofollow\">Rack::Response</a>, you can do something like:</p>\n\n<pre><code>rr = Rack::Response.new\nbody = ''\nblock = Proc.new {}\n\ncase @request.path\nwhen '/'\n block = Proc.new {|response| do_stuff }\nwhen '/env'\n body = @env.to_html\nend\n\nrr.write body\nrr.finish &amp;block\n</code></pre>\n\n<p>Wrapping up <code>rr</code>, <code>block</code> and <code>body</code> into whatever object you wish would improve this further.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T15:09:39.233", "Id": "8216", "ParentId": "8203", "Score": "2" } } ]
{ "AcceptedAnswerId": "8216", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T20:31:45.153", "Id": "8203", "Score": "2", "Tags": [ "ruby" ], "Title": "how to pass a block to a function as a parameter" }
8203
<p>Recently I was asked to write algorithm to rearrange elements in two-dimensional array in spiral order.</p> <p>Input array: Output array:</p> <pre><code>[ 1, 2, 3, 4] [ 1, 2, 3, 4 ] [ 5, 6, 7, 8] = &gt; [ 8, 12, 11, 10 ] [ 9, 10, 11, 12] [ 9, 5, 6, 7 ] </code></pre> <p>I came up with the following solution using JavaScript:</p> <pre><code>(function(){ var Spiralify = function(matrix){ function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' } //Matrix is not specified or not an array if( !matrix || !isArray(matrix) ) { console.log('Matrix is not an array'); return; } var rows = matrix.length; if( rows &lt;= 1 ) return matrix; //If first element of matrix is not an array, we cant define amount of columns in matrix, so just wrap it in array and return if(!isArray(matrix[0])) return [matrix]; var cols = matrix[0].length; //If rows of the matrix are empty arrays, return null if( cols == 0 ) return matrix; //If arrays, corresponding to rows, have different amount of elements, return null if(matrix.some(function(el){ return el.length != cols; })) { console.log('All rows must have equal amount of columns'); return; } //If we have only one column, just transpond the array and wrap it into another array if( cols == 1) return [matrix.map(function(i){ return i[0]; })]; function getUpperCorner(r1,c1,r2,c2) { for(var i=c1;i&lt;=c2;i++) tmpArray.push(matrix[r1][i]); for(var j=r1+1;j&lt;=r2;j++) tmpArray.push(matrix[j][c2]); if(r2-r1 &gt; 0) getLowerCorner(r1+1,c1,r2,c2-1); } function getLowerCorner(r1,c1,r2,c2) { for(var i=c2;i&gt;=c1;i--) tmpArray.push(matrix[r2][i]); for(var j=r2-1;j&gt;=r1;j--) tmpArray.push(matrix[j][c1]); if(r2-r1 &gt; 0) getUpperCorner(r1,c1+1,r2-1,c2); } var tmpArray = []; getUpperCorner(0,0,rows-1,cols-1); var result = new Array(rows); for(var i=0;i&lt;rows;i++) result[i] = tmpArray.splice(0,cols); return result; } var matrix1 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]; var matrix2 = [[1,2,3,4,5],[6,7,8],[11,12,13,14,15]]; var matrix3 = [[1,2,3,4]]; var matrix4 = [[1],[2],[3],[4],[5],[6]]; var matrix5 = null; var matrix6 = 1234; var matrix7 = []; var matrix8 = [[],[],[]]; var matrix9 = [1,2,3,4]; var matrix10 = 'Hello'; console.log (Spiralify(matrix1)); console.log (Spiralify(matrix2)); console.log (Spiralify(matrix3)); console.log (Spiralify(matrix4)); console.log (Spiralify(matrix5)); console.log (Spiralify(matrix6)); console.log (Spiralify(matrix7)); console.log (Spiralify(matrix8)); console.log (Spiralify(matrix9)); console.log (Spiralify(matrix10)); })(window); </code></pre> <p>But this solution was a show-stopper. I'm trying to learn from the defeat and would really appreciate some feedback on why this code is unappropriate.</p>
[]
[ { "body": "<p>I'm not sure what exactly about your code made it a \"show-stopper.\" Your use of <code>tmpArray</code> has a bit of a <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> to it. There are issues of readability (why does the line <code>for(var i=c1;i&lt;=c2;i++)</code> only have one space in it??). Your core algorithm (<code>getUpperCorner</code> and <code>getLowerCorner</code>) isn't documented and is fairly hard to read.</p>\n\n<p>Personally, though, I would have approached this as a straight recursion problem. So you have the following matrix:</p>\n\n<pre><code> 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n</code></pre>\n\n<p>Your \"spiral\" begins with the the top row, <code>1 2 3 4</code>. So chop that off and save it.</p>\n\n<pre><code> 1 2 3 4\n✂ ┄┄┄┄┄┄┄┄┄┄┄┄\n 5 6 7 8\n 9 10 11 12\n</code></pre>\n\n<p>Now you'll notice that the rightmost column of the remaining part, <code>8 12</code>, is the next part of the spiral. But what if we turn it 90º counter-clockwise?</p>\n\n<pre><code> 5 6 7 8 =&gt; 8 12\n 9 10 11 12 7 11\n 6 10\n 5 9\n</code></pre>\n\n<p>Now <code>8 12</code> the top row! Chop it off and repeat:</p>\n\n<pre><code> 8 12\n✂ ┄┄┄┄┄┄\n 7 11 =&gt; 11 10 9 =&gt; 11 10 9\n 6 10 7 6 5 ✂ ┄┄┄┄┄┄┄┄┄┄\n 5 9 7 6 5 =&gt; 5 =&gt; 5\n 6 ✂ ┄┄┄\n 7 6 =&gt; 6 7 (end!)\n 7\n</code></pre>\n\n<p>By now you've seen the pattern. To get a matrix's \"spiral\" you just take off the top row, rotate what's left, then get <em>its</em> spiral, and so on.</p>\n\n<pre><code>Def Spiralify( Matrix )\n If( Matrix has only one row )\n Return( the row )\n\n Else\n FirstRow := first row of Matrix\n RestOfMatrix := all of Matrix except the first row\n\n NextMatrix := RotateLeft( RestOfMatrix )\n\n NextSpiral := Spiralify( NextMatrix )\n\n Result := JoinArrays( FirstRow, NextSpiral )\n\n Return( Result )\n</code></pre>\n\n<p><code>RotateLeft</code> will actually make up the most lines of code, but it's just a straightforward nested loop, and the rest basically writes itself.</p>\n\n<h2>Update</h2>\n\n<p>I had some time to write up an actual implementation. Rather than paste it here you can <a href=\"http://jsfiddle.net/jrunning/5A3eE/\" rel=\"nofollow\">check it out on jsFiddle</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T08:06:11.093", "Id": "8210", "ParentId": "8207", "Score": "4" } } ]
{ "AcceptedAnswerId": "8210", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T04:16:27.450", "Id": "8207", "Score": "5", "Tags": [ "javascript", "algorithm", "array" ], "Title": "Rearrange elements in two-dimensional array spiral order" }
8207
<p>This snippets works, but I think it can be optimized:</p> <pre><code>/* highlight input, if it is empty */ $(function() { var highlight_if_no_val=function () { $(this).toggleClass('highlight-input', !$(this).val()); } $('#id_index-EditForm-gpnr').keyup(highlight_if_no_val).each(highlight_if_no_val); } ); </code></pre> <p>Is there a simpler solution?</p> <p>The <code>.each(hightlight_...)</code> is done to set the highlight after the page loaded (it can be initially empty or initially filled).</p>
[]
[ { "body": "<p>Just a thought ... with explination:</p>\n\n<pre><code>// Move your variable function outside of your ready call to make it accessible later\n// if needed, for instance in another script call from a dynamically drawn in view,\n// Alsot, shorten the name so as to save milliseconds on call time, and minutes in\n// coding it (possibly repeatedly) later.\n// I left the name descriptive, but you could really shortin even more\nfunction zero_highlight() {\n $(this).toggleClass('highlight-input', !$(this).val());\n}\n// Now begin the ready code. FYI, for others looking at this, you might should have\n// mentioned you were using jQuery (though looking at it with an experienced eye,\n// it appears obvious)\n$(function() {\n // Here again you might really want to consider a name change, call change,\n // especially in using .each as (i found in personal experience) jquery's \n // .each funtion tends to work much more functionally when calling a tagname\n // or classname as opposed to name multiple items with the same ID\n // Not to mention, having multiple items with the same ID could be devastating\n // to your dynamic functionality in later code.\n $('.frm-edit-gpnr').keyup(zero_highlight).each(zero_highlight);\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-11T01:33:29.387", "Id": "13898", "Score": "0", "body": "\"shorten the name so as to save milliseconds on call time\" .. pretty sure that's not how it works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-11T01:59:24.450", "Id": "13899", "Score": "0", "body": "lol, well every character is counted (from olden days this was a burden) altho now days its not as important" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T19:31:00.937", "Id": "8861", "ParentId": "8212", "Score": "0" } }, { "body": "<p>Your code looks good enough. \"optimize\" is a vague action. </p>\n\n<pre><code>1. /* highlight input, if it is empty */\n2. jQuery(function ($) {\n3. function toggleHighlightIfEmpty() {\n4. var $this;\n5. $this = $(this);\n6. $this.toggleClass('highlight-input', !$this.val());\n7. }\n8. $('#id_index-EditForm-gpnr').on('keyup.highlight', toggleHighlightIfEmpty).trigger('keyup.highlight');\n9. });\n</code></pre>\n\n<h3>Line 2:</h3>\n\n<p>I'd use the aliasing form of <code>document.ready</code> to prevent conflicts with other libs</p>\n\n<h3>Line 3:</h3>\n\n<p>I'd use the function declaration form over variable declaration form for the internal function. It's really a personal preference sort-of-thing. Additionally, using <code>camelCase</code> is relatively standard for JavaScript function names.</p>\n\n<h3>Lines 4-6:</h3>\n\n<p>I'd store a reference to <code>$this</code> so that you don't keep calling the jQuery factory function. It shouldn't be significant in any way for performance, but it can save some headaches with perens which can be easily misplaced</p>\n\n<h3>Line 8:</h3>\n\n<p>I'd set the event using a namespaced event name so that it can be triggered and removed simply by calling <code>$(...).off('keyup.highlight')</code>. Instead of passing the function to <code>each</code> again, I prefer to use <code>trigger</code>. If you need backwards compatibility, use <code>bind</code> instead of <code>on</code>.</p>\n\n<p>None of these \"optimizations\" should lead to code that's in any significant way different as far as performance is concerned. It really comes down to personal preference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T03:51:30.797", "Id": "9307", "ParentId": "8212", "Score": "3" } } ]
{ "AcceptedAnswerId": "9307", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T11:16:18.993", "Id": "8212", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Highlight input if empty" }
8212
<p>I recently started cleaning up my projects and decided that I want to create a personal repository of useful bits of code. I found this bitmap code between them and heavily edited it and I'd appreciate if someone could review it, because I'm not that used to bitwise operations and such. Is the code portable enough, or there should be changes? </p> <h2>bitmap.h</h2> <pre><code>#ifndef BITMAP__ #define BITMAP__ #define BIT (8*sizeof(byte)) #define BITMAP_NOTFOUND -1 typedef enum{false=0, true} bool; typedef unsigned char byte; bool bitmapGet (byte *, int); void bitmapSet (byte *, int); void bitmapReset (byte *, int); int bitmapSearch(byte *, bool, int, int); #endif </code></pre> <h2>bitmap.c</h2> <pre><code>#include "bitmap.h" static bool get (byte, byte); static void set (byte *, byte); static void reset(byte *, byte); /* CAREFUL WITH pos AND BITMAP SIZE! */ bool bitmapGet(byte *bitmap, int pos) { /* gets the value of the bit at pos */ return get(bitmap[pos/BIT], pos%BIT); } void bitmapSet(byte *bitmap, int pos) { /* sets bit at pos to 1 */ set(&amp;bitmap[pos/BIT], pos%BIT); } void bitmapReset(byte *bitmap, int pos) { /* sets bit at pos to 0 */ reset(&amp;bitmap[pos/BIT], pos%BIT); } int bitmapSearch(byte *bitmap, bool n, int size, int start) { /* Finds the first n value in bitmap after start */ /* size is the Bitmap size in bytes */ int i; /* size is now the Bitmap size in bits */ for(i = start+1, size *= BIT; i &lt; size; i++) if(bitmapGet(bitmap,i) == n) return i; return BITMAP_NOTFOUND; } static bool get(byte a, byte pos) { /* pos is something from 0 to 7*/ return (a &gt;&gt; pos) &amp; 1; } static void set(byte *a, byte pos) { /* pos is something from 0 to 7*/ /* sets bit to 1 */ *a |= 1 &lt;&lt; pos; } static void reset(byte *a, byte pos) { /* pos is something from 0 to 7*/ /* sets bit to 0 */ *a &amp;= ~(1 &lt;&lt; pos); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-30T18:32:34.880", "Id": "242703", "Score": "0", "body": "To anyone that is still following this post, I commited the code to github [here](https://github.com/DictumMortuum/clib).\n\nI also added all of your comments as issues. Thanks for your comments and I will start implementing them." } ]
[ { "body": "<p>If you expect your code will ever be used from C++ (which a lot of C code is) then you should not use any identifiers with a double underscore.</p>\n\n<pre><code>#ifndef BITMAP__\n // ^^ May cause problems in C++\n</code></pre>\n\n<p>As this is reserved for the implementation in C++. Also the term BITMAP is very generic and you are very likely to clash with other libraries try and make it more unique to your project.</p>\n\n<p>You are assuming that a char is 8 bits.</p>\n\n<pre><code>#define BIT (8*sizeof(byte))\n</code></pre>\n\n<p>The standard does not say this (it is at least 8 bits) but it is actually defined via the macro CHAR_BITS so you should use:</p>\n\n<pre><code>#define BIT (CHAR_BITS*sizeof(byte))\n</code></pre>\n\n<p>Your header file is how most people will first see your code and try and understand how to use it. Thus putting the parameter names into the header file is probably a good idea as it helps document their usage.</p>\n\n<pre><code>bool bitmapGet (byte *, int);\nvoid bitmapSet (byte *, int);\nvoid bitmapReset (byte *, int);\nint bitmapSearch(byte *, bool, int, int);\n</code></pre>\n\n<p>Additional the action of <code>bitmapSearch</code> is not obvious thus a comment on its usage in the header would probably be a good idea. Actually a small blurb about how the first parameter can be an array would probably be a good idea (as it is not obvious without reading the code).</p>\n\n<p>Be careful with comments:</p>\n\n<pre><code>/* pos is something from 0 to 7*/\n</code></pre>\n\n<p>This is only true if you make assumptions (A: that sizeof(byte) == 1 B: you multiply this by 8). The comment should have been:</p>\n\n<pre><code>/* pos is a value between [0, BIT) */\n</code></pre>\n\n<p>Note the use of '[' on the left and ')' on the right. It is mathematical notation indicating that 0 is inclusive and BIT is not included in the range (it is common in both C/C++ documentation).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T18:29:26.860", "Id": "8223", "ParentId": "8213", "Score": "7" } }, { "body": "<ol>\n<li><p>Your types are unnecessary - just use unsigned char and int as the standard library would. </p></li>\n<li><p>On the same topic, your enum bool is unnecessary because in C non-zero indicates the true state. You confirm that yourself because get() assumes that the value 1 is true. Everyone assumes this and so the type is redundant. Moreover it is also wrong because if I change your enum to</p>\n\n<pre><code>typedef enum{true=0, false} bool;\n</code></pre>\n\n<p>your function fails, even though it is logically a reasonable thing to do.</p>\n\n<p>If you want to use a bool like that your should return one of its values explicitly:</p>\n\n<pre><code>return ((a &gt;&gt; pos) &amp; 1) ? true : false;\n</code></pre>\n\n<p>but there is really no point in this. Just return an int as the standard library would.</p></li>\n<li><p>bitmapGet() returning a bool seems mis-named to me. The bitmap bits have values 1 and 0, not true and false (even though these are <em>currently</em> the same). Calling it bitmapIsSet() would be more logical.</p></li>\n<li><p>sizeof(char) is 1 by definition, so BIT can be replaced with CHAR_BIT</p></li>\n<li><p>Opening brackets for functions are normally at column 0</p></li>\n<li><p>The order of parameters for bitmapSearch would be more logical is the size followed the thing it refers to (bitmap).</p></li>\n<li><p>The start parameter for bitmapSearch is wrong. To specify a search starting from bit 0 (surely the most common) the caller must pass -1 !!</p></li>\n<li><p>Why pass the 'pos' parameter as a 'byte' ? You have defined 'byte' to represent the bitmap bytes and 'pos' is certainly not one of those. You will get compiler warnings if they are enabled (they should be) about passing arguments with different widths due to prototypes. And restricting 'pos' to a byte may add an extra machine instruction (look at the assembler) while and achieving nothing. If you could define a type pos_t with the range 0..7 that you seem to want then you might argue that it was in some way correct, but as you cannot do that in C and clearly the byte value has the range 0..255, it is no better than using an int.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T16:09:09.553", "Id": "8255", "ParentId": "8213", "Score": "5" } }, { "body": "<p>Do didn't ask about performance, but you can speed up <code>bitmapSearch</code> for sparse bitmaps by first looking at a byte at a time. If looking for a 1, you can skip bytes that are 0x00, and if looking for a 0, you can skip bytes that are 0xFF. After that, you can scan the bits on the next byte or use a look-up table on it.</p>\n\n<p>As far as the API goes, you might add</p>\n\n<pre><code>byte * bitmapAlloc(int sizeInBits);\nvoid bitmapFree(byte * bitmap);\n</code></pre>\n\n<p>so the client doesn't have to worry about how many bytes to allocate.</p>\n\n<p>And/or provide a macro to help with allocations. A macro instead of a function if you want it to appear in array allocations.</p>\n\n<pre><code>#define BITMAP_BYTE_COUNT_FOR(n) ((n)+BIT-1)/BIT)\n</code></pre>\n\n<p>I'd also have <code>bitmapSearch</code> take its size as a bit count instead of a byte count. Then if the client only cares about, say, 26 bits for letters, they don't have to worry about a search returning 27 because the bitmap really have 32 bits in it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:42:00.487", "Id": "8365", "ParentId": "8213", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T11:39:27.493", "Id": "8213", "Score": "12", "Tags": [ "c", "image", "bitwise" ], "Title": "Bitmap implementation" }
8213
<p>I'm trying to create URL parse class., so i can check URL Segment / part, </p> <p>Example:</p> <ol> <li><a href="http://localhost/myproject/class/method/arg/other" rel="nofollow">http://localhost/myproject/class/method/arg/other</a> (localhost) </li> <li><a href="http://www.myproject.com/class/method/arg/other" rel="nofollow">http://www.myproject.com/class/method/arg/other</a> (live site)</li> <li><a href="http://www.myproject.com/class/method/arg/other?param=value" rel="nofollow">http://www.myproject.com/class/method/arg/other?param=value</a> (with get param)</li> </ol> <p>In urls above:<br /></p> <ul> <li><code>$url-&gt;segment(1)</code> : class</li> <li><code>$url-&gt;segment(2)</code> : method</li> </ul> <p>If argument null, it will return the last segment:</p> <ul> <li><code>$url-&gt;segment()</code> : other</li> </ul> <p>I need suggestions for improvement this class, here is the code:</p> <pre><code>&lt;?php class url { private $url; public function segment($arg=null) { if($arg==null) { $this-&gt;url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']); if(isset($_GET)) { $this-&gt;url = explode('?',$this-&gt;url); $this-&gt;url = $this-&gt;url[0]; } $this-&gt;url = explode('/', trim($this-&gt;url, '/')); return end($this-&gt;url); } else { $this-&gt;url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']); if(isset($_GET)) { $this-&gt;url = explode('?',$this-&gt;url); $this-&gt;url = $this-&gt;url[0]; } $this-&gt;url = explode('/', trim($this-&gt;url, '/')); array_unshift($this-&gt;url, null); unset($this-&gt;url[0]); if(isset($this-&gt;url[$arg])) { return $this-&gt;url[$arg]; } else { return null; } } } } ?&gt; </code></pre>
[]
[ { "body": "<p>Just a quick note: there is some duplication in the two branches of the first <code>if</code>. You could write the following:</p>\n\n<pre><code>&lt;?php\n public function segment($arg=null)\n {\n $this-&gt;url = str_replace(BASEDIR,'',$_SERVER['REQUEST_URI']);\n if(isset($_GET))\n {\n $this-&gt;url = explode('?',$this-&gt;url);\n $this-&gt;url = $this-&gt;url[0];\n }\n $this-&gt;url = explode('/', trim($this-&gt;url, '/')); \n\n\n if($arg==null)\n {\n return end($this-&gt;url);\n }\n else\n {\n array_unshift($this-&gt;url, null);\n unset($this-&gt;url[0]);\n if(isset($this-&gt;url[$arg]))\n {\n return $this-&gt;url[$arg];\n }\n else\n {\n return null;\n }\n }\n }\n} \n?&gt;\n</code></pre>\n\n<p>Actually, the <code>else</code> keyword is unnecessary since if the <code>$arg == null</code> condition is <code>true</code> the function returns.</p>\n\n<pre><code> ...\n if($arg==null)\n {\n return end($this-&gt;url);\n }\n\n array_unshift($this-&gt;url, null);\n unset($this-&gt;url[0]);\n if(isset($this-&gt;url[$arg]))\n {\n return $this-&gt;url[$arg];\n }\n // else is unnecessary here too\n return null;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T14:52:46.757", "Id": "8215", "ParentId": "8214", "Score": "1" } } ]
{ "AcceptedAnswerId": "8215", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T13:31:44.823", "Id": "8214", "Score": "2", "Tags": [ "php" ], "Title": "URL segment class" }
8214
<p>This code is for continuing the execution after an exception, and this is ugly:</p> <pre><code> int step=0; do{ try{ switch(step) { case 0: step=1; methodAAAAACanThrowException(); break; case 1: step=2; methodBBBBBCanThrowException(); break; case 2: step=3; methodCCCCCanThrowException(); break; //.... //more and more //.... case 25: step=26; methodZZZZZCanThrowException(); } }catch( Exception ex) { Logger.getLogger(ABC.class.getName()).log(Level.SEVERE, null, ex); } }while(step&lt;26); } </code></pre> <p><strong>but writing a single try-catch loop for every call, seems even uglier..</strong></p> <p>Is there any other more elegant option for doing that? thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T18:41:39.113", "Id": "12849", "Score": "2", "body": "The fact that you want do this is a bad sign. Why do you want to do this? What kind of function is this? What kind of methods is it calling? Chances are a better way to design your solution exists." } ]
[ { "body": "<p>How about something like this?</p>\n\n<p>Define a one-method interface like so:</p>\n\n<pre><code>public interface TryAndLogFailure { void execute(); }\n</code></pre>\n\n<p>Then define a method which takes an object which implements the interface and does your exception handling for you:</p>\n\n<pre><code>public void tryAndLogFailure(TryAndLogFailure talf) {\n try {\n talf.execute();\n } catch (Exception e) {\n logger.log(...);\n }\n}\n</code></pre>\n\n<p>Now your calls to the methods can be sequential:</p>\n\n<pre><code>tryAndLogFailure(new TryAndLogFailure{ public void execute() { methodAAAACanThrowException(); } });\ntryAndLogFailure(new TryAndLogFailure{ public void execute() { methodBBBBCanThrowException(); } });\n// etc...\ntryAndLogFailure(new TryAndLogFailure{ public void execute() { methodZZZZCanThrowException(); } });\n</code></pre>\n\n<p>Admittedly, this could probably be worked a little more to make it prettier, but this is my first crack off the top of my head. If only Java had support for closures.</p>\n\n<p>(Also - I should note that I agree with Winston. The reason why this code feels ugly is because the concept itself is ugly. Catching <code>Exception</code> is almost never a good idea and requires strong justification. Given more context, we may be able to help you redesign the code to avoid this sort of code smell.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T17:27:28.620", "Id": "12889", "Score": "1", "body": "Hello @mike9322, +1 for the answer, catching Exception is not the central point about this issue, I have post a similar question in stackoverflow, I think this is a Java debt, as you mention perhaps closures, I don't know, but is very messy to \"retry\" or continue the call of consecutive methods when some of them throws an exception, here is a better description of the general issue, http://stackoverflow.com/questions/2700173/java-exception-handling-in-non-sequential-tasks-pattern-good-practice this is my first post here, just to read different opinions, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T22:09:29.417", "Id": "13028", "Score": "1", "body": "This might be technically sound but it hurts my eyes and brain. Having to do this is just another reason why Java needs lambda. `tryandLogFailure(() => methodAAAACanThrowException());` would of been perfect." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T18:48:57.803", "Id": "8225", "ParentId": "8222", "Score": "6" } }, { "body": "<p>The combination of <code>do</code> and <code>switch</code> is pointless. It's doing the same thing as simply calling each method sequentially and nothing more. </p>\n\n<p>Just put those calls inside a <code>try</code> block.</p>\n\n<pre><code>try {\n methodAAAAACanThrowException();\n methodBBBBBCanThrowException();\n\n}catch(Exception e) {\n Logger.getLogger(ABC.class.getName()).log(Level.SEVERE, null, ex);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T17:16:44.503", "Id": "12888", "Score": "1", "body": "Wrong, that won't work, if methodAAAAACanThrowException(); throw an Exception then methodBBBBBCanThrowException(); won't be executed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T16:11:48.533", "Id": "17274", "Score": "0", "body": "Uh, ok. I'll leave it here so everyone will know what not to do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T00:20:47.093", "Id": "8235", "ParentId": "8222", "Score": "0" } }, { "body": "<p>It doesn't have to be as complicated as the other answers. And there are valid reasons for logging and continuing execution of a method.</p>\n\n<p>It appears you are using the execution of the steps to advance to the next step regardless of exceptions. So it seems better to use a for loop. </p>\n\n<p>I'm not really liking the use of switch statements to execute methods in order, but I think fixing that might go beyond the original intent of this question. Too bad Java doesn't have native lambda.</p>\n\n<pre><code>// Execute all steps regardless of exceptions\nvoid executeAllSteps() {\n for (int step = 0; step &lt; 26; ++step) {\n try {\n executeStep(step);\n } catch (Exception ex) {\n // Collect the exception in a list or add it to \n // a log file.\n }\n }\n}\n\nvoid executeStep (int step) throws Exception {\n switch(step) {\n case 0:\n methodAAAAACanThrowException();\n break;\n case 1:\n methodBBBBBCanThrowException();\n break;\n case 2:\n methodCCCCCanThrowException();\n break;\n case 25:\n methodZZZZZCanThrowException(); \n break; \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:34:48.683", "Id": "8346", "ParentId": "8222", "Score": "4" } } ]
{ "AcceptedAnswerId": "8225", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T17:10:02.353", "Id": "8222", "Score": "2", "Tags": [ "java", "exception-handling", "exception" ], "Title": "Exception handling continuing the excecution" }
8222
<p>I want to be able to convert a list of objects into a string csv format. I've written this extension method below but have a feeling I'm missing something as this seems like potentially a common thing to want to do.</p> <pre><code>private static readonly char[] csvChars = new[] { ',', '"', ' ', '\n', '\r' }; public static string ToCsv&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem) { if ((source == null) || (getItem == null)) { return string.Empty; } var builder = new StringBuilder(); var items = from item in source.Select(getItem) where item != null select item.ToString(); foreach (var str in items) { if (str.IndexOfAny(csvChars) &gt; 0) { builder.Append("\"").Append(str).Append("\"").Append(", "); } else { builder.Append(str).Append(", "); } } var csv = builder.ToString(); return csv.Length &gt; 0 ? csv.TrimEnd(", ".ToCharArray()) : csv; } </code></pre> <p>Is there anything I can do to improve this or refactor to a more elegant or working solution. Or even an existing method out there already that I may have missed.</p> <p>UPDATE: Updated to take into account quotations as per Jesse comments below.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T17:48:46.640", "Id": "12890", "Score": "0", "body": "You are excluding null values. Shouldn't a null value still be represented in the CSV output? Depends on what you're using this for, I suppose." } ]
[ { "body": "<p><a href=\"http://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules\" rel=\"nofollow noreferrer\">If your items contain a comma, carriage return or other special CSV character, you must delimit it with quotation marks</a>.</p>\n\n<pre><code>namespace CsvStuff\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n\n internal static class CsvConstants\n {\n public static char[] TrimEnd { get; } = { ' ', ',' };\n\n public static char[] CsvChars { get; } = { ',', '\"', ' ', '\\n', '\\r' };\n }\n\n public abstract class CsvBase&lt;T&gt;\n {\n private readonly IEnumerable&lt;T&gt; values;\n\n private readonly Func&lt;T, object&gt; getItem;\n\n protected CsvBase(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem)\n {\n this.values = values;\n this.getItem = getItem;\n }\n\n public override string ToString()\n {\n var builder = new StringBuilder();\n\n foreach (var item in\n from element in this.values.Select(this.getItem)\n where element != null\n select element.ToString())\n {\n this.Build(builder, item).Append(\", \");\n }\n\n return builder.ToString().TrimEnd(CsvConstants.TrimEnd);\n }\n\n protected abstract StringBuilder Build(StringBuilder builder, string item);\n }\n\n public class CsvBare&lt;T&gt; : CsvBase&lt;T&gt;\n {\n public CsvBare(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n return builder.Append(item);\n }\n }\n\n public sealed class CsvTrimBare&lt;T&gt; : CsvBare&lt;T&gt;\n {\n public CsvTrimBare(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n return base.Build(builder, item.Trim());\n }\n }\n\n public class CsvRfc4180&lt;T&gt; : CsvBase&lt;T&gt;\n {\n public CsvRfc4180(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n item = item.Replace(\"\\\"\", \"\\\"\\\"\");\n return item.IndexOfAny(CsvConstants.CsvChars) &gt;= 0\n ? builder.Append(\"\\\"\").Append(item).Append(\"\\\"\")\n : builder.Append(item);\n }\n }\n\n public sealed class CsvTrimRfc4180&lt;T&gt; : CsvRfc4180&lt;T&gt;\n {\n public CsvTrimRfc4180(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n return base.Build(builder, item.Trim());\n }\n }\n\n public class CsvAlwaysQuote&lt;T&gt; : CsvBare&lt;T&gt;\n {\n public CsvAlwaysQuote(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n return builder.Append(\"\\\"\").Append(item.Replace(\"\\\"\", \"\\\"\\\"\")).Append(\"\\\"\");\n }\n }\n\n public sealed class CsvTrimAlwaysQuote&lt;T&gt; : CsvAlwaysQuote&lt;T&gt;\n {\n public CsvTrimAlwaysQuote(IEnumerable&lt;T&gt; values, Func&lt;T, object&gt; getItem) : base(values, getItem)\n {\n }\n\n protected override StringBuilder Build(StringBuilder builder, string item)\n {\n return base.Build(builder, item.Trim());\n }\n }\n\n public static class CsvExtensions\n {\n public static string ToCsv&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem, Type csvProcessorType)\n {\n if ((source == null)\n || (getItem == null)\n || (csvProcessorType == null)\n || !csvProcessorType.IsSubclassOf(typeof(CsvBase&lt;T&gt;)))\n {\n return string.Empty;\n }\n\n return csvProcessorType\n .GetConstructor(new[] { source.GetType(), getItem.GetType() })\n ?.Invoke(new object[] { source, getItem })\n .ToString();\n }\n\n private static void Main()\n {\n var words = new[] { \",this\", \" is \", \"a\", \"test\", \"Super, \\\"luxurious\\\" truck\" };\n\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvAlwaysQuote&lt;string&gt;)));\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvRfc4180&lt;string&gt;)));\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvBare&lt;string&gt;)));\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvTrimAlwaysQuote&lt;string&gt;)));\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvTrimRfc4180&lt;string&gt;)));\n Console.WriteLine(words.ToCsv(word =&gt; word, typeof(CsvTrimBare&lt;string&gt;)));\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T21:43:02.437", "Id": "12855", "Score": "0", "body": "Excellent. Have edited my post to reflect your suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T22:22:15.680", "Id": "12856", "Score": "0", "body": "I made an edit to my code. IndexOfAny() should be >= 0 instead of > 0. Whoops!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T22:34:30.950", "Id": "12857", "Score": "0", "body": "There's a chance that I may not want to include quotations. Would you suggest just adding a boolean flag to the method parameter to handle this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T22:37:01.830", "Id": "12858", "Score": "0", "body": "Hm. Boolean flag would likely be the quickest, but it's not a very object-oriented solution. Let me noodle on that for a few and put something up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T23:34:46.903", "Id": "12859", "Score": "0", "body": "Ok, I gave it a little thought and updated the answer. There's a lot of code, but it allows for some additional flexibility." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T00:04:39.790", "Id": "12862", "Score": "0", "body": "That looks great. A bit more code like you said but not a huge amount really and provides the kind of flexibility I'm looking for. Just going to leave it up for a bit and see if anyone else has any comments on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T15:14:16.290", "Id": "12885", "Score": "1", "body": "@JesseC.Slicer +1 for the comprehensive example! But I think there's one more thing to add for it to be complete: if the value enclosed in quotes contains a quote itself, then that quote has to be doubled." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T15:43:02.013", "Id": "12887", "Score": "0", "body": "@w0lf you are correct, thanks for catching that. I am about to post a fix." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-23T21:26:08.467", "Id": "8229", "ParentId": "8228", "Score": "7" } }, { "body": "<p>Here is my suggested version, which you should take as coming from a fellow learner.</p>\n\n<ol>\n<li><p>ToCsv is doing too much. I would be inclined to keep it very simple\nand perform only its very narrow responsibility: properly\ntransforming a sequence of strings to a properly formatted csv\nstring. Let the caller transform its sequence of arbitrary objects\ninto strings.</p></li>\n<li><p>String.Join exists in the BCL, which is exactly suited to this\npurpose.</p></li>\n<li>Properly encodes the quote character</li>\n</ol>\n\n<hr>\n\n<pre><code>private class Program\n{\n private static void Main(string[] args)\n {\n int[] someInts = {1, 2, 3, 4, 10, 9, 8};\n string[] someStrings = {\"one\", \"two\", \"seven\", \"eight\"};\n string[] specialStrings = {\"o'ne\", \"\\\"tw\\\"o\", \",,three\", \"fo,ur\", \"five\"};\n\n Console.WriteLine(someInts.Select(s =&gt; s.ToString()).ToCsv());\n Console.WriteLine(someStrings.ToCsv());\n Console.WriteLine(specialStrings.ToCsv());\n }\n}\n\npublic static class CsvHelpers\n{\n private static readonly char[] csvSpecialChars = new[] { ',', '\"', ' ', '\\n', '\\r' };\n\n public static string ToCsv(this IEnumerable&lt;string&gt; source)\n {\n if (source == null)\n {\n return string.Empty;\n }\n\n var encodedStrings = from item in source\n select EncodeCsvField(item);\n\n return string.Join(\",\", encodedStrings);\n }\n\n private static string EncodeCsvField(string input)\n {\n string encodedString = input.Replace(\"\\\"\", \"\\\"\\\"\");\n if (input.IndexOfAny(csvSpecialChars) &gt;= 0)\n {\n encodedString = \"\\\"\" + encodedString + \"\\\"\";\n }\n\n return encodedString;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:13:20.647", "Id": "12899", "Score": "0", "body": "I sort of wanted to stay away from putting the dependancy on the string object itself in the IEnumerable hence the use of generics. However didn't really know about the Join operater. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T21:13:19.983", "Id": "12905", "Score": "0", "body": "My reasoning was that you either provide the function to project from your object to string or just do the projection (possibly through LINQ so you could defer the execution) at the call site. Seemed simpler to just do the projection at the call site if needed so that the extension method has only one responsibility. Cheers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T17:22:11.873", "Id": "8256", "ParentId": "8228", "Score": "3" } }, { "body": "<p>A couple of things:</p>\n\n<ol>\n<li><p>Although you are using a StringBuilder (which is good in this case), you're generating a string for each row of data. If you're intending to use this to create multiple rows of data, then it will not quite as efficient as it could be. Maybe this is no big deal, although that might depend on how much data you're processing.</p></li>\n<li><p>Although I don't feel it's a major concern, I don't like stripping off the trailing comma. I always like to avoid messing up my output in the first place, rather than having additional code at the end that fixes the problem. One thing to realize, though, is that your StringBuilder generates an entire string in memory to contain the row of data, but when you call TrimEnd, I believe that this will create <em>yet another</em> string containing the entire row of data. Not very efficient.</p></li>\n</ol>\n\n<p>I imagine that in most cases, this might be used to output to a file, or perhaps some other kind of stream. Therefore, it would make more sense to me to rewrite this functionality to write to a stream.</p>\n\n<p>I've provided an alternate implementation below. The core functionality is in the WriteAsCsv method for the TextWriter. There are a few overloads to make this functionality easy to use for someone who has access to a FileStream object, a StringBuilder object, or just the original IEnumerable object.</p>\n\n<p>This approach uses an enumerator in order to avoid the issue with the trailing comma.</p>\n\n<pre><code> static void WriteCsvValue(System.IO.TextWriter writer, string str)\n {\n if (str.IndexOfAny(csvChars) &gt; 0)\n {\n writer.Write(\"\\\"\");\n writer.Write(str); // TODO: perform any necessary escaping\n writer.Write(\"\\\"\");\n }\n else\n {\n writer.Write(str);\n }\n }\n\n public static void WriteAsCsv&lt;T&gt;(this System.IO.TextWriter writer, IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem)\n {\n if ((source == null) || (getItem == null))\n {\n return;\n }\n\n var items = from item in source.Select(getItem)\n where item != null\n select item.ToString();\n\n using (var enumerator = items.GetEnumerator())\n {\n if (enumerator.MoveNext())\n {\n WriteCsvValue(writer, enumerator.Current);\n\n while (enumerator.MoveNext())\n {\n writer.Write(\", \");\n WriteCsvValue(writer, enumerator.Current);\n }\n }\n }\n }\n\n public static void WriteAsCsv&lt;T&gt;(this System.IO.Stream stream, IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem)\n {\n if ((source == null) || (getItem == null))\n {\n return;\n }\n\n using (var writer = new System.IO.StreamWriter(stream))\n {\n writer.WriteAsCsv(source, getItem);\n }\n }\n\n public static void AppendAsCsv&lt;T&gt;(this StringBuilder builder, IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem)\n {\n if ((source == null) || (getItem == null))\n {\n return;\n }\n\n using (var writer = new System.IO.StringWriter(builder))\n {\n writer.WriteAsCsv(source, getItem);\n }\n }\n\n public static string ToCsv&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, object&gt; getItem)\n {\n StringBuilder builder = new StringBuilder();\n builder.AppendAsCsv(source, getItem);\n return builder.ToString();\n }\n</code></pre>\n\n<ul>\n<li>A StreamWriter is a TextWriter that wraps a Stream object.</li>\n<li>A StringWriter is a TextWriter that wraps a StringBuilder object.</li>\n</ul>\n\n<p>The gist of what I've done here is to decompose your original approach into separate pieces, making it easier to consume in multiple different ways.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:15:45.150", "Id": "12900", "Score": "0", "body": "Although efficiency in the particular case I'm using it for isn't an issue as I'm not dealing with 100's of lines etc it's still something I didn't take into account. thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:20:29.870", "Id": "12903", "Score": "0", "body": "@dreza if you don't care to use an enumerator (I know it feels clunky, at least until you get used to it), you could avoid having to strip off the trailing comma by prepending the comma: `if(builder.Length>0)builder.Append(\", \");`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:54:46.960", "Id": "12904", "Score": "0", "body": "@dreza - See [my answer on StackOverflow](http://stackoverflow.com/questions/8992953/best-way-to-convert-all-strings-in-liststring-to-a-single-comma-separated-stri/8993927#8993927) to a similar question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T17:43:07.663", "Id": "8257", "ParentId": "8228", "Score": "2" } } ]
{ "AcceptedAnswerId": "8229", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T20:47:55.270", "Id": "8228", "Score": "6", "Tags": [ "c#", "csv" ], "Title": "Converting a list to a CSV string" }
8228
<p>I'd like some feedback on my implementation to get all the permutations of a set.</p> <p>Eg:</p> <pre><code>@Test public void test() { def data = [["A","B"],["A","B","C","D"],["D","E","F"]] def expected = toResultSet("ABD,ABE,ABF,ACD,ACE,ACF,ADE,ADF,BAD,BAE,BAF,BCD,BCE,BCF,BDE,BDF"); def result = SetPermutations.getSetPermutations(data); assert result.containsAll(expected); assert result.size() == expected.size(); } </code></pre> <p>Note that:</p> <ul> <li>The input is a collection of collections</li> <li>Each collection may have a different number of items</li> <li>Each item may appear in more than 1 collection (in the input) (ie., <code>data[0]</code> and <code>data[1]</code> both contain <code>"A"</code>)</li> <li>Each resulting permutation must contain exactly 1 item from each of the input sets</li> <li>Each item may only appear once in a given permutation (ie., <code>'AAB'</code> is invalid)</li> </ul> <p>Here is my implementation: (Note, my test is in groovy, but the implementation is java)</p> <pre><code>public class SetPermutations&lt;E&gt; { private List&lt;E&gt; permutationSet; private final Collection&lt;Collection&lt;E&gt;&gt; input; private final int maxDepth; private final Set&lt;List&lt;E&gt;&gt; result; public static &lt;E&gt; Set&lt;List&lt;E&gt;&gt; getSetPermutations(Collection&lt;Collection&lt;E&gt;&gt; input) { SetPermutations&lt;E&gt; setPermutations = new SetPermutations&lt;E&gt;(input); return setPermutations.build(); } private SetPermutations(Collection&lt;Collection&lt;E&gt;&gt; input) { this.input = input; maxDepth = input.size() - 1; result = new HashSet&lt;List&lt;E&gt;&gt;(); } private Set&lt;List&lt;E&gt;&gt; build() { List&lt;Collection&lt;E&gt;&gt; list = new ArrayList&lt;Collection&lt;E&gt;&gt;(input); int currentDepth = 0; permutationSet = newPermutationSet(); permute(list,currentDepth); return result; } private void permute(List&lt;Collection&lt;E&gt;&gt; list, int currentDepth) { Collection&lt;E&gt; collection = list.get(currentDepth); for (E object : collection) { if (permutationSet.contains(object)) continue; permutationSet.add(object); if (currentDepth != maxDepth) { permute(list, currentDepth + 1); permutationSet.remove(object); } else { result.add(permutationSet); // Allow the recursion to continue on a new permutationSet, // but remove our item from it. permutationSet = clonedPermutationSet(); permutationSet.remove(object); } } } private List&lt;E&gt; newPermutationSet() { return new ArrayList&lt;E&gt;(); } private List&lt;E&gt; clonedPermutationSet() { return new ArrayList&lt;E&gt;(permutationSet); } } </code></pre> <p>I have a few specific questions:</p> <ul> <li>Am I reinventing the wheel here? I searched, and couldn't find a suitable implementation for this problem anywhere, but I find it hard to believe that this hasn't been solved before (better than my solution)</li> <li>Is there a better way for me to have implemented this?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T18:43:53.773", "Id": "12892", "Score": "0", "body": "Are you deliberately using `Collection<Object>`, or is this something that should be handled by making the collections generic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:58:12.310", "Id": "12896", "Score": "0", "body": "Great idea -- no specific reason, I've just tweaked it to use Generics." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:03:42.363", "Id": "12897", "Score": "0", "body": "I've updated the post to show the generics version - feedback greatly appreciated." } ]
[ { "body": "<p>There's a number of things going on here, but the first thing that comes to mind is that you're placing an object on the heap that you simply discard (the entire class) for no apparent reason (speaking logically, not in terms of objects created). Given that you don't appear to keep the object at all, this is unnecessary - do this all with static methods. Additionally, this is <em>not</em> threadsafe, and the basic design cannot be adjusted to execute on multiple threads. Furthermore, you're returning a <code>Set&lt;List&lt;E&gt;&gt;</code>, but your results are <em>logically</em> <code>Set&lt;Set&lt;E&gt;&gt;</code> (because you don't have repeats) - You probably ought to either adjust your results, or change your return results.</p>\n\n<p>There's also a compile error in your code since you switched to the generics version, because of type inference (and this took me a while to figure out).</p>\n\n<p>Most of the disconnect is occurring because of the odd blend of static and instance methods. Additionally, you're attempting to use a builder pattern for something that doesn't really call for it - as near as the <em>caller</em> of your method knows, your <code>SetPermutations</code> class is never instantiated (which is false). Also, you add <code>object</code> to <code>permutationSet</code>... and then almost immediately remove it. Regardless of the performance implications of that, it's a terrible thing to do to a developer's mind.</p>\n\n<hr/>\n\n<p>Here's my (intial) take on the issue. Note that this version is threadsafe (so long as <code>T</code> is an immutable object), and amenable to (easier) threading. There are a few areas that could maybe be tweaked, especially as I'm creating a few more objects than I actually need (notably, my termination condition in <code>permute</code>), but this should be a better starting place.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n\npublic abstract class SetPermutations { \n\n private SetPermutations() {\n // no state.\n }\n\n public static &lt;T&gt; Set&lt;Set&lt;T&gt;&gt; getSetPermutations(final Collection&lt;? extends Collection&lt;T&gt;&gt; input) {\n if (input == null) {\n throw new IllegalArgumentException(\"Input not provided!\");\n }\n final List&lt;Set&lt;T&gt;&gt; saved = new ArrayList&lt;Set&lt;T&gt;&gt;();\n for (Collection&lt;T&gt; c : input) {\n Set&lt;T&gt; s = new HashSet&lt;T&gt;(c);\n c.remove(null);\n if (c.size() &gt;= 1) {\n saved.add(s);\n } else {\n throw new IllegalArgumentException(\"Input includes null/empty collection!\");\n }\n }\n\n return permute(new HashSet&lt;T&gt;(), saved);\n } \n\n private static &lt;T&gt; Set&lt;Set&lt;T&gt;&gt; permute(final Set&lt;T&gt; initial, final List&lt;Set&lt;T&gt;&gt; itemSets) {\n\n if (itemSets.isEmpty()) {\n return Collections.singleton(initial);\n }\n\n final Set&lt;T&gt; items = itemSets.get(0);\n final List&lt;Set&lt;T&gt;&gt; remaining = itemSets.subList(1, itemSets.size());\n final int computedSetSize = initial.size() * items.size() * remaining.size();\n final Set&lt;Set&lt;T&gt;&gt; computed = new HashSet&lt;Set&lt;T&gt;&gt;(computedSetSize, 1);\n\n for (T item : items) {\n if (!initial.contains(item)) {\n Set&lt;T&gt; permutation = new HashSet&lt;T&gt;(initial);\n permutation.add(item);\n computed.addAll(permute(permutation, remaining));\n }\n }\n\n return computed;\n }\n\n} \n</code></pre>\n\n<p>And here's the (revised) JUnit test to prove behaviour:</p>\n\n<pre><code>@Test \npublic void setPermutationsTest() { \n List&lt;List&lt;String&gt;&gt; data = new ArrayList&lt;List&lt;String&gt;&gt;();\n data.add(Arrays.asList(\"A\", \"B\"));\n data.add(Arrays.asList(\"A\",\"B\",\"C\",\"D\"));\n data.add(Arrays.asList(\"D\",\"E\"));\n Set&lt;Set&lt;String&gt;&gt; expected = new HashSet&lt;Set&lt;String&gt;&gt;();\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"A\", \"B\", \"D\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"A\", \"B\", \"E\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"A\", \"C\", \"D\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"A\", \"C\", \"E\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"A\", \"D\", \"E\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"B\", \"C\", \"D\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"B\", \"C\", \"E\")));\n expected.add(new HashSet&lt;String&gt;(Arrays.asList(\"B\", \"D\", \"E\")));\n Set&lt;Set&lt;String&gt;&gt; result = SetPermutations.&lt;String&gt;getSetPermutations(data); \n assertTrue(result.containsAll(expected)); \n assertTrue(result.size() == expected.size()); \n} \n</code></pre>\n\n<p>(I removed <code>\"F\"</code> from the last collection, as it wasn't adding anything in terms of conditions - it fufilled the same function as <code>\"E\"</code>).</p>\n\n<hr/>\n\n<p>EDIT: </p>\n\n<p>The main reason why this is (more, and as much as can be reasonably coded for) threadsafe is the fact that you're not (completely) operating on a 'saved' copy:</p>\n\n<ol>\n<li>You save off <code>maxDepth</code> <em>before</em> copying the 'exterior' collection. If the size of that collection changes, <code>maxDepth</code>'s value is now incorrect (results undefined).</li>\n<li>You copy (and work from) the 'exterior' collection, but don't copy the 'interior' collections (The copy constructors <em>might</em> be deep for <strong>existing</strong> collections, but I doubt it, and <em>won't</em> be for custom collections). This means that if any of the interior collections are modified during process run, you won't get correct results.</li>\n</ol>\n\n<p>As for the static method instantiating a version of itself - there's no problem with that. In fact, that generally forms the basis of a <a href=\"http://en.wikipedia.org/wiki/Factory_pattern\" rel=\"nofollow\">Factory Pattern</a>. The catch is that the instantiation is being <em>returned</em> - that is, the desired result <em>is</em> the instantiation. Here, the only result is that you end up with a confusing use of instance variables. The <code>permutationSet</code> methods end up being unwanted noise (It would have been better to explicitly just use the constructors), and are misleading to boot (you're returning a <strong>LIST</strong>). Additionally, because of the use of the instance variables, it becomes non-trivial to reason about the state of the various collections. <strong>NONE</strong> of the work done by instance methods benefits significantly from working on instance variables. The only (theorhetical) benefit gained is that you work with a single copy of a result <code>HashSet</code> (because I define intermediate ones) - however, if it's an issue, the necessary collection should be passed in (as in a <code>load()</code> method.<br>\nAlso, by permorming the instantiation as you have, you've completely eliminated any potential hope of threading the process (a potential concern, given that this is basically an O(n ^ m) process, where n is the number of collections, and m is the size of the collections, assuming roughly equal collection sizes). With a thread pool and using futures, a non-instantiated version (or at least, not instantiated like this) can be threaded fairly trivially.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T00:14:39.410", "Id": "12915", "Score": "0", "body": "Thanks for this - I appreciate the feedback. I'll need to step through the code to fully grok it. However, would you mind expanding on why this is more threadsafe than the original? Additionally, I'm interested to know why you believe it's bad for a static method to instantiate a version of itself -- ie., why should the caller care about the internals of how the invocation works?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T22:43:38.827", "Id": "8267", "ParentId": "8230", "Score": "3" } } ]
{ "AcceptedAnswerId": "8267", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T22:31:18.817", "Id": "8230", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Getting permutations of a set" }
8230
<p>I have following code that is used of one time skipping some functionality(actually do something only one time until <code>SkipSomeStuff</code> is <code>true</code>):</p> <pre><code>private bool _skipSomeStuff; public bool SkipSomeStuff { set { _skipSomeStuff = value; } get { if (_skipSomeStuff) { _skipSomeStuff = false; return true; } return false; } } </code></pre> <p>Is such construction ok to use, or I should change it with something?</p>
[]
[ { "body": "<p>It is very confusing to set a property just to discover that it returns something else just after you set it. Properties are supposed to keep the value you give them. (At least logically)</p>\n\n<p>And since your SkipSomeStuff property is public, you have no guarantee you won't access that property by accident before the intended recipient accesses it, and the stuff isn't skipped after all.</p>\n\n<p>How about keeping the skipSomeStuff member, but set it using a method called SkipStuffNextTime() or something like that? Nobody will misunderstand the intent of your code that way, and only the code it's relevant for will access and reset it.</p>\n\n<pre><code>private bool skipSomeStuff = false;\n\npublic void SkipStuffNextTime() {\n skipSomeStuff = true;\n}\n\npublic void DoSomeStuff() {\n if (skipSomeStuff) {\n skipSomeStuff = false;\n return;\n }\n // do the stuff\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T02:56:15.327", "Id": "12865", "Score": "0", "body": "+1 for the plug for maintainability. P.S. A certain property that emits a value different from the underlying field - but never updates the field itself! This damn thing has wreaked havoc in our application. And guess what you see in the debugger when you hover over the property? Yes, the wrong answer (i.e. wrong value)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T08:24:52.220", "Id": "12868", "Score": "1", "body": "@radarbob - I imagine that if you accidentally hover your mouse over that property at the wrong time while debugging, you might inadvertently \"use up\" the value, causing your application to run incorrectly. Nasty problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T09:06:40.913", "Id": "12869", "Score": "0", "body": "@Dr.Wily'sApprentice interesting suggestion. I'll try)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T09:07:51.113", "Id": "12870", "Score": "0", "body": "@Lars-Erik thanks for answering. I'll refactor this crap)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:32:28.710", "Id": "12873", "Score": "0", "body": ":)\nIf you add an accessor property (only getter), you can even write some unit-tests which confirms that everything works as expected." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T23:59:02.980", "Id": "8233", "ParentId": "8232", "Score": "10" } } ]
{ "AcceptedAnswerId": "8233", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T23:34:53.020", "Id": "8232", "Score": "3", "Tags": [ "c#" ], "Title": "One time property reading" }
8232
<p>I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).</p> <p>Simple List Class:</p> <pre><code>class Cell: def __init__( self, data, next = None ): self.data = data self.next = next </code></pre> <p>Concatenate Function:</p> <pre><code>def list_concat(A, B): current = A while current.next != None: current = current.next current.next = B return A </code></pre> <p>List create (that takes forever!):</p> <pre><code>def create_list(n): a = cell.Cell(0) for i in (range(1,n)): b = cell.Cell(i) new_list = cell.list_concat(a, b) return new_list </code></pre> <p>This is an assignment, but efficiency is not part of it. I am just wondering if there is a more efficient way to create a large list using this implementation of the structure.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T01:06:36.780", "Id": "12864", "Score": "1", "body": "do you really need a linked list?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:50:25.270", "Id": "12985", "Score": "0", "body": "Comparisons with None are best done based on identity (since None is a singleton), so `while current.next is not None` will suffice. Given that `Cell` has no defined boolean truthness, it is as object \"always True\" and you could reduce the while loop to `while current.next`." } ]
[ { "body": "<p>Just assign to the previous node's <code>next</code> attribute directly in the loop:</p>\n\n<pre><code>def create_list(n):\n for i in range(n):\n c = cell.Cell(n)\n if i == 0:\n lst = c\n else:\n prev.next = c\n prev = c\n return lst\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T20:09:53.303", "Id": "13539", "Score": "0", "body": "Do you propose to test i==0 at every step of the loop?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T02:18:54.930", "Id": "8239", "ParentId": "8237", "Score": "1" } }, { "body": "<pre><code>def create_list(n):\n a = cell.Cell(0)\n for i in (range(1,n)):\n</code></pre>\n\n<p>You don't need the parens around <code>range(1,n)</code> </p>\n\n<pre><code> b = cell.Cell(i)\n new_list = cell.list_concat(a, b) \n return new_list\n</code></pre>\n\n<p>It'll be faster if you build the list in reverse order.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T03:30:20.513", "Id": "8240", "ParentId": "8237", "Score": "1" } }, { "body": "<p>The current algorithm has a failure in using the <code>list_concat</code> during list creation. The <code>list_concat</code> function walks to the end of the list for each node you want to add. So adding a node becomes O(n). This means creating a list of 10,000 items takes 1+2+3...+10,000 steps. That's O(n*n) performance.</p>\n\n<p>As hinted, you should add the next node in the creation loop. You then get code that looks like this (I left out the <code>list_concat</code> function as it's not used):</p>\n\n<pre><code>class Cell(object):\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\n\ndef create_list(length=1):\n linked_list = Cell(0)\n head = linked_list\n for prefill_value in xrange(1, length):\n head.next = Cell(prefill_value)\n head = head.next\n return linked_list\n</code></pre>\n\n<p>You could also create the list in reverse order, allowing you to immediately fill the <code>next</code> attribute of the Cell. Your create_list function then looks like this (the <code>reversed</code> function should not be used for really huge lengths (several million) because it's created in-memory):</p>\n\n<pre><code>def create_list(length=1):\n tail = Cell(length - 1)\n for prefill_value in xrange(length - 2, -1, -1):\n tail = Cell(prefill_value, tail)\n return tail\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:55:13.033", "Id": "12986", "Score": "0", "body": "Of course, if you don't need the values of the `Cells` to be increasing the `xrange` statement could be drastically simplified. This would make the second, reverse, `create_list` function a lot easier on the eyes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:38:04.483", "Id": "8327", "ParentId": "8237", "Score": "4" } }, { "body": "<pre><code>def list_concat(A, B):\n current = A\n while current.next != None:\n current = current.next\n current.next = B\n # Why 'return A' when the caller already gave A?\n</code></pre>\n\n<p>Aside from adding a function that implimented <code>list_concat</code> for arrays, you could just make a simple edit to create_list:</p>\n\n<pre><code>def create_list(n):\n a = cell.Cell(0)\n for i in (range(1,n)):\n b = cell.Cell(i)\n cell.list_concat(a, b) \n a = b \n return a\n</code></pre>\n\n<p>Now, every time list_concat runs, it starts at the end of the list and just appends b. </p>\n\n<p>I'd recomend, over the above, writing a class that held the first and last nodes in the list. That way, it'd be as simple as</p>\n\n<pre><code>def create_list(n):\n list = List()\n for x in range( 0, n ):\n list.put_at_end( Cell(x) ) # or list.append_cell(x)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T00:20:32.407", "Id": "8841", "ParentId": "8237", "Score": "1" } } ]
{ "AcceptedAnswerId": "8327", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T01:02:06.747", "Id": "8237", "Score": "6", "Tags": [ "python", "algorithm" ], "Title": "Faster way to create linked list of length n in Python" }
8237
<p>I have a code which was not refactored at all. I refactored it to some extent, but stuck at a point where I cannot think of anything further.</p> <p><strong>Tractor.java:</strong></p> <pre><code>package com.farm; public class Tractor implements MethodsInterface { private int[] position; private int[] field; private String orientation; public Tractor(){ position = new int[]{0,0}; field = new int[]{5,5}; orientation = "N"; } public void move(String command) { if(command=="F"){ moveForwards(); }else if(command=="T"){ turnClockwise(); } } private void moveForwards() { if(orientation=="N"){ position = new int[]{position[0], position[1]+1}; } else if(orientation == "E"){ position = new int[]{position[0]+1, position[1]}; } else if(orientation == "S"){ position = new int[]{position[0], position[1]-1}; }else if(orientation == "W"){ position = new int[]{position[0]-1, position[1]}; } if(position[0] &gt; field[0] || position[1] &gt; field[1]) { try { throw new TractorInDitchException(); } catch (TractorInDitchException e) { e.printStackTrace(); } } } private void turnClockwise() { if(orientation=="N"){ orientation = "E"; }else if(orientation == "E"){ orientation = "S"; }else if(orientation == "S"){ orientation = "W"; }else if(orientation == "W"){ orientation = "N"; } } public int getPositionX() { return position[0]; } public int getPositionY() { return position[1]; } public String getOrientation() { return orientation; } } </code></pre> <p><strong>TractorInDitchException.java:</strong></p> <pre><code>package com.farm; public class TractorInDitchException extends Exception{ } </code></pre> <p><strong>MethodsInterface.java:</strong></p> <pre><code>package com.farm; public interface MethodsInterface { public int getPositionX(); public int getPositionY(); public String getOrientation(); } </code></pre> <p>What else could be refactored?</p>
[]
[ { "body": "<p>First, the code compares Strings using <code>==</code>. This will compare the <em>reference</em> rather than the contents of the String. Use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo%28java.lang.String%29\" rel=\"nofollow\"><code>String.compareTo(String)</code></a> or <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareToIgnoreCase%28java.lang.String%29\" rel=\"nofollow\"><code>String.compareToIgnoreCase(String)</code></a>. </p>\n\n<p>Better yet, do not use a <code>String</code> as an argument in your <code>move()</code> method. It would be ideal to use an <code>enum</code>, but a char will do as well. The same holds for your variable <code>orientation</code>.</p>\n\n<p><code>MethodsInterface</code> is not a very descriptive name. It seems to describe the location and orientation of objects, so consider a more descriptive name. Maybe <code>SpatialInfo</code>.</p>\n\n<p><code>Position</code> is an array of <code>int</code>s. It seems to be 2-dimensional, so consider the use of <code>Point</code>. In fact, I would prefer a <code>Point</code> or <code>Position</code> class above an array whether you use 2D or 3D.</p>\n\n<p>I'm not sure why your <code>TractorInDitchException</code> is an <code>Exception</code>. Exceptions are used for handling exceptional situations in program flow. I imagine that your tractor ending up in a ditch, although <em>not</em> an everyday situation on your simulated farm, should be covered by the regular program flow.</p>\n\n<p>There's not much point in having a try-catch block around a single <code>throw</code> operation anyway, when the only point of the try-catch block is to catch the very <code>Exception</code> that you're deliberately throwing.</p>\n\n<p>A message to the user, and perhaps some kind of flag on the Tractor object that it is in the ditch, would be more useful.</p>\n\n<p>If all you want is the stack trace, you can use <code>new Throwable().printStackTrace()</code> (see <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace%28%29\" rel=\"nofollow\">Javadoc</a>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T09:09:04.590", "Id": "8243", "ParentId": "8238", "Score": "6" } }, { "body": "<ol>\n<li><p>Instead of magic constants like <code>\"N\"</code>, <code>\"S\"</code> etc. use an enum which contains named constants and their values are checked on compile time.</p>\n\n<pre><code>public enum Orientation {\n NORTH, SOUTH, WEST, EAST\n}\n</code></pre>\n\n<p>With plain <code>String</code>s it's too easy to set an invalid value to the <code>orientation</code> field.</p></li>\n<li><p>You can move the <code>turnClockwise</code> method to an enum:</p>\n\n<pre><code>public enum Orientation {\n NORTH {\n @Override\n public Orientation turnClockwise() {\n return EAST;\n }\n },\n SOUTH {\n @Override\n public Orientation turnClockwise() {\n return WEST;\n }\n },\n WEST {\n @Override\n public Orientation turnClockwise() {\n return NORTH;\n }\n },\n EAST {\n @Override\n public Orientation turnClockwise() {\n return SOUTH;\n }\n };\n\n public abstract Orientation turnClockwise();\n\n}\n</code></pre>\n\n<p>It increases <a href=\"http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29\">cohesion</a> and <a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\">replaces conditional with polymorphism</a>.</p>\n\n<p>(I'd also try to create a <code>Position</code> class with <code>x</code> and <code>y</code> coordinates and move the statements from the <code>moveForwards</code> method to this class like <code>goNorth()</code>, <code>goWest()</code> etc. Then a new <code>Position moveForward(Position current)</code> method in the <code>Orientation</code> enum would call one of the <code>Position.go*()</code> methods.)</p></li>\n<li><p>I'd change this array:</p>\n\n<pre><code>position = new int[] {0, 0};\n</code></pre>\n\n<p>to two ints:</p>\n\n<pre><code>private int positionX;\nprivate int positionY;\n</code></pre>\n\n<p>Indexes here (<code>0</code> and <code>1</code>) are <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">magic constants</a>.</p></li>\n<li><p>The <code>moveForwards</code> and the the <code>Tractor</code> class looks unfinished. Noone writes the <code>field</code> array.</p></li>\n<li><p>This:</p>\n\n<pre><code>try {\n throw new TractorInDitchException();\n} catch (final TractorInDitchException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>could be written as</p>\n\n<pre><code>new TractorInDitchException().printStackTrace();\n</code></pre>\n\n<p>without the <code>try-catch</code> structure. A logger framework (for example SLFJ and Logback) would be better here.</p></li>\n<li><p>What should happen when the tractor reach the border of the field? (When the index is negative or greater than or equal to the size of the array.) </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T14:19:24.600", "Id": "12883", "Score": "0", "body": "+1 for a great thorough answer. Further to #2, I'd move the `Orienation` enum out of the `Tractor` class so that is available for the any future classes that may need it (such as `FieldCar` or `SheepDog`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T14:59:50.790", "Id": "12884", "Score": "0", "body": "Thanks, @RobertGowland! I agree. Actually, I don't like inner classes too much, so one file per class/enum/interface is the default for me :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T20:25:21.100", "Id": "13012", "Score": "0", "body": "Is the tractor being in the ditch really an exception case while running the code? In other words, it seems proper to use the State concept then forcing the VM to dump the current stack if the tractor moves somewhere that causes problems." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T09:44:40.823", "Id": "8244", "ParentId": "8238", "Score": "8" } } ]
{ "AcceptedAnswerId": "8244", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T01:59:40.990", "Id": "8238", "Score": "6", "Tags": [ "java", "object-oriented" ], "Title": "Farm tractor implementation" }
8238
<p>I have the following code to do remember-me style login:</p> <pre><code>&lt;?php session_start(); if(!isset($_SESSION['login'])) $_SESSION['login'] = 0; if(isset($_COOKIE['web_login_cookie']) &amp;&amp; $_SESSION['login'] == 0) { $sql = mysql_query("SELECT * FROM users"); while($row = mysql_fetch_array($sql)) { $pass = sha1($row['password'] . '@#$%$#%dsf@#$SDFg'); if($_COOKIE['web_login_cookie'] == $pass) { $_SESSION['userID'] = $row['userID']; $_SESSION['login'] = 1; if($row['level'] == 1) { $_SESSION['admin'] = 1; } } } if(mysql_num_rows($sql) == 0) { setcookie("web_login_cookie", "", time()+(60*60*24*14)); session_destroy(); } } ?&gt; </code></pre> <p>I have this code in my header file. Is this secure enough or will it pose any security risks in the future?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:16:23.603", "Id": "12871", "Score": "0", "body": "Calculating and comparing every user's cookie every time will be insanely slow rather soon i think.\nThree links to read: http://stackoverflow.com/questions/549/the-definitive-guide-to-website-authentication\nhttp://en.wikipedia.org/wiki/HMAC\nhttp://www.openwall.com/phpass/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:21:00.663", "Id": "12875", "Score": "2", "body": "Please read about the `WHERE` clause in SQL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:22:59.783", "Id": "12876", "Score": "0", "body": "hi Avocado, i have read that, then what should i do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:27:26.317", "Id": "62384", "Score": "1", "body": "It's not related to security, but downloading an iterating through the whole `user` table on every page request will be a bottleneck in the application." } ]
[ { "body": "<p>With that:<code>$_COOKIE['web_login_cookie'] == $pass</code>, you store password (hash) in cookie.\nbest, not to be put in the cookie. Just said the status of connection in the session (server side).</p>\n\n<p>Control the login/password with PHP et put just <code>$_SESSION['login'] = 1</code> in session.</p>\n\n<p>You must check your login form against the injection MYSQL.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:17:57.897", "Id": "8250", "ParentId": "8245", "Score": "2" } }, { "body": "<p>I don’t like the idea of storing the password hash in a cookie. It is easy to steal and grants unlimited access. The cookie is transmitted with every single HTTP request. I would prefer using an access token with limited lifetime. Anyway most people store passwords in their browser and this is easy to steal as well – so this seems not to be a massive security break.</p>\n\n<p>The bigger problem is that your login only relies on the password – you don’t need to know the corresponding username to login. This makes brute forcing a lot easier. And more important: your login will break, if two users use the same password. Then user2 will (unintentionally) gain access to user1’s account.</p>\n\n<p>PS: As mentioned in comments, don’t loop over every line in your table, use a <code>WHERE</code> clause instead. And I don’t understand, what you are trying to achieve with your <code>mysql_num_rows</code> code block…</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:34:26.150", "Id": "12879", "Score": "0", "body": "So is it better to store username inside cookies to prevent user2 will (unintentionally) gain access to user1’s account" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:55:01.893", "Id": "12880", "Score": "0", "body": "Your edit is a huge improvement. Don't use `substr` to divide userid and passhash, instead define a delimeter (which must not occur both in username or passhash). And also be aware of SQL Injections - cookies can be manipulated as easy as GET and POST params." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:29:05.353", "Id": "8251", "ParentId": "8245", "Score": "5" } }, { "body": "<p>Your system makes it easy to do a bulk guessing attack on all users if the ‘salt’ is known to an attacker: All he has to do is to provide the hash of the salted password that might be used by an arbitrary user. Due to the <code>while</code> loop, your script will pick the right one out whose password hash matches the one provided in the cookie.</p>\n\n<p>Chances are that someone of the users uses <code>123456</code> as their password, so using <code>5ecec7b7b6672e8f419f34bf1c5fa38298e08a70</code> as cookie value would be a good guess.</p>\n\n<p>Besides the issue that you store the password in a cookie (no matter in what form), you use that value for both identification (<em>Who is it?</em>) and authentication (<em>Is it really him/her?</em>). This is also the reason why the mentioned attack would work.</p>\n\n<p>Instead of using a cookie for authentication, just use the session mechanism. Although here the session ID is also used for both identification and authentication, a session is only valid for a limited time and the session ID should be unguessable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:11:13.763", "Id": "12882", "Score": "0", "body": "Hi, please check the updated code, do you think this is any better?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:57:02.250", "Id": "8252", "ParentId": "8245", "Score": "1" } }, { "body": "<p>As others have mentioned, storing the password in the cookie leaves you wide open to replay attacks. If uoi ever try to scale this up to more than single character user ids, then you're going to run into problems with SQL injection - particularly since you then use the userid returned from the query rather than the user id which was supplied in the cookie. And you destroy the cookie when the user logs in - so it only remembers you once?</p>\n\n<p>Sorry - but I'd recommend you go and read the many duplicate questions on SO regarding remember me functionality and start again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:30:55.053", "Id": "8253", "ParentId": "8245", "Score": "1" } }, { "body": "<p>I usually generate a login cookie like this and then I only have to verify the hash when the user tries to login through cookie authentication. Will further explain this answer when the time is on my side :)</p>\n\n<pre><code>$expiration = time() + 2629743;\n\n$key = hash_hmac('md5', $user_id . $expiration . $_SERVER['REMOTE_ADDR'], 'my-secret-key');\n$hash = hash_hmac('md5', $user_id . $expiration . $_SERVER['REMOTE_ADDR'], $key);\n\n$cookie = $user_id . '|' . $expiration . '|' . $hash;\nsetcookie('auth_cookie', $cookie, $expiration);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T15:28:52.520", "Id": "8254", "ParentId": "8245", "Score": "0" } }, { "body": "<p>The right way to manage passwords in PHP was covered in great detail in <a href=\"http://www.php-security.org/2010/05/26/mops-submission-10-how-to-manage-a-php-applications-users-and-passwords/\" rel=\"nofollow\">this</a> article that won the \"Month of PHP security\" in 2010.</p>\n\n<p>I realise this isn't a great answer for this site, but I would strongly recommend anyone writing a login system read that article, even if they are not using PHP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T22:52:18.990", "Id": "8268", "ParentId": "8245", "Score": "0" } } ]
{ "AcceptedAnswerId": "8251", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:18:48.597", "Id": "8245", "Score": "4", "Tags": [ "php", "mysql", "authentication" ], "Title": "PHP login cookie authentication" }
8245
<p>How expensive is this query?</p> <p>Lets say for example if I don't have a field called <code>total_comments</code> in my <code>blog</code> table. All I want to know is the blog has comments or not.</p> <pre><code>SELECT EXISTS (SELECT true FROM comments WHERE blog_id = b.id) as has_comments FROM blogs b </code></pre> <p>How else could this be achieved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T11:20:53.333", "Id": "12872", "Score": "0", "body": "It depends on how often you execute the query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T15:20:05.920", "Id": "12886", "Score": "0", "body": "also depends (a lot) whether you have an index on the blog_id field of the comments table." } ]
[ { "body": "<p>UPDATE: Ah...I've reread your original query. When I first read it, I thought that you were only retrieving this for a single blog, but now I see that you're retrieving for every blog record.</p>\n\n<p>This might be inefficient, though I'm not sure. I suppose it depends on how good MySQL is at dealing with that subquery.</p>\n\n<p>Below is probably the most straightforward approach:</p>\n\n<pre><code>SELECT\n blogs.blog_id,\n COUNT(comments.blog_id)\nFROM blogs\nLEFT OUTER JOIN comments on\n comments.blog_id = blogs.blog_id\nGROUP BY\n blogs.blog_id\n</code></pre>\n\n<p>Of course, this gives you a count, which is more information that was asked for, but this will probably be pretty efficient if you have an index on blog_id.</p>\n\n<p>Another alternative is to union together a result of the blogs that have comments with another result of the blogs that don't have comments.</p>\n\n<pre><code>SELECT blog_id, true\nFROM blogs\nWHERE\n EXISTS (\n SELECT true\n FROM comments\n WHERE\n comments.blog_id = blogs.blog_id\n )\n\nUNION ALL\n\nSELECT blog_id, false\nFROM blogs\nWHERE\n NOT EXISTS (\n SELECT true\n FROM comments\n WHERE\n comments.blog_id = blogs.blog_id\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T07:08:38.233", "Id": "12925", "Score": "0", "body": "Thanks it going to be interesting to see the performance between count+group vs exists. And in your second solution you put subquery in the where where mine is in the select. Will have to do some benchmarks here. I am going to mark this as the correct solution. But will update this question with the benchmarks later this week." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T14:38:05.263", "Id": "12932", "Score": "0", "body": "@Contra - I'm not sure about MySQL, but I believe that in older versions of SQL Server, you would get better performance by putting an \"exists\" condition in the where clause rather than as a column in the result. I believe that modern versions of SQL Server are intelligent enough to optimize the query either way, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T18:40:58.520", "Id": "8258", "ParentId": "8246", "Score": "1" } } ]
{ "AcceptedAnswerId": "8258", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T10:30:55.207", "Id": "8246", "Score": "2", "Tags": [ "mysql", "sql" ], "Title": "MySQL query: blog entry has comments or not" }
8246
<p>I looked at the <a href="http://pypi.python.org/pypi?:action=list_classifiers" rel="nofollow">pypi classifiers</a> and <a href="http://wiki.python.org/moin/PyPiXmlRpc" rel="nofollow">some guide</a> to help me write the following script, and here's me wondering if it can be improved:</p> <pre><code>import xmlrpc.client # pypi language version classifiers PY3 = ["Programming Language :: Python :: 3"] PY2 = ["Programming Language :: Python :: 2"] PY27 = ["Programming Language :: Python :: 2.7"] PY26 = ["Programming Language :: Python :: 2.6"] PY25 = ["Programming Language :: Python :: 2.5"] PY24 = ["Programming Language :: Python :: 2.4"] PY23 = ["Programming Language :: Python :: 2.3"] def main(): client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi') # get module metadata py3names = [name[0] for name in client.browse(PY3)] py2names = [name[0] for name in client.browse(PY2)] py27names = [name[0] for name in client.browse(PY27)] py26names = [name[0] for name in client.browse(PY26)] py25names = [name[0] for name in client.browse(PY25)] py24names = [name[0] for name in client.browse(PY24)] py23names = [name[0] for name in client.browse(PY23)] cnt = 0 for py3name in py3names: if py3name not in py27names \ and py3name not in py26names \ and py3name not in py25names \ and py3name not in py24names \ and py3name not in py23names \ and py3name not in py2names: cnt += 1 print("Python3-only packages: {}".format(cnt)) main() </code></pre> <p><strong>Sidenote</strong>:</p> <pre><code>$ time python3 py3k-only.py Python3-only packages: 259 real 0m17.312s user 0m0.324s sys 0m0.012s </code></pre> <p>In addition, can you spot any functionality bugs in there? Will it give accurate results, assuming that pypi has correct info?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T08:03:35.633", "Id": "12968", "Score": "0", "body": "[**a more complete script**](http://stackoverflow.com/a/9012768)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:57:08.127", "Id": "116565", "Score": "0", "body": "@jamal you killed the evolution of the Question, and now the Answer looks odd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:57:46.420", "Id": "116566", "Score": "0", "body": "The answer was never edited, though. It had to correspond to just the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:59:22.690", "Id": "116567", "Score": "0", "body": "Yeah, but look at *Why do you have a single string in a list?* for example. You got rid of that part of the original Question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:00:39.853", "Id": "116570", "Score": "0", "body": "I still see that in this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:04:45.030", "Id": "116573", "Score": "0", "body": "Oh, I see my mistake. I still unlove your Edit, because my Question showed the progress as I made the code better, as a result of feedback. You simply made that disappear. Your deed makes me sad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:16:09.840", "Id": "116575", "Score": "0", "body": "Only thing I like is title change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T20:24:59.977", "Id": "116592", "Score": "0", "body": "I'm sorry, but it's to help make the post easier to follow. You can still post a follow-up if you'd like further review, or a self-answer if you want to show your improvements (but they'll have to explain the changes). The Help Center now explains this in depth." } ]
[ { "body": "<pre><code>import xmlrpc.client\n\n# pypi language version classifiers\nPY3 = [\"Programming Language :: Python :: 3\"]\n</code></pre>\n\n<p>Why do you have a single string in a list?</p>\n\n<pre><code>PY2 = [\"Programming Language :: Python :: 2\"]\nPY27 = [\"Programming Language :: Python :: 2.7\"]\nPY26 = [\"Programming Language :: Python :: 2.6\"]\nPY25 = [\"Programming Language :: Python :: 2.5\"]\nPY24 = [\"Programming Language :: Python :: 2.4\"]\nPY23 = [\"Programming Language :: Python :: 2.3\"]\n</code></pre>\n\n<p>You should put all these strings in one list.</p>\n\n<pre><code>def main():\n client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi')\n\n # get module metadata\n py3names = [name[0] for name in client.browse(PY3)]\n py2names = [name[0] for name in client.browse(PY2)]\n py27names = [name[0] for name in client.browse(PY27)]\n py26names = [name[0] for name in client.browse(PY26)]\n py25names = [name[0] for name in client.browse(PY25)]\n py24names = [name[0] for name in client.browse(PY24)]\n py23names = [name[0] for name in client.browse(PY23)]\n</code></pre>\n\n<p>If you put the python 2.x versions in a one list, you should be able to fetch all this data\ninto one big list rather then all of these lists.</p>\n\n<pre><code> cnt = 0\n</code></pre>\n\n<p>Don't uselessly abbreviate, spell out <code>counter</code></p>\n\n<pre><code> for py3name in py3names:\n if py3name not in py27names \\\n and py3name not in py26names \\\n and py3name not in py25names \\\n and py3name not in py24names \\\n and py3name not in py23names \\\n and py3name not in py2names:\n cnt += 1\n</code></pre>\n\n<p>I'd do something like: <code>python3_only = [name for name in py3name if py3name not in py2names]</code>. Then I'd get the number of packages as a len of that.</p>\n\n<pre><code> print(\"Python3-only packages: {}\".format(cnt))\n\nmain()\n</code></pre>\n\n<p>Usually practice is to the call to main inside <code>if __name__ == '__main__':</code> so that it only gets run if this script is the main script.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T11:17:50.083", "Id": "12930", "Score": "0", "body": "I think you meant `py3only = [name for name in py3names if name not in py2names]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T11:20:03.870", "Id": "12931", "Score": "0", "body": "BTW, with your suggested change to put all Python 2 classifiers in one list, the only modules that get excluded are those which match all the Python 2 classifiers. That is, my output includes a lot of packages that also have Python 2 versions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T14:59:22.510", "Id": "12933", "Score": "1", "body": "@Tshepang, yes on the first comment, not if you do it properly on the second comment. I didn't expressly state how to do it, but you can go through the list, pass each element to the client.browse() one at a time, and then combine the lists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T22:07:09.930", "Id": "12952", "Score": "0", "body": "@Tshepang, yes that's the idea. But you'd be better off to use a list literal instead of the append lines to build `PY2` you might also consider using a nested list comprehension in the fetch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:16:36.647", "Id": "12959", "Score": "1", "body": "@Tshepang, ` py2names = [name[0] for classifier in PY2 \n for name in client.browse([classifier])]`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:49:30.193", "Id": "8260", "ParentId": "8259", "Score": "3" } } ]
{ "AcceptedAnswerId": "8260", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:07:49.007", "Id": "8259", "Score": "5", "Tags": [ "python" ], "Title": "Checking which pypi packages are Py3k-only" }
8259
<p>I've been working on this class for a while now and would appreciate some feedback, even if it's just nitpicking. I've added basic instructions on how to use the class below along with some questions.</p> <pre><code>&lt;?php /** * @category Security * @version 1.0 * @author First Last &lt;email@mail.com&gt; * */ class SessionHandler { /** * @description PDO database handle * @access private * @var PDO database resource * */ private $_db = NULL; /** * @description Database table name where sessions are stored. * @access private * @var string * */ private $_table_name = 'sessions'; /** * @description Cookie name where the session ID is stored. * @access private * @var string * */ private $_cookie_name = 'session_cookie'; /** * @description Number of seconds before the session expires. Default is 2 hours. * @access private * @var integer * */ private $_seconds_till_expiration = 7200; // 2 hours /** * @description Number of seconds before the session ID is regenerated. Default is 5 minutes. * @access private * @var integer * */ private $_renewal_time = 300; // 5 minutes /** * @description Closes the session when the browser is closed. * @access private * @var boolean * */ private $_expire_on_close = FALSE; /** * @description IP address that will be checked against the database if enabled. Must be a valid IP address. * @access private * @var string * */ private $_ip_address = FALSE; /** * @description User agent that will be checked against the database if enabled. * @access private * @var string * */ private $_user_agent = FALSE; /** * @description Will only set the session cookie if a secure HTTPS connection is being used. * @access private * @var boolean * */ private $_secure_cookie = FALSE; /** * @description A hashed string which is the ID of the session. * @access private * @var string * */ private $_session_id = ''; /** * @description Data stored by the user. * @access private * @var array * */ private $_data = array(); /** * @description Initializes the session handler. * @access public * @param array - configuration options * @return void * */ public function __construct(array $config) { // Sets user configuration $this-&gt;_setConfig($config); // Runs the session mechanism if ($this-&gt;_read()) { $this-&gt;_update(); } else { $this-&gt;_create(); } // Cleans expired sessions if necessary and writes cookie $this-&gt;_cleanExpired(); $this-&gt;_setCookie(); } /** * @description Regenerates a new session ID for the current session. * @access public * @return void * */ public function regenerateId() { // Acquires a new session ID $old_session_id = $this-&gt;_session_id; $this-&gt;_session_id = $this-&gt;_generateId(); // Updates session ID in the database $stmt = $this-&gt;_db-&gt;prepare("UPDATE {$this-&gt;_table_name} SET time_updated = ?, session_id = ? WHERE session_id = ?"); $stmt-&gt;execute(array(time(), $this-&gt;_session_id, $old_session_id)); // Updates cookie $this-&gt;_setCookie(); } /** * @description Sets a specific item to the session data array. * @access public * @param string - session data array key * @param string - data value * @return void * */ public function setData($key, $value) { $this-&gt;_data[$key] = $value; $this-&gt;_write(); // Writes to database } /** * @description Unsets a specific item from the session data array. * @access public * @param string - session data array key * @return void * */ public function unsetData($key) { if (isset($this-&gt;_data[$key])) unset($this-&gt;_data[$key]); } /** * @description Returns a specific item from the session data array. * @access public * @param string - session data array key * @return string - data value/FALSE * */ public function getData($key) { return isset($this-&gt;_data[$key]) ? $this-&gt;_data[$key] : FALSE; } /** * @description Returns all items in the session data array. * @access public * @return array * */ public function getAllData() { return $this-&gt;_data; } /** * @description Destroys the current session. * @access public * @return void * */ public function destroy() { // Deletes session from the database if (isset($this-&gt;_session_id)) { $stmt = $this-&gt;_db-&gt;prepare("DELETE FROM {$this-&gt;_table_name} WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); } // Kills the cookie setcookie( $this-&gt;_cookie_name, '', time() - 31500000, NULL, NULL, NULL, NULL ); } /** * @description The main session mechanism: * - Reads session cookie and retrives session data * - Checks session expiration * - Verifies IP address (if enabled) * - Verifies user agent (if enabled) * @access private * @return void * */ private function _read() { // Fetches session cookie $session_id = isset($_COOKIE[$this-&gt;_cookie_name]) ? $_COOKIE[$this-&gt;_cookie_name] : FALSE; // Cookie doesn't exist! if (! $session_id) { return FALSE; } $this-&gt;_session_id = $session_id; // Fetches the session from the database $stmt = $this-&gt;_db-&gt;prepare("SELECT data, time_updated, user_agent, ip_address FROM {$this-&gt;_table_name} WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); $result = $stmt-&gt;fetch(PDO::FETCH_ASSOC); // Did a session exist? if ($result !== FALSE &amp;&amp; count($result) &gt; 0) { // Checks if the session has expired in the database if (! $this-&gt;_expire_on_close) { if (($result['time_updated'] + $this-&gt;_seconds_till_expiration) &lt; time()) { $this-&gt;destroy(); return FALSE; } } // Checks if the user's IP address matches the one saved in the database if ($this-&gt;_ip_address) { if ($result['ip_address'] != $this-&gt;_ip_address) { $this-&gt;_flagForUpdate(); return FALSE; } } // Checks if the user's user agent matches the one saved in the database if ($this-&gt;_user_agent) { if ($result['user_agent'] != $this-&gt;_user_agent) { $this-&gt;_flagForUpdate(); return FALSE; } } // Checks if the session has been requested to regenerate a new ID (hack attempt) $this-&gt;_checkUpdateFlag(); // Checks if the session ID needs to be renewed (time exceeded) $this-&gt;_checkIdRenewal(); // Sets user data $user_data = unserialize($result['data']); if ($user_data) { $this-&gt;_data = $user_data; unset($user_data); } // All good! return TRUE; } // No session found return FALSE; } /** * @description Creates a session. * @access private * @return void * */ private function _create() { // Generates session ID $this-&gt;_session_id = $this-&gt;_generateId(); // Inserts session into database $stmt = $this-&gt;_db-&gt;prepare("INSERT INTO {$this-&gt;_table_name} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)"); $stmt-&gt;execute(array($this-&gt;_session_id, $this-&gt;_user_agent, $this-&gt;_ip_address, time())); } /** * @description Updates a current session. * @access private * @return void * */ private function _update() { // Updates session in database $stmt = $this-&gt;_db-&gt;prepare("UPDATE {$this-&gt;_table_name} SET time_updated = ? WHERE session_id = ?"); $stmt-&gt;execute(array(time(), $this-&gt;_session_id)); } /** * @description Writes session data to the database. * @access private * @return void * */ private function _write() { // Custom data doesn't exist if (count($this-&gt;_data) == 0) { $custom_data = ''; } else { $custom_data = serialize($this-&gt;_data); } // Writes session data to database $stmt = $this-&gt;_db-&gt;prepare("UPDATE {$this-&gt;_table_name} SET data = ?, time_updated = ? WHERE session_id = ?"); $stmt-&gt;execute(array($custom_data, time(), $this-&gt;_session_id)); } /** * @description Sets session cookie. * @access private * @return void * */ private function _setCookie() { setcookie( $this-&gt;_cookie_name, $this-&gt;_session_id, ($this-&gt;_expire_on_close) ? 0 : time() + $this-&gt;_seconds_till_expiration, // Expiration timestamp NULL, NULL, $this-&gt;_secure_cookie, // Will cookie be set without HTTPS? TRUE // HttpOnly ); } /** * @description Removes expired sessions from the database. * @access private * @return void * */ private function _cleanExpired() { // 0.1 % chance to clean the database of expired sessions if (mt_rand(1, 1000) == 1) { $stmt = $this-&gt;_db-&gt;prepare("DELETE FROM {$this-&gt;_table_name} WHERE (time_updated + {$this-&gt;_seconds_till_expiration}) &lt; ?"); $stmt-&gt;execute(array(time())); } } /** * @description Creates a unique session ID. * @access private * @return string * */ private function _generateId() { $salt = 'x7^!bo3p,.$$!$6[&amp;Q.#,//@i"%[X'; $random_number = mt_rand(0, mt_getrandmax()); $ip_address_fragment = md5(substr($_SERVER['REMOTE_ADDR'], 0, 5)); $timestamp = md5(microtime(TRUE) . time()); $hash_data = $random_number . $ip_address_fragment . $salt . $timestamp; $hash = hash('sha256', $hash_data); return $hash; } /** * @description Checks if the session ID needs to be regenerated and does so if necessary. * @access private * @return void * */ private function _checkIdRenewal() { // Gets the last time the session was updated $stmt = $this-&gt;_db-&gt;prepare("SELECT time_updated FROM {$this-&gt;_table_name} WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); $result = $stmt-&gt;fetch(PDO::FETCH_ASSOC); if ($result !== FALSE &amp;&amp; count($result) &gt; 0) { // Checks if the session ID has exceeded it's permitted lifespan. if ((time() - $this-&gt;_renewal_time) &gt; $result['time_updated']) { // Regenerates a new session ID $this-&gt;regenerateId(); } } } /** * @description Flags a session so that it will receive a new ID on the next subsequent request. * @access private * @return void * */ private function _flagForUpdate() { $stmt = $this-&gt;_db-&gt;prepare("UPDATE {$this-&gt;_table_name} SET flagged_for_update = '1' WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); } /** * @description Checks if the session has been requested to regenerate a new ID and does so if necessary. * @access private * @return void * */ private function _checkUpdateFlag() { // Gets flagged status $stmt = $this-&gt;_db-&gt;prepare("SELECT flagged_for_update FROM {$this-&gt;_table_name} WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); $result = $stmt-&gt;fetch(PDO::FETCH_ASSOC); if ($result !== FALSE &amp;&amp; count($result) &gt; 0) { // Flagged? if ($result['flagged_for_update']) { // Creates a new session ID $this-&gt;regenerateId(); // Updates database $stmt = $this-&gt;_db-&gt;prepare("UPDATE {$this-&gt;_table_name} SET flagged_for_update = '0' WHERE session_id = ?"); $stmt-&gt;execute(array($this-&gt;_session_id)); } } } /** * @description Sets configuration. * @access private * @param array - configuration options * @return void * */ private function _setConfig(array $config) { // Sets database handle if (isset($config['database'])) { $this-&gt;_db = $config['database']; } else { throw new Exception('Database handle not set!'); } // -------------------------------------------- // Cookie name if (isset($config['cookie_name'])) { // Checks if alpha-numeric if (! ctype_alnum(str_replace(array('-', '_'), '', $config['cookie_name']))) { throw new Exception('Invalid cookie name!'); } $this-&gt;_cookie_name = $config['cookie_name']; } // -------------------------------------------- // Database table name if (isset($config['table_name'])) { // Checks if alpha-numeric if (! ctype_alnum(str_replace(array('-', '_'), '', $config['table_name']))) { throw new Exception('Invalid table name!'); } $this-&gt;_table_name = $config['table_name']; } // -------------------------------------------- // Expiration time in seconds if (isset($config['seconds_till_expiration'])) { // Anything else than digits? if (! is_int($config['seconds_till_expiration']) || ! preg_match('#[0-9]#', $config['seconds_till_expiration'])) { throw new Exception('Seconds till expiration must be a valid number.'); } // Negative number or zero? if ($config['seconds_till_expiration'] &lt; 1) { throw new Exception('Seconds till expiration can not be zero or less. Enable session expiration when the browser closes instead.'); } $this-&gt;_seconds_till_expiration = (int) $config['seconds_till_expiration']; } // -------------------------------------------- // End the session when the browser is closed? if (isset($config['expire_on_close'])) { // Not TRUE or FALSE? if (! is_bool($config['expire_on_close'])) { throw new Exception('Expire on close must be either TRUE or FALSE.'); } $this-&gt;_expire_on_close = $config['expire_on_close']; } // -------------------------------------------- // How often should the session be renewed? if (isset($config['renewal_time'])) { // Anything else than digits? if (! is_int($config['renewal_time']) || ! preg_match('#[0-9]#', $config['renewal_time'])) { throw new Exception('Session renewal time must be a valid number.'); } // Negative number or zero? if ($config['renewal_time'] &lt; 1) { throw new Exception('Session renewal time can not be zero or less.'); } $this-&gt;_renewal_time = (int) $config['renewal_time']; } // -------------------------------------------- // Check IP addresses? if (isset($config['check_ip_address'])) { // Not a string? if (! is_string($config['check_ip_address'])) { throw new Exception('The IP address must be a string similar to this: \'172.16.254.1\'.'); } // Invalid IP? if (! preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $config['check_ip_address'])) { throw new Exception('Invalid IP address.'); } $this-&gt;_ip_address = $config['check_ip_address']; } // -------------------------------------------- // Check user agent? if (isset($config['check_user_agent'])) { $this-&gt;_user_agent = substr($config['check_user_agent'], 0, 999); } // -------------------------------------------- // Send cookie only when HTTPS is enabled? if (isset($config['secure_cookie'])) { if (! is_bool($config['secure_cookie'])) { throw new Exception('The secure cookie option must be either TRUE or FALSE.'); } $this-&gt;_secure_cookie = $config['secure_cookie']; } } } </code></pre> <p>Here is how you would use the class. Notice how I have commented out the configuration options, this is because these are all set internally by default to give me a cleaner outside injection of configs so that I can omit them. I also inject the IP/UA so that it can be acquired in a proper manner which is not the job of the session class.</p> <pre><code>&lt;?php // Database connection $pdo = new PDO('mysql:host=localhost;dbname=security', 'root', '', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING)); // ----------------------------------------------------------------------------------------- // Loads session handler include_once('classes/session-class.php'); // SESSION HANDLER CONFIGRATION $config['database'] = $pdo; // PDO Database handle /* $config['cookie_name'] = 'session_cookie'; // Name of the cookie $config['table_name'] = 'sessions'; // Database table name $config['seconds_till_expiration'] = 7200; // How many seconds it takes before the session expires. Default is 2 hours. $config['renewal_time'] = 300; // How many seconds it takes before the session ID is renewed. Default is 5 minutes. $config['expire_on_close'] = FALSE; // The session is terminated when the browser is closed. $config['secure_cookie'] = FALSE; // Decides whether the cookie should only be set when a HTTPS connection exists. $config['check_ip_address'] = $_SERVER['REMOTE_ADDR']; // Will check the user's IP address against the one stored in the database. Make sure this is a string which is a valid IP address. FALSE by default. $config['check_user_agent'] = $_SERVER['HTTP_USER_AGENT']; // Will check the user's user agent against the one stored in the database. FALSE by default. */ try { $session = new SessionHandler($config); } catch (Exception $e) { echo $e-&gt;getMessage(); exit; } </code></pre> <p><strong>Questions:</strong></p> <ol> <li>How can I improve the existing code?</li> <li>Any obvious security or logic flaws?</li> <li>Documented/commented well enough or too extensively?</li> <li>For variables that are strings that will get set: use <code>FALSE</code> or <code>NULL</code> as default value? (e.g. <code>$_user_agent = FALSE</code> vs <code>NULL;</code>)</li> <li>A better way to check for valid integers?</li> <li>The <code>_setConfig()</code> method. Nasty or not? Is splitting it into smaller methods pointless?</li> <li>Is there any benefit of commenting class variables?</li> <li><code>@param void</code> and <code>@return void</code> unnecessary?</li> <li>Is it safe to omit single quotes for values in a database query with prepared statements? <code>?</code> vs <code>'?'</code>.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T14:10:22.753", "Id": "91698", "Score": "0", "body": "This question has a lot of views, so I'm assuming people are using your code. Would you mind posting your completed class in an edit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T18:03:21.277", "Id": "91753", "Score": "0", "body": "I haven't looked at this code in years and would recommend anyone planning to use it to read through it carefully before doing so. I quit this project in favor of starting a more modular and unit tested one, but from reading that one I couldn't verify if it was any more stable than this production wise as I left php shortly after, so I decided not to post it. The code here might work as expected, but I would not advise anyone to use this untested code. Do not take the code here as an example of good coding, but as a learning reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T19:22:40.797", "Id": "91766", "Score": "0", "body": "Thanks for the update. It looked like you may have been prepping this to release it publicly, which is why I asked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-04T09:41:51.803", "Id": "181417", "Score": "0", "body": "Your code is near to perfect !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-04T20:53:18.667", "Id": "181542", "Score": "0", "body": "@n01ze I disagree. This class is nothing but a facade for database operations and thus send them all individually instead of as a transaction (where would be possible). It also has way too many responsibilities and was for that reason a pain to debug (yes, I still remember!). To top it off, this lead to subtle, yet dangerous bugs that could compromise the whole security of the session mechanism altogether (yes, I remember this too, it was that bad!). As I mentioned above; learning reference only, don't take this as an example of good code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T04:12:42.510", "Id": "181594", "Score": "0", "body": "@Seralize Yep may be you are right , but the way you utilize all oop concept , DI etc are really commendable.And I liked the Doc Block too, its clear and very descriptive.Any ways Here you are just playing with Cookies, according to me it would be much better to manipulate SESSION from php's session handler interface or just function.Your class gave a idea , based on that I am gonna write a Session handling class that takes Session interface handlers into account.Thanks mate , Good Day" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-10T08:47:16.037", "Id": "183488", "Score": "0", "body": "@Seralize check my class that overwrite php default session handlers http://codereview.stackexchange.com/questions/100448/simple-php-session-handler-class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-13T14:58:29.320", "Id": "239937", "Score": "0", "body": "What exactly is the point of `@access private` when the method clearly states that it is private?" } ]
[ { "body": "<p>Your code looks very good. I like the way you are using Dependency Injection. This code is a good example for other people to follow.</p>\n\n<p>Here are just a few points, seeing as no-one else has answered.</p>\n\n<blockquote>\n <p><strong>1. How can I improve the existing code?</strong> </p>\n</blockquote>\n\n<p>Move the work that you do while constructing the object out of the constructor. Miško Hevery says it better than i could <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"noreferrer\">here.</a> Basically it makes it harder for you to test or extend the object. What I would do is replace your constructor with your setConfig method code as it is checking the configuration of the object you are creating (which is a good thing to do while constructing your object).</p>\n\n<p>I would rewrite it with all of the checks and exceptions thrown first and then an assignment of all the fields done at the end of the constructor.</p>\n\n<p>I would move the following from the constructor:</p>\n\n<pre><code>// Runs the session mechanism\nif ($this-&gt;_read()) {\n $this-&gt;_update();\n} else {\n $this-&gt;_create();\n}\n</code></pre>\n\n<p>and make it a public method which would be called after the object was constructed. I'm not sure what you would call it. To me it looks like the whole thing could be named <code>update</code> because it updates or creates the session.</p>\n\n<p>I would also move the cleanExpired and setCookie out of the constructor. I'm not sure that cleanExpired really belongs with this class. At least with it as a separate method you would have more control over the time at which it was called.</p>\n\n<hr>\n\n<p>Very minor: Consider arranging the methods alphabetically within the class.</p>\n\n<p>Very minor: I think 1 <code>if</code> statement is better than 2, consider changing the following:</p>\n\n<pre><code> if (! $this-&gt;_expire_on_close)\n {\n if (($result['time_updated'] + $this-&gt;_seconds_till_expiration) &lt; time())\n</code></pre>\n\n<p>to:</p>\n\n<pre><code> if (! $this-&gt;_expire_on_close &amp;&amp;\n (($result['time_updated'] + $this-&gt;_seconds_till_expiration) &lt; time()))\n</code></pre>\n\n<p>the logic is grouped together and is very readable.</p>\n\n<blockquote>\n <p><strong>2. Any obvious security or logic flaws?</strong></p>\n</blockquote>\n\n<p>No obvious ones that I can see, but I didn't look very hard and am not a security expert. I'd recommend checking out the password salting answers on stack overflow for specific advice on that.</p>\n\n<blockquote>\n <p><strong>3. Documented/commented well enough or too extensively?</strong></p>\n</blockquote>\n\n<p>Looks good, it is nice to see the docblock comments.</p>\n\n<blockquote>\n <p><strong>4. For variables that are strings that will get set: use FALSE or NULL as default value? (e.g. $_user_agent = FALSE vs NULL;)</strong></p>\n</blockquote>\n\n<p>My preference is for NULL. It makes the check seem more natural:</p>\n\n<pre><code> if (isset($_user_agent) &amp;&amp;\n // vs the more magical / less self explanatory.\n if (($_user_agent) &amp;&amp;\n</code></pre>\n\n<blockquote>\n <p><strong>5. A better way to check for valid integers?</strong></p>\n</blockquote>\n\n<p>I have heard that the <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"noreferrer\">PHP filter functions</a> are good for this sort of thing.</p>\n\n<blockquote>\n <p><strong>6. The _setConfig() method. Nasty or not? Is splitting it into smaller methods pointless?</strong></p>\n</blockquote>\n\n<p>See 1. I wouldn't split it up.</p>\n\n<blockquote>\n <p><strong>7. Is there any benefit of commenting class variables?</strong></p>\n</blockquote>\n\n<p>Up to you. Is @access needed? I thought that was generated automatically?</p>\n\n<blockquote>\n <p><strong>8. @param void and @return void unnecessary?</strong></p>\n</blockquote>\n\n<p>Yes, I think they are unnecessary.</p>\n\n<blockquote>\n <p><strong>9. Is it safe to omit single quotes for values in a database query with prepared statements? ? vs '?'.</strong></p>\n</blockquote>\n\n<p>Yes, the ? is a placeholder, trying to use '?' would make it a value and the query would no longer work (I think).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T01:41:03.733", "Id": "13559", "Score": "0", "body": "I've modified the class ever so slightly since posting the review and funnily enough I had already changed it in most ways as suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-10T20:32:15.287", "Id": "382272", "Score": "0", "body": "how do i store and echo session values. a small documentation would be helpful i tried `<?php\n include_once('classes/session-class.php');\n session_start();\n $session = new mySessionHandler($config);\n // put your code here\n echo $config['cookie_name'];\n ?>` this doesn't work" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-10T23:27:44.643", "Id": "382287", "Score": "0", "body": "You would need to look at the public methods of the class `SessionHandler` (not `mySessionHandler`). It looks like the `setData` and `getData` methods could help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-22T06:36:18.450", "Id": "384934", "Score": "0", "body": "@Paul when i restart browser it doesn't update it create a new session in database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-23T06:58:43.400", "Id": "385019", "Score": "1", "body": "Perhaps the config option for `expire_on_close` but @Seralize is the one who wrote the code. They would know better." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T07:56:21.837", "Id": "8445", "ParentId": "8261", "Score": "7" } }, { "body": "<p>A point on style... In all languages, I've always considered the underscore prefix to indicate reserved words, constants etc (PHP uses it for $_SESSION, $_GET and so forth, which fits this convention).</p>\n\n<p>So better to use a <em>trailing</em> underscore in your class members, if you must use one at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T19:45:09.567", "Id": "42696", "ParentId": "8261", "Score": "1" } } ]
{ "AcceptedAnswerId": "8445", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:06:28.613", "Id": "8261", "Score": "27", "Tags": [ "php", "security", "session" ], "Title": "Custom session handler class - is it robust enough?" }
8261
<p>I am using this code for a fast JSON API without routes.</p> <p>Does this code contain any useless parts? Is the class loader efficient enough? Are there any better options? Is <code>ReflectionMethod</code> slow if used once?</p> <pre><code>&lt;?php /* * Init stuff */ session_start(); define('ROOT', realpath( dirname(__FILE__) ) . '/'); set_include_path(ROOT . 'src/'); spl_autoload_extensions('.php'); spl_autoload_register(); ini_set('error_reporting', E_ALL &amp; ~E_DEPRECATED); ini_set('display_errors', 1); //To change in prod to 0 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; ini_set('log_errors', 1); ini_set('error_log', ROOT . 'tmp/logs/application.log'); date_default_timezone_set('Europe/Paris'); /* * Process stuff */ $params = explode( '/', trim( key($_GET), '/' ) ); $paramsCount = count($params); if ($paramsCount &gt;= 2) { try { $controllerMethod = new ReflectionMethod( '\app\controller\\' . $params[1], $params[2] ); if ($paramsCount - 2 &gt;= $controllerMethod-&gt;getNumberOfRequiredParameters()) { \ens\controller\Request::$lang =&amp; $params[0]; \ens\controller\Request::$data =&amp; $_POST; $response = $controllerMethod-&gt;invokeArgs( null, array_splice($params, 3) ); } else { $response = array('status' =&gt; 400); } } catch (ReflectionException $e) { $response = array('status' =&gt; 300); } } else { $response = array('status' =&gt; 301); } if (!headers_sent()) { header('Content-Type: application/json'); } echo json_encode($response); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T23:09:04.390", "Id": "12910", "Score": "0", "body": "Have you benchmarked it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T23:12:08.443", "Id": "12911", "Score": "0", "body": "You mean the class loader?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T01:15:49.057", "Id": "12916", "Score": "1", "body": "Yeah, you ask if it's efficient enough. Have you run into performance problems that would suggest that it isn't?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T09:29:49.043", "Id": "12927", "Score": "0", "body": "The problem with benchmarking a class loader is that the class is loaded only once. So I don't know in what kind of loop to put it! I am thinking about a shell benchmark or generating some thousands random classes and loading them all? Can one of these work better than another? I saw that the default spl_autoload() is making stat-ing files before loading." } ]
[ { "body": "<p>I don't think there are any useless parts. It's quite easy to read actually!</p>\n\n<ol>\n<li>No validation at all of $_GET and $_POST? It doesn't look like namespaces support relative navigations, but that seems a bit dangerous, except if you can Always Trust User Input.</li>\n<li>The \"init stuff\" could be put in another file and required.</li>\n<li>ÉNS is a bit weird for an application name (private joke, sorry).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T17:15:02.200", "Id": "15352", "Score": "0", "body": "First, thank you for review. 1. Q: What is relative navigation[namespaces]? 2. Good for styling. 3. ENS is a acronym." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:23:04.070", "Id": "15386", "Score": "0", "body": "1. \\ens\\controller\\..\\super_secret::DestroyEverything 3. I was thinking about the École Normale Supérieure, that's all. -- By the way, I don't have much to say, because I think it's quite good as it is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T09:04:35.743", "Id": "9689", "ParentId": "8262", "Score": "1" } }, { "body": "<p>IMHO, all the <code>ini_set</code> doesn't belong here, but in the php.ini, unless you can't edit it for some reasons…</p>\n\n<p>If so, it belong in a <a href=\"http://www.serversidemagazine.com/php/bootstrap-php-code/\" rel=\"nofollow\">bootstrap file</a>, as for the constant definitions and the include</p>\n\n<blockquote>\n <p>A bootstrap file usually starts by including those libraries that are necessary for the file itself to function correctly. This involves setting general directory and file paths, loading configuration files, etc.</p>\n</blockquote>\n\n<p>This bootstrap file can also be very useful for many reasons described on the link i provided like:</p>\n\n<blockquote>\n <p>[…] set up different application statuses such as Development, Production or Testing […]</p>\n</blockquote>\n\n<p>An other thing:</p>\n\n<p>IMHO, the test <code>if (!headers_sent())</code> is pretty useless <em>as is</em>.</p>\n\n<p>As you are returning JSON, you <strong>need</strong> to send this <code>header('Content-Type: application/json')</code>, so, if you can't for any reason, you should raise an error or an exception, not just doing nothing and echoing your JSON as if nothing happened…</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T05:25:03.527", "Id": "10204", "ParentId": "8262", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:09:19.927", "Id": "8262", "Score": "7", "Tags": [ "php", "performance", "reflection", "controller", "url-routing" ], "Title": "Dispatcher for a JSON API without routes" }
8262
<p>I'm a complete beginner in Python and programming in general. I made a program for <strong><a href="http://www.spotify.com/us/jobs/tech/best-before/" rel="nofollow">Spotify's Best Before puzzle</a></strong>. It was accepted. I have looked a litle around on internet and looked at other solutions to the problem, and everyone I have seen have importet several modules, inclusive the Calendar module. I understand this is probably a good solution, but I wanted to make everything myself as a practice.</p> <p>I would really appreciate all tips and hint, but mainly without haveing to import code. It's primarily the <code>printer(a)</code> and det <code>dataMaker()</code> that needs modification.</p> <pre><code>normYear = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] leapYear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] answerList = [] u''' Check if any of the integers are years ''' def yearCheck(): for x in xrange(0, 3): a = dataList[x] if len(a) &gt; 2: if not len(a) == 4 and int(a) in xrange(2000,3000): if int(a) in xrange(100,1000): dataList[x] = int(a) + 2000 else: print data + u" is illegal" u''' Make integers and sort ''' def integer(): for x in xrange(0, 3): dataList[x] = int(dataList[x]) dataList.sort() u''' Check for possible leap years ''' def leapYears(): global leapList leapList = [] for x in xrange(0, 3): if dataList[x] % 4 == 0: if dataList[x] % 100 == 0: if dataList[x] % 400 == 0: leapList.append(x) else: leapList.append(x) u''' Changes year type ''' def defYear(a): global xYear if a in leapList: xYear = leapYear else: xYear = normYear u''' Printer ''' def printer(a): if dataList[a] &lt; 2000: dataList[a] += 2000 year = dataList[a] del dataList[a] if not dataList[0] == 0: month = dataList.pop(0) day = dataList.pop(0) answerList.append(unicode(year)) answerList.append(unicode(u'%02d' % month)) answerList.append(unicode(u'%02d' % day)) print u'-'.join(answerList) else: print data + u" is illegal" u''' Looks for legal dates, first [Y&lt;M&lt;D] then [M&lt;Y&lt;D] then [M,D,Y] ''' def dateMaker(): for x in xrange(0,4): defYear(x) if x == 0: if dataList[1] &lt;= 12 and dataList[2] &lt;= xYear[dataList[1]-1]: printer(x) break elif x == 1: if dataList[0] &lt;= 12 and dataList[2] &lt;= xYear[dataList[0]-1]: printer(x) break elif x == 2: if dataList[0] &lt;= 12 and dataList[1] &lt;= xYear[dataList[0]-1]: printer(x) break else: print data + u" is illegal" u''' Program ''' data = raw_input() dataList = data.split(u"/") yearCheck() integer() leapYears() dateMaker() </code></pre>
[]
[ { "body": "<p>First of all, the code is hard to read because :</p>\n\n<ul>\n<li>almost all the functions access global values. it is much better to send a value as a parameter, it makes the flow explicit.</li>\n<li>the list is modified in place; again this makes hard to know which version of the list a function is manipulating. create new version for each pass of the processing.</li>\n<li>Many python idioms are not used ( like the <code>for x in list</code>)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T22:12:59.477", "Id": "8265", "ParentId": "8263", "Score": "3" } }, { "body": "<ol>\n<li>You have unicode strings as comments. Just use comments.</li>\n<li>You rely on manipulating global state, not a good idea. Instead,\nhave function return things. You don't use any return statements\nanywhere in your code. </li>\n<li>You use <code>not a == b</code> instead of <code>a != b</code> in several places</li>\n<li>You use <code>a in xrange(b,c)</code> where <code>b &lt;= a &lt; c</code> would be better</li>\n<li>All of your for loops use xrange, usually you want to iterate over the container directly</li>\n<li>Your yearCheck function doesn't do anything. The <code>if</code> condition is impossible to satisfy. It looks like you discovered this, because you've implemented the logic down in the printer function. </li>\n<li>You delay converting the data components to integer, this only serves to complexicate your code.</li>\n<li>You generate a list of leap years, but you only ever check the years 0, 1, 2 and 3. </li>\n<li>You keep the data inside the list the whole time. Code is easier to follow if you don't do that. Pull the data out of lists into local variables rather then indexing into the list.</li>\n</ol>\n\n<p>Here is a reworking of your approach:</p>\n\n<pre><code>NORMAL_MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\nLEAP_MONTHS = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ndef get_month_lengths(year): \n \"\"\"\n Returns appropriate months for a particular year\n \"\"\"\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n return LEAP_MONTHS\n else:\n return LEAP_MONTHS\n return NORMAL_MONTHS\n\n\ndef print_date(year, month, day):\n \"\"\"\n Print the given date\n \"\"\"\n if year &lt; 2000:\n year += 2000\n print u'%04d-%02d-%02d' % (year, month, day)\n\n# Looks for legal dates, first [Y&lt;M&lt;D] then [M&lt;Y&lt;D] then [M,D,Y] \n\ndef dateMaker(data):\n \"\"\"\n Try different ways of interpretating the date\n \"\"\"\n a, b, c = data\n\n for year, month, day in [(c,b,a), (c,a,a), (b,a,c)]:\n month_lengths = get_month_lengths(year)\n if month &lt;= 12 and day &lt;= month_lengths[month - 1]:\n print_date(year, month, day)\n return\n\n print unicode(data) + u\" is illegal\"\n\n\ndata = sorted(map(int, raw_input().split(u\"/\")))\ndateMaker(data)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T23:28:11.350", "Id": "12912", "Score": "0", "body": "Removed print(year, month, day).\nChanged order of a,b,c in for function.\nAdded 0 to month lists to make it right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T23:36:09.107", "Id": "12913", "Score": "0", "body": "@mart0903, I don't like adding extra padding to lists like that. I subtracted one from the month instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T01:49:32.710", "Id": "12917", "Score": "0", "body": "That's good. But another problem is if you type in 0/0/2 that gives out 2002/00/00 or 0/34/11 that gives error" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:29:20.243", "Id": "12960", "Score": "0", "body": "@mart0903, true enough. I'd probably check for zeros first off and then report an error to the user." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T22:20:02.240", "Id": "8266", "ParentId": "8263", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:18:44.847", "Id": "8263", "Score": "4", "Tags": [ "python" ], "Title": "Spotify puzzle problem in python" }
8263
<p>In our software we enable certain features based on the existence of a flag. The <code>Flags</code> class is a static class used to determine the existence of such a flag.</p> <p>I came across one piece of logic that I wrote that I feel could benefit from refactoring. The boolean logic works, but I think it's difficult to understand or read because it relies very heavily on short-circuiting.</p> <p>The basic logic is:</p> <ol> <li>Get all menu items.</li> <li>Return a subset of those menu items by using the following rule: <ul> <li>Some menu items are tied to a specific flag that is expected to be hard-coded in some way. The menu item name may not match the associated flag.</li> <li>Any other menu items should be displayed.</li> </ul></li> </ol> <p>Any help would be much appreciated.</p> <pre><code>private IEnumerable&lt;MenuItemDefinition&gt; GetMenuItems() { return GetAllMenuItems().Where(mi =&gt; (mi.MethodName != "NewWidget" || Flags.HasFlag("Feature1")) &amp;&amp; (mi.MethodName != "NewDongle" || Flags.HasFlag("Feature2"))); } </code></pre>
[]
[ { "body": "<p>If you control the MenuItemDefinition class, why not just add a feature tag to it?</p>\n\n<pre><code>public class MenuItemDefinition\n{\n public string MethodName { get; set; }\n public string Feature { get; set; }\n}\n\n// each instance\nnew MenuItemDefinition { MethodName = \"NewWidget\", Feature = \"Widgets\" }\n\n// GetMenuItems():\nreturn GetAllMenuItems().Where(m =&gt; FeatureIsEnabled(m.Feature));\n</code></pre>\n\n<p>If not, you could put them in a dictionary:</p>\n\n<pre><code>var items = new Dictionary&lt;string, MenuItemDefinition[]&gt; {\n { \"Widgets\", new[] {\n new MenuItemDefinition { MethodName = \"NewWidget\" },\n new MenuItemDefinition { MethodName = \"DeleteWidget\" }\n },\n { \"Default\", new[] {\n // ....\n }\n}\n\nreturn items.Where(pair =&gt; FeatureIsEnabled(pair.Key)).SelectMany(pair =&gt; pair.Value);\n</code></pre>\n\n<p>Or better yet, build the initial list based upon content in a dictionary. That way you don't run the risk of having typos in the switch or the initial setup:</p>\n\n<pre><code>var dict = new Dictionary&lt;string, string[]&gt; \n{\n { \"Widgets\", new[] { \"NewWidget\", \"DeleteWidget\" },\n { \"Default\", new[] { \"...\" }\n ...\n}\n\nvar menuItems = dict\n .Where(p =&gt; FeatureIsEnabled(p.Key))\n .SelectMany(p =&gt; p.Value)\n .Select(mn =&gt; new MenuItemDefinition { MethodName = mn });\n\n// GetMenuItems()\nreturn menuItems; // :)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T17:00:13.303", "Id": "12938", "Score": "0", "body": "Hi @Lars-Erik, thanks for the answer. I've provided additional information in the example that answers your question, I hope that is helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T18:55:46.827", "Id": "12944", "Score": "0", "body": "I got it, entirely new answer. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:08:49.410", "Id": "12946", "Score": "0", "body": "Thanks for the updated response. I'm not able to make changes to the MenuItemDefinition class, but if I were able to, this would be the best solution. For reference, I've posted my solution separately as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:28:48.957", "Id": "12948", "Score": "0", "body": "Oh no, not the switch! It's evil. ;)\nAt least pull it out and hide it in a method as I first described.\nAnyway, I added a third proposal, which I hope appeals." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T20:17:37.213", "Id": "12950", "Score": "0", "body": "Ah yes, switch is very evil indeed! The GetMenuItems() method is in fact the method that hides the implementation so we are already in a hidden place for such evil things. That being said, I like the dictionary approach even more!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T09:09:14.230", "Id": "8276", "ParentId": "8264", "Score": "3" } } ]
{ "AcceptedAnswerId": "8276", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T22:03:14.427", "Id": "8264", "Score": "5", "Tags": [ "c#", "linq" ], "Title": "Lambda .Where() expression to return selected/flagged objects" }
8264
<p>I've probably done some pretty horrendous things here, but I'm throwing it out for people to give me some feedback that I can start using to immediately improve my Clojure coding style.</p> <p>Additional suggestions would be performance enhancements as well as areas where I could use transients if it is advisable.</p> <p>So far I've been told:</p> <ol> <li>I should make use of <code>vector-of</code></li> <li>Use primitives such as int and double to avoid boxing and unboxing</li> <li>Type hint string functions</li> </ol> <p>I would be grateful for suggestions that I use to turn this code into more idiomatic Clojure code.</p> <pre><code>(ns tagger.core "Running Viterbi on some text" (:require [clojure.string :as str] [clojure.contrib.generic.functor :as functor] [clojure.contrib.math :as math] [clojure.set :as set] [clojure.data :as data] [clojure.data.finger-tree :as ft])) (def ^:dynamic *epsilon* 0.01) (defn applyAll [fs x] (map #(% x) fs)) (defn split-evenly [coll] (partition (quot (count coll) 10) coll)) (defn nil?-zero [fn &amp; args] (let [val (apply fn args)] (if (nil? val) 0 val))) ;; Counts needed are: ;; word counts W ;; tag counts T ;; word-tag counts W-T ;; previous tag to current tag counts T(i+1)-Ti ;; Problem set ;; A sample set to play with (def str-to-tags (slurp "resources/sample.txt")) (defn str-&gt;tags [string] (filter #(not (empty? %)) (str/split string #"[\s]"))) (defn tag-&gt;W-T [tag] "Converts a tag such as In/IN into a W-T such as [In IN]" (str/split tag #"[//]")) (defn sentence-&gt;tags [sentence] (map #(second %) sentence)) (defn strip-tags [tag] (first tag)) (defn this-and-that [xs] (map-indexed (fn [i x] [x (concat (take i xs) (drop (inc i) xs))]) xs)) (def cleaned-tag-str (filter #(= (count %) 2) (map tag-&gt;W-T (str-&gt;tags str-to-tags)))) (defn split-sentences [tag-str] "Splits the str into sentences" (reduce #(if (= (second (first %2)) ".") (ft/conjr (pop %1) (ft/conjr (peek %1) (first %2))) (ft/conjr %1 %2)) (ft/double-list) (map #(apply ft/double-list %) (partition-by #(= "." (second %)) tag-str)))) (defn split-sentences-start-end [tag-str] "Splits the str into sentences with added start and end tags" (reduce #(if (= (second (first %2)) ".") (conj (vec (drop-last %1)) (conj (vec (conj (vec (conj (last %1) ["START" "START"])) (first %2))) ["END" "END"])) (conj (vec %1) %2)) [] (partition-by #(= "." (second %)) tag-str))) (def sentences (split-sentences cleaned-tag-str)) (def testing-and-training-sentences "A list containing 10 pairs of testing sentences and training sentences" (map (fn [[fst rst]] (ft/double-list fst (apply concat rst))) (this-and-that (split-evenly sentences)))) (defn add-start-end [sentence-list] (map #(ft/consl (ft/conjr % ["END" "END"]) ["START" "START"]) sentence-list)) (def testing-and-training-sentences-start-end (map #(map add-start-end %) testing-and-training-sentences)) (def training-tag-list-start-end (map (comp #(map sentence-&gt;tags %) second) testing-and-training-sentences-start-end)) (def testing-and-training-tag-list-start-end (map (fn [sample] (map #(map sentence-&gt;tags %) sample)) testing-and-training-sentences-start-end)) (defn insert [m k] "Inserts a key k into a map m if it does not exist or increments the count if it does" (let [val (m k)] (assoc m k (inc (if (nil? val) 0 val))))) (defn nested-insert [m [word tag]] "Inserts a key k into a nested map m of tags and words if it does not exist or increments the count if it does" (let [val (get-in m [tag word])] (assoc-in m [tag word] (inc (if (nil? val) 0 val))))) (defn word-count [tagged-str] "Example of how to get word counts" (reduce #(insert %1 (first %2)) {} tagged-str)) (defn tag-count [tagged-str] "Example of how to get tag counts" (reduce #(insert %1 (second %2)) {} tagged-str)) (defn nested-tag-word-count [tagged-str] "Nested counts in the format of {tag {word count}}" (reduce #(nested-insert %1 %2) {} tagged-str)) (def tag-count-training-list (map #(tag-count (apply concat (second %))) testing-and-training-sentences)) (def word-count-training-list (map #(word-count (apply concat (second %))) testing-and-training-sentences)) (def nested-tag-word-count-training-list (map #(nested-tag-word-count (apply concat (second %))) testing-and-training-sentences)) (defn out-of-step-list [tag-list] "Creates a list of vector pairs where the second element is the next values first element" (map vector (rest tag-list) tag-list)) (def training-previous-tag-tag-list-start-end (map #(map out-of-step-list %) training-tag-list-start-end)) (def training-tag-count-start-end (map (comp frequencies flatten) training-tag-list-start-end)) (defn nested-previous-tag-tag-count [previous-tag-tag-list] "Nested counts in the format of {prior-tag {tag count}}" (reduce #(nested-insert %1 %2) {} (apply concat previous-tag-tag-list))) (def nested-previous-tag-tag-count-training-list (map nested-previous-tag-tag-count training-previous-tag-tag-list-start-end)) (defn unique-keys-count [m] (count (keys m))) (def unique-words-count-training-list (map count word-count-training-list)) ;; Calculating probabilities (defn make-prob-fn-map [[nested-t-w-count word-count unique-wc nested-prior-t-t-count tag-count-st-end unique-tc]] {:prob-word-given-tag ;; Construct Emission Probabilities (fn [word tag] (let [word-given-tag (nil?-zero get-in nested-t-w-count [tag word]) tc (nil?-zero word-count word)] (/ (+ word-given-tag *epsilon*) (+ tc (* *epsilon* unique-tc))))) :prob-tag-given-previous-tag ;; Construct Transition Probabilities (fn [tag previous-tag] (let [tag-given-prior-tag-prob (nil?-zero get-in nested-prior-t-t-count [previous-tag tag]) tc (nil?-zero tag-count-st-end previous-tag)] (/ (+ tag-given-prior-tag-prob *epsilon*) (+ tc (* *epsilon* unique-tc)))))}) (defn viterbi-init [v path obs states start-p emit-p] "Initializes viterbi for us" (reduce #(into %1 {%2 [(* (start-p %2) (emit-p (first obs) %2)) (conj path %2)]}) {} states)) (defn extract-prob-state [v path] "Extracts the current probability and state for a given [v path]" [(first (v path)) path]) (defn viterbi-step [prior obs states trans-p emit-p] "Goes through one step of viterbi for us, taking a prior state and performing one step" (apply merge (map (comp (fn [[path v]] {(last path) [v path]}) #(apply max-key val %) #(apply merge %)) ((fn [obs] (map #(applyAll (map (comp (fn [[v past-st]] (fn [current-st] {(conj (second (prior past-st)) current-st) (* v (trans-p current-st past-st) (emit-p obs current-st))})) (partial extract-prob-state prior)) states) %) states)) obs)))) (defn viterbi [observations states start-prob trans-prob emit-prob] (let [init (viterbi-init [] [] observations states start-prob emit-prob)] (reduce #(viterbi-step %1 %2 states trans-prob emit-prob) init (rest observations)))) (defn viterbi-solution [observations states start-prob trans-prob emit-prob] (apply max-key #(first (val %)) (viterbi observations states start-prob trans-prob emit-prob))) (defn extract-path [solution] "Extracts the path from a viterbi solution" (second (second solution))) (defn extract-tag-count [seq] (reduce insert {} (flatten (map second (second seq))))) (defn extract-states [seq] (into #{} (flatten (map #(map second %) (second seq))))) (defn extract-observations [seq] (map #(map first %) (first seq))) (defn extract-testing-tags [seq] (map #(map second %) (first seq))) (defn compare-matches [compare] "Compares vector containing a path and testing set and gives the matches" (map (comp (fn [m] (/ (nil?-zero m true) (+ (nil?-zero m true) (nil?-zero m false)))) frequencies (fn [[a b]] (map #(= %1 %2) a b))) compare)) (defn average-accuracy [accuracy-scores] (/ (apply + accuracy-scores) (double (count accuracy-scores)))) (defn run-viterbi [] "Runs viterbi with transition and emission calculated using the same training data via cross validation" (let [states (map extract-states testing-and-training-sentences) observations (map extract-observations testing-and-training-sentences) prob-map (map make-prob-fn-map (map vector nested-tag-word-count-training-list word-count-training-list unique-words-count-training-list nested-previous-tag-tag-count-training-list training-tag-count-start-end (map count states))) transition-prob (map :prob-tag-given-previous-tag prob-map) emission-prob (map :prob-word-given-tag prob-map) start-prob (map (fn [trans-p] #(trans-p % "START")) transition-prob) testing-tags-list (map extract-testing-tags testing-and-training-sentences)] (map #(map vector %1 %2) testing-tags-list (map (fn [[obs-list sts start-p trans-p emit-p]] (map (fn [obs] (extract-path (viterbi-solution obs sts start-p trans-p emit-p))) obs-list)) (map vector observations states start-prob transition-prob emission-prob))))) (defn -main [] (average-accuracy (map (comp average-accuracy compare-matches) (run-viterbi)))) ;; Checking functions (defn close-to-1 [val] (&gt; 0.000001 (math/abs (- 1 val)))) ;; Assert that Probabilities are sensible? (defn check-probs? [] (assert (let [states (map extract-states testing-and-training-sentences) observations (map extract-observations testing-and-training-sentences) prob-map (map make-prob-fn-map (map vector nested-tag-word-count-training-list word-count-training-list unique-words-count-training-list nested-previous-tag-tag-count-training-list training-tag-count-start-end (map count states))) transition-prob (map :prob-tag-given-previous-tag prob-map) emission-prob (map :prob-word-given-tag prob-map) start-prob (map (fn [trans-p] #(trans-p % "START")) transition-prob) testing-tags-list (map extract-testing-tags testing-and-training-sentences)] (every? true? (map close-to-1 (map (fn [[start-pr st]] (apply + (map start-pr st))) (map vector start-prob states))))) "Start Probabilities are not sensible") (assert (let [states (map extract-states testing-and-training-sentences) observations (map extract-observations testing-and-training-sentences) prob-map (map make-prob-fn-map (map vector nested-tag-word-count-training-list word-count-training-list unique-words-count-training-list nested-previous-tag-tag-count-training-list training-tag-count-start-end (map count states))) transition-prob (map :prob-tag-given-previous-tag prob-map) emission-prob (map :prob-word-given-tag prob-map) start-prob (map #(partial % "START") transition-prob) testing-tags-list (map extract-testing-tags testing-and-training-sentences)] (every? true? (map (fn [[emit-pr st wctl]] (every? true? (map close-to-1 (map (fn [word] (apply + (map #(emit-pr word %) st))) (keys wctl))))) (map vector emission-prob states word-count-training-list)))) "Emmission probabilities are not sensible") (assert (every? true? (let [states (map extract-states testing-and-training-sentences) observations (map extract-observations testing-and-training-sentences) prob-map (map make-prob-fn-map (map vector nested-tag-word-count-training-list word-count-training-list unique-words-count-training-list nested-previous-tag-tag-count-training-list training-tag-count-start-end (map count states))) transition-prob (map :prob-tag-given-previous-tag prob-map) emission-prob (map :prob-word-given-tag prob-map) start-prob (map #(partial % "START") transition-prob) testing-tags-list (map extract-testing-tags testing-and-training-sentences)] (map (fn [[trans-pr st]] (every? true? (map close-to-1 (map (fn [prior] (apply + (map #(trans-pr % prior) st))) (disj st "."))))) (map vector transition-prob states)))) "Transisition probabilities are not sensible")) </code></pre> <p>Here is sample.txt:</p> <blockquote> <pre><code>====================================== In/IN [ an/DT Oct./NNP 19/CD review/NN ] of/IN ``/`` [ The/DT Misanthrope/NN ] ''/'' at/IN [ Chicago/NNP 's/POS Goodman/NNP Theatre/NNP ] (/( [ ``/`` Revitalized/VBN Classics/NNS ] Take/VBP [ the/DT Stage/NN ] in/IN [ Windy/NNP City/NNP ] ,/, ''/'' [ Leisure/NN ] &amp;/CC [ Arts/NNS ] )/) ,/, [ the/DT role/NN ] of/IN [ Celimene/NNP ] ,/, played/VBN by/IN [ Kim/NNP Cattrall/NNP ] ,/, was/VBD mistakenly/RB attributed/VBN to/TO [ Christina/NNP Haag/NNP ] ./. [ Ms./NNP Haag/NNP ] plays/VBZ [ Elianti/NNP ] ./. ====================================== (/( See/VB :/: ``/`` [ Revitalized/VBN Classics/NNS ] Take/VBP [ the/DT Stage/NN ] in/IN [ Windy/NNP City/NNP ] ''/'' --/: [ WSJ/NNP Oct./NNP 19/CD ] ,/, [ 1989/CD ] )/) ====================================== ====================================== [ Rolls-Royce/NNP Motor/NNP Cars/NNPS Inc./NNP ] said/VBD [ it/PRP ] expects/VBZ [ its/PRP$ U.S./NNP sales/NNS ] to/TO remain/VB [ steady/JJ ] at/IN about/IN [ 1,200/CD cars/NNS ] in/IN [ 1990/CD ] ./. [ The/DT luxury/NN auto/NN maker/NN last/JJ year/NN ] sold/VBD [ 1,214/CD cars/NNS ] in/IN [ the/DT U.S./NNP Howard/NNP Mosher/NNP ] ,/, [ president/NN ] and/CC [ chief/JJ executive/NN officer/NN ] ,/, said/VBD [ he/PRP ] anticipates/VBZ [ growth/NN ] for/IN [ the/DT luxury/NN auto/NN maker/NN ] in/IN [ Britain/NNP ] and/CC [ Europe/NNP ] ,/, and/CC in/IN [ Far/JJ Eastern/JJ markets/NNS ] ./. ====================================== [ BELL/NNP INDUSTRIES/NNP Inc./NNP ] increased/VBD [ its/PRP$ quarterly/NN ] to/TO [ 10/CD cents/NNS ] from/IN [ seven/CD cents/NNS ] [ a/DT share/NN ] ./. [ The/DT new/JJ rate/NN ] will/MD be/VB [ payable/JJ Feb./NNP 15/CD ] ./. [ A/DT record/NN date/NN has/VBZ n't/RB ] been/VBN set/VBN ./. [ Bell/NNP ] ,/, based/VBN in/IN [ Los/NNP Angeles/NNP ] ,/, makes/VBZ and/CC distributes/VBZ [ electronic/JJ ] ,/, [ computer/NN ] and/CC [ building/NN products/NNS ] ./. ====================================== [ Investors/NNS ] are/VBP appealing/VBG to/TO [ the/DT Securities/NNPS ] and/CC [ Exchange/NNP Commission/NNP ] not/RB to/TO limit/VB [ their/PRP$ access/NN ] to/TO [ information/NN ] about/IN [ stock/NN purchases/NNS ] and/CC [ sales/NNS ] by/IN [ corporate/JJ insiders/NNS ] ./. ====================================== [ A/DT SEC/NNP proposal/NN ] to/TO ease/VB reporting/NN [ requirements/NNS ] for/IN [ some/DT company/NN executives/NNS ] would/MD undermine/VB [ the/DT usefulness/NN ] of/IN [ information/NN ] on/IN [ insider/NN trades/NNS ] as/IN [ a/DT stock-picking/JJ tool/NN ] ,/, [ individual/JJ investors/NNS ] and/CC [ professional/JJ money/NN managers/NNS ] contend/VBP ./. </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T10:07:06.597", "Id": "25646", "Score": "0", "body": "This is not \"Viterbi\", but \"applying Viterbi to part-of-speech tagging\". The Viterbi is very useful in other areas, not only NLP. I would have liked to comment on the actual algorithm, but you don't have enough comments here. Oh, and since you're have nice pure function, you could test them, eg. `(deftest test-split (is (= [\"a\" b\"] \"a b\")))` or something like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T17:54:28.613", "Id": "25660", "Score": "0", "body": "Hi @Cygal, what do you mean that I don't \"have enough comments here\". Good point, I'll add the test cases :)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T06:56:36.863", "Id": "25688", "Score": "0", "body": "Oops, the comments are in docstrings. I guess it takes just too much effort to comment on the algorithm, and I can't comment on the Clojure since, well, I don't know Clojure. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T07:11:01.717", "Id": "25959", "Score": "0", "body": "Nobody in for a Clojure review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T14:40:06.703", "Id": "25969", "Score": "0", "body": "Looks like it doesn't it :(, thanks for putting up the bounty though @Cygal!" } ]
[ { "body": "<p>First of all, good job! This is obviously a complex algorithm and it looks like it's working.</p>\n\n<p>I'm going to do this incrementally. So I'll save this and keep editing as I go. And since it's so long, I won't get to everything. Plus I don't understand the algorithm too well.</p>\n\n<p>First of all, doc strings in Clojure go before the arguments. I used to make this mistake all the time. The reason is that you can have multi-variate functions.</p>\n\n<p>1:</p>\n\n<pre><code>(defn insert [m k]\n \"Inserts a key k into a map m if it does not exist or increments the count if it does\"\n (let [val (m k)]\n (assoc m k (inc (if (nil? val) 0 val)))))\n</code></pre>\n\n<p>My version:</p>\n\n<pre><code>(defn insert \n \"Inserts a key k into a map m if it does not exist or increments the count if it does\"\n [m k]\n (update-in m [k] (fnil inc 0)))\n</code></pre>\n\n<p>See <a href=\"http://clojuredocs.org/clojure_core/clojure.core/update-in\">update-in</a> and <a href=\"http://clojuredocs.org/clojure_core/clojure.core/fnil\">fnil</a>.</p>\n\n<p>2:</p>\n\n<p><code>#()</code> construction is unnecessary here:</p>\n\n<pre><code>(defn sentence-&gt;tags [sentence]\n (map #(second %) sentence))\n</code></pre>\n\n<p>My version:</p>\n\n<pre><code>(defn sentence-&gt;tags [sentence]\n (map second sentence))\n</code></pre>\n\n<p>3:</p>\n\n<pre><code>(defn word-count [tagged-str]\n \"Example of how to get word counts\"\n (reduce #(insert %1 (first %2)) {} tagged-str))\n</code></pre>\n\n<p>Could this be replaced by using <a href=\"http://clojuredocs.org/clojure_core/clojure.core/frequencies\">frequencies</a>?</p>\n\n<p>4:</p>\n\n<p>Now it's starting to get hairy. I may make some mistakes here, because the code is not factored.</p>\n\n<pre><code>(defn viterbi-init [v path obs states start-p emit-p]\n \"Initializes viterbi for us\"\n (reduce\n #(into %1 {%2 [(* (start-p %2)\n (emit-p (first obs) %2))\n (conj path %2)]})\n {}\n states))\n</code></pre>\n\n<p>This definitely has too many levels of into/reduce. You could do a <code>(reduce #(assoc %1 %s ...) {} states)</code> pattern. Do we need <code>v</code>? And why are we passing in a list <code>obs</code> when we only need the first? And it's often a good idea to put the driving sequence in the first or last position, so you can do threading. Let's try it this way:</p>\n\n<pre><code>(defn viterbi-init \n \"Initializes viterbi for us\"\n [states path ob start-p emit-p]\n (into {}\n (for [state states]\n [state\n [(* (start-p state) (emit-p ob state))\n (conj path state)]])))\n</code></pre>\n\n<p>5:</p>\n\n<p>This one is very hairy. I don't quite understand it, but I will try.</p>\n\n<pre><code>(defn viterbi-step [prior obs states trans-p emit-p]\n \"Goes through one step of viterbi for us, taking a prior state and performing one step\"\n (apply merge (map\n (comp (fn [[path v]] {(last path) [v path]}) #(apply max-key val %) #(apply merge %))\n ((fn [obs]\n (map #(applyAll (map (comp (fn [[v past-st]]\n (fn [current-st]\n {(conj (second (prior past-st)) current-st)\n (* v (trans-p current-st past-st)\n (emit-p obs current-st))}))\n (partial extract-prob-state prior)) states) %) states))\n obs))))\n</code></pre>\n\n<p>So, I tried and failed to refactor this myself. But I will give my general feedback. What this function, which is a map of a map of a map of a map, tells me is that there is a failure of abstraction. <code>viterbi-step</code> should be should be a high-level function which should read somewhat like the inner loop of a pseudo-code implementation of Viterbi. This function relies too much on the structure of the data structures involved. Deeply nested structures are common, but a single function that accesses them so deeply is not. A good rule of thumb is at most 1 nested map/reduce within a function.</p>\n\n<p>There need to be functions which act as your primitive operations here. I can see that you began writing some near the top. You should continue that trend here. Then your functions would be operating at a certain level and calling functions from the level below.</p>\n\n<p>An alternative approach would be to turn the algorithm into a sequential series of steps. This may or may not apply here, but it is hard for me to tell. As an example (not real code!):</p>\n\n<pre><code>(defn viterbi-step [prior obs states trans-p emit-p]\n (-&gt; obs\n (calculate-priors)\n (extract-prob-states states)\n (extract-path)\n (merge)))\n</code></pre>\n\n<p>Again, it's just an example. But the idea is that each function takes the data it needs and creates a new data structure that is the result of that calculation. I don't know if this is possible with this algorithm. But it could be. One hint I can give is that you know you are on the right track when your functions are returning \"appropriate\" data structures. That is, when the data is a mapping, you return a map. When it's a set, you return a set. Also, the functions don't take much more data than they need to calculate the answer. I suggest you take the iterative algorithm description and work backwards from the final output.</p>\n\n<p>Again, nice going. It was a pleasure to go through it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T16:56:53.613", "Id": "26087", "Score": "0", "body": "Hi @Eric, thanks for the feedback, I'm a bit busy right now (as it's been a while since I coded this, but I'll have a bash later, likely next weekend at going through the code in my question, cleaning it up and incorporating your suggestions.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T22:02:48.733", "Id": "16015", "ParentId": "8270", "Score": "6" } }, { "body": "<p>Another suggestion would be to use maps as method arguments.</p>\n\n<p>instead of :</p>\n\n<pre><code>(defn viterbi-step [prior obs states trans-p emit-p] \n</code></pre>\n\n<p>using maps:</p>\n\n<pre><code>(defn viterbi-step [{:keys [prior obs states trans-p emit-p] :as m}]\n</code></pre>\n\n<p>So when viterbi-step is called, you can avoid passing all the arguments, instead you can <em>assoc</em> the new arguments onto the map passed to the existing method:</p>\n\n<pre><code>(defn viterbi [observations states start-prob trans-prob emit-prob]\n (let [init (viterbi-init [] [] observations states start-prob emit-prob)]\n (reduce #(viterbi-step (assoc m :prior %1 :obs %2)) init (rest observations))))\n</code></pre>\n\n<p>We can avoid having to type out all the arguments again just to pass it to another function. Rewriting the viterbi-solution method thus:</p>\n\n<pre><code>(defn viterbi-solution [{:keys [observations states start-prob trans-prob emit-prob] :as m}]\n (apply max-key #(first (val %)) (viterbi m)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T03:48:53.580", "Id": "24329", "ParentId": "8270", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T03:35:34.500", "Id": "8270", "Score": "8", "Tags": [ "clojure", "machine-learning", "natural-language-processing" ], "Title": "Using Viterbi algorithm to analyze sentences" }
8270
<p>I ran into an issue where I was doing this:</p> <pre><code>dictionary1 = {} dictionary2 = {} foo = dictionary1.get('foo', dictionary1.get('bar', dictionary2.get('baz'))) </code></pre> <p>I.e. if the value isn't supplied in one dict, it would fall back on the next and then on the next. In this case <code>dictionary1</code> has a key that is deprecated that I'm getting in case the new style on isn't there, dictionary2 is completely different. It looks pretty ugly though, the alternative seem to be to break it up across multiple lines like:</p> <pre><code>foo = dictionary2.get('baz') foo = dictionary1.get('bar', foo) foo = dictionary1.get('foo', foo) </code></pre> <p>Which might be better, though it seems like it could be confusing to read the code in the reverse order. I wonder if there's an alternative more straight forward and prettier solution?</p>
[]
[ { "body": "<p>Your code attempts to fetch the values of <em>all</em> keys when it probably only really needs one. You do not want to be doing this.</p>\n\n<p>I think it would be better to create a list representing the priorities of what values you wish to retrieve and attempt to retrieve them.</p>\n\n<pre><code>def get_value(priorities):\n for key, dictionary in priorities:\n try:\n return dictionary[key]\n except KeyError:\n pass\n return None\n\npriorities = [\n ('foo', dictionary1),\n ('bar', dictionary1),\n ('baz', dictionary2),\n]\nfoo = get_value(priorities)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T07:04:04.767", "Id": "8275", "ParentId": "8272", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T05:43:42.427", "Id": "8272", "Score": "2", "Tags": [ "python" ], "Title": "How can I make handling multiple {}.get('value', {}.get('foo')) pretty?" }
8272
<p>As part of my project, a game, I have progress bars with countdown timers. These are updated every 250ms, to keep a relatively smooth animation if the countdown time is short.</p> <p>Here's my function:</p> <pre><code>var time_format = function(time) { var elms, names, ret, i, n; elms = [ time / 29030400, time / 2419200 % 12, time / 604800 % 4, time / 86400 % 7, time / 3600 % 24, time / 60 % 60, time % 60 ]; names = "yr mo w d h m s".split(" "); ret = []; for( i=0; i&lt;elms.length; i++) { n = Math.floor(elms[i]); if( n) ret.push(n+names[i]); } ret = ret.join(" "); if( ret == "") ret = "0s"; return ret; }; </code></pre> <p>I'm just wondering if any optimisations can be made to this code. There may be up to ten progress bars on a single page (after that data is paginated). My main concern is that <code>Math.floor</code> call, is there a faster way to floor a number?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T13:28:08.647", "Id": "62838", "Score": "0", "body": "You cand use n = elms[i] >> 0. Bit operations are faster." } ]
[ { "body": "<p>Try this:</p>\n\n<pre><code>var time_format = (function() {\n\n var names = \"yr mo w d h m s\".split(\" \");\n\n return function(time) {\n var elms, ret, i, n;\n elms = [\n time / 29030400,\n time / 2419200 % 12,\n time / 604800 % 4,\n time / 86400 % 7,\n time / 3600 % 24,\n time / 60 % 60,\n time % 60\n ];\n ret = [];\n for( i=0; i&lt;elms.length; i++) {\n n = elms[i];\n n = n | n;\n if( n) ret.push(n+names[i]);\n }\n ret = ret.join(\" \");\n if( ret == \"\") ret = \"0s\";\n return ret;\n }\n}());\n</code></pre>\n\n<p>It moves the array initialization out of the function and into a closure so it's only evaluated once.</p>\n\n<p>And, it uses a faster way to do the floor operation. See <a href=\"http://ernestdelgado.com/archive/benchmark-on-the-floor/\" rel=\"nofollow\">this article</a> for different ways to do floor and their timing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T06:21:40.907", "Id": "12923", "Score": "0", "body": "Would `n = elms[i] ^ 0;` work too? I've seen that one used in a few places." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T06:31:05.707", "Id": "12924", "Score": "0", "body": "@Kolink - It seems to work. To characterize it's performance, you'd have to set up a test to measure the speed vs. the other options." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T06:18:19.513", "Id": "8274", "ParentId": "8273", "Score": "1" } } ]
{ "AcceptedAnswerId": "8274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T05:47:43.923", "Id": "8273", "Score": "2", "Tags": [ "javascript" ], "Title": "JavaScript function for printing a countdown" }
8273
<p><strong>PL/SQL</strong> (Procedural Language/Structured Query Language) is Oracle Corporation's procedural language extension for SQL.</p> <p>Oracle clearly distinguishes between SQL and PL/SQL so PL/SQL should not be confused with regular SQL. Plain DML statements should be tagged with <a href="/questions/tagged/sql" class="post-tag" title="show questions tagged &#39;sql&#39;" rel="tag">sql</a> and <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged &#39;oracle&#39;" rel="tag">oracle</a>.</p> <p>Questions about PL/SQL should probably be tagged <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged &#39;oracle&#39;" rel="tag">oracle</a> as well.</p> <h2>Oracle Documentation: 12c Release 1</h2> <ul> <li><a href="https://docs.oracle.com/database/121/LNPLS/toc.htm" rel="nofollow noreferrer">PL/SQL Language Reference</a></li> <li><a href="https://docs.oracle.com/database/121/ARPLS/toc.htm" rel="nofollow noreferrer">PL/SQL Packages and Types Reference</a></li> <li><a href="https://docs.oracle.com/database/121/TDDDG/tdddg_subprograms.htm#TDDDG40000" rel="nofollow noreferrer">Chapter 5 Developing Stored Subprograms and Packages</a> from <a href="https://docs.oracle.com/database/121/TDDDG/toc.htm" rel="nofollow noreferrer">2 Day Developer's Guide</a></li> </ul> <h2>New PL/SQL Features in 12c Release 1</h2> <p>This is a series of articles written by Steven Feuerstein and published in <a href="https://blogs.oracle.com/oraclemagazine/" rel="nofollow noreferrer">Oracle Magazine</a>.</p> <ul> <li><a href="https://blogs.oracle.com/oraclemagazine/plsql-enhancements" rel="nofollow noreferrer">PL/SQL Enhancements</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/sql-in-plsql-enhancements" rel="nofollow noreferrer">SQL in PL/SQL Enhancements</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/sophisticated-call-stack-analysis" rel="nofollow noreferrer">Sophisticated Call Stack Analysis</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/when-packages-need-to-lose-weight" rel="nofollow noreferrer">When Packages Need to Lose Weight</a></li> </ul> <h2>Oracle Documentation: 11g Release 2</h2> <ul> <li><a href="https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/title.htm" rel="nofollow noreferrer">PL/SQL Language Reference</a></li> <li><a href="https://docs.oracle.com/cd/E11882_01/appdev.112/e40758/title.htm" rel="nofollow noreferrer">PL/SQL Packages and Types Reference</a></li> <li><a href="http://docs.oracle.com/cd/E11882_01/appdev.112/e10766/tdddg_subprograms.htm" rel="nofollow noreferrer">Chapter 5 Developing Stored Subprograms and Packages</a> from <a href="http://docs.oracle.com/cd/E11882_01/appdev.112/e10766/toc.htm" rel="nofollow noreferrer">2 Day Developer's Guide</a></li> </ul> <h2>Oracle Documentation: Previous releases</h2> <ul> <li><a href="https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/toc.htm" rel="nofollow noreferrer">10g Release 2</a></li> <li><a href="https://docs.oracle.com/cd/B10501_01/appdev.920/a96624/toc.htm" rel="nofollow noreferrer">9i Release 2</a></li> </ul> <h2>Wisdom from the Stack</h2> <ul> <li><a href="https://stackoverflow.com/q/2041879">A good reference for Oracle PL/SQL</a></li> <li><a href="https://web.archive.org/web/20161206042729/http://stackoverflow.com/questions/290829/differences-between-sql-and-pl-sql" rel="nofollow noreferrer">Differences between SQL and PL/SQL</a></li> <li><a href="https://dba.stackexchange.com/q/1121">How to differentiate between SQL and PL/SQL?</a> from <a href="https://dba.stackexchange.com">https://dba.stackexchange.com</a></li> <li><a href="https://stackoverflow.com/q/563090">Double quotes around identifier</a></li> <li><a href="https://stackoverflow.com/a/32003976">Save all your code to a VCS</a></li> </ul> <h2>PL/SQL Tutorial</h2> <ul> <li><a href="http://www.way2tutorial.com/plsql/tutorial.php" rel="nofollow noreferrer">PL/SQL Tutorial on way2tutorial</a></li> <li><a href="http://www.plsql-tutorial.com" rel="nofollow noreferrer">PL/SQL Tutorial on plsql-tutorial</a></li> <li><a href="http://www.tutorialspoint.com/plsql/" rel="nofollow noreferrer">PL/SQL Tutorial on tutorialspoint</a></li> </ul> <h2>PL/SQL 101</h2> <p>This is a twelve part series of articles on understanding and using PL/SQL. It is written by Steven Feuerstein and published in <a href="https://blogs.oracle.com/oraclemagazine/" rel="nofollow noreferrer">Oracle Magazine</a>.</p> <ol> <li><a href="https://blogs.oracle.com/oraclemagazine/building-with-blocks" rel="nofollow noreferrer">Building with Blocks</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/controlling-the-flow-of-execution" rel="nofollow noreferrer">Controlling the Flow of Execution</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-strings" rel="nofollow noreferrer">Working with Strings</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-numbers-in-plsql" rel="nofollow noreferrer">Working with Numbers in PL/SQL</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-dates-in-plsql" rel="nofollow noreferrer">Working with Dates in PL/SQL</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/error-management" rel="nofollow noreferrer">Error Management</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-records" rel="nofollow noreferrer">Working with Records</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-collections" rel="nofollow noreferrer">Working with Collections</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/bulk-processing-with-bulk-collect-and-forall" rel="nofollow noreferrer">Bulk Processing with BULK COLLECT and FORALL</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/the-data-dictionary-make-views-work-for-you" rel="nofollow noreferrer">The Data Dictionary: Make Views Work for You</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/wrap-your-code-in-a-neat-package" rel="nofollow noreferrer">Wrap Your Code in a Neat Package</a></li> <li><a href="https://blogs.oracle.com/oraclemagazine/working-with-cursors" rel="nofollow noreferrer">Working with Cursors</a></li> </ol> <h2>Book recommendations</h2> <ul> <li><a href="http://shop.oreilly.com/product/9780596001803.do" rel="nofollow noreferrer">Learning Oracle PL/SQL By Steven Feuerstein, Bill Pribyl</a></li> <li><a href="http://shop.oreilly.com/product/0636920024859.do" rel="nofollow noreferrer">Oracle PL/SQL Programming, 6th Edition By Steven Feuerstein, Bill Pribyl</a></li> <li><a href="https://www.mhprofessional.com/9780071494458-usa-oracle-database-11g-plsql-programming-group" rel="nofollow noreferrer">Oracle Database 11g PL/SQL Programming By Michael McLaughlin</a></li> <li><a href="http://shop.oreilly.com/product/9781565926745.do" rel="nofollow noreferrer">Oracle PL/SQL Programming: A Developer's Workbook By Steven Feuerstein, Andrew Odewahn</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0137144229" rel="nofollow noreferrer" rel="nofollow noreferrer">Oracle PL/SQL by Example By Benjamin Rosenzweig, Elena Silvestrova Rakhimov</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-25T15:17:55.490", "Id": "8279", "Score": "0", "Tags": null, "Title": null }
8279
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural language extension for SQL. Questions about PL/SQL should probably be tagged "oracle" as well.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T15:17:55.490", "Id": "8280", "Score": "0", "Tags": null, "Title": null }
8280
Oracle is a relational DBMS (Database Management System) created by Oracle Corporation.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T15:18:32.587", "Id": "8282", "Score": "0", "Tags": null, "Title": null }
8282
<blockquote> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>fib = (x) -&gt; return 0 if x == 0 return 1 if x == 1 return fib(x-1) + fib(x-2) i = 2 fib_sum = 0 while (fib i) &lt; 4000000 n = fib i if n % 2 is 0 then fib_sum += fib i i++ alert fib_sum </code></pre> <p>I am looking for a more &quot;functional&quot; solution but I am stuck.</p> <h3>Edit</h3> <p>Optimized the solution:</p> <pre><code>limit = 4000000 sum = 0 a = 1 b = 1 while b &lt; limit if b % 2 is 0 then sum += b h = a + b a = b b = h alert sum #4613732 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T16:29:39.573", "Id": "12935", "Score": "0", "body": "1) If your code is working, an advice would be to go to the thread corresponding to that problem on projecteuler. It's always pretty interesting.\n\n\n2) If your code isn't working (or is too slow which might be the case) : you might want to write not a more functional but a more efficient way to compute the fibonacci numbers (try to think of the different recursive calls you are generating when computing `fib(10)` for instance)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T16:52:50.927", "Id": "12936", "Score": "0", "body": "Thanks, forgot they had solutions attached after it is solved. This algorithm made it a ton faster(edited above), although not the elegant functional solution I was looking for." } ]
[ { "body": "<h2>Better CoffeeScript</h2>\n\n<p>First of all, if you're going to use CoffeeScript, then use its full potential and do away with <code>h</code>:</p>\n\n<pre><code>limit = 4000000\nsum = 0 \n\n[a, b] = [1, 1]\n\nwhile b &lt; limit\n sum += b if b % 2 is 0\n [a, b] = [b, a + b]\n\nconsole.log sum\n</code></pre>\n\n<p>It's nice and easy to read, and I'd use this implementation instead of a recursive one in \"real code\", but it's still instructive to think about a functional equivalent.</p>\n\n<h2>Memoization</h2>\n\n<p>What you're looking for is named memoization. The trick is that you should store the values of <code>fib(n)</code> in an array. This allows you to lookup in the array for most cases instead of computing the value again. You'll be able to use <code>fib()</code> in a natural but optimized way.</p>\n\n<pre><code>memo = [1, 1]\n\nfib = (x) -&gt;\n if typeof memo[x] != 'number'\n memo[x] = fib(x - 1) + fib(x - 2)\n\n return memo[x]\n</code></pre>\n\n<p>Now we have a function that compute <code>memo[x]</code> if needed, and returns it for every call. This means that the first call to fib(3) is going to compute it using <code>memo[2]</code> and <code>memo[1]</code>, but all subsequent calls are going to be \"free\".</p>\n\n<p>I can now use this implementation to compute the sum over even values:</p>\n\n<pre><code>fib_sum = (i) -&gt;\n // Initialize i to 0 for the first call\n if i is undefined then i = 0\n\n return 0 if fib(i) &gt; limit\n\n if fib(i) % 2 == 0\n return fib_sum(i + 1) + fib(i)\n else \n return fib_sum(i + 1)\n</code></pre>\n\n<p>You can use a tail-recursive function if you want but this won't help since you're probably going to overflow before doing a stack overflow.</p>\n\n<h2>Purely functional from the outside</h2>\n\n<p>Now the implementation seems functional but there's still this \"memo\" array that we would like to hide. Well, closures are the perfect way to achieve this. This is called the \"pattern module\" in JavaScript. Here's the full code:</p>\n\n<pre><code>fibonacci = (() -&gt;\n 'use strict'\n\n memo = [1, 1]\n limit = 4000000\n\n fib = (x) -&gt;\n if typeof memo[x] != 'number'\n memo[x] = fib(x - 1) + fib(x - 2)\n\n return memo[x]\n\n even_sum = (i) -&gt;\n if i is undefined then i = 0\n\n return 0 if fib(i) &gt; limit\n\n if fib(i) % 2 == 0\n return even_sum(i + 1) + fib(i)\n else \n return even_sum(i + 1)\n\n return {nth: fib, even_sum: even_sum}\n)()\n\nconsole.log fibonacci.even_sum(); # 4613732\n</code></pre>\n\n<p>There's no way to know that out <code>fibonacci</code> module uses an array internally, but it's still used and allows for very fast code. Benchmarking show that it's as fast as the iterative version, and takes about 0.02s on my machine.</p>\n\n<h2>Automatic memoization?</h2>\n\n<p>It turns out that <em>JavaScript: The Good Parts</em> mentions that you can have <a href=\"http://goo.gl/jCWnO\" rel=\"nofollow\">automatic memoization</a> and uses fibonacci as an example. It can be interesting to try to apply this to our fib_sum, but I'll leave it as an exercise. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T13:52:34.673", "Id": "11554", "ParentId": "8283", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T16:13:53.487", "Id": "8283", "Score": "4", "Tags": [ "javascript", "functional-programming", "project-euler", "coffeescript", "fibonacci-sequence" ], "Title": "Project Euler question 2 in CoffeeScript" }
8283
<p>I am running through a file and inserting elements one by one. The counties all contain specific county codes which are duplicated many times throughout the file. I am looking for a way to assign these codes to a specific county while ignoring duplicate county codes.</p> <p>I have two versions I wrote below with runtimes:</p> <p><strong><code>getCodes()</code></strong></p> <pre><code>def get_codes(data): code_info = {} for row in data: county = row["county"] code = int(float(row["code"])) if code &gt; 100000: code = code/100 if county not in code_info: code_info[county] = [] code_info[county].append(code) for county in code_info: code_info[county] = list(set(code_info[county])) return code_info </code></pre> <p><strong><code>get_codes2()</code></strong></p> <pre><code>def get_codes2(data): code_info = {} for row in data: county = row["county"] code = int(float(row["code"])) if code &gt; 100000: code = code/100 if county in code_info: if not code in code_info[county]: code_info[county].append(code) else: code_info[county] = [] code_info[county].append(code) return code_info </code></pre> <p></p> <pre><code>county_data = csv.DictReader(open("county_file.txt")) start = time.time() county_codes = get_codes(county_data) end = time.time() print "run time: " + str(end-start) county_data = csv.DictReader(open("county_file.txt")) start = time.time() county_codes = get_codes2(county_data) end = time.time() print "run time: " + str(end-start) </code></pre> <p>Also, it's probably obvious from this, but county codes that are greater than 100000 can have trailing zeroes accidentally added, so I'm removing them by dividing by 100. As another note, the <code>int(float())</code> conversion is intentional. Sometimes the county codes are values such as "27.7" and need to be converted to "27", other times they are just basic <code>int</code>s.</p> <p>The runtimes on my system:</p> <ul> <li><code>get_codes</code>: 9 seconds</li> <li><code>get_codes2</code>: 14 seconds</li> </ul> <p>How can I improve this further for better performance?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T05:52:30.913", "Id": "13321", "Score": "0", "body": "Python 2.5 supports a [`defaultdict`](http://blog.ludovf.net/python-collections-defaultdict/), which might save some time with the \"if county in code_info\" checks." } ]
[ { "body": "<p>I think you're pretty close to optimal here. I made a few tweaks, to avoid some conditionals by using sets instead. I don't actually know if it'll run faster; you'll need to benchmark it, and it likely depends on the breakdown of how many dupes per county there are.</p>\n\n<pre><code>def get_codes3(data):\n from collections import defaultdict\n codeinfo = defaultdict(set)\n for row in data:\n county = row[\"county\"]\n # remove float() if you can get away with it - are there\n # actually values like '1.5' in the data?\n code = int(float(row[\"code\"]))\n if code &gt; 100000:\n code = code/100\n\n codeinfo[county].add(code)\n # if you can get away with sets instead of lists in your return\n # value, you're good\n return code_info\n # otherwise:\n # return dict([(county, list(info)) for county, info in code_info.iteritems()])\n</code></pre>\n\n<ul>\n<li>You don't need <code>float()</code> unless the data is actually like <code>\"123.45\"</code> - it's not clear if that's the case</li>\n<li><code>set</code>s can work in most places that lists work, so you might not need to convert to a list</li>\n<li>It might be worth it to write a script that does just the <code>x = x/100 if x &gt; 100000</code> part and writes that out to a new file</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:07:33.953", "Id": "12945", "Score": "0", "body": "I ran a few bench marks, the time difference was negligible (usually within a few hundredth of a second).\n\nTo respond to a few of your questions:\n1. Yes, I need int(float()) there. There are some values like \"123.45\" that need to be converted to \"123\", but most are already integers. You are definitely right though, I should have mentioned this in my original post\n2. Yeah, I" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:14:06.703", "Id": "12947", "Score": "0", "body": "2. You may be correct on the set issue, but I need to access the data structure by index later on, so I'd prefer to convert it to a list. 3. That would be ideal solution, but the data in the file may change but the format issue won't. You solution looks a lot more elegant than mine though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:31:45.810", "Id": "12949", "Score": "1", "body": "@MikeJ, if you ran AdamKG's exact code for your benchmark, you should try it again with the import moved outside of the function. As I understand imports are actually pretty expensive. Also, try dropping the square brackets for the alternate return. There's not much reason to generate a list first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:02:03.273", "Id": "12987", "Score": "0", "body": "Additionally, you could write `code = code / 100` as `code /= 100` if you're going for brevity. It doesn't do much for performance, but it's quicker to read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T18:49:47.600", "Id": "8287", "ParentId": "8284", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T17:48:51.273", "Id": "8284", "Score": "2", "Tags": [ "python", "optimization", "parsing", "csv" ], "Title": "Parsing files with county codes" }
8284