body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<blockquote>
<p>HTTP Strict Transport Security (HSTS) is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS.</p>
</blockquote>
<p>Currently, there is no built in support for HSTS in MVC. So I decided to create an filter attribute that I can use as part of my application. There are a few questions about the code I have written which are: </p>
<ul>
<li>I have used an action filter for granularity, but would a module/handler been better? If so, why?</li>
<li>Should the default of the attribute be to include sub domains, or exclude them (currently it excludes them)</li>
<li>The default timeout for the header is 300 seconds. This is a randomly picked arbitrary value. Is this value too much/too little?</li>
</ul>
<p><em>The attribute is designed to compliment the <code>RequireHttpsAttribute</code></em></p>
<pre><code> using System;
using System.Globalization;
using System.Web.Mvc;
public class HSTSAttribute : ActionFilterAttribute
{
private const string HeaderName = "Strict-Transport-Security";
private readonly string _headerValue;
private readonly bool _includeSubDomains;
public HSTSAttribute(bool includeSubDomains = false)
: this(300, includeSubDomains)
{
}
public HSTSAttribute(TimeSpan duration, bool includeSubDomains = false)
: this(duration == null ? 300 : duration.Seconds, includeSubDomains)
{
}
public HSTSAttribute(int duration, bool includeSubDomains = false)
{
if (duration <= 0)
{
throw new ArgumentException();
}
var includeSubDomainsSuffix = includeSubDomains ? String.Empty : "; includeSubDomains";
_headerValue = String.Format("max-age={0}{1}", duration.ToString(CultureInfo.InvariantCulture)
, includeSubDomainsSuffix);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// HSTS headers should be sent via HTTPS responses only : http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2
// They should also not be duplicated
if (filterContext.HttpContext.Request.IsSecureConnection
&& filterContext.HttpContext.Response.Headers[HeaderName] == null)
{
filterContext.HttpContext.Response.AddHeader(HeaderName, _headerValue);
}
base.OnResultExecuted(filterContext);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T15:59:05.290",
"Id": "85678",
"Score": "0",
"body": "In production you'll use durations of at least a month. The only reason for small values is that you can recover more quickly when you discover that part of you website doesn't work with HTTPS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T16:01:27.483",
"Id": "85679",
"Score": "0",
"body": "Why have defaults at all? These are so important decisions that forcing the user to choose explicitly may be a good idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-28T01:31:08.977",
"Id": "296239",
"Score": "0",
"body": "You should also use TotalSeconds on the TimeSpan instead of Seconds."
}
] | [
{
"body": "<p>I would suggest setting the message on ArgumentException to your parameter name</p>\n\n<p>e.g.</p>\n\n<pre><code>throw new ArgumentException(\"'duration' must be greater than 0\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:47:58.230",
"Id": "85109",
"Score": "0",
"body": "can you explain why you would do this please? it makes for a better review. Thank you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:56:58.823",
"Id": "85111",
"Score": "0",
"body": "it should also be `throw new ArgumentException(duration + \" must be greater than 0\");` duration is a variable and doesn't belong inside of quotes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:51:57.423",
"Id": "85124",
"Score": "1",
"body": "@Malachi that would end up being the contents of the parameter being included in the message, not the name of the parameter. That was included as part of my edit :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:18:57.660",
"Id": "85127",
"Score": "0",
"body": "my bad, you wanted the variable to be written out in the exception, sorry took me a minute to follow that @StuartBlackler"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:44:47.047",
"Id": "48482",
"ParentId": "48314",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48482",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T10:16:46.337",
"Id": "48314",
"Score": "6",
"Tags": [
"c#",
"security",
"asp.net-mvc"
],
"Title": "Implementing HTTP Strict-Transport-Security via MVC action filter"
} | 48314 |
<p>Recently I have given an interview to a widely well-known technology firm. The first interview was general and it went well but they rejected based on some technical things. They did not mention it so I expect may be due to my Coding Exercise that I submitted is not well designed.</p>
<p>It would be great if someone point out me my mistakes in the coding exercise. I have uploaded complete project code at git. <a href="https://github.com/aahad/Interviews/" rel="nofollow noreferrer">https://github.com/aahad/Interviews/</a></p>
<p>The Coding Exercise description was:</p>
<blockquote>
<p>Given a list of test results (each with a test date, Student ID, and
the student’s Score), return the Final Score for each student for a
user inputted date range. A student’s Final Score is calculated as the
average of his/her 5 highest test scores. You can assume each student
has at least 5 test scores.</p>
<p>We will evaluate your answer on:</p>
<ul>
<li>Correctness, does it work?</li>
<li>Is it tested?</li>
<li>Is it well designed?</li>
<li>Is the code easy to comprehend?</li>
<li>Would this code be easy to extend or maintain? </li>
</ul>
<p>Your implementation must be your own, making use of your standard
library. Please feel free to consult any relevant documentation.</p>
</blockquote>
<p><strong>The code works fine as per the given requirements and it does not have any issues</strong>. </p>
<p>I only expect that it might be possible that it is not designed well OR it could be designed in much better way, OR its not fast, scalable etc. These might be the reasons that's why got rejected.</p>
<p><strong>Code</strong></p>
<p>The code can also be found on <a href="https://github.com/aahad/Interviews/" rel="nofollow noreferrer">https://github.com/aahad/Interviews/</a></p>
<p><strong>Project Structure</strong>
<img src="https://i.stack.imgur.com/CSGBm.png" alt="enter image description here"></p>
<p>The <strong>Controller Package</strong> (<strong>com.students.controller</strong>) has three classes:</p>
<p><strong>DataLoader</strong> ( 102 lines ) </p>
<pre><code>package com.students.controller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;
import com.students.model.Student;
import com.students.model.StudentTest;
import com.students.util.AppConfig;
import com.students.util.Utility;
/*
* This class is loading Student Data from a properties file via AppConfig.getStudentsDataFile()
*
*/
public class DataLoader {
private final static Logger LOGGER = Logger.getLogger(DataLoader.class .getName());
public static ArrayList<Student> loadStudentsData() {
ArrayList<Student> studentsCollection = new ArrayList<Student>(100);
try (BufferedReader br = new BufferedReader(new FileReader( AppConfig.getStudentsDataFile()) ) ) {
String recordLine = new String();
String lineItems[] = new String[3];
while ((recordLine = br.readLine()) != null) {
Student student = new Student();
StudentTest studentTest = new StudentTest();
lineItems = recordLine.split(",") ;
System.out.println( lineItems[0] + " " + lineItems[1] + " " + lineItems[2] );
student.setStudentID( Integer.parseInt(lineItems[1]) ); // second item is ID
int index ;
if ( (index = studentsCollection.indexOf(student) ) > -1 ) {
student = studentsCollection.get(index);
}
studentTest.setTestDate( Utility.convertStringIntoDate( lineItems[0] ) ); // first item is Date
studentTest.setTestScore( Float.parseFloat(lineItems[2] ) ); // first item is Score
student.addStudentTest(studentTest);
if ( index == -1) {
studentsCollection.add(student);
}
}
} catch (IOException e) {
LOGGER.warning( e.getMessage() );
}
return studentsCollection;
}
public static String[] getStudentRecordInParts(String record) {
if (record == null || record.length() < 1 )
throw new IllegalArgumentException("");
String items[] = new String[3];
int index =0;
StringBuffer item =new StringBuffer();
for(int i=0; i < record.length() ; i++ ) { //one record looks like 10-04-2014,1,60
if (record.charAt(i) != ',') {
item.append( record.charAt(i) );
}else {
items[index] = item.toString() ; //add into array
item.delete(0, item.length()); //clear previous item
index++;
}
}
if (item.length() > -1 ) { //Add last item into array
items[index] = item.toString() ;
}
//LOGGER.info(items.toString());
return items;
}
}
</code></pre>
<p><strong>DateSearchController</strong> class ( 41 lines )</p>
<pre><code>package com.students.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.TreeSet;
import com.students.model.Student;
import com.students.model.StudentTest;
/*
* This class works as a controller to search records by date and populate Search Results collection
*
*/
public class DateSearchController {
public static TreeSet<SearchResult> searchStudentScore( Date frmDate, Date toDate) {
ArrayList<Student> students = DataLoader.loadStudentsData();
TreeSet<SearchResult> results =new TreeSet<SearchResult>() ;
for(Iterator<Student> iterator = students.iterator() ; iterator.hasNext(); ) {
Student st = iterator.next();
SearchResult rs =new SearchResult();
for( Iterator<StudentTest> testItrator = st.getStudentTestsCollection().iterator(); testItrator.hasNext(); ) {
StudentTest stest = testItrator.next();
if ( stest.getTestDate().compareTo(frmDate ) >=0 && stest.getTestDate().compareTo(toDate) <= 0 ) {
rs.setStudentID(st.getStudentID());
rs.addScore( stest.getTestScore() );
}
}
results.add(rs);
}
return results;
}
}
</code></pre>
<p><strong>SearchResult</strong> class ( 71 lines )</p>
<pre><code>package com.students.controller;
import java.util.TreeSet;
/*
* This class will hold all results score and will return final score
*
*/
public class SearchResult implements Comparable{
private int student;
private TreeSet<Double> scores = new TreeSet<Double>();
public void setStudentID(int student) {
this.student = student;
}
public int getStudentID() {
return this.student ;
}
public double getFinalScore() {
Object[] arr = scores.toArray();
double finalScore = 0;
int index = 0;
for(int i=arr.length - 1; i >= 0; i--) {
finalScore += (double)arr[i];
index++;
if( index == 5 ) break;
}
return finalScore / index;//
}
public void addScore(double dl) {
scores.add(dl);
}
@Override
public String toString() {
return this.student + " - " + getFinalScore();
}
@Override
public boolean equals(Object v) {
return this.student == ((SearchResult)v).student ;
}
@Override
public int hashCode() {
int hash = 5;
hash = 89 + hash + (this.scores != null ? this.scores.hashCode() : 0);
hash += 89 + hash + this.student;
return hash;
}
@Override
public int compareTo(Object v) {
return (this.student - ((SearchResult)v).student);
}
}
</code></pre>
<p>The <strong>Model Package</strong> (<strong>com.students.model</strong>) contains two classes:</p>
<p><strong>Student</strong> class (50 lines)</p>
<pre><code>package com.students.model;
import java.util.ArrayList;
import java.util.TreeSet;
/*
* This is the main student class to hold each record entry
*
*/
public class Student {
private int studentID;
private ArrayList<StudentTest> testsCollections ;
public Student() {
testsCollections = new ArrayList<StudentTest>();
}
public void setStudentID(int id) {
this.studentID = id;
}
public int getStudentID() {
return this.studentID ;
}
public void addStudentTest(StudentTest test) {
this.testsCollections.add(test);
}
public ArrayList<StudentTest> getStudentTestsCollection() {
return this.testsCollections ;
}
@Override
public boolean equals(Object v) {
return this.studentID == ((Student)v).studentID ;
}
@Override
public int hashCode() {
int hash = 5;
hash = 89 + hash + (this.testsCollections != null ? this.testsCollections.hashCode() : 0);
hash += 89 + hash + this.studentID;
return hash;
}
}
</code></pre>
<p><strong>StudentTest</strong> class (31 lines )</p>
<pre><code>package com.students.model;
import java.util.Date;
import java.util.TreeSet;
/*
* This student Test class hold record details by date and score
*
*/
public class StudentTest {
private Date date;
private double score;
public void setTestDate(Date date) {
this.date = date;
}
public Date getTestDate() {
return this.date ;
}
public void setTestScore(double score) {
this.score = score;
}
public double getTestScore() {
return this.score ;
}
}
</code></pre>
<p>The <strong>View Package</strong> (<strong>com.students.view</strong>) contains only one class:</p>
<p><strong>Command</strong> class (29 lines)</p>
<pre><code>package com.students.view;
import java.util.Iterator;
import java.util.TreeSet;
import com.students.controller.DateSearchController;
import com.students.controller.SearchResult;
import com.students.util.AppConfig;
/*
* Here is the main Class with main method , it is just going to search all loaded recorded and show final results
*
*/
public class Command {
public static void main(String[] arg) {
TreeSet<SearchResult> sr = DateSearchController.searchStudentScore( AppConfig.getFromDate(), AppConfig.getToDate());
for(Iterator<SearchResult> it = sr.iterator(); it.hasNext();) {
SearchResult st = it.next();
System.out.println( st );
}
}
}
</code></pre>
<p>The <strong>Util Package</strong> (<strong>com.students.util</strong>) contains two classes:</p>
<p><strong>AppConfig</strong> class (55 lines)</p>
<pre><code>package com.students.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;
/*
* This class loads Application configuration details form properties file
*
*/
public class AppConfig {
public static final Properties prop = new Properties();
private static AppConfig appConfig;
private final static Logger LOGGER = Logger.getLogger(AppConfig.class .getName());
static {
getInstance();
}
private AppConfig() {
try (InputStream appConfig= new FileInputStream("config.properties") ) {
// load properties
prop.load(appConfig );
} catch (IOException io) {
io.printStackTrace();
}
}
public static synchronized AppConfig getInstance() {
if (appConfig == null) {
appConfig = new AppConfig();
}
LOGGER.info("loaded instance");
return appConfig;
}
public static String getStudentsDataFile() {
return prop.getProperty("filepath");
}
public static Date getFromDate() {
return Utility.convertStringIntoDate( prop.getProperty("FromDate") );
}
public static Date getToDate() {
return Utility.convertStringIntoDate( prop.getProperty("ToDate") );
}
}
</code></pre>
<p><strong>Utility</strong> class (27 lines)</p>
<pre><code>package com.students.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
public class Utility {
private final static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private final static Logger LOGGER = Logger.getLogger(Utility.class .getName());
public static Date convertStringIntoDate(String date) {
Date dt= new Date();
try{
dt = formatter.parse(date);
}catch(ParseException e){
LOGGER.info("Exam Date format Exception: " + e.getStackTrace() ) ;
}
return dt;
}
}
</code></pre>
<p>The project has one configuration (<strong>config.properties</strong>) file that has three things:</p>
<ol>
<li><p>The path and name of a data file that contains students records that will be
processed in the application and will be shown as per requirements i.e. </p>
<blockquote>
<p>Given a list of test results (each with a test date, Student ID, and
the student’s Score), return the Final Score for each student for a
user inputted date range. A student’s Final Score is calculated as the
average of his/her 5 highest test scores. You can assume each student
has at least 5 test scores.</p>
</blockquote></li>
<li><p>From Date </p></li>
<li>To Date</li>
</ol>
<p>The students data is saved in a CVS file under data folder inside the project and its path is set in the config.properties file. Data file can be placed on any path but config.properties path needs to be pointed out correctly.</p>
<p>Each student record will look like ( <strong>YYYY-MM-DD , StudentID , Exam Score</strong> )</p>
<p><img src="https://i.stack.imgur.com/WkEOK.png" alt="enter image description here"></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:32:31.920",
"Id": "84822",
"Score": "0",
"body": "I don't have time for a full review and might do it later, but just a first thing I noticed: Object should not have `ArrayList` as a type, but only use the interface `List`. Similarly, use `Set` as a type instead of `TreeSet` etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:45:37.520",
"Id": "84825",
"Score": "0",
"body": "To add one more thing: [Don't use a static DateFormatter field](http://stackoverflow.com/questions/8426382/simple-date-format)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:56:23.117",
"Id": "84829",
"Score": "0",
"body": "The first thing that came to my mind when reading the exercise: why reinvent the wheel? I'd just drop the CSV into a database and write a single query. Done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:57:52.717",
"Id": "84831",
"Score": "1",
"body": "@Prinzhorn Not every application can use databases, besides it's an interview question and third-party libraries were disallowed – I think databases would be disallowed as well."
}
] | [
{
"body": "<h1>General</h1>\n<ul>\n<li>Your formatting isn't very clean. You have random spaces, empty lines and indentations everywhere.</li>\n<li><a href=\"https://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered\">Use interfaces instead of concrete types where possible</a>.</li>\n<li>You use a logger, but either hardly use it, or write unhelpful information. Either use it properly and consistently everywhere with helpful messages, or drop it entirely.</li>\n</ul>\n<h1>Class <code>Student</code></h1>\n<ul>\n<li><strong>EDIT:</strong> Since the ID is integral part of the student class you should set it in the constructor and remove <code>setStudentID</code> since it makes no sense to change it after the fact.</li>\n<li><code>testsCollections</code> isn't a good field name. It's a single collection of test so <code>testsCollection</code> or even better just <code>tests</code>.</li>\n<li><code>getStudentTestsCollection</code> (better: <code>getTests</code>) shouldn't return your internal list representation otherwise external code could modify your list. Use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29\" rel=\"nofollow noreferrer\"><code>collections.unmodifiableList</code></a> to protect from that.</li>\n<li>Don't include the tests into the hash code. Two <code>Student</code> objects with the same ID represent the same student irregardless of the assigned tests. Also keep in mind that two objects that are <code>equal()</code> must return the same hash code.</li>\n</ul>\n<h1>class <code>StudentTest</code></h1>\n<ul>\n<li><p><code>StudentTest</code> is a bad name. It hasn't anything to do with students. <code>Test</code> is fine or - if you think could be confused with development tests - maybe <code>TestScore</code>.</p>\n</li>\n<li><p>Drop <code>Test</code> from all the getters and setters.</p>\n</li>\n</ul>\n<h1>class <code>AppConfig</code></h1>\n<p><code>AppConfig</code> may be a bit over-engineered for such a simple project. Representing each setting as it's own getter leads to a lot of maintenance every time you add a new setting. Using <code>Properties</code> directly or just a thin wrapper around it would suffice IMHO. Actually in this case I'd drop it all together and get the parameters from the command line, since theses aren't settings, but data.</p>\n<h1>class <code>DateSearchController</code></h1>\n<ul>\n<li>Loading the data doesn't belong in the search method. It should be done before.</li>\n<li>Iterators? Seriously? It's (<em>check watch</em>) 2014. Use the enhanced <code>for</code> loop.</li>\n</ul>\n<h1>class <code>DataLoader</code></h1>\n<ul>\n<li>Consider using a third party CSV file reader.</li>\n<li>Prefilling <code>recordLine</code>and <code>lineItems</code> makes no sense what so ever since they are overwritten. You are aware that <code>String</code>s are immutable?</li>\n<li>Also <code>lineItems</code> is only used inside the <code>while</code> loop, so it be declared there.</li>\n<li>Now it's getting confusing. You first create a <code>Student</code> object, set its ID, but then search your list of Students for an one with the same ID and if you find one, throw the one you just created away without using it? Or looking at the bigger picture: Each line in the file represents a <code>Test</code>, yet you create a <code>Student</code> object for each line.</li>\n<li>What is <code>getStudentRecordInParts</code>? You don't seem to use it.</li>\n</ul>\n<p><strong>EDIT</strong>: Added more stuff.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:35:03.887",
"Id": "48338",
"ParentId": "48320",
"Score": "6"
}
},
{
"body": "<p>Adding to @RoToRa's points:</p>\n\n<ul>\n<li><p>Unused methods <code>DataLoader.getStudentRecordInParts()</code> and <code>SearchResult.compareTo()</code></p></li>\n<li><p>I don't quite get why <code>AppConfig</code> is specifically constructed to be a singleton, since there really isn't a global state to speak of in your application, much less a good use case for a singleton. I concur with RoToRa, it's perhaps better to read them in and pass to your other methods accordingly.</p></li>\n<li><p>I can't help but feel that your solution is over-engineered for the simple question provided... You document two 'model' classes but <code>SearchResult</code> sounds like one as well. <code>DataLoader</code> creates a new <code>Student</code> class when reading every line, but they get discarded if you can retrieve a previous entry from your <code>List</code> of <code>Student</code>s. <code>StudentTest</code> does nothing other than to wrap two values, it's not even properly used by <code>SearchResult</code> since that takes in the numeric test scores straight. All these mean that you have effectively employed three different classes just to read three values into a <code>List</code> and to perform the required computation.</p></li>\n<li><p>Your <code>equals()</code> and <code>hashcode()</code> implementations in both <code>Student</code> and <code>SearchResult</code> is inconsistent. This is confusing to other programmers at best, and will introduce bugs at worst because modifying these classes may unknowingly alter whether instances will still be equal to each other or not.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:54:11.003",
"Id": "48339",
"ParentId": "48320",
"Score": "2"
}
},
{
"body": "<p>You could have used a Map instead of ArrayList for students collection. Here in the below code you are searching for student for each record. If you have 100 students and average 6 records per student then you have worst case complexity of O(600). So using Map makes sense here. </p>\n\n<pre><code> if ( (index = studentsCollection.indexOf(student) ) > -1 ) {\n\n student = studentsCollection.get(index);\n\n }\n</code></pre>\n\n<p>Other thing is for the exception you are throwing here. You can definately add some meaningful message to this exception. Makes no sense in hiding that record was null or empty. </p>\n\n<pre><code>if (record == null || record.length() < 1 )\n throw new IllegalArgumentException(\"\");\n</code></pre>\n\n<p>Yes I also feel that the whole application is over engineered. This task shouldn't be this much verbose. If I am given authority of judging a guy who writes this much code for simple task then I would be a little worried. The reason is that I am maintaing an application which is way too much over engineered intentionally and now we are facing a hard time maintaing it. I shared my thoughts so that you can see the other aspect as well . Hope this helps. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:00:43.523",
"Id": "48354",
"ParentId": "48320",
"Score": "2"
}
},
{
"body": "<p>Something nobody else noticed is the Utility class is not thread safe since it re-uses an existing SimpleDateFormat <a href=\"http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow\">see Synchronization section in the SimpleDateFormat API</a>. SimpleDateFormat is not thread safe and must be synchronized externally if an instance is re-used. The Utility class can also hide the parse exception (logging it as INFO which may also be missed) resulting in an incorrect date being returned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:11:47.363",
"Id": "48576",
"ParentId": "48320",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48338",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T11:58:06.937",
"Id": "48320",
"Score": "8",
"Tags": [
"java",
"interview-questions"
],
"Title": "Calculate final test score from a list of test results"
} | 48320 |
<p>Below is the code for the problem at <a href="http://www.codechef.com/problems/ROTSTRNG/" rel="nofollow">Codechef</a>. I have made use of the <code>String</code> method <code>.equals</code> in my solution which is working fine for all the test inputs. However, I am getting a Time Limit Exceeded when I submit to the Judge. I need your ideas on optimizing the code.</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String args[]) throws IOException
{
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
int not=Integer.parseInt(in.readLine());
for(int i=0;i<not;i++)
{
String s=in.readLine();
int count=0;
String inp[]=in.readLine().trim().split(" ");
int m=Integer.parseInt(inp[0]);
int p=Integer.parseInt(inp[1]);
//System.out.println(m+" "+p);
String temp=s;
for(int b=0;b<(Integer.MAX_VALUE/2);b++)
{
//System.out.println(temp);
String s1=rotate(m,temp);
//System.out.println(s1);
count++;
if(s1.equals(s))
break;
String s2=rotate(p,s1);
//System.out.println(s2);
count++;
if(s2.equals(s))
break;
temp=s2;
}
if(count>0)
System.out.println(count);
else
System.out.println(-1);
}
} private static String rotate(int m, String s) {
char sa[]=s.toCharArray();
int l=sa.length;
StringBuilder sb=new StringBuilder();
for(int j=m-1;j>=0;j--)
{
sb.append(sa[l-1-j]);
}
for(int k=0;k<(l-m);k++)
sb.append(sa[k]);
return sb.toString();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:58:34.113",
"Id": "84832",
"Score": "4",
"body": "The first step to clean code is proper formatting and avoiding pointless empty lines. Please fix your code, it will make it easier to read and review."
}
] | [
{
"body": "<p>I would use an entirely different strategy to determine the number of times needed to rotate the string: addition.</p>\n\n<p>Since rotating a string by <code>a</code> and then <code>b</code> yields the same result as rotating it <code>a+b</code>, we do not need to keep track of the string at all, only the equivalent rotation. However, we do need to be able to detect if the string is actually just concantenations of some substring; in that case we can treat it as if its length were the length of the repeated substring.</p>\n\n<p>Here are the steps I would use for each string:</p>\n\n<ol>\n<li><p>Match the string against the regular expression <code>(.+?)\\1+</code>. This uses a backreference to find the iterated portions of the string. (FYI, this regex may need some adjustment.)</p>\n\n<pre><code>static final Pattern iteratedSubstring = Pattern.compile(\"(.+?)\\\\1+\");\nstatic int reducedLength(String string){\n Matcher m = iteratedSubstring.matcher();\n if(m.matches(input)) return m.group(1).length()\n\n return string.length()\n}\n</code></pre></li>\n<li><p>Repeatedly accumulate the two rotations until the rotation is congruent to zero modulo the length.</p>\n\n<pre><code>static int identityRotationCount(final int length, int ... rotations){\n rotations = Arrays.stream(rotations).parallel().flatMap(i->i%length).toArray();\n\n /* alternately, if you can't use java 8 you can do this, although it's slower:\n for(int idx = 0; idx < rotations.length; idx++)\n rotations[idx] %= length;\n */\n\n int count = 0, rotation = 0;\n\n while(true)\n for(int rot: rotations){\n count++;\n rotation += rot;\n if(rotation == length) return count;\n if(rotation > length) rotation -= length;\n }\n}\n</code></pre>\n\n<p>There may be even faster methods to compute this, including variants on algorithms for finding a <a href=\"http://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"nofollow\">GCD</a> or other discrete algebra type things. </p></li>\n<li><p>At least at first, you should be using a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html\" rel=\"nofollow\"><code>Scanner</code></a> to process the input, because inevitable parsing logic bugs from doing the parsing yourself will make debugging anything else extremely difficult.</p>\n\n<pre><code>try(Scanner in = new Scanner(System.in), PrintWriter out = System.out){\n // ...\n}\n</code></pre></li>\n<li><p>Finish the program:</p>\n\n<pre><code>in.nextInt(); //discard input entry count, don't need it.\n\nwhile(true){\n if(!in.hasNextLine()) break;\n String string = in.nextLine();\n\n if(!in.hasNextInt()) break;\n int monkey = in.nextInt();\n\n if(!in.hasNextInt()) break;\n int po = in.nextInt();\n\n out.println(identityRotationCount(reducedLength(string), monkey, po));\n}\n</code></pre></li>\n<li><p>If you do not want to use a <code>Scanner</code>, try something like this:</p>\n\n<pre><code>try(BufferedReader in = new BufferedReader(System.in), PrintWriter out = System.out){\n int n = Integer.parseInt(in.readLine());\n\n for(int idx = 0; idx < n; idx++){\n String string = in.readLine();\n\n String [] rots = in.readLine().split(\"\\\\s\");\n\n int monkey = Integer.parseInt(rots[0]),\n po = Integer.parseInt(rots[1]);\n\n out.println(identityRotationCount(reducedLength(string), monkey, po));\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:04:00.317",
"Id": "85000",
"Score": "0",
"body": "CodeChef has language specific [suggestions and considerations (Java)](http://www.codechef.com/wiki/java) for their challenges. `Scanner` usage is mentioned."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:12:36.180",
"Id": "48350",
"ParentId": "48323",
"Score": "5"
}
},
{
"body": "<p>First of all, clean up your code, it's a mess.</p>\n\n<hr>\n\n<p>Java normally uses a modified K&R Style with the opening braces on the same line and omitting braces is not allowed, like this:</p>\n\n<pre><code>void test() {\n if (something) {\n // code\n } else {\n // code\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public static void main(String args[]) throws IOException\n{\n</code></pre>\n\n<p>Your main method should not throw exceptions, <em>ever</em>. It should handle exceptions and fail gracefully if necessary.</p>\n\n<hr>\n\n<pre><code>BufferedReader in =new BufferedReader(new InputStreamReader(System.in));\n\nint not=Integer.parseInt(in.readLine());\n</code></pre>\n\n<p>First rule of naming variables is: You name the variables after what they contain. <code>not</code> is a not very good name for a variable, neither is <code>in</code> or <code>sa</code>. Ideally you could read every line of the code without context and tell what it does.</p>\n\n<p>Quick: Tell me what this code piece does: <code>sb.append(sa[l-1-j]);</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:21:48.050",
"Id": "85019",
"Score": "1",
"body": "I would argue that a variable name like `in` could be very descriptive, depending on how you are using it. If you are declaring it in a try resource block, then it is extremely descriptive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:15:11.677",
"Id": "48439",
"ParentId": "48323",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:22:33.097",
"Id": "48323",
"Score": "4",
"Tags": [
"java",
"strings",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "\"Rotating the string\" optimization"
} | 48323 |
<p>I'm writing a driver in C for a WiFi module attached to a PIC18 microcontroller. I want to implement some functions that I'm familiar with in computer application level programming like Window's API <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms740121%28v=vs.85%29.aspx">recv</a> function for WinSock.
The module itself already implements the WiFi communication protocol and the TCP/IP stack, and communicate with the PIC18 microcontroller through UART.</p>
<p>Is this the correct way to achieve this? Efficiency is very important here (It's an embedded system too).</p>
<pre><code>#define RECEIVE_TIMEOUT 200
#define RECEIVE_RETRY_COUNT 4
UINT16 ReceiveData(void* _data, UINT16 length)
{
UINT16 received = 0;
UINT8 retry_count = 0;
while(received < length)
{
if(UART1_Data_Ready())
{
((BYTE*)_data)[received] = ReceiveByte();
received++;
continue;
}
if(retry_count == RECEIVE_RETRY_COUNT)
break;
retry_count++;
Delay_ms(RECEIVE_TIMEOUT/RECEIVE_RETRY_COUNT);
}
return received;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:39:43.593",
"Id": "84806",
"Score": "0",
"body": "Could you give further details about `ReceiveByte()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:49:45.883",
"Id": "84808",
"Score": "0",
"body": "@no1 The ReceiveByte() part is just a simple UART read. `UART1_Read()`. I don't know the specific of this function because it's from a library."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:11:42.700",
"Id": "84815",
"Score": "1",
"body": "How is `Delay_ms` implemented? nop loop, or asynchronous?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:13:22.660",
"Id": "84816",
"Score": "0",
"body": "@rolfl `Delay_ms()` Is implemented as loop."
}
] | [
{
"body": "<p>The only thing I see wrong with the algorithm is that if you don't have any data coming in from the WiFi module, you could potentially sit and wait for 200ms (the value of <code>RECEIVE_TIMEOUT</code>) before returning to the caller to say \"no data\". Is there other work that your main program could be doing during that time? If so, it might be worthwhile to split the check for incoming data and the reading of that data into separate functions.</p>\n\n<hr>\n\n<ul>\n<li><p>When setting up constants that measure physical quantities, I like to attach the units of measurement to the symbolic name. That way, it becomes obvious if you pass a millisecond quantity into a function that expects seconds or microseconds (or kilograms or... you get the idea).</p>\n\n<pre><code>#define RECEIVE_TIMEOUT_ms 200\n[... code elided ...]\n\n Delay_ms(RECEIVE_TIMEOUT_ms/RECEIVE_RETRY_COUNT);\n</code></pre></li>\n<li><p>The first parameter to the function is declared as <code>void *</code>, but its only use is as a <code>BYTE *</code>:</p>\n\n<pre><code>UINT16 ReceiveData(void* _data, UINT16 length)\n{\n [... code elided ...]\n ((BYTE*)_data)[received] = ReceiveByte();\n [... code elided ...]\n}\n</code></pre>\n\n<p>This is a strong hint that it should be declared as a <code>BYTE *</code> in the first place.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:16:32.200",
"Id": "84817",
"Score": "0",
"body": "This is exactly the problem I though could happen in this code, but I don't know what is the best solution to fix that. Any ideas? As for the other things you mentioned, for the defines there is a comment above them which explains what are they doing and what physical quantities they are using, but if you say it's not enough i'll take your advice :). As for the parameter type, I have a question: Where should I really use `void*` as parameter? (Except function pointer and parameterless function)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:44:04.163",
"Id": "84824",
"Score": "0",
"body": "Look into using the UART's \"data ready\" interrupt for detecting incoming data, and potentially using a Timer/Counter for the delay function as well. The explanatory comments on the #defines are great, but in the code, the definition can be far away from the point of use, so I think the extra information in the macro name is helpful. IMO, `void *` is only useful where you truly don't know or care about the type of something, e.g. malloc(), memset(), etc., or if you're defining a standard API that takes an unspecified user-defined type that they take responsibility for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:12:12.320",
"Id": "48332",
"ParentId": "48325",
"Score": "3"
}
},
{
"body": "<p>Your code is running synchronously (the <code>Delay_ms</code> is a spin loop). As a result, no other code can be running when you are waiting.</p>\n\n<p>Ideally, you should be using an interrupt handler (<code>PIR1.RCIF</code>) to wait on the message, and when the USART indicates there is data available, you can append it to a message buffer, and signal the main-loop code when the data buffer is complete.</p>\n\n<p>Consider reading up on some code examples <a href=\"http://ww1.microchip.com/downloads/en/DeviceDoc/usart.zip\" rel=\"nofollow\">( <strong>Link to zip file</strong> )</a>, and <a href=\"http://ww1.microchip.com/downloads/en/DeviceDoc/31018a.pdf\" rel=\"nofollow\">the USART data sheet (pdf)</a> for details on the interrupt handler.</p>\n\n<p>Using an interrupt would be a much better solution.</p>\n\n<p>On the other hand, your code is not spinning on the USART very efficiently anyway.</p>\n\n<p>You are waiting a full <code>Delay_ms</code> loop when the data may be available much sooner.</p>\n\n<p>Consider spinning the following way:</p>\n\n<pre><code>#define RECEIVE_TIMEOUT 200\n#define RECEIVE_RETRY_COUNT 4\n\nUINT16 ReceiveData(void* _data, UINT16 length)\n{\n UINT16 received = 0;\n UINT8 retry_count = 0;\n UINT16 timeout = 0;\n\n while(received < length)\n {\n timeout = TIMER1TICK; // pick a timer that cycles.... in your system\n timeout += TIMEALLOWED; // add the allowed timeout to the current time.\n while(TIMER1TICK != timeout && !UART1_Data_Ready())\n {\n // spin until data comes available on the USART\n\n }\n\n if(!UART1_Data_Ready())\n break; // timeout ....\n\n ((BYTE*)_data)[received] = ReceiveByte();\n received++;\n\n }\n\n return received;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:27:29.750",
"Id": "48336",
"ParentId": "48325",
"Score": "4"
}
},
{
"body": "<p>Just a small note on sleeping when waiting for input. As others have said\nyour loop is inefficient in that it uses a simple busy loop. This has at\nleast two potential problems:</p>\n\n<ol>\n<li><p>it prevent other activities from executing;</p></li>\n<li><p>it uses power.</p></li>\n</ol>\n\n<p>But these are not necessarily problems for <strong>your</strong> application. And if in\nyour application there really is nothing else to be done until bytes arrive\nand if power consumption is not a problem, then a busy loop is by far the\nsimplest solution.</p>\n\n<p>Using interrupts will inevitably complicate the rest of your code and should\nbe avoided <strong>unless really necessary</strong> (for example if there are other\ncomputing tasks that need to run while waiting for input).</p>\n\n<p>If 1 above is not important but 2 is (ie if you need to minimise power use)\nyou could put the core to sleep during waiting and have the byte-receive wake\nit. This would retain the benefit of avoiding interrupt handling. You would\nneed to set a timer to wake the core too if you need a timeout.</p>\n\n<p>On the details of your code, I dislike the use of Windows types in an embedded\nsystem. What is wrong with <code>int</code> and <code>char</code> or their unsigned varieties?</p>\n\n<p>Your leading underscore on <code>_data</code> is reserved by something or other and is anyway\npointless.</p>\n\n<p>I don't object to passing in a <code>void *</code> (after all, C stdlib functions <code>recv</code>\nand <code>read</code> do this), but I would assign it to a local variable of appropriate\ntype and avoid casts. This makes absolutely no difference when the buffer is\nused just once, as here and is just a personal preference.</p>\n\n<p>And using <code>continue</code> is usually frowned on and often unnecessary.</p>\n\n<pre><code>int ReceiveData(void *data, int length)\n{\n unsigned char *p = data;\n int received = 0;\n int retry = 0;\n\n while (received < length)\n {\n if (UART1_Data_Ready())\n {\n p[received++] = ReceiveByte();\n }\n else if (++retry <= RECEIVE_RETRY_COUNT)\n {\n Delay_ms(RECEIVE_TIMEOUT/RECEIVE_RETRY_COUNT);\n }\n else break;\n }\n return received;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:59:12.803",
"Id": "48376",
"ParentId": "48325",
"Score": "5"
}
},
{
"body": "<p>One more thing missed in other comments. The <code>UART</code> is capable of detecting errors. They do happen, and must be reported upstairs. You must read and analyze <code>RCSTA</code> before reading <code>RCREG</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T01:22:26.487",
"Id": "48379",
"ParentId": "48325",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48376",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:34:43.957",
"Id": "48325",
"Score": "7",
"Tags": [
"c",
"networking",
"embedded"
],
"Title": "Writing an interface for networking in an embedded system"
} | 48325 |
<p>Aim is to provide total head movement in different disk scheduling algorithms namely FCFS, SSTF, LOOK, C-LOOK, SCAN, C-SCAN.</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <math.h>
using namespace std;
int compare (const void * a, const void * b)
{
if ( *(int*)a < *(int*)b ) return -1;
if ( *(int*)a == *(int*)b ) return 0;
if ( *(int*)a > *(int*)b ) return 1;
}
void shift(int a[],const int size)
{
for(int i=1;i<=size;i++)
a[i-1]=a[i];
}
class disk
{
private :
int request[101];
int sorted_request[101];
int number_of_request;
int max;
int direction;
public :
disk()
{
cout<<"\nEnter maximum disk limit : ";
cin>>max;
}
void receive_request()
{
enter_request_number:
cout<<"\nEnter number of requests (max. 100): ";
cin>>number_of_request;
if(number_of_request>100)
goto enter_request_number;
current_location:
cout<<"\nEnter current location : ";
cin>>request[0];
sorted_request[0]=request[0];
if(request[0]>max||request[0]<0)
goto current_location;
current_direction:
cout<<"\nEnter current direction(0:left / 1:right) : ";
cin>>direction;
if(direction!=0&&direction!=1)
goto current_direction;
for(int i=1;i<=number_of_request;i++)
{
cout<<"\nEnter request number "<<i<<" : ";
cin>>request[i];
sorted_request[i]=request[i];
if(request[i]>max||request[i]<0)
{
cout<<"\nInvalid request !! Enter again!!";
i--;
}
}
qsort(sorted_request+1,number_of_request,sizeof(int),compare);
}
int fcfs()
{
int head_movement=0;
for(int i=1;i<=number_of_request;i++)
head_movement+=abs(request[i]-request[i-1]);
return head_movement;
}
int sstf()
{
int head_movement=0,flag=0,nor=number_of_request;
int request[101];
request[0]=sorted_request[0];
for(int i=1;i<=number_of_request;i++)
{
if(sorted_request[i]>sorted_request[0]&&flag==0)
flag=i;
request[i]=sorted_request[i];
}
while(nor)
{
if(flag==0)
{
head_movement+=request[0]-request[nor];
request[0]=request[nor];
}
else if(flag==1)
{
head_movement+=abs(request[nor]-request[0]);
break;
}
else if((request[flag]-request[0])>(request[0]-request[flag-1]))
{
head_movement+=request[0]-request[flag-1];
request[0]=request[flag-1];
flag--;
shift(request+flag,nor-flag);
}
else
{
head_movement+=request[flag]-request[0];
request[0]=request[flag];
shift(request+flag,nor-flag);
}
nor--;
}
return head_movement;
}
int SCAN()
{
int head_movement=0,flag=0;
for(int i=1;i<=number_of_request;i++)
if(sorted_request[i]>sorted_request[0]&&flag==0)
flag=i;
if(direction==1)
{
if(flag==1)
head_movement+=sorted_request[number_of_request]-sorted_request[0];
else
{
head_movement+=max-sorted_request[0];
head_movement+=max-sorted_request[1];
}
}
else
{
if(flag==0)
head_movement+=abs(sorted_request[number_of_request]-sorted_request[0]);
else
{
head_movement+=sorted_request[0];
head_movement+=sorted_request[number_of_request];
}
}
return head_movement;
}
int CSCAN()
{
int head_movement=0,flag=0;
for(int i=1;i<=number_of_request;i++)
if(sorted_request[i]>sorted_request[0]&&flag==0)
flag=i;
if(flag==1)
head_movement+=sorted_request[number_of_request]-sorted_request[0];
else
{
head_movement+=max-sorted_request[0];
head_movement+=max;
head_movement+=max-sorted_request[flag-1];
}
return head_movement;
}
int LOOK()
{
int head_movement=0,flag=0;
for(int i=1;i<=number_of_request;i++)
if(sorted_request[i]>sorted_request[0]&&flag==0)
flag=i;
if(direction==1)
{
if(flag==1)
head_movement+=sorted_request[number_of_request]-sorted_request[0];
else
{
head_movement+=sorted_request[number_of_request]-sorted_request[0];
head_movement+=sorted_request[number_of_request]-sorted_request[1];
}
}
else
{
if(flag==0)
head_movement+=abs(sorted_request[number_of_request]-sorted_request[0]);
else
{
head_movement+=sorted_request[1];
head_movement+=sorted_request[number_of_request]-sorted_request[1];
}
}
return head_movement;
}
int CLOOK()
{
int head_movement=0,flag=0;
for(int i=1;i<=number_of_request;i++)
if(sorted_request[i]>sorted_request[0]&&flag==0)
flag=i;
if(flag==1)
head_movement+=sorted_request[number_of_request]-sorted_request[0];
else
{
head_movement+=sorted_request[number_of_request]-sorted_request[0];
head_movement+=sorted_request[number_of_request]-sorted_request[1];
head_movement+=sorted_request[flag-1]-sorted_request[1];
}
return head_movement;
}
~disk(){}
};
int main()
{
disk hdd;
hdd.receive_request();
cout<<"Total head movement in ";
cout<<"FCFS is "<<hdd.fcfs()<<endl;
cout<<"Total head movement in ";
cout<<"SSTF is "<<hdd.sstf()<<endl;
cout<<"Total head movement in ";
cout<<"SCAN is "<<hdd.SCAN()<<endl;
cout<<"Total head movement in ";
cout<<"CSCAN is "<<hdd.CSCAN()<<endl;
cout<<"Total head movement in ";
cout<<"LOOK is "<<hdd.LOOK()<<endl;
cout<<"Total head movement in ";
cout<<"CLOOK is "<<hdd.CLOOK()<<endl;
_getche();
}
</code></pre>
| [] | [
{
"body": "<p>You are using C++, but overall, your code looks like C. There are numerous ways to improve your code readability by replacing C standard features by C++ ones. I will give some examples.</p>\n\n<h1><code>using namespace std;</code></h1>\n\n<p>Wirting <code>using namespace std;</code> is generally <a href=\"https://stackoverflow.com/a/1452738/1364752\">considered bad practice</a>, especially when written in the global namesapce: it leads to potential name clashes and namespace pollution. You should just add <code>std::</code> before every function/calss/variable from the standard library.</p>\n\n<h1>Headers</h1>\n\n<p>Several remarkes here:</p>\n\n<ul>\n<li><code><math.h></code> is a C header, in C++, you should include <code><cmath></code> instead, which is its C++ equivalent.</li>\n<li><code><conio.h></code> is an old non-portable header. For input/output operations, you should generally use <code><iostream></code> and stick with it.</li>\n<li>Also, it's good practice to organize your include directives in alphabetical ordering. That helps to check whether some header has already been included or not, and to avoid including twice some header.</li>\n</ul>\n\n<h1>Standard library collections</h1>\n\n<p>Instead of using old C arrays and pointers, you can use standard library containers. For example, a fixed sized array <code>int arr[30]</code> can be replaced by the equivalent <code>std::array<int, 30></code> in C++11 (this container is not directly available in the older versions of the standard).</p>\n\n<h1>Standard library algorithms</h1>\n\n<p>Instead of the old <code>qsort</code>, which requires to take a function pointer with <code>void*</code> pointers and do some ugly casts, you should use <code>std::sort</code> in the standard header <code><algorithm></code>. It should be at least as fast (if not faster) and easier to read and write. You can replace this line:</p>\n\n<pre><code>qsort(sorted_request+1,number_of_request,sizeof(int),compare);\n</code></pre>\n\n<p>by this one:</p>\n\n<pre><code>std::sort(std::begin(sorted_request), std::end(sorted_request));\n</code></pre>\n\n<h1>Miscellaneous notes</h1>\n\n<p>I can't cover all your code because it would have to be refactored to use more standard library features beforehand, but here are some notes:</p>\n\n<ul>\n<li>Upper case names should only be used for preprocessor macros. Therefore, your functions <code>CSCAN</code> and <code>LOOK</code> (and the other ones) should be named <code>cscan</code> and <code>look</code> instead.</li>\n<li>I'm not at ease with using <code>std::cin</code> in the constructor of <code>disk</code>. Such user interaction should not appear at construction, but be handled later by the client code of the class.</li>\n<li><code>if(direction=1)</code> is probably a bug, it should be <code>if(direction==1)</code>, using proper compiler flags (<code>-Wall</code>, <code>-Wextra</code>, etc...) should tell you when you use an assignment instead of a comparison in <code>if</code>.</li>\n<li>There is a typo in <code>recieve_request</code>: it should be <code>receive_request</code>.</li>\n</ul>\n\n<p>Overall, you should really consider looking at the C++ standard library and using its classes and algorithms to replace many things in your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:26:14.127",
"Id": "84820",
"Score": "0",
"body": "*It (`std::sort`) should be as fast (as `qsort`).* Actually, in a lot of cases, it should be significantly *faster*, as the comparison can generally be inlined - whereas it usually cannot be for `qsort`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:29:33.777",
"Id": "84821",
"Score": "0",
"body": "@Yuushi I'll add \"at least\" :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:50:49.647",
"Id": "84847",
"Score": "0",
"body": "@Morwenn: Good call--in fact, in *this* case (comparing `int`s) `std::sort` will most likely be noticeably faster than `qsort`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:33:55.490",
"Id": "84850",
"Score": "0",
"body": "@Morwenn Can you please explain how to use this line :\n\n `std::sort(std::begin(sorted_request), std::end(sorted_request));`\n\n\nwhen I do not want to start form begning or go upto the end"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:00:14.557",
"Id": "84857",
"Score": "2",
"body": "@viditjain It's like pointer arithmetic. Thus, if you want to sort from 3 to 10 do:\n`std::sort(std::begin(sorted_request) + 3, std::begin(sorted_request) + 10);`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:23:45.303",
"Id": "48334",
"ParentId": "48326",
"Score": "13"
}
},
{
"body": "<p>Morwenn has already given feedback I'd consider quite good, so I'll restrict myself to areas he hasn't already covered.</p>\n\n<p>First, you have some code I think could be structured quite a bit more nicely. Contrary to Morwenn's comments, some parts of your code look more like ancient Fortran or BASIC rather than C. For example:</p>\n\n<pre><code>current_direction:\ncout<<\"\\nEnter current direction(0:left / 1:right) : \";\ncin>>direction;\nif(direction!=0&&direction!=1)\n goto current_direction;\n</code></pre>\n\n<p>Even in C, you'd normally prefer a <code>do</code>/<code>while</code> loop to a <code>goto</code> for this:</p>\n\n<pre><code>do { \n cout<<\"\\nEnter current direction(0:left / 1:right) : \";\n cin>>direction;\n} while (direction != 0 && direction != 1);\n</code></pre>\n\n<p>This particular loop also seems to be asking for data that it seems like it has essentially no business asking for in the first place. I'd think if you're going to simulate a disk drive, the inputs should simply be disk locations of reads/writes, and possibly an initial head location (with some sensible default, such as track 0). Pretty much everything else should be results from the simulation, not inputs to it.</p>\n\n<p>At a somewhat higher level, this doesn't strike me as a particularly good type of program to make interactive. To produce results that mean much of anything it almost certainly needs to process quite a bit of input. Personally, I can't imagine interactively entering the data for even <em>one</em> meaningful run, not to mention (for example) two or three runs to compare results for different usage patterns.</p>\n\n<p>At least as a user, I'm quite certain I'd <em>strongly</em> prefer a program that let me enter data into a file, and just specify the name of that file on the command line to get a set of results. This gives me much better dependability and repeatability. Just for example, if I get strange results from a particular set of inputs, I want to be able to re-examine those inputs, assure they were what I intended, re-run the simulation if needed, and so on.</p>\n\n<p>I hope it doesn't sound condescending or nasty (because I honestly don't intend it that way), but this is a large part of what separates toys from tools. As it stands right now, your program is basically a toy. You can run it a few times to prove that it produces reasonable output for a small amount of input, but I can't imagine that anybody would actually want to use it on a regular basis.</p>\n\n<p>Using it is too labor intensive, and requires nearly perfect attention to detail on the part of the user. It's all too easy for the user to slip up and enter the same data twice, skip data they intended to enter, etc. Worse, when a user gets a particular set of results it's next to impossible for them to be sure what input produced that results. Simulations are typically used for lots of \"what if\" kinds of situations--in a typical case, a user wants to know what happens if one specific detail in one place changes. With a program like this, he has to re-enter <em>all</em> the data just to make that one minor change in one place.</p>\n\n<p>So, while it's important to clean up the internals as well, I think the biggest and most important change that's needed is to define some simple file format for inputs, and at least allow the user to specify a file as the input instead of forcing them to enter their data interactively. The file format doesn't need to be complex at all, but (if you intend this to be put to real use) you might consider some format that's at least somewhat standardized (and there are <em>lots</em> of those to choose from).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-28T18:21:48.130",
"Id": "104648",
"Score": "0",
"body": "why is using goto considered a bad practice??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-28T20:27:25.770",
"Id": "104679",
"Score": "0",
"body": "@viditjain: Primarily because using `goto` tends to lead to code with control structures that are difficult to understand or reason about. With something like `do {...} while (x);`, I can expect `x` to be false immediately after the loop exits."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:55:48.947",
"Id": "48360",
"ParentId": "48326",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:34:44.123",
"Id": "48326",
"Score": "8",
"Tags": [
"c++"
],
"Title": "Disk Scheduling Algorithm"
} | 48326 |
<p>After coding my divisor code which I did as a practice for my GCSE stuff which I have to take soon, I have decided to ask the community if there are any bugs or ways I can improve my code. </p>
<pre><code>import time, math
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= math.sqrt(intnum):
if (intnum % i) == 0:
numbers.insert(0,i)
numbers.insert(0,int(intnum/i))
print(i,":", int(intnum/i))
i += 1
numbers = sorted(numbers, reverse = True)
print("The Highest Proper Divisor Is\n--------\n",str(numbers[1]) , "\n--------\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors." )
except ValueError:
error("NOT VALID NUMBER")
except OverflowError:
error("NUMBER IS TO LARGE")
except:
error("UNKNOWN ERROR")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
</code></pre>
<p>I don't care how small the improvement is all I want are ways in which I can make it better! </p>
<p>When inputting 262144 I get</p>
<pre><code>Enter your Number: 262144
The divisors of your number are:
1 : 262144
2 : 131072
4 : 65536
8 : 32768
16 : 16384
32 : 8192
64 : 4096
128 : 2048
256 : 1024
512 : 512
The Highest Proper Divisor Is
--------
131072
--------
It took 0.09 seconds to finish finding the divisors.
----------------------------------
Do You Want Restart?
</code></pre>
| [] | [
{
"body": "<p>I'm new, so can't comment, otherwise, would have commented. This isn't a bug, but you don't necessarily need the brackets in python for ifs and things like that:\nInstead of:</p>\n\n<pre><code>if (intnum % i) == 0:\n</code></pre>\n\n<p>you could just do:</p>\n\n<pre><code>if intnum % i == 0:\n</code></pre>\n\n<p>I know it might not be very helpful, but in some cases, I think it can help readability if you ever edit it again. I used to put brackets in coming from c# but it really could confuse you - I spent hours looking for an error because of the unessential brackets.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:09:01.153",
"Id": "84813",
"Score": "0",
"body": "ahh ok ive also come from c# programming @user41412 this is a realy helpful thing to point out. Do you know if this also works with things like print? and while?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:11:24.730",
"Id": "84814",
"Score": "0",
"body": "@ Oliver Perring, Well, with Python 3, you obviously need the `print('Hello World')` brackets, with while loops, for the condition, you don't, so you could say `while x != 2:` instead of `while (x != 2):` In your case, `while(running):` needs only be `while running:` That's why I prefer Python to other languages - its relatively simple"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:50:38.670",
"Id": "84827",
"Score": "2",
"body": "Hi, and welcome to Code Review. Here we welcome any answers that have valuable suggestions, even if they are small. This is a decent answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T10:37:20.730",
"Id": "84929",
"Score": "0",
"body": "Tips like this make code far harder to interpret for other programmers. Does it really take much more time to write `if ((intnum % i) == 0):`?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:59:24.560",
"Id": "48329",
"ParentId": "48328",
"Score": "5"
}
},
{
"body": "<p>Here are some thoughts on this code:</p>\n\n<h2>Chose descriptive function names</h2>\n\n<p>The name <code>programme</code> is not really very descriptive of what the function does. You might call it something like <code>factor</code> to give the reader of your code a better idea of what it actually does.</p>\n\n<h2>Document your code</h2>\n\n<p>Python supports the use of multiple different kinds of comments, including ones that can be made into unit tests. Get in the habit of commenting your code carefully.</p>\n\n<h2>Separate I/O from calculation</h2>\n\n<p>The main purpose of the program is to factor numbers into divisors which is something that is potentially reusable. Both to make it more clear as to what the program is doing and to allow for future re-use, I'd suggest extracting the factoring part into a separate function and the have the input from the user be done within the main routine or some other input-only function.</p>\n\n<h2>Separate timing from the thing being timed</h2>\n\n<p>On my machine, the timer always reports 0.0 seconds, which makes it hard to compare the effects of changes in the code. For that reason, what's often done is to call the routine to be timed multiple times to get better resolution. In order to do that, you'd have to remove the timing from the routine you're timing, which is good design practice anyway. Right now, the <code>print</code> function is part of the code that's being timed.</p>\n\n<h2>Think of your user</h2>\n\n<p>Right now, the user has to enter \"yes\" or the equivalent and then enter another number to be factored. However, the prompt doesn't suggest that \"y\" is a valid answer. Adding that to the prompt would help the user understand what the computer is expecting. Better still, would be t eliminate that question and to simply ask for the next number with a number '0' being the user's way to specify no more numbers. Of course the prompt should be changed to tell the user of this fact.</p>\n\n<h2>Expand the range</h2>\n\n<p>Right now, the size of numbers that can be factored is limited to what will fit within an <code>int</code>, but it would be much more interesting to be able to factor really large numbers.</p>\n\n<h2>Use <code>divmod()</code> to save some time</h2>\n\n<p>Right now, for every successfully discovered divisor, the program performs three division operations: one for <code>%</code>, and then two more to insert the number into <code>numbers</code> and again to <code>print</code>. Instead, you could do the division once using the <a href=\"https://docs.python.org/2/library/functions.html#divmod\"><code>divmod</code></a> function which gives you both the quotient and remainder at the same time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T00:17:08.433",
"Id": "84902",
"Score": "0",
"body": "In Python 3, all numbers will fit in an `int`, assuming sufficient memory is available. In other words, int has [unlimited precision](https://docs.python.org/3/library/stdtypes.html#typesnumeric)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T00:31:51.790",
"Id": "84904",
"Score": "0",
"body": "@codesparkle: when I enter 38018301831 the program reports \"ERROR - NUMBER IS TO LARGE\" suggesting a range limitation. Can you explain what's happening?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T02:02:53.330",
"Id": "84908",
"Score": "1",
"body": "That's because of `numbers = array(\"i\",[])`. The OP should have used `numbers = []` instead. So the restriction doesn't come from the use of the Python `int`, but from the use of the `array` with a type code of `i` which translates to a C `long` (which is not long enough to hold 38018301831)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T02:17:12.260",
"Id": "84909",
"Score": "0",
"body": "@codesparkle: Ah, thanks for the explanation. After I modified the code to use a plain list, it factors even large numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:56:35.020",
"Id": "85305",
"Score": "0",
"body": "@codesparkle thanks for pointing out the array thingy...I didn't know that's how u made a list I though like many other languages it had to be formatted so I tried import array, it worked so guessed that was the way to do it!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:52:18.630",
"Id": "48347",
"ParentId": "48328",
"Score": "12"
}
},
{
"body": "<p>Here are a couple small things:</p>\n\n<ul>\n<li><p>Where you do</p>\n\n<pre><code>print(\"----------------------------------\")\n</code></pre>\n\n<p>it might be easier to do <code>print(\"-\" * 34)</code>. I use this all the time with really long repeat elements. It also makes it easy to keep things the same length sometimes.</p></li>\n<li><p>Where you have</p>\n\n<pre><code>print(\"The Highest Proper Divisor Is\\n--------\\n\",str(numbers[1]) , ...\n</code></pre>\n\n<p>it is really long, perhaps you could break it into multiple prints somewhat like this:</p>\n\n<pre><code>print(\"-\" * 34)\nprint(\"ERROR - {}\".format(error))\nprint(\"-\" * 34)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:53:50.457",
"Id": "84844",
"Score": "2",
"body": "Even simpler would be this:\n`print(\"{0}\\nERROR - {1}\\n{0}\\n\".format(\"-\"*34,format(error))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:07:10.620",
"Id": "84971",
"Score": "0",
"body": "@Edward I don't quite understand how your suggestion works! Can you please explain to me. Sorry for being a noob and all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:12:48.610",
"Id": "84985",
"Score": "0",
"body": "@OliverPerring: No problem. The [`format`](https://docs.python.org/2/library/functions.html#format) function uses a thing called a [format specification](https://docs.python.org/2/library/string.html#formatspec) which is a little like the C language `printf` if you're familiar with that. In my suggestion, `{0}` is a placeholder for the first argument (which is `\"-\"*34` in this case) and `{1}` is for the second argument. The format string just uses `{0}` twice to print the two lines of `-` characters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:53:46.440",
"Id": "85302",
"Score": "0",
"body": "@Edward that makes sense I did use to use printf but not very well looks a little simpler in python will play around with it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T11:49:54.177",
"Id": "85756",
"Score": "0",
"body": "Thnx ive now added this to my code along with a few extra selections...when i have time i will updatw the question and add in the changes"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:59:28.880",
"Id": "48348",
"ParentId": "48328",
"Score": "5"
}
},
{
"body": "<p>First issue: <strong>This is a micro-optimization and therefore not necessarily a good idea.</strong></p>\n\n<p>I note that you say</p>\n\n<pre><code>while i <= math.sqrt(intnum):\n</code></pre>\n\n<p>which recomputes the square root every time. You could compute it once and store it. Alternatively you could say</p>\n\n<pre><code>while i * i <= intnum:\n</code></pre>\n\n<p>which is likely to be a cheaper and more accurate computation than finding the square root.</p>\n\n<p>Second issue: <strong>Typo</strong></p>\n\n<pre><code>except ValueError:\n error(\"NOT VALID NUMBER\")\nexcept OverflowError:\n error(\"NUMBER IS TO LARGE\")\nexcept:\n error(\"UNKNOWN ERROR\")\n</code></pre>\n\n<p>STOP SHOUTING AT ME. Also you have a typo. It should be \"TOO LARGE\", not \"TO LARGE\".</p>\n\n<p>Issue 3: <strong>Minor Bug</strong></p>\n\n<p>Try putting in a perfect square. The <code>numbers</code> list will contain two copies of the root. That is harmless in your program as it stands, but if your intention is to use that list for something else in the future, it seems bizarre that there should be a duplicate.</p>\n\n<p>Issue 4: <strong>Minor performance issue</strong></p>\n\n<p>Why add the inverse divisors to the list in the first place? You could remove</p>\n\n<pre><code> numbers.insert(0,int(intnum/i))\n</code></pre>\n\n<p>You know that <code>numbers[0]</code> is one, so you could simply say:</p>\n\n<pre><code>largestProper = 1 if len(numbers) = 1 else intnum/numbers[1]\n</code></pre>\n\n<p>Issue 5: <strong>Scalability issue</strong></p>\n\n<p>The performance is very poor if the number is very large; this is an extremely naive way to solve this problem.</p>\n\n<p>A less naive way would be to compute a sequence of prime numbers, then test the number to see what prime numbers it is divisible by. Once you know the prime factorization of the number then the set of proper divisors is the set of all combinations of multiplications of the elements of the prime factorization.</p>\n\n<p>To take a small example, suppose you are trying to find all the divisors of 120. Your technique is to loop from 1 to 11 trying out each possible divisor. Instead you could first say \"120 is divisible by 2, leaving 60. 60 is divisible by 2 leaving 30. 30 is divisible by 2 leaving 15. 15 is divisible by 3 leaving 5. 5 is divisible by 5 leaving 1, we're done.\" Now you know that the factorization is 2x2x2x3x5. To find the largest proper divisor you replace the smallest number by 1 -- 1x2x2x3x5 is the largest proper divisor of 120. </p>\n\n<p>To find all the divisors, you try all the combinations of 0, 1, 2 or 3 twos, 0 or 1 threes, 0 or 1 fives:</p>\n\n<pre><code>1x1x1x1x1 -- zero twos, zero threes, zero fives\n1x1x2x1x1 -- one two, zero threes, zero fives\n1x2x2x1x1 -- two twos, zero threes, zero fives\n2x2x2x1x1 -- three twos, zero threes, zero fives\n1x1x1x3x1 -- zero twos, one three, zero fives\n1x1x2x3x1 -- one two, one three, zero fives\n...\n</code></pre>\n\n<p>And so on. </p>\n\n<p>This seems a lot more complicated -- and it is -- but this algorithm is <em>far</em> faster for really large numbers. If you were trying to factor a 20 digit number your system would have to try ten billion or more trial divisions. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:55:06.240",
"Id": "85304",
"Score": "0",
"body": "mmmm I don't quite understand how to do this...ive tried multiple times and failed again and again any pointers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:23:14.483",
"Id": "85308",
"Score": "0",
"body": "@OliverPerring: I am not a python programmer so I don't know what the pythonic way to do so is. Consider looking up \"Cartesian Product\"; the set of all divisors is related to the Cartesian Product of the factorization."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:03:27.717",
"Id": "48356",
"ParentId": "48328",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48347",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:46:32.910",
"Id": "48328",
"Score": "7",
"Tags": [
"python",
"mathematics",
"python-3.x"
],
"Title": "Are there any bugs or ways to make my divisor code better?"
} | 48328 |
<p><a href="http://learnyouahaskell.com/modules#loading-modules" rel="nofollow noreferrer">Learn You a Haskell</a> shows the <code>intersperse</code> function:</p>
<pre><code>ghci> intersperse '.' "MONKEY"
"M.O.N.K.E.Y"
ghci> intersperse 0 [1,2,3,4,5,6]
[1,0,2,0,3,0,4,0,5,0,6]
</code></pre>
<p>Note that the interspersed element only appears <strong>inside</strong> of the elements. </p>
<blockquote>
<p>list elem ... item ... list elem ..... item .. list elem</p>
</blockquote>
<p>Originally, I tried to write this function in terms of a <code>fold</code>.</p>
<pre><code>intersperse' :: [a] -> a -> [a]
intersperse' ys i = foldl (\acc x -> acc ++ [x] ++ [i]) [] ys
</code></pre>
<p>But, my approach failed since interspersed item was getting appended to the last element. Also, the lambda appended (<code>++</code>) to the <code>acc</code> each time, which isn't <a href="https://codereview.stackexchange.com/questions/48101/implementing-nub-distinct#comment84558_48104">good</a>.</p>
<p>So I decided to use <code>pattern matching</code>:</p>
<pre><code>is' :: [a] -> a -> [a]
is' [] _ = []
is' (x:xs) i
| null xs = [x]
| otherwise = x : (i : (is' xs i))
</code></pre>
<p>Could the <code>fold</code> approach have worked? If so, how? Also, how's my <code>is'</code> implementation?</p>
| [] | [
{
"body": "<blockquote>\n <p>Could the fold approach have worked? If so, how?</p>\n</blockquote>\n\n<pre><code>intersperse' i = foldr (\\x ys -> x : if null ys then [] else i : ys) []\n</code></pre>\n\n<p>In the fold, we cannot access the rest of the input, only the rest of the output. However, if and only if the input was empty, the output will be empty. So <code>null ys</code> happens to works here.</p>\n\n<p>Interesting aspects:</p>\n\n<ol>\n<li><p>I changed the argument order to match the standard <code>intersperse</code>. This happens to work better with the foldr-based definition. More importantely, I feel that <code>intersperse</code> is more often partially applied with an element than with a list, so the element should go first.</p></li>\n<li><p>I use <code>foldr</code> instead of <code>foldl</code> to increase laziness and avoid the accumulator construction. Note how I don't need <code>acc ++ [x]</code> because I only add elements to the front of lists.</p></li>\n<li><p>I make sure that <code>intersperse'</code> produces the first <code>(:)</code> cell before the <code>null</code> check.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:06:35.760",
"Id": "48349",
"ParentId": "48333",
"Score": "5"
}
},
{
"body": "<p>Just include some \"special handling\" for the first element:</p>\n\n<pre><code>intersperse' x (y:zs) = y : foldr (\\z acc -> x : z : acc) [] zs \n\n//or shorter \nintersperse' x (y:zs) = y : concat [[x,z] | z <- zs]\n\n//or monadic madness\nintersperse' x (y:ys) = y : (ys >>= (x:).return)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T08:08:58.940",
"Id": "48391",
"ParentId": "48333",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48349",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:13:15.657",
"Id": "48333",
"Score": "5",
"Tags": [
"haskell",
"reinventing-the-wheel"
],
"Title": "Writing Data.List's intersperse"
} | 48333 |
<p>This is a teaching sample intended to illustrate use of mutability and list consing in F#. The structure is intended to be a thread-safe stack structure, which multiple threads can push to/pop from concurrently. Concerns:</p>
<ul>
<li>Will this actually be thread safe?</li>
<li>Are the locks necessary?</li>
<li>Is there an immutable way to do the same thing? I don't think one can use the traditional immutable method here of having the Push/Pop return a new stack instance because different clients will see divergent views of the stack.</li>
</ul>
<p>The code looks like this: </p>
<pre><code>type ConcurrentStack<'T>() =
let mutable _stack : List<'T> = []
member this.Push value =
lock _stack (fun () ->
_stack <- value :: _stack)
member this.TryPop() =
lock _stack (fun () ->
match _stack with
| result :: newStack ->
_stack <- newStack
result |> Some
| [] -> None
)
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Will this actually be thread safe?</p>\n</blockquote>\n\n<p>Yes, I think it will. All access to the <code>_stack</code> field is protected by a lock, so I do not see why this wouldn't be thread safe.</p>\n\n<p>A nice coincidence of using immutable lists is that you can also nicely implement <code>IEnumerable<'T></code> or even just return the list of all elements currently in the stack - because the data type is immutable, it can be safely shared with other threads (this means, you won't get into the usual troubles with <em>\"Collection was modified; enumeration operation cannot continue\"</em> that you'd get in C#. </p>\n\n<blockquote>\n <p>Are the locks necessary?</p>\n</blockquote>\n\n<p>I think so. Without the lock, one thread could start evaluating <code>Push</code> by evaluating <code>value::_stack</code>, then another thread could modify <code>_stack</code> and the original thread would then overwrite <code>_stack</code> with the <em>old</em> value of <code>value::_stack</code> (and so the effect of the other thread would be lost!)</p>\n\n<blockquote>\n <p>Is there an immutable way to do the same thing? I don't think one can use the traditional immutable method here of having the Push/Pop return a new stack instance because different clients will see divergent views of the stack.</p>\n</blockquote>\n\n<p>If the idea is to have multiple threads sharing the state, then they'll need some way of sharing & mutating the state. Another approach in F# would be to use an agent and keep the current <code>_stack</code> as a parameter of the asynchronous loop - in that case, you're not using mutation in the F# code you write (but there is hidden mutation and synchronization going on in the agent).</p>\n\n<p>Logically, the agent-based version is quite similar to the one you have using locks - it might be a bit nicer for other reasons (getting locks right is hard, agents do not make it possible to do the same kinds of errors), but that really depends on what you want to illustrate!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:19:46.063",
"Id": "84838",
"Score": "0",
"body": "Thanks Tomas. Looks like that'll be safe to put in my PluralSight course. Terrified of spreading misinformation!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:59:31.253",
"Id": "48340",
"ParentId": "48335",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Are the locks necessary?</p>\n</blockquote>\n\n<p>Some synchronization is necessary, but it doesn't necessarily have to be a lock.</p>\n\n<p>Another option would be to use <a href=\"http://msdn.microsoft.com/en-us/library/bb297966.aspx\" rel=\"nofollow\"><code>Interlocked.CompareExchange</code></a>. But doing that is more complicated, so I would stick with the lock, unless profiling showed that the lock is what's slowing your code down.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:01:23.707",
"Id": "48355",
"ParentId": "48335",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48340",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T14:24:43.213",
"Id": "48335",
"Score": "2",
"Tags": [
"f#"
],
"Title": "A concurrency-safe stack structure"
} | 48335 |
<p><strong><edit:</strong> There's a major problem in the code. It is basically the one in the comment regarding backpressure. I'll rework the code within a a few days...</p>
<p>It's time for a quick code review, good points, examples, handholding if anyone has time to spare for commenting and, yes, even nitpicking too. I wrote a short piece of code, purpose of which is to</p>
<ol>
<li>Read a resource on some predefined intervals. This resource can be at least a file or a network resource, so preferably the source and how to read it could be configured and be testable. The contents can text in JSON or XML or a CSV file or bytes or whatever. At least JSON for the purposes for this example. I assume all data can be read in one go. </li>
<li>When the resource has been polled and data received, it needs to be transformed into some nice, strongly typed form.</li>
<li>After the data has been transformed into a strongly typed form, it gets processed in various ways. It would be nice if one could have a notion of "tubes" here, which would work in asynchronously and independently so that an error in one "tube" could be just logged whereas processing in other ones go on.</li>
<li>After processing data it's being tucked into various places. Like various queues (or a queue), files and so forth.</li>
</ol>
<p>The code follows, but I'm not satisfied with it. For one, even if the idea of <code>getData</code> works with <code>dataPoller</code>, I need to add the <code>Async.RunSynchronously</code> in case I use an <code>async</code> method, or if not, omit it. Is there a way to do this either way independent of how <code>getData</code> is defined?</p>
<p>I've been reading about the excellent chap <a href="http://fsharpforfunandprofit.com/" rel="nofollow">Scott Wlaschin's</a> excellent <a href="http://www.slideshare.net/ScottWlaschin/railway-oriented-programming" rel="nofollow">railway oriented programming</a> tutorial and am thinking how could apply the lessons here. For one, extending this excellent looking framework of thought to async isn't really clear to me (as written in the end of the slides). I'm also thinking if I could employ <a href="https://www.nuget.org/packages/Microsoft.Tpl.Dataflow" rel="nofollow">TPL.Dataflow</a> or <a href="https://github.com/VesaKarvonen/Hopac" rel="nofollow">Hopac</a>, which looks like being a fit (defining processing DAGs) to this kind of a processing...</p>
<p>... But really, I'd be happy even if someone would advise me if there's a neater way to write this poller (the <code>Async.RunSynchronously</code> part). The rest is something I know I'll be tempted to tackle on the cost of writing a program that actually does something.</p>
<p>Currently I have a module in a file <code>CommonLibrary.fs</code> like so</p>
<pre><code>namespace CommonLibrary
[<AutoOpen>]
module Infrastructure =
open System.Reactive
open System.Reactive.Linq
//The current version of Rx does not have a notion of backpressure so if call durations rise, so will the process memory consumption too.
let dataPoller(interval, source) = Observable.Interval(interval) |> Observable.map(fun _ -> source)
[<AutoOpen>]
module DomainTypes =
open System
open FSharp.Data
type Data = {
someData: string
}
type DataPieces = {
contents: seq<Data> option
}
type DataPiecesProvider = JsonProvider<Sample = "DataPiece.json", Culture = "en-US">
let getData uri = async {
try
let! data = DataPiecesProvider.AsyncLoad(uri)
//Omitted for brevity, but basically here's a bunch of parsing code,
//which spans for a about ten lines.
//let datas =
return { contents = Some(datas) }
with _ -> return { contents = None }
}
</code></pre>
<p>And then I have the main file, <code>Program.fs</code> where I call these facilities as follows</p>
<pre><code>open System
open System.IO
open System.Threading
open System.Text
open CommonLibrary
[<Literal>]
let pollingUri = "http://xyz/json"
[<EntryPoint>]
let main argv =
let exampleDataPump =
dataPoller(TimeSpan.FromSeconds(1.0), Async.RunSynchronously(getData pollingUri))
|> Observable.subscribe(fun i -> printfn "%A" (i.contents.Value |> Seq.head))
Thread.Sleep(System.Threading.Timeout.Infinite);
//These aren't never reached, but for the sake of completeness.
exampleDataPump.Dispose()
0
</code></pre>
<p><strong><edit 2014-05-04:</strong> So, I have a version two of the code. The original idea was to ask things (as you can see) of it, but I believe I have a better story.</p>
<p>Wheareas this version too could be improved in many ways (for one, it lacks documentation), I believe it has the problematic nature of relying on exceptions to count for retrying, well, in exceptional conditions. A better strategy could be to catch everything at the source, make it a domain event DU (taking cues from <strong>Scott's</strong> slides) and then handling them in the Rx pipeline.</p>
<p>In any event, here's the newest code. I'll work on the DU version too and add it here. Hopefully in the near future -- sooner than these edits. Then there's something to compare and discuss if there's something to discuss.</p>
<p><strong>In CommonLibrary.fs</strong></p>
<pre><code>let getData uri = async {
let! data = DataPiecesProvider.AsyncLoad(uri)
//Omitted for brevity, but basically here's a bunch of parsing code,
//which spans for a about ten lines.
//let datas = ...
return datas //seq<Data>
[<Extension>]
type ObservableExtensions =
[<Extension>]
[<CompiledName("PascalCase")>]
static member inline retryAfterDelay<'TSource, 'TException when 'TException :> System.Exception>(source: IObservable<'TSource>, retryDelay: int -> TimeSpan, maxRetries, scheduler: IScheduler): IObservable<'TSource> =
let rec go(source: IObservable<'TSource>, retryDelay: int -> TimeSpan, retries, maxRetries, scheduler: IScheduler): IObservable<'TSource> =
source.Catch<'TSource, 'TException>(fun ex ->
if maxRetries <= 0 then
Observable.Throw<'TSource>(ex)
else
go(source.DelaySubscription(retryDelay(retries), scheduler), retryDelay, retries + 1, maxRetries - 1, scheduler))
go(source, retryDelay, 1, maxRetries, scheduler)
type DataPumpOperations =
static member dataPump(source: Async<_>): IObservable<_> = Async.StartAsTask(source).ToObservable()
static member dataPump(source: seq<_>): IObservable<_> = source |> Observable.toObservable
</code></pre>
<p><strong>In Program.fs</strong></p>
<pre><code>let constantRetryStrategy(retryCount: int) =
TimeSpan.FromSeconds(1.0)
let maxRetries = 5
let ds = (getData pollingUri)
let t = Observable.Create(fun i -> (DataPumpOperations.dataPump ds).retryAfterDelay(constantRetryStrategy, maxRetries, Scheduler.Default).Subscribe(i)).Delay(TimeSpan.FromSeconds(1.0)).Repeat().Subscribe(fun i -> printfn "%A" (i |> Seq.head).origin)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:00:50.637",
"Id": "85519",
"Score": "0",
"body": "I'll update this shortly. It turns out this became quite a largish issue to handle haphazardly. See a closely related question at https://stackoverflow.com/questions/23404185/how-to-write-a-generic-recursive-extension-method-in-f."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:05:56.670",
"Id": "48342",
"Score": "2",
"Tags": [
"f#",
"system.reactive"
],
"Title": "Polling, parsing, validating and handling data cleanly and efficiently"
} | 48342 |
<p>This is a follow-up of <a href="https://codereview.stackexchange.com/q/47975/39083">'any' class implementation</a>. After posting <a href="https://codereview.stackexchange.com/a/48250/39083">my answer</a>, I kept working on the code towards parameterizing with respect to memory management as I had promised. I ended up in some pretty non-trivial piece of code that I decided to post here as a new question for review.</p>
<p>Basically, this is quite close to <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/any.html" rel="noreferrer"><code>boost::any</code></a>, with a number of differences. From my perspective it could be a complete replacement to <code>boost::any</code>, that I like to call <code>some</code>.</p>
<p><em>Minor</em> differences:</p>
<ul>
<li><p>Member-function, reference (not pointer)-based, type-checked/-unchecked data access (casting).</p></li>
<li><p>Simplified type-checked access via <code>dynamic_cast</code> instead of manual <code>typeid</code> checking. Using <code>std::bad_cast</code> instead of a custom exception type.</p></li>
<li><p>Type provided for casting should be already <code>decay</code>ed; no references removed.</p></li>
<li><p>Conversion operators.</p></li>
<li><p>Free of <code>const_cast</code> hacks.</p></li>
<li><p>No <code>type()</code> functionality exposed; <code>is<T>()</code> check interface instead. Internally, custom type identification mechanism bypassing <code>typeid</code> and RTTI.</p></li>
<li><p>Move semantics fully supported. No constraints e.g. on reading from <code>const</code> rvalue references or providing non-<code>const</code> rvalue references to temporary objects.</p></li>
<li><p>Using <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization" rel="noreferrer">empty base optimization</a>, empty objects are stored with no space overhead on top of the required virtual function table.</p></li>
</ul>
<p><em>Major</em> differences:</p>
<ul>
<li><p>Templated on a memory-management object that is roughly what an <em>allocator</em> is for STL containers, yet with a different, custom interface.</p></li>
<li><p>Default "allocator" type provides customizable storage space on stack. Similarly to <a href="http://john-ahlgren.blogspot.gr/2012/03/small-string-optimization-and-move.html" rel="noreferrer">small string optimization</a>, and without run-time overhead, objects not larger than this space are placed on stack; larger ones on the free store.</p></li>
</ul>
<p>So <code>some</code> is maybe somewhere between <code>boost::any</code> and <a href="http://www.boost.org/doc/libs/1_54_0/doc/html/variant.html" rel="noreferrer"><code>boost::variant</code></a> (in using the stack rather than restricting to pre-defined types). To get a rough idea about this "allocator", here is what it would look like if it used the free store only:</p>
<pre><code>struct alloc
{
template<typename D, typename V>
D *copy(V &&v) { return new D{std::forward<V>(v)}; }
template<typename D, typename V, typename B>
B *move(V &&v, B *&p) { B *q = p; p = nullptr; return q; }
template<typename D>
void free(D *p) { delete p; }
};
</code></pre>
<p>This would really work, but it's not used in my examples. Here is the actual default one, including its own stack space:</p>
<pre><code>template<size_t N = 16>
class store
{
char space[N];
template<typename T>
static constexpr bool
fits() { return sizeof(typename std::decay<T>::type) <= N; }
public:
template<typename D, typename V>
D *copy(V &&v)
{
return fits<D>() ? new(space) D{std::forward<V>(v)} :
new D{std::forward<V>(v)};
}
template<typename D, typename V, typename B>
B *move(V &&v, B *&p)
{
B *q = fits<D>() ? copy<D>(std::forward<V>(v)) : p;
p = nullptr;
return q;
}
template<typename D>
void free(D *p) { fits<D>() ? p->~D() : delete p; }
};
</code></pre>
<p>Typically, on a 64-bit machine, 8 bytes go for the virtual function table, so the remaining 8 of the default size can store up to e.g. a <code>long</code> or a <code>double</code> without invoking any free store operation.</p>
<p>Expression <code>fits<D>()</code> is evaluated at compile time, so whenever it evaluates to false, <code>store</code> is equivalent to <code>alloc</code>, without any run time overhead. For <code>N = 0</code>, it is always equivalent (or I think so, right?).</p>
<p>Now, here is the complete definition of <code>some</code>:</p>
<pre><code>template<typename A = store<>>
class some : A
{
using id = size_t;
template<typename T>
struct type { static void id() { } };
template<typename T>
static id type_id() { return reinterpret_cast<id>(&type<T>::id); }
template<typename T>
using decay = typename std::decay<T>::type;
template<typename T>
using none = typename std::enable_if<!std::is_same<some, T>::value>::type;
//-----------------------------------------------------------------------------
struct base
{
virtual ~base() { }
virtual bool is(id) const = 0;
virtual base *copy(A&) const = 0;
virtual base *move(A&, base*&) = 0;
virtual void free(A&) = 0;
} *p = nullptr;
template<typename T>
struct data : base, std::tuple<T>
{
using std::tuple<T>::tuple;
T &get() & { return std::get<0>(*this); }
T const &get() const& { return std::get<0>(*this); }
bool is(id i) const override { return i == type_id<T>(); }
base *copy(A &a) const override
{
return a.template copy<data>(get());
}
base *move(A &a, base *&p) override
{
return a.template move<data>(std::move(get()), p);
}
void free(A &a) override { a.free(this); }
};
//-----------------------------------------------------------------------------
template<typename T>
T &stat() { return static_cast<data<T>*>(p)->get(); }
template<typename T>
T const &stat() const { return static_cast<data<T> const*>(p)->get(); }
template<typename T>
T &dyn() { return dynamic_cast<data<T>&>(*p).get(); }
template<typename T>
T const &dyn() const { return dynamic_cast<data<T> const&>(*p).get(); }
base *move(some &s) { return s.p->move(*this, s.p); }
base *copy(some const &s) { return s.p->copy(*this); }
base *read(some &&s) { return s.p ? move(s) : s.p; }
base *read(some const &s) { return s.p ? copy(s) : s.p; }
template<typename V, typename U = decay<V>, typename = none<U>>
base *read(V &&v) { return A::template copy<data<U>>(std::forward<V>(v)); }
template<typename X>
some &assign(X &&x)
{
if (!p) p = read(std::forward<X>(x));
else
{
some t{std::move(*this)};
try { p = read(std::forward<X>(x)); }
catch(...) { p = move(t); throw; }
}
return *this;
}
void swap(some &s)
{
if (!p) p = read(std::move(s));
else if (!s.p) s.p = move(*this);
else
{
some t{std::move(*this)};
try { p = move(s); }
catch(...) { p = move(t); throw; }
s.p = move(t);
}
}
//-----------------------------------------------------------------------------
public:
some() { }
~some() { if (p) p->free(*this); }
some(some &&s) : p{read(std::move(s))} { }
some(some const &s) : p{read(s)} { }
template<typename V, typename = none<decay<V>>>
some(V &&v) : p{read(std::forward<V>(v))} { }
some &operator=(some &&s) { return assign(std::move(s)); }
some &operator=(some const &s) { return assign(s); }
template<typename V, typename = none<decay<V>>>
some &operator=(V &&v) { return assign(std::forward<V>(v)); }
friend void swap(some &s, some &r) { s.swap(r); }
void clear() { if(p) { p->free(*this); p = nullptr; } }
bool empty() const { return p; }
template<typename T>
bool is() const { return p ? p->is(type_id<T>()) : false; }
template<typename T> T &&_() && { return std::move(stat<T>()); }
template<typename T> T &_() & { return stat<T>(); }
template<typename T> T const &_() const& { return stat<T>(); }
template<typename T> T &&cast() && { return std::move(dyn<T>()); }
template<typename T> T &cast() & { return dyn<T>(); }
template<typename T> T const &cast() const& { return dyn<T>(); }
template<typename T> operator T &&() && { return std::move(_<T>()); }
template<typename T> operator T &() & { return _<T>(); }
template<typename T> operator T const&() const& { return _<T>(); }
};
</code></pre>
<p>Here is a <a href="http://coliru.stacked-crooked.com/a/61de929c06e026b4" rel="noreferrer">live example</a> with an extensive set of tests for most functionality.</p>
<p>Now, what I would like:</p>
<ul>
<li><p>Not much interested in <em>style</em> like function/variable names, indentation etc. I know the code is not really for sharing; it's very compact with one-line function definitions where possible, with one-letter parameters in most cases, and no comments. <em>Please ignore that</em>.</p></li>
<li><p>Can you see or find any <em>bugs</em> that may have by-passed my tests? Any possibility for <em>leaks</em>? I know this is necessarily low-level code.</p></li>
<li><p>Can you see any unnecessary <em>performance</em> loss or anything else that could be easily further optimized?</p></li>
<li><p>I have done my best to provide a <em>strong exception guarantee</em> to all operations. <code>assign</code> and <code>swap</code> are the most non-trivial ones, where due the (potential) use of the stack, operation sequencing is not enough and I had to write <code>try</code>/<code>catch</code> blocks around the most critical operations.</p>
<ul>
<li><p>Do you think everything is <em>correct</em>? For instance, I have made the assumption that if <code>A</code> is moved to <code>B</code> without <code>throw</code>ing, then <code>B</code> can be safely moved back to <code>A</code>.</p></li>
<li><p>If yes, could it be done in a <em>more efficient</em> way? In <code>assign</code>, for instance, I am making an additional move (in fact, copy) operation to handle the possibility that some constructor throws.</p></li>
</ul></li>
<li><p>I have found out that all tests work fine without <em>self-test</em> on assignment. Is there any case where this might fail?</p></li>
<li><p>I have preferred to explicitly use constructors (placement-<code>new</code>) and destructors for stack operations. I know direct use of <code>std::copy</code> would be equivalent for <em>trivially copyable</em> types and more efficient, but I think is too low-level and would make the code even more complex. Should I reconsider?</p></li>
<li><p>Is it well-defined to <code>delete</code> an object or explicitly call its destructor via a call to a <code>virtual</code> function (even if it's sure this is the last operation on it)? I couldn't find any other way to choose the right operation (<code>delete</code> vs. destructor call).</p></li>
<li><p>Not sure if needed, but, any idea how to simplify the <em>allocator interface</em> so that it could be used in a more general setting? I know it's clearly different from <code>std::allocator</code> in any case.</p></li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T11:10:58.133",
"Id": "84930",
"Score": "0",
"body": "After `some t{std::move(*this)};`, isn't it UB to access anything in the class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:30:28.487",
"Id": "85026",
"Score": "0",
"body": "@BЈовић After that, I know that `p==nullptr` and anything previously stored in `space` has been moved, so `space` is free to reuse (its content is undefined, but I am not attempting to read it). This is exactly the state after default-initialization, i.e. `*this` is `empty`. The very next operation is of the form `p = ...`, i.e. something new is read into `*this`. I think this is well-defined, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:22:21.797",
"Id": "85075",
"Score": "0",
"body": "No idea. You are doing `return *this;` after that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T10:49:32.157",
"Id": "89942",
"Score": "0",
"body": "How about `using id = void (*)();` You never know what size a function pointer is going to have. Also put your `any` in some repository please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T11:25:18.570",
"Id": "89945",
"Score": "0",
"body": "@user1095108 You are right this is a weak point. That's why I later wrote a cleaner solution for a [type ID](http://codereview.stackexchange.com/q/48594/39083), which does not need any `reinterpret_cast` at all. The improved `any`, called `some`, is now [here](https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/struct/some.hpp). This is already part of a repository, but is no longer independent. Among several other things, it uses the improved [type ID](https://github.com/iavr/ivl2/blob/master/include/ivl/root/core/type/core/id.hpp), part of the same repository."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T11:31:51.460",
"Id": "89946",
"Score": "0",
"body": "@user1095108 You are free to use or improve this version here, which is not in a repository, but in a [live example](http://coliru.stacked-crooked.com/a/61de929c06e026b4) along with samples showing how to use it. This is completely independent. By the way, note that I eventually also removed the conversion operators due to [problems](http://stackoverflow.com/q/23389672/2644390). I also replaced `dynamic_cast` with type ID equality for checked access."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T11:37:44.173",
"Id": "89947",
"Score": "0",
"body": "@user1095108 If you want to try the repository version, its samples are [here](https://github.com/iavr/ivl2/blob/master/test/struct/some.cpp)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T12:13:31.223",
"Id": "89950",
"Score": "0",
"body": "@iavr You're too ambitious in trying to reimplement `STL`, there are parts of it I am sure you don't want to (re)implement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-22T19:53:45.303",
"Id": "141927",
"Score": "0",
"body": "@iavr Check out my new [`any`](http://codereview.stackexchange.com/questions/78296/any-that-can-hold-arrays)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-28T09:11:40.857",
"Id": "339824",
"Score": "0",
"body": "I was looking for a substitute for boost::any and I think that your implementation does perfectly the job. Thank you very much for sharing it. I have one issue for which your input would be welcome. Your code compiles well with `VS studio 15` but the executable crashes. The problem comes after the second `swap` call. Surprisingly the first swap does the job by swapping between a `std::vector<int>` and a `std::string` but when swapping back something occurs in between that triggers the crash. Given the complexity of the code (at least for me), I could not make it through. How to solve this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-28T11:51:29.360",
"Id": "339825",
"Score": "0",
"body": "@EricPellegrini Have you seen this? https://codereview.stackexchange.com/q/78296/31562"
}
] | [
{
"body": "<p>The very idea of the storage inside <code>some</code> made me think about the problems it brings in <code>swap()</code> and <code>assign()</code>. I was first thinking about adding the <code>swap()</code> <strong><em>as another virtual method</em></strong>, possibly even the assignment. That could help you solve the problem in a bit different way - you will know if you are moving the pointer or need to copy/move the object from one embedded storage to another.</p>\n\n<p>But on second thought, the optimization behind the scene could as well be solved with good <a href=\"http://en.cppreference.com/w/cpp/memory/allocator\" rel=\"nofollow noreferrer\">allocator</a> for small objects utilizing some free-list and spinlocks or some other lockfree technique - e.g. <a href=\"http://www.boost.org/doc/libs/1_43_0/libs/pool/doc/index.html\" rel=\"nofollow noreferrer\">boost::pool</a> or <a href=\"http://pastebin.com/MrWmhJs5\" rel=\"nofollow noreferrer\">my own same-size allocator</a> <em>(very old school project)</em>. That will help you a lot with the problem of exceptions in swap/assign, without the need for temporary, <code>try..catch</code> and repair.</p>\n\n<p>If you still think about using the storage, I would not inherit it in <code>some</code>, but in inner class containing the pointer first (one base class having the pointer) and the store next (second base class or composition, <em>which would be better regarding next paragraph</em>). This could speed it a bit more by making it more sequential on reading (pointer first, vmtptr next, data last). You could as well move the vmtptr next to data pointer (no matter the storage), with few more tricks with <a href=\"http://en.cppreference.com/w/cpp/memory/new/operator_new\" rel=\"nofollow noreferrer\">placement new</a> (separating virtual methods from the data and <em>a bit terrible hack</em> to access the data pointer next to <code>this</code> as you know the layout). I wouldn't write this not seeing you trying to optimize it with the embedded storage, which itself is <em>overkill</em> - <a href=\"http://en.cppreference.com/w/cpp/memory/allocator\" rel=\"nofollow noreferrer\"><code>std::allocator</code></a> should handle this - I still think that solving this (fast allocation of tiny objects) will render your embedded storage as not needed <em>(and possibly helping other containers on the way)</em>.</p>\n\n<p>The allocator seems more like a feature of <code>some</code>, than allocator or usable extension/option for it. I would personally not expose it and make <code>some</code> a simple class (not a template). Or pass a real (but universal) allocator, something like <code>std::allocator<char></code>, with <a href=\"http://en.cppreference.com/w/cpp/memory/allocator_traits/allocate\" rel=\"nofollow noreferrer\"><code>allocate</code></a> and <a href=\"http://en.cppreference.com/w/cpp/memory/allocator_traits/deallocate\" rel=\"nofollow noreferrer\"><code>deallocate</code></a> optimized for tiny blocks. You could as well use <a href=\"http://www.cplusplus.com/reference/memory/allocator/rebind/\" rel=\"nofollow noreferrer\"><code>rebind</code></a> for all the types.</p>\n\n<hr>\n\n<h2>The Alloc/Store Interface</h2>\n\n<ul>\n<li><code>copy</code> accepts universal (rvalue) reference and therfore looks like to be something else, but from the code I can see you use it on one and only place - <code>data::copy</code> which uses it with simple (lvalue) reference. I think that it would be a good idea to change the signature to match it (otherwise it may became <em>a sort of move</em> instead of copy). Actually, it mimics <code>construct(allocate(1), v)</code>.</li>\n<li><code>move</code> seems to be there to move data from one storage to another (either embeded or heap). It looks to be doing what it was designed for, but I would change the inner <code>copy<D></code> to <code>new(space) ...</code>, to make it more clear (and understandable).</li>\n<li><code>free</code> is good, it means destroy + possibly dispose.</li>\n<li><code>swap</code> is something I would definitelly add (using <a href=\"http://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"nofollow noreferrer\">std::swap</a>) to help you solve the problems you have in <code>some::swap()</code> - I would just copy the <code>noexcept</code> from it and remove <code>try..catch</code>. It simply <em>should not</em> throw and you can take advantage of std::swap and possible specializations (<code>using std::swap; swap(x,y)</code> - you may look <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">there for copy-and-swap</a> to get some more related info).</li>\n</ul>\n\n<hr>\n\n<p><strong><em>Author:</strong> Expression <code>fits<D>()</code> is evaluated at compile time, so whenever it evaluates to false, <code>store</code> is equivalent to <code>alloc</code>, without any run time overhead. For <code>N = 0</code>, it is always equivalent (or I think so, right?).</em></p>\n\n<p>For me it looks to be related to this:</p>\n\n<pre><code>template<size_t N = 16>\nclass store\n{\n char space[N];\n\n template<typename T>\n static constexpr bool\n fits() { return sizeof(typename std::decay<T>::type) <= N; }\n</code></pre>\n\n<p><code>sizeof</code> will never return negative value, and <em>zero-size</em> array at the end of structure is allowed from what I know (at least good working extension I have used few times). If you run into problems, you can simply specialize the template (for <code>N = 0</code>).</p>\n\n<hr>\n\n<p><strong><em>Now it seems I have nothing to add</strong>, unless I see some feedback ;)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T23:13:40.373",
"Id": "62473",
"ParentId": "48344",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:26:25.883",
"Id": "48344",
"Score": "31",
"Tags": [
"c++",
"c++11",
"memory-management",
"reinventing-the-wheel",
"variant-type"
],
"Title": "Yet another 'any' class implementation, named 'some'"
} | 48344 |
A data type or a class designed to emulate a data type that holds a single value of a type that is either from an explicitly (compile-time) specified list, or arbitrary. The actual type of the stored value is only known at runtime. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:32:31.760",
"Id": "48346",
"Score": "0",
"Tags": null,
"Title": null
} | 48346 |
<p>I am writing the Cloud function for <a href="https://parse.com/docs/cloud_code_guide" rel="nofollow">Parse</a> whose purpose is to update my database with a provided array of data objects. The main problem are the nested promises, which doesn't look right. Any help to refactor this code or any other critiques?</p>
<pre><code>/**
* Updating multiple object arrays:
* Look for object with the same idKey and update with supplied data or create new if none is found
* Expect Data {schema: <schema_name>, idKey: <name_of_id_key>, data: <object_array>}
*/
Parse.Cloud.define("updater", function(request, response) {
var _ = require('underscore');
var schema = request.params.schema,
idKey = request.params.idKey,
objectArray = request.params.data;
var Class = Parse.Object.extend(schema),
parseObject,
id,
query;
_.each(objectArray, function(dataObject){
id = dataObject[idKey];
if (!id) return response.error("Supplied Object " + dataObject + " has no id Key '" + idKey + "' set!");
// now query for the same idKey
query = new Parse.Query(Class);
query.equalTo(idKey, id);
query.find().then(
function(array){
if(array) {
// found at least one object - take the first
parseObject = array[0];
// use the new dataObject to update parseObject
parseObject.set(dataObject);
parseObject.save().then(
/*
* should this go outside the promise?
*/
function(object){
// success
},
function(error){
return response.error(error);
});
} else {
// nothing found - create new
parseObject = new Class(dataObject);
parseObject.save().then(
function(object){
// success
},
function(error){
return response.error(error);
});
}
}
);
parseObject = new Class(dataObject);
parseObject.save().then(
function(object){
// success
},
function(error){
response.error(error);
});
});
response.success("Success!");
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:44:12.853",
"Id": "84855",
"Score": "0",
"body": "This may just be me not knowing Parse's system, but the flow seems a little shaky: It looks like it'll call `response.success` right away, because it doesn't wait for all the save operations to finish. And if one of those do fail, it'll call `response.error` - except, as mentioned, I imagine the response object has long since been resolved successfully, and I imagine it can only be resolved once. And even if one save fails, the code keeps going with the rest of the objects. It all seems kinda suspect to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:22:55.727",
"Id": "84918",
"Score": "0",
"body": "@Flambino Good point - these should be chained with `.then` - have to re-think it ..."
}
] | [
{
"body": "<p>I'd start with refactoring the promises functions and remove any code repetition, something like this:</p>\n\n<pre><code>...\n\nfunction success(object){\n // success \n}\nfunction error(error){\n return response.error(error);\n}\n...\n\nquery.find().then(function(array){\n if(array) {\n // found at least one object - take the first\n parseObject = array[0]; \n parseObject.set(dataObject); \n } else {\n // nothing found - create new\n parseObject = new Class(dataObject);\n } \n parseObject.save().then(success,error); \n});\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:20:27.987",
"Id": "84917",
"Score": "0",
"body": "Well that still has `.then` inside another `.then` which I understand is to be avoided with promises."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:50:12.127",
"Id": "48364",
"ParentId": "48357",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:10:23.457",
"Id": "48357",
"Score": "2",
"Tags": [
"javascript",
"database",
"node.js",
"asynchronous",
"promise"
],
"Title": "Cleaning up nested promises in Cloud function"
} | 48357 |
<p>I'm writing a Perl program to take a set of clauses and a conclusion literal and produce a resolution-refutation proof (if possible) using a breadth-first set of support (SOS) search algorithm.</p>
<p>The actual searching part of the program runs extremely slow, because I have many nested loops. I imagine it may also have to do with the system calls for the I/O taking place, but I'm not sure.</p>
<p>Here is the code for the searching part of the program.</p>
<p><code>@clauses</code> and <code>@SOS</code> are both 2D arrays. The <code>@clauses</code> contain all of the clauses including the negated conclusion. In the beginning of the algorithm you see <code>@SOS</code> gets initialized with the negated conclusion as its only value. It then grows with clauses as resolutions are found.</p>
<pre><code>#Begin breadth-first/SOS search/add algorithm
$SOS[0][0]=$conclusion2;
my $cSize=@clauses;
say "\nworking......";
my $dots=0;
SOSROW:
for(my $a; $a<@SOS; $a++)
{
if((($dots % 7) ==0))
{
print "\n";
}
if($dots==14)
{
print "You might want to get some coffee.\n";
}
if($dots==35)
{
print "I'm being VERY Thorough.\n";
}
if($dots==63 || $dots==140)
{
print "Hows that coffee?\n";
}
if($dots==105)
{
print "I think it might be time for a second cup of coffee\n"
}
print ".";
$dots++;
#Iterate through each clause on tier i
CLAUSEROW:
for(my $i=0; $i<@clauses; $i++)
{
SOSCOL:
for(my $b; $b<=$#{@SOS[$a]};$b++)
{
CLAUSECOL:
for(my $j=0; $j<=$#{@clauses[$i]}; $j++)
{
if($SOS[$a][$b] eq "~$clauses[$i][$j]"
|| $clauses[$i][$j] eq "~$SOS[$a][$b]")
{
my @tmp;
#Found a resolution, so add all other literals from
#both clauses to each set as a single clause
##*Algorith improvement**##
# First add them to a temporary array, then add them to the actual lists,
# only if the clause does not already appear.
#Start with the SOS literals (use a hash to keep track of duplicates)
my %seen;
for(my $c=0; $c<$#{@SOS[$a]}+1; $c++)
{
if($c != $b)
{
$seen{$SOS[$a][$c]}=1;
push @tmp, "$SOS[$a][$c]";
}
}
#Now add the literals from the non-SOS clause
for(my $k=0; $k<$#{@clauses[$i]}+1; $k++)
{
if($k != $j)
{
if(!$seen{$clauses[$i][$k]})
{
push @tmp,"$clauses[$i][$k]";
}
}
}
#Check to see if the clause is already listed
my $dupl='not';
my @a1=Unicode::Collate->new->sort(@tmp);
my $s1= join(undef, @a1);
for(my $i=0; $i<@clauses; $i++)
{
my @a2= Unicode::Collate->new->sort(@{@clauses[$i]});
my $s2= join(undef,@a2);
if($s1 eq $s2 )
{
$dupl ='did';
}
}
if($dupl eq 'not')
{
my $s=$cSize+$cAdd;
$res++;
$sAdd++;
$cAdd++;
push @{$SOS[$sAdd]}, @tmp;
push @{$clauses[$s]}, @tmp;
#Print out the new clauses.
print RESULTS"clause $s: ";
my $clause = $cSize+$a-1;
if($SOS[$sAdd][0])
{
print RESULTS "{";
for(my $j=0; $j<$#{@clauses[$s]}+1; $j++)
{
if($clauses[$s][$j])
{
print RESULTS "$clauses[$s][$j]";
}
if($j!=$#{@clauses[$s]})
{
print RESULTS ",";
}
}
print RESULTS "} ($i,$clause)\n";
}
#If you found a new res, but there was nothing to push, you found
# the contradiction, add {} as a clause, signal that you're done and break.
else
{
print RESULTS "{} ($i, $clause)\n";
$flag=1;
last SOSROW;
}
}
}
}
}
}
}
close(RESULTS);
</code></pre>
<p>I am interested in ways to possibly improve this code <em>without changing the searching method</em> (that is, breadth-first SOS).</p>
<p>As it stands, it works okay for small sets, but with sets with a lot of clauses, or rather, a lot of literals in the clauses, it takes a really long time to complete. For example, I just ran it on a file containing 16 clauses. The largest clause had 16 literals. It took about 24 hours to complete.</p>
<p>I also welcome any and all criticism of my code, no matter how harsh (as long as it's constructive).</p>
<p><strong>EDIT:</strong> I feel that multi-threading would be a good solution, but now I'm trying to figure out the best place to use threads. I've decided to use two threads because, I'm not sure what machine will be running this program, but I can be fairly certain it will have at least two cores.</p>
<p>Actually, is there an environment variable that could tell me how many cores the CPU has, or that I could parse the number from? That way I could dynamically determine the thread amount.</p>
<p>Either way, I have two ideas so far</p>
<ul>
<li><p>I am thinking I could break up the second loop into multiple concurrent threads so each time the outer-most loop finished, the second loop (checking the SOS clause against all other clauses) could be broken up into x groups that are executed concurrently.</p></li>
<li><p>Or, because on each pass of the outer loop, multiple clauses could be added to the SOS set, I could break that group up and check them against the other clauses concurrently, instead of sequentially.</p></li>
</ul>
<p>Is there any reason one solution would be better than the other?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:31:58.727",
"Id": "84851",
"Score": "0",
"body": "would using multiple threads help at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:54:25.080",
"Id": "84852",
"Score": "0",
"body": "if you can split your job into chunks, why not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T17:21:32.927",
"Id": "84853",
"Score": "0",
"body": "the thing is I've never used multi threading before, so I'm not sure how I would go about implementing it. could I divide the clauses to be compared into x separate groups and have them compared in parallel. But then, how would I decide how many groups. It depends on the machine and how many processors it has, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:36:44.907",
"Id": "84854",
"Score": "0",
"body": "think of threading like running your script multiple times, but on separate data sets. If you can make separate data sets, you can also run them in parallel."
}
] | [
{
"body": "<p>You seem to have taken away little from my efforts to help you write good Perl code. In particular you <em>must</em> add</p>\n\n<pre><code>use warnings\n</code></pre>\n\n<p>to the top of <em>every</em> Perl program, which in this case would have resulted in line after line of errors like</p>\n\n<pre><code>Scalar value @clauses[$s] better written as $clauses[$s]\n</code></pre>\n\n<p>You also should use Perl's range iterator. The C-style <code>for</code> loop is a clumsy tool, and you are also mixing together <code>$#array</code>, <code>$#array + 1</code>, <code>@array</code>, and <code>@array - 1</code> in your loop limits.</p>\n\n<p>To iterate over the indices of a Perl array you should write</p>\n\n<pre><code>for my $i (0 .. $#array) {\n ...\n}\n</code></pre>\n\n<p>unless you have a strange and unusual requirement. It is also best to keep to <code>$i</code>, <code>$j</code>, <code>$k</code> etc. for array indices as everyone knows what they mean. <code>$s</code> is usually a string, and <code>$a</code> and <code>$b</code> are fobidden because they are used by the Perl <code>sort</code> engine.</p>\n\n<p>So your loops</p>\n\n<pre><code>for (my $i = 0; $i < @clauses; $i++) { ... }\n\nfor (my $j = 0; $j < $#{ @clauses[$s] } + 1; $j++) { ... }\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for my $i (0 .. $#clauses) { ... }\n\nfor my $j (0 .. $#{ $clauses[$i] }) { ... }\n</code></pre>\n\n<p>which I hope you will agree is much more readable.</p>\n\n<p>If you make at least these changes then you will get a lot more help from people who will then be able to understand your code better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:04:11.683",
"Id": "84858",
"Score": "0",
"body": "again, Borodin, I have use v5.14. this is only a segment as I said. I meant to ask you, if use 5.14 only turns on strict and not warnings, because I get no such errors. yes that does appear more readable, i suppose. I am used to the c style and thats what i was using, so in my error checking I could be sure that my syntax wasn't causing an error. I will get to changing that.\n\nAlso, is using a/b actually affecting my program? or just bad practice. \n\nfinally, any input on the multi-threading thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:06:14.217",
"Id": "84859",
"Score": "0",
"body": "never mind obviously i doesn't i just tried it. I could have sworn i remember reading in the orielly book that it does, that would have helped me out a lot"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:07:35.080",
"Id": "84860",
"Score": "1",
"body": "@user3002620: You *did* ask me and I answered you [*here*](http://stackoverflow.com/questions/23317796/cant-use-string-a-b-c-as-an-array-ref#comment35702183_23318196)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:12:00.190",
"Id": "84863",
"Score": "1",
"body": "@user3002620: I can't tell whether your misuse of `$a` and `$b` is affecting anything because I can't see your full program, but it is a far better solution just to avoid them, then I can be certain that you aren't causing a problem; that is why good practice is good practice. I can't make a recommendation on how to optimise your code until you have written it so that I can see what it is doing. That is why I am offering you advice to improve the legibility of your code. It should need no comments, or very few, to make it comprehensible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:12:21.373",
"Id": "84864",
"Score": "0",
"body": "oh yep, i skipped right over that last sentence. I should have just tried it immediately. But my program was running while I was talking to you and I was running it over a remote connection in which i couldn't open another window or tab to check."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:15:05.550",
"Id": "84867",
"Score": "0",
"body": "I was under the impression that comments were good practice? Also, The only method I currently know to post code is to copy and paste my prog in the box. the clipboard only copies like 50 lines, is there an easier way to do it, so i can get my whole program in less painfully?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:03:30.970",
"Id": "85049",
"Score": "0",
"body": "@user3002620: It used to be taught that an abundance of comments makes a program more intelligible, but that was when FORTRAN and BASIC with single-letter identifiers were dominant languages - forty or more years ago. Since then a combination of useful identifiers and object-oriented programming has allowed programs to describe their own functionality. More recently, good use of identifiers, white space, and expressive statements are much more valuable. Comments are still sometimes necessary, when *what* the code is doing needs to be supplemented with an explanation of *why* it is doing it"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T18:53:04.517",
"Id": "48359",
"ParentId": "48358",
"Score": "7"
}
},
{
"body": "<p>I found the general style of your program hard to read. You use 8-space indentation but have so many levels that the most of your code isn't visible without scrolling. Other for indentation, you use very little spaces in your code, for example around operators. This line:</p>\n\n<pre><code>for(my $j=0; $j<=$#{@clauses[$i]}; $j++) {\n</code></pre>\n\n<p>Could be made more readable as</p>\n\n<pre><code>for(my $j = 0; $j <= $#{ @clauses[$i] }; $j++) {\n</code></pre>\n\n<p>I used the automatic Perl code formatter “<a href=\"https://metacpan.org/pod/distribution/Perl-Tidy/bin/perltidy\" rel=\"nofollow noreferrer\">Perl::Tidy</a>” with a configuration I use, which produced the more readable below output. All I did manually was to reflow the comments and remove empty lines.</p>\n\n<pre><code># begin breadthfirst/sos search/add algorithm\n$SOS[0][0] = $conclusion2;\nmy $cSize = @clauses;\nsay \"\\nworking......\";\nmy $dots = 0;\n\nSOSROW:\nfor (my $a ; $a < @SOS ; $a++) {\n if ((($dots % 7) == 0)) {\n print \"\\n\";\n }\n\n if ($dots == 14) {\n print \"You might want to get some coffee.\\n\";\n }\n\n if ($dots == 35) {\n print \"I'm being VERY Thorough.\\n\";\n }\n\n if ($dots == 63 || $dots == 140) {\n print \"Hows that coffee?\\n\";\n }\n if ($dots == 105) {\n print \"I think it might be time for a second cup of coffee\\n\";\n }\n\n print \".\";\n $dots++;\n\n # iterate through each clause on tier i\n CLAUSEROW:\n for (my $i = 0 ; $i < @clauses ; $i++) {\n SOSCOL:\n for (my $b ; $b <= $#{ @SOS[$a] } ; $b++) {\n CLAUSECOL:\n for (my $j = 0 ; $j <= $#{ @clauses[$i] } ; $j++) {\n if ( $SOS[$a][$b] eq \"~$clauses[$i][$j]\"\n || $clauses[$i][$j] eq \"~$SOS[$a][$b]\")\n {\n my @tmp;\n\n # found a resolution, so add all other literals from\n # both clauses to each set as a single clause\n\n # Algorith improvement:\n # first add them to a tmp array, then add them to the actual lists\n # only if the clause does not already appear.\n\n #start with the SOS literals(use a hash to keep track of duplicates)\n my %seen;\n for (my $c = 0 ; $c < $#{ @SOS[$a] } + 1 ; $c++) {\n if ($c != $b) {\n $seen{ $SOS[$a][$c] } = 1;\n push @tmp, \"$SOS[$a][$c]\";\n }\n }\n\n # now add the literals from the non-SOS clause\n for (my $k = 0 ; $k < $#{ @clauses[$i] } + 1 ; $k++) {\n if ($k != $j) {\n if (!$seen{ $clauses[$i][$k] }) {\n push @tmp, \"$clauses[$i][$k]\";\n }\n }\n }\n\n # check to see if the clause is already listed\n my $dupl = 'not';\n my @a1 = Unicode::Collate->new->sort(@tmp);\n my $s1 = join(undef, @a1);\n\n for (my $i = 0 ; $i < @clauses ; $i++) {\n my @a2 =\n Unicode::Collate->new->sort(@{ @clauses[$i] });\n my $s2 = join(undef, @a2);\n if ($s1 eq $s2) {\n $dupl = 'did';\n }\n }\n\n if ($dupl eq 'not') {\n my $s = $cSize + $cAdd;\n $res++;\n $sAdd++;\n $cAdd++;\n push @{ $SOS[$sAdd] }, @tmp;\n push @{ $clauses[$s] }, @tmp;\n\n # print out the new clauses.\n print RESULTS\"clause $s: \";\n my $clause = $cSize + $a - 1;\n if ($SOS[$sAdd][0]) {\n print RESULTS \"{\";\n for (\n my $j = 0 ;\n $j < $#{ @clauses[$s] } + 1 ;\n $j++\n )\n {\n if ($clauses[$s][$j]) {\n print RESULTS \"$clauses[$s][$j]\";\n }\n\n if ($j != $#{ @clauses[$s] }) {\n print RESULTS \",\";\n }\n }\n\n print RESULTS \"} ($i,$clause)\\n\";\n }\n\n # if you found a new res, but there was nothing to\n # push, you found the contradiction, add {} as a\n # clause, signal that you're done and break.\n else {\n print RESULTS \"{} ($i, $clause)\\n\";\n\n $flag = 1;\n last SOSROW;\n }\n }\n }\n }\n }\n }\n}\n\nclose(RESULTS);\n</code></pre>\n\n<p>The most crucial issues with this code besides formatting are mentioned <a href=\"https://codereview.stackexchange.com/a/48359/21609\">by Borodin in his answer</a>.</p>\n\n<p>Beyond those issues, I made the following observations:</p>\n\n<ul>\n<li><p>you did <code>join(undef, @a1)</code>. This makes very little sense, if you want to join strings without a delimiter, use the empty string: <code>join('', @a1)</code>.</p></li>\n<li><p>You perform an Unicode sort <code>Unicode::Collate->new->sort(@tmp)</code>, and that multiple times. Unless there is a real need for this, I'd recommend to use the faster builtin sort: <code>sort @tmp</code>. Here there is no need, and you just need the sorting to be consistent.</p></li>\n<li><p>You use the variable <code>$dup</code> as a boolean flag with values <code>\"not\"</code> or <code>\"dup\"</code>. Instead, choose a proper variable name and use values that are boolean on their own:</p>\n\n<pre><code>my $found_duplicates = 0;\n...\n $found_duplicates = 1;\n...\nif (not $found_duplicates) {\n ...\n</code></pre></li>\n<li><p>The provided code snippet refers to many variables that are declared outside of this snippet (if they are declared at all). These have very broad scopes, which is a bad sign.</p></li>\n<li><p>You regularly output some status (usually a period, every seven periods a line, and sometimes a quip). I'd suggest moving this code into a separate subroutine so the actual algorithm is less cluttered. Your loop would then only contain a simple <code>display_status($dots++)</code>.</p>\n\n<pre><code>my %quips = (\n 14 => \"You might want to get some coffe\",\n 35 => \"I'm being VERY thorough\",\n ...\n);\n\nsub display_status {\n my ($round) = @_;\n print \"\\n\" if $round % 7 == 0;\n print \"$quips{$round}\\n\" if exists $quips{$round};\n print \".\";\n}\n</code></pre></li>\n<li><p>Initialize all your variables. All of them, without excuse. <code>use warnings</code> if you need a friendly reminder.</p></li>\n<li><p>Some of your search loops can be terminated early when you've found something. E.g.</p>\n\n<pre><code># check to see if the clause is already listed\nmy $dupl = 'not';\nmy @a1 = Unicode::Collate->new->sort(@tmp);\nmy $s1 = join(undef, @a1);\n\nfor (my $i = 0 ; $i < @clauses ; $i++) {\n my @a2 =\n Unicode::Collate->new->sort(@{ @clauses[$i] });\n my $s2 = join(undef, @a2);\n if ($s1 eq $s2) {\n $dupl = 'did';\n }\n}\n</code></pre>\n\n<p>could be improved to</p>\n\n<pre><code># check to see if the clause is already listed\nmy $found_duplicates = 0;\nmy $s1 = join '', sort @tmp;\n\nCLAUSE:\nfor my $clause (@clauses) {\n my $s2 = join '', sort @$clause;\n if ($s1 eq $s2) {\n $found_duplicates = 1;\n last CLAUSE;\n }\n}\n</code></pre></li>\n<li><p>Use foreach loops wherever you can, e.g. <code>for my $clause (@clauses)</code> rather than using indices.</p></li>\n<li><p>This code is basically replicating <code>join</code>:</p>\n\n<pre><code>print RESULTS \"{\";\nfor (\n my $j = 0 ;\n $j < $#{ @clauses[$s] } + 1 ;\n $j++\n )\n{\n if ($clauses[$s][$j]) {\n print RESULTS \"$clauses[$s][$j]\";\n }\n\n if ($j != $#{ @clauses[$s] }) {\n print RESULTS \",\";\n }\n}\n\nprint RESULTS \"} ($i,$clause)\\n\";\n</code></pre>\n\n<p>It can be simplified to</p>\n\n<pre><code>my $list_of_clauses = join ',', map { $_ || '' } @{ $clauses[$s] };\nsay RESULTS \"{$list_of_clauses} ($i, $clause)\";\n</code></pre>\n\n<p>This needs a bit of explanation. <code>map</code> is a function that takes a block and a list. It sets <code>$_</code> to each element of the input list in turn and then evaluates the block. The result of the block is added to the output list:</p>\n\n<pre><code>my @output;\nfor (@input) {\n push @output, the_block($_);\n}\n</code></pre>\n\n<p>So for each element <code>map { $_ || '' } @list</code> returns the list element if it's true-ish, or the empty string otherwise.</p></li>\n</ul>\n\n<h3>Edit: comprehensive refactoring</h3>\n\n<p>I went through the code and gradually improved it. There are many optimizations that can be employed, such as calculating data structures in the outermost possible loop, or using hashes for linear-time lookup. I also tried to rename most variables to something sensible. This should have lowered the algorithmic complexity of the outer loops from \\$O(n^2 \\cdot m^2)\\$ to \\$O(n^2 \\cdot m)\\$ (which isn't much in the grand scheme of things, but might still be a 16× speedup under some input). More importantly, in many parts my refactoring should have a far lower constant factor.</p>\n\n<p>I could have employed further optimizations if I'd known the exact initial makeup of <code>@SOS</code> and <code>@clauses</code>. For example certain checks have to added when elements can be <code>undef</code>, or when the input clauses might contain duplicate elements. Furthermore the input is currently treated as strings. If they are actually numbers or can be mapped to numbers, certain simplifications could be employed.</p>\n\n<p>After having spent a lot of time with this code, I've come to the conclusion that this problem is not easily parallelizable. Certainly, it would be possible to run the <code>MATCH</code> loop inside worker threads which get passed a pair of rows and return a bunch of new clauses. A main thread would then aggregate the new clauses and extend your data structures, then dispatch new jobs. However, the speedup obtainable in this way is likely to be small compared with other optimizations you could take (such as rewriting part of the program in C, or doing more caching of data structures that get recalculated).</p>\n\n<pre><code># begin breadthfirst/sos search/add algorithm\n$SOS[0][0] = $conclusion2;\n\nmy $initial_clause_offset = $#clauses;\n\nmy %known_clauses;\nfor my $clause (@clauses) {\n my $key = join '', sort @$clause;\n $known_clauses{$key} = 1;\n}\n\nsay \"\";\nsay \"working......\";\n\nSOS_ROW:\nfor (my $sos_row = 0 ; $sos_row < @SOS ; $sos_row++) {\n my $the_sos_row = $SOS[$sos_row];\n\n display_status($sos_row);\n\n # build the hash of seen elements for this row\n my %seen;\n $seen{$_}++ for @$the_sos_row;\n\n CLAUSE_ROW:\n for (my $clause_row = 0 ; $clause_row < @clauses ; $clause_row++) {\n my $the_clause_row = $clauses[$clause_row];\n\n MATCH:\n for my $match (find_matches($the_sos_row, $the_clause_row)) {\n my ($sos_col, $clause_col) = @$match;\n\n # We found a resolution, so we combine all other literals from\n # both clauses to each a single new clause.\n # We add the new clause only if it isn't already known\n\n # make a copy of the SOS clause\n # and remove the $sos_col-th element\n my @sos_literals = @$the_sos_row;\n my $removed = splice @sos_literals, $sos_col, 1;\n\n # shadow-delete the $removed element from the hash\n # but only if it was seen once. It will be there again in the next\n # loop iteration. This is admittedly a bit arcane.\n local $seen{$removed} = $seen{$removed};\n delete $seen{$removed} if $seen{$removed} == 1;\n\n # copy the literals from the non-SOS clause\n # and remove $clause_col-th element\n # and remove seen elements\n my @non_sos_literals = @$the_clause_row;\n splice @non_sos_literals, $clause_col, 1;\n @non_sos_literals = grep { not $seen{$_} } @non_sos_literals;\n\n my @new_clause = sort(@sos_literals, @non_sos_literals);\n my $new_clause_key = join '', @new_clause;\n\n # skip this new clause if the clause is already known\n next MATCH if $known_clauses{$new_clause_key};\n\n # else add this clause to the known clauses etc.\n push @SOS, \\@new_clause;\n push @clauses, \\@new_clause;\n $known_clauses{$new_clause_key} = 1;\n $res++;\n\n # print out the new clauses.\n my $clause = $initial_clause_offset + $sos_row;\n my $list_of_clauses = join ',', map { $_ || '' } @new_clause;\n say RESULTS\n \"clause $#clauses: {$list_of_clauses} ($clause_row, $clause)\";\n\n # if you found a new res, but there was nothing to\n # push, you found the contradiction, add {} as a\n # clause, signal that you're done and break.\n if (not @new_clause) {\n $flag = 1;\n last SOS_ROW;\n }\n }\n }\n}\n\nclose(RESULTS);\n\n# Return pairs of indices for all matching elements between the two arrays.\n# Only uses O(n + m) complexity!\nsub find_matches {\n my ($sos_row, $clause_row) = @_;\n\n # build a hash of clause items that map to their columns\n # in principle, this could be cached.\n my %clause_col;\n for my $i (0 .. $#$clause_row) {\n $clause_col{ $clause_row->[$i] } = $i;\n $clause_col{ '~' . $clause_row->[$i] } = $i;\n }\n\n # we now look up possible matching items,\n # and add the indices to the matches\n my @matches;\n for my $sos_col (0 .. $#$sos_row) {\n my $item = $sos_row->[$i];\n my $clause_col = $clause_col{$item} // $clause_col{\"~$item\"};\n push @matches, [ $sos_col, $clause_col ] if defined $clause_col;\n }\n\n return @matches;\n}\n\nmy %quips;\n\nBEGIN {\n %quips = (\n 14 => \"You might want to get some coffe\",\n 35 => \"I'm being VERY thorough\",\n 63 => \"How's that coffee?\",\n 105 => \"I think it might be time for a second cup of coffee\",\n 140 => \"How's that coffee?\",\n );\n}\n\nsub display_status {\n my ($round) = @_;\n print \"\\n\" if $round % 7 == 0;\n print \"$quips{$round}\\n\" if exists $quips{$round};\n print \".\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T21:51:16.223",
"Id": "84880",
"Score": "0",
"body": "added a fairly comprehensive refactoring that should result in much faster run time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:20:23.833",
"Id": "48362",
"ParentId": "48358",
"Score": "4"
}
},
{
"body": "<p>There is unlikely to be any benefit from multithreading your application until you have identified a section of code that is most responsible for any delay.</p>\n\n<p>In general, a program that could benefit from multithreading will divide its time between CPU-intensive and IO-intensive sections.</p>\n\n<p>If your program does little or no IO and just uses the CPU sequentially until it finds a result (think of something like calculating π to many decimal places) then there is no benefit in multithreading.</p>\n\n<p>Likewise, if the CPU has very little to do except wait until comparatively snail-paced IO to complete (suppose the task is to copy one disk file to another) then again there is no purpose in multithreading.</p>\n\n<p>Where multithreading <em>can</em> give huge benefits is if the amount of processing is more or less equal to the time taken communicating with external devices. In that case a process can prepare the contents of the next output during the time taken to deliver the previous set of data.</p>\n\n<p>Ideal balances like that are rare, and it is much more common that the overheads of multi-threading outweigh the benefits. In particular it is left to the operating system to divide the CPU workload between the available processors, and since you have no control over that decision it may well be that a single-threaded solution is the optimal one.</p>\n\n<p>In the end there is a limit to how fast any given machine can execute the algorithm that you have coded. Unless there are obvious places in your program where useful processing could be done while waiting for IO to complete, it is unlikely that clever coding can compete with what the operating system already does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:45:47.273",
"Id": "48456",
"ParentId": "48358",
"Score": "0"
}
},
{
"body": "<p>These answers are great, but they're all missing one simple thing. </p>\n\n<p>I know you said you want to stick with the breadth-first SOS algorithm. </p>\n\n<p>and you can/should, but have you considered adding subsumption capabilities to your code?</p>\n\n<p>It would only take a couple of lines above that first inner loop. </p>\n\n<p>My bet is that it's the large amount of values in the arrays that's causing the slowdown and not the actual amount of arrays.</p>\n\n<p>Best case scenario, jobs that take hours now, only take seconds with subsumption. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T05:10:46.077",
"Id": "48543",
"ParentId": "48358",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48362",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:28:06.253",
"Id": "48358",
"Score": "3",
"Tags": [
"perl",
"optimization",
"io"
],
"Title": "Optimizing system calls and nested loops"
} | 48358 |
<p>I want to create a container that has an <code>AutoList</code> object list. I wonder if my container is correct.</p>
<pre><code>class Auto{
string model;
int co2;
public:
Auto ();
Auto(string m, int c);
~Auto(){};
string GetModel(){return model;}
void SetModel(string s){model = s;}
int GetCo2(){return co2;}
void SetCo2(int k){co2 = k;}
bool operator < (const Auto &kitas);
};
class AutoList{
private:
Auto data;
AutoList *next;
public:
AutoList(Auto a = Auto(), AutoList *al = NULL):
data(a), next(al){}
~AutoList(){}
void SetData(const Auto &a){data = a;}
Auto GetData() const {return data;}
void Set(AutoList *newaut){next = newaut;}
const AutoList *Get() const {return next;}
AutoList *Get(){return next;}
};
// I need to make a container class which saves AutoList object list.
class Container{ // is this class is container of AutoList object LIST???
private:
AutoList *beg, *end, *d;
public:
Container():beg(NULL), end(NULL), d(NULL){}
~Container(){Delete();}
void Delete();
Container(const Container & kitas);
Container & operator = (const Container & kitas);
void Begin(){d = beg;}
bool True(){return d != NULL;}
void Next(){d = d->Get();}
AutoList GetAutoList(){return d->GetData();}
void SetAutoList(const Auto & data);
};
void Container::Delete(){
while(beg){
d = beg;
beg = beg->Get();
delete d;
}
end = NULL;
}
void Container::SetAutoList(const Auto & data){
//..........
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>The absence of <code>std::</code> in front of <code>string</code> can imply that you're using <code>using namespace std</code>. If so, this should be removed as it can break code (mainly with name-clashing) that includes this file. Read <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a> for more information.</p></li>\n<li><p>Your variables could have more descriptive names. There are many single-character names, which is discouraged except when they're used as loop counters. Giving poor names can greatly reduce readability as other readers may not be able to understand their purpose.</p>\n\n<p>One example is <code>co2</code>. If this is short for something, then spell it out. You may already know what it means, but it doesn't mean others will understand it as well.</p></li>\n<li><p>Accessors (\"getters\"), conditional overloaded operators, and any other member member function that doesn't modify data members should be <code>const</code>. This will also make the intent clear to the reader and prevent any accidental modification of data members.</p>\n\n<p>Examples:</p>\n\n<pre><code>int getSomething() const { return something; }\n</code></pre>\n\n<p></p>\n\n<pre><code>bool operator==(Class const& rhs) const { return something == rhs.something; }\n</code></pre></li>\n<li><p>I see that you're trying to maintain The Rule of Three in <code>Container</code> (as it contains pointers as members), which is good. However, it appears to be incomplete as there's nothing in the overloaded copy constructor except for a placeholder. There's also a declaration for the overloaded assignment operator, but no implementation.</p>\n\n<p>For such instances of code to be added, it's common to leave a <code>// TODO</code> comment to state what must still be done in the future. This is much more clearer to readers than a line of ellipses.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T20:03:07.127",
"Id": "48367",
"ParentId": "48363",
"Score": "3"
}
},
{
"body": "<p><code>AutoList</code> is for Node of <code>Auto</code>. The name <code>AutoList</code> is very confusing. I would name it as <code>AutoNode</code> so that a reader can know that it's a node element and not a List in itself. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:50:09.273",
"Id": "84888",
"Score": "1",
"body": "+1. It honestly took me a while to realize that, hence why I haven't mentioned it myself. Naming really is important. Bearing this in mind, you may mention that getters/setters are not good for node implementations (if you know enough about that)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T22:42:03.003",
"Id": "48371",
"ParentId": "48363",
"Score": "4"
}
},
{
"body": "<p>Class call \"Auto\"</p>\n\n<pre><code>class Auto{\n</code></pre>\n\n<p>But to simular to the <code>auto</code> keyword for my liking.</p>\n\n<p>If the destructor does nothing.</p>\n\n<pre><code> ~Auto(){};\n</code></pre>\n\n<p>Then don't add it to your class; the compiler generated version works fine.</p>\n\n<p>Hate Getters/Setters. Its bad design. You are exposing the internals of your class. Use <strong>only</strong> as a last resort. The members of your class should do the operations required.</p>\n\n<pre><code> string GetModel(){return model;}\n void SetModel(string s){model = s;}\n int GetCo2(){return co2;}\n void SetCo2(int k){co2 = k;}\n</code></pre>\n\n<p>Also note: Geters don't mutate the state of your object (or should not). So you should mark them as const. Since they are not going to mutate the state you can return a const reference to the internal member.</p>\n\n<pre><code> string const& GetModel() const {return model;}\n /// ^^^^^^ Return a const ref to member.\n // ^^^^^ Note this function does not mutate the object.\n</code></pre>\n\n<p>Same applies to comparison functions. You don't mutate the state so mark it as const.</p>\n\n<pre><code> bool operator < const (const Auto &kitas);\n // ^^^^^\n</code></pre>\n\n<p>This is not a list object. More like a node in the list.\n class AutoList{</p>\n\n<p>Usless Destructor again:</p>\n\n<pre><code> ~AutoList(){}\n</code></pre>\n\n<p>This is really the list. The term container is very generic. Call it a list.</p>\n\n<pre><code>class Container{ // is this class is container of AutoList object LIST???\n</code></pre>\n\n<p>The member <code>d</code> seems to be used as a temprary. I don't think you actually need it as a member. Declare a local variable in each member.</p>\n\n<pre><code> AutoList *beg, *end, *d;\n</code></pre>\n\n<p>Iterators in C++ are well defined. They are objects that respond to ++ and * (de-reference). Return an object like this. Otherwise your list can only support one iterator.</p>\n\n<pre><code> void Begin(){d = beg;}\n void Next(){d = d->Get();}\n bool True(){return d != NULL;}\n AutoList GetAutoList(){return d->GetData();}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:35:08.917",
"Id": "48431",
"ParentId": "48363",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:24:19.340",
"Id": "48363",
"Score": "2",
"Tags": [
"c++",
"beginner",
"container"
],
"Title": "Containers and lists"
} | 48363 |
<p>I have made 2 scripts in Ruby. The first program creates an .rtf file with cards (file with colored table with persons) from a list of people in text file. The second program does the same, but in an HTML file. In the first, I can use the gem library, but I'm not allowed to do so in the second.</p>
<p>My teacher said that in both cases, code could be two times shorter. He also said that I'm not organising stuff in class and methods; that could be a problem if I start to write more advanced codes in future. I'm asking where and how I could improve my code to be shorter and organised in classed/method. I placed my notes in the comments.</p>
<pre><code>require 'rubygems'
require 'rtf'
include RTF
def card(t, person, style1, style2, i)
style = CharacterStyle.new
x = i/2.0.floor
y = i % 2
if x % 2 == 0
style = style1
t[x][y].shading_colour = $olive
else
style = style2
t[x][y].shading_colour = $maroon
end
person = person.split(";")
# I could bet that there's some way to automatically apply line_break command after all following lines.
t[x][y].apply(style) << "name: " + person[0]
t[x][y].line_break
t[x][y].apply(style) << "surname: " + person[1]
t[x][y].line_break
t[x][y].apply(style) << "date_of_birth: " + person[2]
t[x][y].line_break
t[x][y].apply(style) << "salary: " + person[3]
t[x][y].line_break
t[x][y].apply(style) << "phone: " + person[4]
t[x][y].line_break
t[x][y].apply(style) << "position: " + person[5]
t[x][y].line_break
t[x][y].apply(style) << "email: "+ person[6]
end
document = Document.new(Font.new(Font::ROMAN, 'Times New Roman'), nil, Document::CS_PC, Document::LC_POLISH)
# I don't like using a global variables there but applying them directly in method card would slow down whole script.
$maroon = Colour.new(125, 0, 0)
$olive = Colour.new(125, 125, 0)
style1 = CharacterStyle.new
style1.font = Font.new(Font::MODERN, 'Calibri')
style1.foreground = $maroon
style1.underline = true
style2 = CharacterStyle.new
style2.font = Font.new(Font::ROMAN, 'Times New Roman')
style2.bold = true
style2.foreground = $olive
people = []
f = open('base.txt', "r:UTF-8") { |f| f.read }
f.each_line { |ln| people << ln }
array = document.table(people.length/2.0.ceil,2, 4000,4000,4000)
# I don't like using "i" variable as cell counter of table. I would like to use some useful method instead of that.
i = 0
people.each {|person|
card(array, person, style1, style2, i)
i += 1
}
File.open('cards.rtf', 'w:UTF-8') {|f| f.write(document.to_rtf)}
</code></pre>
<p>Second program</p>
<pre><code>def b(text)
"<b>#{text}</b>"
end
def array(document, person, i)
person = person.split(';')
# I don't like the "i" variable. I think there is an other simple way in ruby to do something diffrent in loop for every second element.
if i % 2 == 0
document << "<tr>"
color1 = 'maroon'
color2 = 'olive'
else
color1 = 'olive'
color2 = 'maroon'
end
# There would be great if i could organise array styles in methods.
document << "<td><p style='background-color:#{color1};font-family:arial;color:#{color2};font-size:20px;'>"
document << b("name: ") + person[0] + "<br />"
document << b("surname: ") + person[1] + "<br />"
document << b("date_of_birth: ") + person[2] + "<br />"
document << b("salary: ") + person[3] + "<br />"
document << b("phone: ") + person[4] + "<br />"
document << b("position: ") + person[5] + "<br />"
document << b("email: ") + person[6] + "<br />"
document << "</p></td>"
if i % 2 == 1
document << "</tr>"
end
end
people = []
f = open('base.txt', "r:UTF-8") { |f| f.read }
f.each_line { |ln| people << ln }
document = ''
# I would like to create document as an object of some class.
document <<
"<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<meta content='text/html; charset=ISO-8859-2'
http-equiv='content-type'>
<title></title>
</head>
<body>
<table>"
i = 0
people.each { |person|
array(document, person, i)
i += 1
}
document <<
"</table>
</body>
</html>"
File.open('document.html', 'w:ISO-8859-2') { |f| f.write document }
</code></pre>
| [] | [
{
"body": "<p>Your code is basically a long a list of discrete steps, rather than an attempt at modelling the data and the task.</p>\n\n<p>The steps for both output formats are</p>\n\n<ol>\n<li>Read</li>\n<li>Parse</li>\n<li>Write</li>\n</ol>\n\n<p>I think your teacher would want you to realize that the first 2 steps are completely independent of the output format: Regardless of whether it's HTML or RTF (or JSON or whatever), you have to read and parse an input file. So get those 2 steps working first, and reuse the same code (e.g. <code>require 'parser'</code>) for either output format.</p>\n\n<p>There's also a lot of built-in stuff in Ruby that you could use to your advantage. So <a href=\"http://www.ruby-doc.org/core-2.0.0/\" rel=\"nofollow\">read the docs</a>. Read as much as you can stomach and then some. Know your tools.<br>\nIn this case, this applies especially to the docs for Enumerable/Array and IO/File, which are things you're most likely to use for this and many, many other things (Enumerable especially)</p>\n\n<p>Other things in your code:</p>\n\n<ul>\n<li><p>Don't just include the entire <code>RTF</code> module in the global scope; put your own code in the RTF module's namespace, include it in a class you define, or just live with writing <code>RTF::</code> in a couple of places. Any of those things are preferable.</p></li>\n<li><p>Don't call a method <code>array</code>. What is one supposed to think when reading that name? It's apparently the method that <em>does everything</em> yet it's just named \"array\", which is a data type/object/concept - everything but a method. Name your methods for what they <em>do</em> or what they <em>are</em> (i.e. their return value). So: Don't name a method <code>card</code>, since it isn't a card; the method <em>does</em> something but that something is not \"card\" either. Same with the <code>b</code> method, which also doesn't really reveal what it does.</p></li>\n<li><p>Why are you reading a file as UTF-8, yet writing it as iso-8859-2 when writing the HTML?</p></li>\n<li><p>You're not really outputting tables. You're just writing a lot of paragraphs, which you can do by, well, just writing a bunch of paragraphs. No table needed. But I imagine that you're supposed to output an actual table with a header row, and the data for each person as a row in that table.</p></li>\n<li><p>Magic, hard coded numbers: No thanks. E.g. width 4000 for table cells? Why 4000?</p></li>\n</ul>\n\n<p>To answer some of you comments:</p>\n\n<blockquote>\n <p>I could bet that there's some way to automatically apply line_break command after all following lines.</p>\n</blockquote>\n\n<p>Yes: A method. Code something like <code>write_line(text)</code>, which writes some text to the document followed by a line break.</p>\n\n<p>Methods don't need to be giant blocks of code. In fact, the shorter a method is, the better. So a 2-line method to write something plus a line break (which also matches the method's name) is a great way to go.</p>\n\n<blockquote>\n <p>I don't like using a global variables there but applying them directly in method card would slow down whole script. </p>\n</blockquote>\n\n<p>Would it? Because I doubt it. But if you're sure: How much does it slow down? And: Does it matter? (My guess here is \"very, very little\", and \"no, it doesn't matter at all\")</p>\n\n<blockquote>\n <p>I don't like using \"i\" variable as cell counter of table. I would like to use some useful method instead of that.</p>\n</blockquote>\n\n<p>See <a href=\"http://www.ruby-doc.org/core-2.0.0/Enumerable.html#method-i-each_with_index\" rel=\"nofollow\">Enumerable#each_with_index</a></p>\n\n<p>Anyway, code: I'd start by defining a parser class:</p>\n\n<pre><code>class Parser\n # cards is an array of hashes\n attr_reader :cards\n\n # Constructor - takes a file path as its argument\n def initialize(path)\n # Read the lines, and parse them individually\n # in a private method. The method may return nils,\n # so call `compact` to get rid of those\n @cards = File.foreach(path).map(&method(:parse_line)).compact\n end\n\n # This returns the names of attributes of a card, i.e.\n # the individual pieces of information for a person.\n # This could be a constant, but I personally prefer\n # a method for this so it can be overridden in sub-\n # classes if necessary\n def attributes\n @attributes ||= %w(name surname date_of_birth salary phone position email).freeze\n end\n\n private\n\n # parse a line from the input file and return a hash\n # or nil, if the line's empty\n def parse_line(line)\n # grab the first n pieces of data in the line\n data = line.strip.split(/;/)[0, attributes.count]\n if data.any?\n Hash[ attributes.zip(data) ] # create a hash\n end\n end\nend\n</code></pre>\n\n<p>That's all you need to read the input file, and convert it into hashes that make the task of outputting the data easier:</p>\n\n<pre><code>Parser.new(\"base.txt\").cards #=> [{ \"name\": \"foo\", \"surname\": \"bar\", \"date_of_birth\": \"1/1/1970\", \"salary\": \"123456\", \"phone\": \"1234567\", \"position\": \"whatever\", \"email\": \"mail@example.com\" }, ... etc ]\n</code></pre>\n\n<p>For writing, I'd recommend making 2 classes: <code>HtmlWriter</code> and <code>RtfWriter</code>. Both operate the same way: They take a parser object and use its <code>cards</code> array to output the information.</p>\n\n<p>Here's a (somewhat overkill) example of a HTML writer class. I'm \"cheating\" and using CSS to do the alternating row colors.</p>\n\n<pre><code>class HtmlWriter\n attr_reader :parser\n\n def initialize(parser)\n @parser = parser\n end\n\n def write(file_path)\n File.write(file_path, content)\n end\n\n def content\n <<-HTML\n<!DOCTYPE html>\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n <style>\n tbody tr { background-color: maroon; color: olive }\n tbody tr:nth-child(odd) { background-color: olive; color: maroon }\n </style>\n</head>\n<body>\n #{table}\n</body>\n</html>\n HTML\n end\n\n protected\n\n def table\n html_tag('table', \"#{table_header}\\n#{table_body}\")\n end\n\n def table_header\n html_tag('thead') do\n html_tag('tr') do\n parser.attributes.map { |value| html_tag('th', value) }\n end\n end\n end\n\n def table_body\n html_tag('tbody') do\n parser.cards.map do |card|\n html_tag('tr') do\n card.map { |_, value| html_tag('td', value) }\n end\n end\n end\n end\n\n def html_tag(name, content = nil)\n content = yield if block_given?\n content = content.join if content.respond_to?(:join)\n \"<#{name}>#{content}</#{name}>\"\n end\nend\n</code></pre>\n\n<p>Or for RTF (I'm sure this could be be improved - I don't know the RTF gem well)</p>\n\n<pre><code>class RtfWriter\n include RTF\n\n attr_reader :parser\n\n def initialize(parser)\n @parser = parser\n end\n\n def write(path)\n File.write(path, document.to_rtf)\n end\n\n def document\n @document ||= begin\n doc = Document.new(Font.new(Font::ROMAN, 'Times New Roman'))\n table = doc.table(parser.cards.count + 1, parser.attributes.count)\n add_header_row(table)\n add_body_rows(table)\n parser.cards.count.times do |row|\n table.row_shading_color(row + 1, color_for_row(row))\n end\n doc\n end\n end\n\n private\n\n def add_header_row(table)\n parser.attributes.each_with_index.map do |name, column|\n table[0][column].bold { |node| node << name }\n end\n end\n\n def add_body_rows(table)\n parser.cards.each_with_index.map do |card, row|\n card.values.each_with_index do |value, column|\n table[row + 1][column] << value\n end\n end\n end\n\n def color_for_row(row)\n colors[row % colors.count]\n end\n\n def colors\n @colors ||= [\n Colour.new(125, 0, 0),\n Colour.new(125, 125, 0)\n ]\n end\nend\n</code></pre>\n\n<p>And, just for fun, here's a JSON formatter...</p>\n\n<pre><code>require 'json/ext' # or just 'json'\n\nFile.write(\"cards.json\", Parser.new('base.txt').cards.to_json())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:17:55.573",
"Id": "48372",
"ParentId": "48366",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T20:00:43.437",
"Id": "48366",
"Score": "2",
"Tags": [
"ruby",
"classes"
],
"Title": "Creating an .rtf file with cards from a list of people"
} | 48366 |
<p>A recruiter gave me a homework problem as a part of the recruiting process and after receiving my submission he told me that he decided not to proceed with me. When I asked for the reason, he told me that I should ask for advice online from more experienced Python programmers. He said that "the issues were algorithm design and code structure". The (short) description of the problem and the code are in <a href="https://gist.github.com/armant/11357872">this gist</a>. Please let me know what you think he was pointing at.</p>
<p>Problem description:</p>
<blockquote>
<p>Given a page of content with alphanumeric words, and a search phrase
of N words, write an algorithm that will return the shortest snippet
of content that contains all N words in any order. Example: The
George Washington Bridge in New York City is one of the oldest bridges
ever constructed. It is now being remodeled because the bridge is a
landmark. City officials say that the landmark bridge effort will
create a lot of new jobs in the city.</p>
<p>Search Terms:</p>
<pre class="lang-none prettyprint-override"><code>Landmark City Bridge
</code></pre>
<p>Result:</p>
<pre class="lang-none prettyprint-override"><code>bridge is a landmark. City
</code></pre>
</blockquote>
<p>Solution:</p>
<pre><code>import sys
import re
def FindShortest(CurrentTerm):
for MatchIndex in MatchIndexes[CurrentTerm]:
#check
#print MatchIndexes[CurrentTerm].index(MatchIndex)
global LeftBorder
global RightBorder
global FinalLeftBorder
global FinalRightBorder
if CurrentTerm == 0:
LeftBorder = MatchIndex
RightBorder = MatchIndex + len(SearchTerms[0]) - 1
#check
#print ("With MatchIndex ", MatchIndex, " assigned LeftBorder to ",
# LeftBorder, " and RightBorder to ", RightBorder)
if len(MatchIndexes) > 1:
FindShortest(1)
else:
if FinalRightBorder - FinalLeftBorder > RightBorder - LeftBorder:
FinalLeftBorder = LeftBorder
FinalRightBorder = RightBorder
#check
#print ("Changed values with MatchIndex ", MatchIndex,
#" and CurrentTerm ", CurrentTerm, " New FinalLeftBorder is ",
#FinalLeftBorder, " and new FinalRightBorder is ", FinalRightBorder)
else:
OptimalRightBorderFound = False
OldLeftBorder = LeftBorder
OldRightBorder = RightBorder
if MatchIndex < LeftBorder:
LeftBorder = MatchIndex
#check
#print "With MatchIndex ", MatchIndex, " assigned LeftBorder to ", LeftBorder
elif MatchIndex + len(SearchTerms[CurrentTerm]) - 1 > RightBorder:
RightBorder = MatchIndex + len(SearchTerms[CurrentTerm]) - 1
OptimalRightBorderFound = True
#check
#print "With MatchIndex ", MatchIndex, " assigned RightBorder to ", RightBorder
else:
OptimalRightBorderFound = True
#print "OptimalRightBorderFound is True with MatchIndex ", MatchIndex
if CurrentTerm < len(SearchTerms) - 1:
FindShortest(CurrentTerm + 1)
else:
if FinalRightBorder - FinalLeftBorder > RightBorder - LeftBorder:
FinalLeftBorder = LeftBorder
FinalRightBorder = RightBorder
#check
#print ("Changed values with MatchIndex ", MatchIndex,
# " and CurrentTerm ", CurrentTerm, " New FinalLeftBorder is ",
# FinalLeftBorder, " and new FinalRightBorder is ", FinalRightBorder)
LeftBorder = OldLeftBorder
RightBorder = OldRightBorder
#check
#print "LeftBorder became ", LeftBorder, " again, and RightBorder became ", RightBorder, " again"
if OptimalRightBorderFound:
break
f = open('input.txt', 'r')
#put all text in the file in the string Text
Text = ""
for line in f:
Text += line
#check
#print Text
#remove the last line, containing the search terms, from Text
Text = Text[:len(Text) - len(line)]
#check
#print Text
#put search terms, which are on the last line of the text, in the SearchTerms list
SearchTerms = re.findall(r'\w+', line)
#check
#print SearchTerms
#record the indexes of all word matches
MatchIndexes = []
for Term in SearchTerms:
#check
#print Term
TempList = []
if Term.lower() == Text[:len(Term)].lower():
TempList.append(0)
RegexVariable = r"\W" + Term + r"\W"
p = re.compile(RegexVariable, re.IGNORECASE)
#print p
for Matches in p.finditer(Text):
#check
#print Matches
#print Matches.start(), Matches.group()
TempList.append(Matches.start() + 1)
#check
#print TempList
if TempList == []:
print "At least one of the search terms is not present in the text."
sys.exit()
MatchIndexes.append(TempList)
#check
#print MatchIndexes
#find the shortest snippet
FinalLeftBorder = 0
FinalRightBorder = len(Text) - 1
LeftBorder = 0
RightBorder = 0
FindShortest(0)
#check
#print FinalLeftBorder, " ", FinalRightBorder
#print the result
for i in range(FinalLeftBorder, FinalRightBorder + 1):
sys.stdout.write(Text[i])
f.close()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T00:27:10.697",
"Id": "84903",
"Score": "2",
"body": "There are some good algorithms discussed in [this question](http://stackoverflow.com/questions/2954626/algorithm-to-find-the-smallest-snippet-from-searching-a-document)"
}
] | [
{
"body": "<p>Some quick (as in \"I'm procrastinating\") tips:</p>\n\n<ul>\n<li><p>Use standard naming. ReplaceTheseFormsOfVariableNames with these_forms_of_variable_names, at least in accordance to <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a>.</p></li>\n<li><p>State in global variables is pretty much always bad. Encapsulate that behaviour in returns.</p></li>\n<li><p>Files need safety. I suggest you look up the <code>with</code> statement. You'd use</p>\n\n<pre><code>with open(...) as myfile:\n do_stuff_with(myfile)\n</code></pre></li>\n<li><p><strong>Never</strong> use addition on strings or list-like structures in a loop unless they've been explicitly designed for it, or you know enough to <em>know</em> it doesn't apply. <code>f.read()</code> would have worked better.</p></li>\n<li><p><code>x[:len(x) - y]</code> is better just written <code>x[:-y]</code>.</p></li>\n<li><p>Encapsulate more things in functions and classes.</p></li>\n<li><p><code>sys.stdout.write</code> is a bit of an odd thing to use; <code>print</code> will do fine and a function that just returns a list (with no printing) would have worked yet nicer.</p></li>\n<li><p>All those debug statements don't make reading the code any easier.</p></li>\n</ul>\n\n<p>I think something you're missing is just experience with real code. Reading stuff like <a href=\"https://github.com/grantjenks/sorted_containers/tree/master/sortedcontainers\">arbitrary open source Python code</a> or <a href=\"https://github.com/PythonCharmers/python-future/blob/master/future/utils/__init__.py\">maybe this</a> or how about <a href=\"https://github.com/python/cpython/tree/237284d0a73e472f836adc72f090432ae7c5dfad/Lib/json\">some standard-library stuff</a>¹ will help you get to grips with how code is meant to <em>feel</em>. Because the overriding sense I got from reading your code is that it wasn't Python, largely because it's too different. I never got to the point where I cared about the algorithm. If you were working in a team you'd be creating a lot of difficulty just by being nonstandard, and I assume that harmed your chances a lot.</p>\n\n<p>¹ Chosen arbitrarily; I just remembered these particular things I'd read recently being bytesize enough to recommend.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T00:50:06.990",
"Id": "48378",
"ParentId": "48374",
"Score": "7"
}
},
{
"body": "<p>I would agree with the recruiter: this code does not make a good first impression.</p>\n\n<h2>Red flags</h2>\n\n<p>Any one of these issues could be grounds for disqualification within the first few seconds of reading.</p>\n\n<ul>\n<li><p><strong>Too much code.</strong> If someone gives you a programming puzzle, chances are that they expect a short, elegant solution. Nobody wants to read a long, rambling answer, so they would not ask a question that requires a lot of code to solve.</p>\n\n<p>The bulk of your code is in one long function. I couldn't point to a chunk of code within that function and say what that chunk's purpose is. The comments that you left are worse-than-useless junk: they are all disabled print statements for debugging.</p>\n\n<p>You have 65 lines, excluding comments and blank lines. My proposed solution below has about half that.</p></li>\n<li><p><strong>Global variables.</strong> It is widely agreed that global variables are to be used only as a last resort. Here, there's absolutely no justification for them. Not only do they make it hard to reason about the code by making side-effects non-localized, they indicate that your function's interface is sloppy: it's unclear what the function's inputs and outputs are.</p></li>\n<li><p><strong>Too many variables.</strong> Within <code>FindShortest()</code>, we have:</p>\n\n<ol>\n<li><code>CurrentTerm</code></li>\n<li><code>MatchIndexes</code> (global?)</li>\n<li><code>LeftBorder</code> (global)</li>\n<li><code>RightBorder</code> (global)</li>\n<li><code>FinalLeftBorder</code> (global)</li>\n<li><code>FinalRightBorder</code> (global)</li>\n<li><code>SearchTerms</code></li>\n<li><code>OptimalRightBorderFound</code></li>\n<li><code>OldLeftBorder</code></li>\n<li><code>OldRightBorder</code></li>\n</ol>\n\n<p>The human mind can keep track of about seven things at once. Ideally, you should only have about three variables per function.</p></li>\n<li><p><strong>Non-idiomatic Python.</strong> You used regular expressions, which is good. Other than that, your answer is written not much differently from a C solution. You need to demonstrate your ability to think at a more abstract level.</p></li>\n<li><p><strong>Non-standard naming.</strong> You should call your function <code>find_shortest</code>, and its parameter <code>current_term</code>, and similarly for all variables. <code>UpperCase</code> identifiers look like class names. See <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a>, which is the standard style guide for Python.</p>\n\n<p>The naming of your functions is particularly important, since its effects extend beyond your own code. You've just indicated that you will burden your future colleagues with non-standard naming.</p></li>\n</ul>\n\n<h2>Yellow flags</h2>\n\n<p>These are also serious issues. They are just not as obvious as the red flags at first glance.</p>\n\n<ul>\n<li><p><strong>Lots of free-floating preparatory code.</strong> There's a lot of code between opening the file and calling <code>FindShortest()</code>. Why does it do, and why is it not packaged in functions too?</p></li>\n<li><p><strong>Careless concatenation.</strong> <code>RegexVariable = r\"\\W\" + Term + r\"\\W\"</code> trusts that <code>Term</code> contains no characters that have special meaning within regular expressions. From that one line of careless concatenation, I would infer that you would probably write code that is vulnerable to SQL injection, cross-site scripting, arbitrary command execution, header-splitting attacks, etc.</p></li>\n<li><p><strong>Irresponsible recursion.</strong> When a function calls itself, that is recursion. However, recursion should be used responsibly: there should be invariants, well-defined function inputs and outputs, a base case, and a recursive case. But you don't have any of those elements, so effectively you have a weird <code>goto</code>.</p></li>\n</ul>\n\n<h2>Proposed solution</h2>\n\n<p>For comparison, here's what I came up with. It's optimized more for simplicity than performance — it's usually beneficial to convey that goal to your interviewer.</p>\n\n<p>Note that it accomplishes the task by chaining three functions, each with well defined inputs and outputs.</p>\n\n<pre><code>from collections import namedtuple\nfrom itertools import product\nimport re\n\nWordPos = namedtuple('WordPos', ['start', 'end'])\n\ndef find_all_words(text, words):\n \"\"\"\n For each word in the list, find all positions in which they\n appear in the text. Results are returned as a dict, with\n the words as keys. Each value is a list, with a WordPos\n object to mark each occurrence of the word in the text.\n \"\"\"\n def positions(text, word):\n word_re = re.compile(r'\\b' + re.escape(word) + r'\\b', re.IGNORECASE)\n return [WordPos(match.start(), match.end()) for match in\n word_re.finditer(text)]\n\n return { word: positions(text, word) for word in words }\n\ndef cluster(found_words):\n \"\"\"\n Given a dict resulting from find_all_words(), pick the\n occurrence of each word that minimizes the length of the\n substring of text that contains them all.\n\n The result is a WordPos object that represents the span of\n the cluster. If any of the words does not appear in the\n text, then this function returns None.\n \"\"\"\n def bounds(combo):\n start = min(word.start for word in combo)\n end = max(word.end for word in combo)\n return WordPos(start, end)\n\n positions = found_words.values()\n combo_bounds = [bounds(combo) for combo in product(*positions)]\n if combo_bounds:\n # Find the shortest combo\n return min(combo_bounds, key=lambda span: span.end - span.start)\n else:\n # At least one search term was not found\n return None\n\ndef excerpt(text, combo_bounds):\n \"\"\"\n Take the substring of text corresponding to the given span.\n \"\"\"\n if not combo_bounds:\n return None\n\n return text[combo_bounds.start : combo_bounds.end]\n\ntest_text = \"\"\"The George Washington Bridge in New York City…\"\"\"\n\ntest_terms = 'Landmark City Bridge'.split()\n\nprint(excerpt(test_text, cluster(find_all_words(test_text, test_terms))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:33:44.940",
"Id": "84912",
"Score": "1",
"body": "Good review! `{word: positions(text, word) for word in words}` would be a dictionary-comprehension alternative to `dict(...)`. The logic for finding `start` and `end`, though simple, is duplicated and could be extracted: `start, end = find_bounds(combo)` instead of having the nested `span` function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:08:25.297",
"Id": "84914",
"Score": "1",
"body": "Thank you so much! This has been more than educational. As @Veedrac rightfully pointed about I am indeed lacking experience with real code (a student with only competitive programming experience under my belt). As you pointed out, my code looks like C code because I only started coding in Python recently. Besides what is already recommended by Veedrac, are there any resources you would recommend me to study to develop more abstract, Pythonic thinking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:54:36.483",
"Id": "84920",
"Score": "2",
"body": "Try following the online book [_Composing Programs_](http://composingprograms.com). If you're used to languages like C, then Section 1.6 (Higher-Order Functions) will blow your mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:18:08.623",
"Id": "85102",
"Score": "3",
"body": "To expand on 200_success's point about commented out print statements, I would suggest replacing them with `assert` statements, unit tests, trips through pdb or another debugger, or removing them all together. Commented out code almost never belongs in a finished product."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:54:50.007",
"Id": "85275",
"Score": "0",
"body": "Thank you! So how do I manipulate global variables within recursion without stating them as global in the recursion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:31:03.327",
"Id": "85277",
"Score": "0",
"body": "Just say NO to global variables. My solution has none."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:09:40.240",
"Id": "48381",
"ParentId": "48374",
"Score": "16"
}
}
] | {
"AcceptedAnswerId": "48381",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:41:55.183",
"Id": "48374",
"Score": "17",
"Tags": [
"python",
"strings",
"interview-questions",
"python-2.x",
"clustering"
],
"Title": "Given a page of content, determine shortest snippet containing all search phrases (no order required)"
} | 48374 |
<p>Given a set T of characters and a string S, find the minimum window in S which will contain all the characters in T in complexity O(n).</p>
<p>eg,
S = “ADOBECODEBANC”
T = “ABC”</p>
<p>Minimum window size is 4 - “BANC”.</p>
<pre><code>public final class MinSubstringWindow {
private MinSubstringWindow() {}
private static void addCharCount(Map<Character, Integer> map, Character ch) {
if (!map.containsKey(ch)) {
map.put(ch, 1);
} else {
int val = map.get(ch);
map.put(ch, val + 1);
}
}
private static Map<Character, Integer> toFindMap(String subset) {
Map<Character, Integer> toFind = new HashMap<Character, Integer>();
for (char ch : subset.toCharArray()) {
addCharCount(toFind, ch);
}
return toFind;
}
public static int mindWindowSize(String str, String subset) {
final Map<Character, Integer> toFind = toFindMap(subset);
final Map<Character, Integer> hasFound = new HashMap<Character, Integer>();
char[] ch = str.toCharArray();
int matchCtr = 0;
boolean matchFound = false;
char currLeftMostChar = 0;
int j = 0; // the trailing position of the sliding window
int i = 0; // the leading position of the sliding window.
int min = Integer.MAX_VALUE;
for (i = 0; i < ch.length; i++) {
if (!toFind.containsKey(ch[i])) continue;
if (!matchFound) {
currLeftMostChar = ch[i];
matchFound = true;
j = i;
}
addCharCount(hasFound, ch[i]);
matchCtr++;
// check if match has been completed.
if (matchCtr >= subset.length()) {
if ((i - j + 1) < min) {
min = i - j + 1;
}
}
// does the first element exceed value ?
if (hasFound.get(currLeftMostChar) > toFind.get(currLeftMostChar)) {
// advance the left pointer, such the window (i-j) is as small as possible.
while (!toFind.containsKey(ch[j]) || hasFound.get(ch[j]) > toFind.get(ch[j])) {
if (hasFound.containsKey(ch[j])) {
int val = hasFound.get(ch[j]);
hasFound.put(ch[j], val - 1);
}
j++;
}
currLeftMostChar = ch[j];
}
}
if (matchCtr < subset.length()) {
throw new IllegalArgumentException("The subset is not found in the input string.");
}
// note: here we dont do (i-j+1) since i has been incremented additionally in a for loop.
return min > (i - j) ? i - j : min;
}
}
</code></pre>
<p>And test section</p>
<pre><code>public class MinSubstringWindowTest {
@Test
public void test1() {
assertEquals(3, MinSubstringWindow.mindWindowSize("apbqcbsa", "ab"));
assertEquals(4, MinSubstringWindow.mindWindowSize("apbqcbsa", "abc"));
assertEquals(3, MinSubstringWindow.mindWindowSize("apbqcbsa", "pq"));
}
@Test
public void test2() {
assertEquals(2, MinSubstringWindow.mindWindowSize("ameya", "ay"));
assertEquals(3, MinSubstringWindow.mindWindowSize("ameya", "my"));
assertEquals(3, MinSubstringWindow.mindWindowSize("ameya", "ae"));
}
}
</code></pre>
| [] | [
{
"body": "<p>The first big issue that crosses my mind: Naming. In particular, commenting variables is <em>always</em> a sign that you did a poor job on giving them good names:</p>\n\n<pre><code>int j = 0; // the trailing position of the sliding window\nint i = 0; // the leading position of the sliding window.\n</code></pre>\n\n<p>There is no reason to name loop variables <code>i</code> and <code>j</code> <em>just because</em>. If they have a meaning beyond just being there for the sake of looping, give them a name representing this. It makes the following code easier to read because the reader won't have to look up and remember their meaning.</p>\n\n<p>After giving them proper names you can also get rid of declaring them outside the loop. Declaring them inside the loop makes the coder smaller, which is good not for the sake of having less lines (LoC is a terrible measurement of quality), but it reduces the overhead when trying to understand what is going on.</p>\n\n<p>This applies especially to <code>i</code> and <code>j</code>, but also to many other names in your program:</p>\n\n<ul>\n<li>What is <code>ch</code> supposed to tell me? I don't need information about the type of a variable – the compiler and IDE do a lot of the work for me here; what I, as a reader, care about is the <em>semantics</em> of variables.</li>\n<li>Is there really any need for shortening <code>matchCounter</code> to <code>matchCtr</code>? Your IDE will help you avoid having to type too much. Of course experienced programmers have \"ctr\" already in their vocabulary and automatically translate it to \"counter\", but there is not really any reason these days to add this extra translation step.</li>\n<li>I'll just leave out the rest, typically the same arguments apply as the ones I stated above.</li>\n</ul>\n\n<p>Let's move on. What was the reasoning for making everything static? You forced yourself to do this:</p>\n\n<pre><code>addCharCount(hasFound, ch[i]);\n</code></pre>\n\n<p>This is called a <em>side-effect</em> method and unless there is no way around it, it should be avoided. It is counter-intuitive that this method actually <em>mutates</em> the passed map (and from experience: this can easily cause very messy code and ugly bugs).</p>\n\n<p>Instead, just make your class a normal (non-static) class with state. It allows you to get rid of some method parameters as they just become class members. </p>\n\n<p>What you <em>can</em> do is make the constructor private (as it is now) and add a static method that creates a new instance and calls the proper method on it. This ensures that the caller doesn't call the method twice on the same instance and you won't have to deal with resetting members.</p>\n\n<p>Refactoring this to a proper class will also allow you to avoid this as well as the block following it:</p>\n\n<pre><code>// check if match has been completed.\nif (matchCtr >= subset.length()) {\n if ((i - j + 1) < min) {\n min = i - j + 1;\n }\n}\n</code></pre>\n\n<p>Again, comments are good for mostly one thing: they signal code smell. If you have an entire block that needs a comment to be explained, it is time to think about whether the better way to go here is to extract a method with a good name that replaces the comment, because – to me – the single most profound fact about comments is that they rot faster than anything else and even the best comments will soon start lying. In other words: comments tend to become not just useless, but dangerous.</p>\n\n<p>And your method is already big enough; too big, I would say. It does too many things on the same level of abstraction, so I would try splitting it up further.</p>\n\n<p>Now to this:</p>\n\n<pre><code>if (matchCtr < subset.length()) {\n throw new IllegalArgumentException(\"The subset is not found in the input string.\");\n}\n</code></pre>\n\n<p>Is it really an illegal argument? You can argue that it is, but I tend to think that it's not. Is an exception even the right way to go here? Is this exceptional behavior you want the caller to deal with because you can't decide what to do here?</p>\n\n<p>Finally, the tests. Again, the thing that really jumps into my eyes are names. What is <code>test</code> and <code>test2</code> supposed to tell me about the test case here? Choose proper names describing the test cases, e.g</p>\n\n<ul>\n<li><code>testShortestWindowAtTheEndOfStringIsFound</code></li>\n<li><code>testShortedWindowWithinStringIsFound</code></li>\n<li>…</li>\n</ul>\n\n<p>Also, at first glance I fail to see why you chose to split your test cases into two tests as you did. I would say that every single assertion here deserves a test on its own (with proper name). This way, if a test fails, the test name alone is enough to tell you what isn't working, you won't have to first find out which assertion went wrong and you can be sure that the other cases are still working.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:08:52.920",
"Id": "48412",
"ParentId": "48375",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T23:54:08.983",
"Id": "48375",
"Score": "6",
"Tags": [
"java",
"algorithm"
],
"Title": "Find minimum window size which includes the subset of characters"
} | 48375 |
<p>I'm writing some code which needs to take a generic <code>java.util.List</code> from another source and adapt to the available functions; eg. does it support <code>add()</code>, <code>set()</code>, etc.</p>
<p>I'm currently just calling the functions on the list and creating a set of available operations, but I'm wondering if there's a better way than <code>try</code>-<code>catch</code>.</p>
<p>Current code: </p>
<pre><code>import java.util.*;
import javax.swing.JPanel;
public class JListPanel<T> extends JPanel {
private static final long serialVersionUID = 832057842976869638L;
private static enum JLPFlag {
ADD, REMOVE, SET;
}
private List<T> list;
private Set<JLPFlag> flags = EnumSet.allOf(JLPFlag.class);
public JListPanel(List<T> backinglist) {
list = backinglist;
setFlags();
}
private void setFlags() {
// store the last state
List<T> prev = Collections.unmodifiableList(list);
boolean empty = list.isEmpty();
try {
if (!empty) {
list.add(list.get(0));
} else {
// hope that list allows null
list.add(null);
}
} catch (Exception e) {
flags.remove(JLPFlag.ADD);
}
try {
list.set(0, list.get(0));
} catch (Exception e) {
flags.remove(JLPFlag.SET);
}
try {
list.remove(0);
} catch (Exception e) {
flags.remove(JLPFlag.REMOVE);
}
if (flags.contains(JLPFlag.REMOVE))
list.removeAll(list);
if (flags.contains(JLPFlag.ADD))
list.addAll(prev);
}
}
</code></pre>
<p>Edit: This is supposed to be a JPanel that contains a list that can be modified by a program and this should reflect those changes on the list display. It's not complete yet, but the ultimate goal is to have a list that can be modified by the user or programmer. It will have some buttons that will be disabled if the list doesn't support the operations, so it might not have <code>add</code> or <code>remove</code> but it might have <code>set</code>.</p>
<p>I've compiled most of the suggestions into this new function: <a href="http://pastebin.com/JPWXdFfi" rel="nofollow">http://pastebin.com/JPWXdFfi</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:58:58.020",
"Id": "84913",
"Score": "2",
"body": "Sorry, I'm having trouble understanding what you are trying to accomplish. Could you provide a few example `List`s and what the expected behaviour should be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T07:12:39.697",
"Id": "84923",
"Score": "0",
"body": "I think this is one of the bad design decisions in the java library. As far as I know there is no other way to check, an 'optional' operation is supported by an actual implementation of the List interface than just calling it and checking for the Exception. :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:08:18.893",
"Id": "84952",
"Score": "0",
"body": "@200 The Java lists are all under the Collections API, and the expected behavior is that any lists which do not support certain functions have the functions disabled in a GUI The flags control that.."
}
] | [
{
"body": "<p><b>After edit original question: </b><br/></p>\n\n<p>I understand what you are trying to do, and very nice if you can do that.\nThat's why I'm trying to think together with you for an solution.<br/>\nThe only thing is that I seems not capable enough to reach to an solution.<br/>\nThat's why I'm still posting mine thoughts.</p>\n\n<p>We have some problems(with solutions) that prevents us to check it at creation of the class : <br/></p>\n\n<ol>\n<li>We init with a list, and after constructing the \"wrapper\" it must be the same list.</li>\n<li>The original list may support one or more methods, add may be supported and an addAll or remove maybe not, </li>\n<li><a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove%28java.lang.Object%29\" rel=\"nofollow\">Adding/removing a null can be supported or not</a>. So if we want to test add we need a instance of T.</li>\n<li>We can make the wrapper abstract and create an <code>abstract T getInstance ();</code> where we give a real instance of <code>T</code> or we disallow a wrapper with an empty <code>List</code>.<br/>This solves issue 3 but still not issue 2 when only add is supported we can't remove our T from the list. (reversed is not a problem cause it shall return <code>false</code> if <code>T</code> isn't in the list)</li>\n<li>Maybe we could use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29\" rel=\"nofollow\">Object</a> <code>clone()</code> what gives a shallow copy but that is in this case no problem as the copy is used to test the methods.<br/>Still a problem if it throws the <code>CloneNotSupportedException</code>.</li>\n<li>We can at construction check if the <code>CloneNotSupportedException</code> is thrown and do the test at runtime => buttons are disabled when user press the button once or buttons are always disabled when cloning isn't possible.</li>\n</ol>\n\n<h2>Other bad solution :</h2>\n\n<p>Create an enum with all known implementations of List.<br/>\nCheck for instanceOf of the class and get the flags from the enum.\n<br/><br/><br/>\n<b>Why possible bad :</b> </p>\n\n<p><code>ArrayList</code> implements everything.\nWhen I create a subclass of <code>ArrayList</code> and throw at the <code>add</code> an <code>UnsupportedOperationException</code> your check for <code>ArrayList</code> is good and set the flags for an <code>ArrayList</code>.<br/>\nStill the <code>add</code> operation shall not work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:45:11.123",
"Id": "84919",
"Score": "0",
"body": "Wells flags are removed in the `catch` clause for unsupported operations, maybe `initFlags()` sound a little better then? The question is still unclear what is being practically achieved here though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T07:00:29.250",
"Id": "84922",
"Score": "1",
"body": "I think I know it, he add all the flags in the `Set<JPLFlag> flags` and remove what isn't possible so at the hand of available flags he knows if the list can do an operation or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:50:55.633",
"Id": "84946",
"Score": "0",
"body": "The method name was wrong as it originally did set flags. I will change it. However, I'd like the list to be the same one as the provided list so that I can change it and the program will have those changes reflected. (This is for a library I'm writing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:54:44.780",
"Id": "84948",
"Score": "0",
"body": "So you want a list that is always editable or a wrapper that will not throw an exception when you do an add operation that is not supported?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:02:34.460",
"Id": "84950",
"Score": "0",
"body": "Hmm, I think I'll add some more text to the OP to explain this better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:28:49.347",
"Id": "84961",
"Score": "0",
"body": "Most implementations also have Serializable, could try that."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T06:05:20.053",
"Id": "48384",
"ParentId": "48382",
"Score": "4"
}
},
{
"body": "<p>Instead of attempting to detect this beforehand, consider providing feedback when adding or removing an element fails due to <code>UnsupportedOperationException</code>, and then disable related actions in your user interface. Or use any domain or prior knowledge available to predict whether these operations will be available.</p>\n\n<p>But to answer your question:</p>\n\n<p>Unfortunately, no, there is no fail-safe way to find out what operations a collection implementation supports. Checking beforehand and catching <code>UnsupportedOperationException</code> is a possible but unreliable approach, and it comes with concerns and pitfalls.</p>\n\n<p>That said, let's check what the java.util.Collection API documentation says about this (notes are mine):</p>\n\n<blockquote>\n <p>The \"destructive\" methods contained in this interface, that is, the methods that modify the collection on which they operate, are (1) specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException (2) if the invocation would have no effect on the collection. For example, invoking the addAll(Collection) method on an unmodifiable collection may, but is not required to, throw the exception if the collection to be added is empty.</p>\n</blockquote>\n\n<p>The wording is a bit unfortunate, but it boils down to:</p>\n\n<ol>\n<li><p><strong>Unsupported operations should throw <code>UnsupportedOperationException</code>.</strong> Catch <code>UnsupportedOperationException</code> rather than <code>Exception</code>. Implementations can throw exceptions for reasons that may be out of your hands (like concurrent modification).</p></li>\n<li><p><strong>Idempotent operations may not throw.</strong> Implementations may choose not to throw UnsupportedOperationException if they can determine that the invocation is a no-op, such as with <code>list.set(0, list.get(0))</code>, or <code>clear()</code> on an empty list.</p></li>\n</ol>\n\n<p>Another potential issue is that lists that support only add or remove, but not both, will be in a modified state after testing:</p>\n\n<pre><code> List<T> prev = new ArrayList<T>(list); // Collections.unmodifiableList(list) is a view, not a copy!\n // list = [A, B]\n try {\n if (!empty) {\n list.add(list.get(0));\n // [A, B, A]\n } else {\n list.add(null);\n }\n } catch (Exception e) {\n flags.remove(JLPFlag.ADD);\n }\n try {\n list.set(0, list.get(0));\n } catch (Exception e) {\n flags.remove(JLPFlag.SET);\n }\n try {\n list.remove(0);\n // Add supported: [B, A] \n // Add not supported: [B]\n } catch (Exception e) {\n flags.remove(JLPFlag.REMOVE);\n }\n if (flags.contains(JLPFlag.REMOVE))\n list.removeAll(list);\n if (flags.contains(JLPFlag.ADD))\n list.addAll(prev);\n // Remove but not Add: []\n // Add but not Remove: [A, B, A, A, B]\n // Both or neither: [A, B]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:01:28.183",
"Id": "84949",
"Score": "0",
"body": "That last part I did think about, but I wasn't sure how to proceed, so I might have to just store a new list internally and have programs pull the list from it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:52:43.303",
"Id": "48399",
"ParentId": "48382",
"Score": "3"
}
},
{
"body": "<p>The first time I read your code I was like.... <em>\"Wait, what?\"</em></p>\n\n<p>Now I start to understand what you are doing here, but I have some comments:</p>\n\n<p>First of all, to answer your specific question: You don't have another option for this than to use try-catch.</p>\n\n<p>I would not use a private field for the flags, but rather change the method signature to return a <code>Set<JLPFlag></code>, then create this set at the beginning of the method:</p>\n\n<pre><code>Set<JLPFlag> flags = EnumSet.allOf(JLPFlag.class);\n</code></pre>\n\n<hr>\n\n<p>I don't like what you are doing here:</p>\n\n<pre><code>if (!empty) {\n list.add(list.get(0));\n} else {\n // hope that list allows null\n list.add(null);\n}\n</code></pre>\n\n<p>It might be better to provide a <code>T testElement</code> to the method, in case <code>null</code> isn't supported and the list is empty.</p>\n\n<hr>\n\n<p>I have bad experience with making an operation on a list that uses the list, like this:</p>\n\n<pre><code>list.removeAll(list);\n</code></pre>\n\n<p>I would change that to:</p>\n\n<pre><code>list.removeAll(new ArrayList<T>(list));\n</code></pre>\n\n<p>Or... you could just use <code>list.clear();</code></p>\n\n<hr>\n\n<p>Your JLPFlag enum can have a method for doing the test logic: (If you like this or not is up to you)</p>\n\n<pre><code>private static enum JLPFlag {\n ADD, REMOVE, SET;\n public <T> boolean supported(List<T> list) {\n try {\n switch (this) {\n case ADD:\n list.add(something);\n return true;\n case REMOVE:\n list.remove(0);\n return true;\n case SET:\n list.set(0, something);\n return true;\n }\n }\n catch (UnsupportedOperationException e) { return false; }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>To restore the list correctly afterwards, I would do this:</p>\n\n<pre><code>List<T> prev = new ArrayList<T>(list);\n// perform operations...\nlist.clear();\nlist.addAll(prev);\n</code></pre>\n\n<p>However, if either <code>ADD</code> or <code>REMOVE</code> fails, you're screwed and won't be able to restore the list.</p>\n\n<p>Using <code>Collections.unmodifiableList(list)</code> is a bad idea IMO as that <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29\" rel=\"nofollow\">reads through</a> to the <code>list</code> object. So if you clear your list, your unmodifiableList will be empty.</p>\n\n<hr>\n\n<p>In the end, I think JvR's suggestion is best:</p>\n\n<blockquote>\n <p>Instead of attempting to detect this beforehand, consider providing feedback when adding or removing an element fails due to UnsupportedOperationException, and then disable related actions in your user interface. Or use any domain or prior knowledge available to predict whether these operations will be available.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:30:57.097",
"Id": "48403",
"ParentId": "48382",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48399",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:35:07.477",
"Id": "48382",
"Score": "6",
"Tags": [
"java",
"collections"
],
"Title": "Detecting available List operations"
} | 48382 |
<p><a href="http://jsfiddle.net/rdesai/8qmyg/15/">Here is the link to the jsFiddle</a> and below is the code:</p>
<p>JS:</p>
<pre><code>$(function() {
var hours = minutes = seconds = milliseconds = 0;
var prev_hours = prev_minutes = prev_seconds = prev_milliseconds = undefined;
var timeUpdate;
// Start/Pause/Resume button onClick
$("#start_pause_resume").button().click(function(){
// Start button
if($(this).text() == "Start"){ // check button label
$(this).html("<span class='ui-button-text'>Pause</span>");
updateTime(0,0,0,0);
}
// Pause button
else if($(this).text() == "Pause"){
clearInterval(timeUpdate);
$(this).html("<span class='ui-button-text'>Resume</span>");
}
// Resume button
else if($(this).text() == "Resume"){
prev_hours = parseInt($("#hours").html());
prev_minutes = parseInt($("#minutes").html());
prev_seconds = parseInt($("#seconds").html());
prev_milliseconds = parseInt($("#milliseconds").html());
updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds);
$(this).html("<span class='ui-button-text'>Pause</span>");
}
});
// Reset button onClick
$("#reset").button().click(function(){
if(timeUpdate) clearInterval(timeUpdate);
setStopwatch(0,0,0,0);
$("#start_pause_resume").html("<span class='ui-button-text'>Start</span>");
});
// Update time in stopwatch periodically - every 25ms
function updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
var startTime = new Date(); // fetch current time
timeUpdate = setInterval(function () {
var timeElapsed = new Date().getTime() - startTime.getTime(); // calculate the time elapsed in milliseconds
// calculate hours
hours = parseInt(timeElapsed / 1000 / 60 / 60) + prev_hours;
// calculate minutes
minutes = parseInt(timeElapsed / 1000 / 60) + prev_minutes;
if (minutes > 60) minutes %= 60;
// calculate seconds
seconds = parseInt(timeElapsed / 1000) + prev_seconds;
if (seconds > 60) seconds %= 60;
// calculate milliseconds
milliseconds = timeElapsed + prev_milliseconds;
if (milliseconds > 1000) milliseconds %= 1000;
// set the stopwatch
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25); // update time in stopwatch after every 25ms
}
// Set the time in stopwatch
function setStopwatch(hours, minutes, seconds, milliseconds){
$("#hours").html(prependZero(hours, 2));
$("#minutes").html(prependZero(minutes, 2));
$("#seconds").html(prependZero(seconds, 2));
$("#milliseconds").html(prependZero(milliseconds, 3));
}
// Prepend zeros to the digits in stopwatch
function prependZero(time, length) {
time = new String(time); // stringify time
return new Array(Math.max(length - time.length + 1, 0)).join("0") + time;
}
});
</code></pre>
<p>HTML:</p>
<pre><code><div id="time">
<span id="hours">00</span> :
<span id="minutes">00</span> :
<span id="seconds">00</span> ::
<span id="milliseconds">000</span>
</div>
<div id="controls">
<button id="start_pause_resume">Start</button>
<button id="reset">Reset</button>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>body {
font-family:"Arial", Helvetica, sans-serif;
text-align: center;
}
#controls{
font-size: 12px;
}
#time {
font-size: 150%;
}
</code></pre>
| [] | [
{
"body": "<p><a href=\"http://jsfiddle.net/8qmyg/17/\">Chess clock anyone?</a> :D</p>\n\n<p>HTML:</p>\n\n<pre><code><!-- \nNever assume just one. Prepare for more than one always. \nWith that, we use classes\n-->\n\n<div class=\"stopwatch\" data-autostart=\"false\">\n <div class=\"time\">\n <span class=\"hours\"></span> : \n <span class=\"minutes\"></span> : \n <span class=\"seconds\"></span> :: \n <span class=\"milliseconds\"></span>\n </div>\n <div class=\"controls\">\n <!-- Some configurability -->\n <button class=\"toggle\" data-pausetext=\"Pause\" data-resumetext=\"Resume\">Start</button>\n <button class=\"reset\">Reset</button>\n </div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>/*\nAlways prefix your styles with a unique selector your widget has\nto prevent your styles from affecting other elements of the same\nselector pattern. In this case, only those under .stopwatch gets\naffected.\n*/\n.stopwatch .controls {\n font-size: 12px;\n}\n\n/* I'd rather stick to CSS rather than JS for styling */\n\n.stopwatch .controls button{\n padding: 5px 15px;\n background :#EEE;\n border: 3px solid #06C;\n border-radius: 5px\n}\n\n.stopwatch .time {\n font-size: 150%;\n}\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>$(function () {\n\n // Never assume one widget is just used once in the page. You might\n // think of adding a second one. So, we adjust accordingly.\n\n $('.stopwatch').each(function () {\n\n // Cache very important elements, especially the ones used always\n var element = $(this);\n var running = element.data('autostart');\n var hoursElement = element.find('.hours');\n var minutesElement = element.find('.minutes');\n var secondsElement = element.find('.seconds');\n var millisecondsElement = element.find('.milliseconds');\n var toggleElement = element.find('.toggle');\n var resetElement = element.find('.reset');\n var pauseText = toggleElement.data('pausetext');\n var resumeText = toggleElement.data('resumetext');\n var startText = toggleElement.text();\n\n // And it's better to keep the state of time in variables \n // than parsing them from the html.\n var hours, minutes, seconds, milliseconds, timer;\n\n function prependZero(time, length) {\n // Quick way to turn number to string is to prepend it with a string\n // Also, a quick way to turn floats to integers is to complement with 0\n time = '' + (time | 0);\n // And strings have length too. Prepend 0 until right.\n while (time.length < length) time = '0' + time;\n return time;\n }\n\n function setStopwatch(hours, minutes, seconds, milliseconds) {\n // Using text(). html() will construct HTML when it finds one, overhead.\n hoursElement.text(prependZero(hours, 2));\n minutesElement.text(prependZero(minutes, 2));\n secondsElement.text(prependZero(seconds, 2));\n millisecondsElement.text(prependZero(milliseconds, 3));\n }\n\n // Update time in stopwatch periodically - every 25ms\n function runTimer() {\n // Using ES5 Date.now() to get current timestamp \n var startTime = Date.now();\n var prevHours = hours;\n var prevMinutes = minutes;\n var prevSeconds = seconds;\n var prevMilliseconds = milliseconds;\n\n timer = setInterval(function () {\n var timeElapsed = Date.now() - startTime;\n\n hours = (timeElapsed / 3600000) + prevHours;\n minutes = ((timeElapsed / 60000) + prevMinutes) % 60;\n seconds = ((timeElapsed / 1000) + prevSeconds) % 60;\n milliseconds = (timeElapsed + prevMilliseconds) % 1000;\n\n setStopwatch(hours, minutes, seconds, milliseconds);\n }, 25);\n }\n\n // Split out timer functions into functions.\n // Easier to read and write down responsibilities\n function run() {\n running = true;\n runTimer();\n toggleElement.text(pauseText);\n }\n\n function pause() {\n running = false;\n clearTimeout(timer);\n toggleElement.text(resumeText);\n }\n\n function reset() {\n running = false;\n pause();\n hours = minutes = seconds = milliseconds = 0;\n setStopwatch(hours, minutes, seconds, milliseconds);\n toggleElement.text(startText);\n }\n\n // And button handlers merely call out the responsibilities\n toggleElement.on('click', function () {\n (running) ? pause() : run();\n });\n\n resetElement.on('click', function () {\n reset();\n });\n\n // Another advantageous thing about factoring out functions is that\n // They are reusable, callable elsewhere.\n reset();\n if(running) run();\n });\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:58:27.777",
"Id": "85071",
"Score": "0",
"body": "In your HTML, why is `class` being used instead of `id`? What is `data-autostart`, `data-pausetext` and `data-resumetext`?\n\nIn your JS, how is the selection of element better than the way I did it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:46:13.097",
"Id": "85076",
"Score": "0",
"body": "@RahulDesai `id` is used if the element is only one. But if you scale the widget, like say if you need more than one, then the widget will break. Using classes allow you to target more than one, since classes can be used on many elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:48:35.380",
"Id": "85077",
"Score": "0",
"body": "@RahulDesai The `data-*` is one way to configure settings in the widget. As long as you follow the right class names and `data-*` configs, you can write widgets without writing JS. That's how Bootstrap does it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:50:28.677",
"Id": "85078",
"Score": "0",
"body": "@RahulDesai Elements should be cached. Everytime you do `$(selector)`, depending on the selector, jQuery is actually running through each element in the DOM, checking if the element matches. If you do that often, it's slow. You're picking up the same elements, fetch it once and reuse the same reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T05:36:55.777",
"Id": "85081",
"Score": "0",
"body": "I did not understand how is doing `var element = $(this);` and using `element` for the rest of the code different from `$(selector)`. Isnt it the same? What does `this` stand for in this context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T07:43:22.103",
"Id": "85085",
"Score": "0",
"body": "@RahulDesai I did an `each()` since, like I said earlier, I adjusted the code to accommodate more than one stopwatch for scalability purposes. The `this` in the iterator function is the DOM element at each iteration, which is each `div.stopwatch`. In order to use jQuery functions on it, I used `var element = $(this)` to wrap it. That way I can use jQuery functions to manipulate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:22:07.220",
"Id": "85273",
"Score": "0",
"body": "Just so as to keep you in loop, please see my StackOverflow question regarding this code here: http://stackoverflow.com/questions/23380668/weird-bug-in-my-stopwatch#23380909"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:50:34.370",
"Id": "85274",
"Score": "0",
"body": "@RahulDesai Those bugs didn't happen on my code. First thing's first, I modified the calculations. Modulo also works when the value is less then the value that divides it. That's why I removed the `if`s. Next, you don't need to add seconds if the value is greater than the value that divides it. It's covered in the seconds calculation. Same goes for the others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:12:43.773",
"Id": "85276",
"Score": "0",
"body": "I didnt get this part: `you don't need to add seconds if the value is greater than the value that divides it.` Where am I doing that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:32:55.473",
"Id": "85278",
"Score": "0",
"body": "@RahulDesai Well you did in the SO post. `if (seconds > 60) seconds %= 60;` and and the increment after those. I removed those on my version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T05:52:07.310",
"Id": "85391",
"Score": "0",
"body": "I fixed one more bug: when I start second stopwatch after a few seconds on starting the first one, the timing wasnt appropriate on the second. Updated fiddle: http://jsfiddle.net/rdesai/8qmyg/47"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T07:56:55.560",
"Id": "48390",
"ParentId": "48383",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "48390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T04:59:58.350",
"Id": "48383",
"Score": "8",
"Tags": [
"javascript",
"jquery",
"datetime",
"jquery-ui"
],
"Title": "jQuery stopwatch"
} | 48383 |
<p>The class routes URLs based on the <code>domain.com/class/method/param/..</code> format. It also checks the request type (GET or POST) and calls the method name GET or POST from the identified class.</p>
<pre><code>class Router {
private $_routes,
$_path,
$_method,
$_found;
public function __construct(Array $routes, $path, $method) {
krsort($routes);
$this->_routes = $routes;
$this->_path = $path;
$this->_method = strtoupper($method);
}
public function load() {
foreach($this->_routes as $regex => $class) {
$regex = str_replace('/', '\/', $regex);
$regex = '^' . $regex . '\/?$';
if(preg_match('/' . $regex . '/i', $this->_path, $params)) {
$this->_found = true;
$this->_classInstantiate($class, $params);
break;
}
}
if(!$this->_found) {
throw new Exception('URL location not found: ' . $this->_path);
}
}
private function _classInstantiate($class, $params) {
if(class_exists($class)) {
$obj = new $class($params);
if(method_exists($obj, $this->_method)) {
$method = $this->_method;
$obj->$method();
} else {
throw new BadMethodCallException('Method not found: ' . $this->_method);
}
} else {
throw new Exception('Class not found: ' . $class);
}
}
}
</code></pre>
<p>I load it up in my entry file like so:</p>
<pre><code>//url to class router
$routes = (Array) $config->routes;
$path = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
$router = new Router($routes, $path, $method);
$router->load();
</code></pre>
<ol>
<li>Am I utilizing dependency injection correctly?</li>
<li>Are there any parts of my class that I should decouple?</li>
<li>Is there anything I could improve in my code when it comes to OO PHP (and MVC)?</li>
</ol>
| [] | [
{
"body": "<p>Let's look at your questions individually:</p>\n\n<p><strong><em>Am I utilizing dependency injection correctly?</em></strong><br>\nYes <em>and</em> no. You are, essentially, injecting the routes. That's fine. But you extract them from a <code>$config</code> object. If you are working out some MVC (micro-) framework, then chances are that config object is an instance of a specific class.</p>\n\n<p>As your code-base grows, so will the config, and chances are pretty good that the <code>Route</code> class will need more data from the config. Instead of passing an array to the constructor then, I'd simply pass the whole <code>$config</code> object, and type-hint that.<br>\nThat way, when you only have to refactor the <code>Route</code> constructor (as opposed to all code that creates a new <code>Route</code> instance) if you decide to add to the config object, something the <code>Route</code> class needs. For example: a list of approved/registered classes that the <code>load</code> method can instantiate:</p>\n\n<pre><code>private $routes = null;\nprivate $classMap = array();\npublic function __construct(Config $conf)\n{\n $this->routes = (array) $conf->routes;\n foreach ($conf->classMap as $class => $paramData)\n {//paramData could contain which arguments are required\n //which are optional, or default values\n $this->classMap[$class] = array(\n 'required' => isset($paramData['required']) ? $paramData['required'] : array(),\n 'defaults' => isset($paramData['defaults']) ? $paramData['defaults'] : array()\n );\n }\n}\n</code></pre>\n\n<p>The <code>load</code> method... There is a lot to say about this, but as it now stands, I have a couple of suggestions:</p>\n\n<p>Why not group the <code>$routes</code> by method? Suppose you have 100 routes in total, 20 of which are <code>POST</code> routes, what good does looping through all 100 routes do?</p>\n\n<p>You are not properly escaping the path regex. Suppose there is a question mark in the <code>$regex</code> string? By calling <code>str_replace('/', '\\/', $regex);</code> you're also not quite doing what you thing you are doing. You're creating an escape sequence, escaping the forward slash, not the backslash you effectively need!<br>\nYou want to escape the delimiter, so you should escape the backslash: use <code>str_replace('/', '\\\\/', $regex);</code><br>\nHowever all this is pretty useless anyway, simply because there exists a ready-made PHP function that can escape a string that is going to be used in <code>preg_match</code> a lot better anyway:</p>\n\n<pre><code> $regex = preg_quote($regex, '/');\n</code></pre>\n\n<p>And instead of calling this function every time the <code>load</code> function is called: use a setter (or 2 setters) for the <code>$this->routes</code> property:</p>\n\n<pre><code>public function setRoutes(array $routes)\n{\n //assume GET && POST keys, too:\n $this->routes = array(\n 'GET' => array(),\n 'POST' => array()\n );\n foreach ($this->routes as $method => $x)\n {//ignore $x\n if (!isset($routes[$method]))\n continue;//ignore. Be weary: case sensitive, a class would be useful here\n foreach ($routes[$method] as $regex => $class)\n {\n //optionally check $class is allowed by $this->classMap!\n $this->routes[$method][preg_quote($regex, '/')] = $class;\n }\n }\n}\n</code></pre>\n\n<p>Now this is written off the top of my head, and a bit messy. What follows is messier still, but just so you know: you can write this as a one-liner, if you use <code>/</code> as the regex delimiter:</p>\n\n<pre><code>$this->routes = array(\n 'GET' => array_combine(\n array_map(\n 'preg_quote',\n array_keys($routes['GET'])\n ),\n $routes['GET']\n ),//same for POST\n);\n</code></pre>\n\n<p>If you decide to use a different delimiter:</p>\n\n<pre><code>$this->routes = array(\n 'GET' => array_combine(\n array_map(\n 'preg_quote',\n array_keys($routes['GET']),\n array_fill(0, count($routes['GET']), '~')//~ is now your delimiter\n ),\n $routes['GET']\n ),\n);\n</code></pre>\n\n<p>Now, the <code>$method</code> and <code>$params</code> arguments from the constructor are only really used in the <code>load</code> method. Why pass them to the constructor? Why not pass them to <code>load</code>, and make them optional? If ever you want to write tests for this class, surely it would be easier to be able to pass invalid/impossible requests to this class.<br>\nAnd even when not testing: Sometimes you want your controller to perform the actions defined in 2 distinct controller actions. By changing the route, and call <code>load</code> again, you could do just that.</p>\n\n<p>Making them optional implies that calling <code>load</code> will have <code>load</code> fall back to the <code>$_SERVER</code> super-global. Even so, let me now tell you why you shouldn't refactor this <code>Route</code> class too much, by answering your next question:</p>\n\n<p><strong><em>Any parts of my class that I should decouple?</em></strong><br>\nPerhaps you should first ask yourself what this class is? Its name, to me, suggests it is a router class. What is a router class's job? Surely, it is to parse, validate, generate URLS, and perhaps redirect.<br>\nThe URL it extracts from a request can then be used by a dispatcher or front-controller to create an instance of a specific controller, and invoke methods.</p>\n\n<p>A router can indeed check to see if there are some request parameters, but processing and validating those parameters falls, in turn, under the responsibility of a <code>Request</code> object.<br>\nOn more details on this matter, <a href=\"https://codereview.stackexchange.com/questions/29469/critique-request-php-request-method-class/29485#29485\">you can check this answer of mine</a>, which reviews a <code>Request</code> object.</p>\n\n<p>So: the answer to this question is: <em>yes</em>. Your code is not SOLID, as it violates the single responsibility principle by acting as a dispatcher, router, and in some ways request object factory.<br>\nWell, it doesn't function as a request object <em>just</em> yet, but it passes the request params to the classes it instantiates. Chances are that, in time, you'll be adding some validation methods to this class, or create a new object (<code>Params</code> or something), and have your <code>Route</code> class create those instances as it passes them to the classes <code>load</code> creates...</p>\n\n<p><strong><em>Anything I could improve in my code when it comes to OOP (and MVC)?</em></strong><br>\nAt this point: you're going to have to work on this some more: you show one class that is quite small. There are signs of promise, but I can't honestly assess your OO skills or correctness of your understanding of OO paradigms and MVC pattern.</p>\n\n<p>The only thing I really <em>can</em> and <strong>will</strong> criticize on is your coding style. Now you may think this is a simple matter of personal preference, but really: it's important to follow certain standards! Such standards <em>exist</em>: Python has PEP, PHP has FIG, their site: <a href=\"http://www.php-fig.org/\" rel=\"nofollow noreferrer\">PHP-FIG</a>.<br>\nOne of the things I've noticed is your tendency of prepending every non-public property/method with an underscore. This practice stems from the days where PHP didn't (yet) have access modifiers - back in the days of PHP4.<br>\nRead through the PSR documents, and conform to those standards as much as you can.<br>\nI try to conform to everything in there, except for my Allman brackets. I know, I need to practice what I preach, but a single deviation from the standards is not that bad, IMO, especially if you have a good IDE, simply re-format your code before commiting to GIT, and nobody need ever know :).</p>\n\n<p>On the last, I have one thing that is rather worrying to me: You create an instance of a given class, and pass the request params to either a <code>GET</code> or <code>POST</code> method. That sounds to me like you have 1 class for each possible URL. That is absolutely <em>not</em> the way to go</p>\n\n<p>Before you start, always see what is already out there: Symfony2, Zend, CI, Cake... are all MVC frameworks that have been around for a long time. They are all open-source, and have a routing component. Just check the source code of those projects, and see if you can't get any ideas from that</p>\n\n<p>Remember: A good programmer is a lazy one. Don't invent something that already exists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:03:59.707",
"Id": "85094",
"Score": "0",
"body": "I take my hat off to you for giving me such a great and constructive answer. So, I'm starting from the top and will ask questions accordingly as I get to the bottom. My config is in fact an array that holds all the setting information, I just processed it so that I could call it like an object. I checked CodeIgniter, and they use an array too for that. **Should I leave the dependency injection `(Array $routes)` as is?**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:10:56.723",
"Id": "85096",
"Score": "1",
"body": "@KidDiamond: That really depends on what kind of code you are writing. If your aim is to build your own framework, then I wouldn't leave it as an array, I'd create an object. an array type-hint allows users to pass `range(1,4)` to your constructor, resulting in regex's like `/^0\\/?$/`, which isn't what you want: you expect the array to be an associative array, where the keys are uri's. An array simply allows too much room for error (as in: invalid data being passed and what not)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T09:48:59.947",
"Id": "48468",
"ParentId": "48396",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48468",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T13:15:04.923",
"Id": "48396",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"mvc",
"url-routing"
],
"Title": "Router for MVC framework"
} | 48396 |
<pre><code>from random import random
def to_color(obj=None):
"""Determine a color (string 000000-ffffff) from the hash of any object
If no argument is passed, a random color is returned.
Args:
obj: any hashable object; string, tuple, ...
Returns:
a color string in range '000000' to 'ffffff'
"""
obj = obj if obj else random()
return "{0:06x}".format(abs(hash(obj)))
</code></pre>
<p>My questions: </p>
<ol>
<li>Is the line <code>obj = obj if obj else random()</code> idiomatic?</li>
<li>Is <code>hash(obj)</code> the "proper" way to get a deterministic yet scrambled string for my purpose?</li>
<li>The <code>abs</code> takes care of negative hash values (e.g. from hashing negative integers). Is there a better way which doesn't collide so easily for small (absolute) integer values? (Right now, <code>to_color(500)</code> is equal to <code>to_color(-500)</code>.)</li>
</ol>
| [] | [
{
"body": "<p>From <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>:</p>\n\n<blockquote>\n <p>Comparisons to singletons like None should always be done with is or\n is not, never the equality operators.</p>\n \n <p>Also, <strong>beware of writing if x when you really mean if x is not None</strong> --\n e.g. when testing whether a variable or argument that defaults to None\n was set to some other value. The other value might have a type (such\n as a container) that could be false in a boolean context!</p>\n</blockquote>\n\n<p>What you should do in your case is : <code>obj = obj if obj is not None else random()</code>.</p>\n\n<p>Then, even though I like the ternary operator, I reckon its usage is not required/idiomatic here. The usual way to handle default parameter is more like</p>\n\n<pre><code>if arg is None:\n arg = default()\n</code></pre>\n\n<p>As far as I can tell, using <code>hash</code> like you did is ok. However, I guess you should handle values that could be out of the range you are expecting (I couldn't find easily something telling which range of values can be returned).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:42:18.893",
"Id": "48413",
"ParentId": "48402",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:23:09.090",
"Id": "48402",
"Score": "2",
"Tags": [
"python"
],
"Title": "Color string from object (random if empty, deterministic else)"
} | 48402 |
<p>Answer is the Parent table and AnswerDetail is the child. Below works, but I'm wondering if there is a better way to do this using EF?</p>
<p><strong>My Method Signature is this:</strong></p>
<pre><code> [HttpPost]
public ActionResult Evaluator(EvaluationVM evaluation, string command)
</code></pre>
<p><strong>It is coming from a MVC 4 application.</strong></p>
<pre><code>Answer AnswerRecord;
AnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID)).Where(y => y.LeaderID != null).FirstOrDefault<Answer>();
if (AnswerRecord == null)
{
//Add New Parent Record:
AnswerRecord.CreatedBy = userName;
AnswerRecord.CreateStamp = DateTime.Now;
db.Entry(AnswerRecord).State = EntityState.Added;
AnswerRecord.UpdatedBy = userName;
AnswerRecord.UpdateStamp = DateTime.Now;
}
AnswerRecord.UpdatedBy = userName;
AnswerRecord.UpdateStamp = DateTime.Now;
//I use this block if I know the child record is new:
adItem = db.AnswerDetails.Find(item.LeaderAnswerDetailKey);
if (adItem != null)
{
adItem.Comment = item.LeaderComment;
adItem.AnswerOptionKey = item.LeaderAnswerOptionKey.Value;
adItem.UpdatedBy = userName;
adItem.UpdateStamp = DateTime.Now;
db.Entry(adItem).State = EntityState.Modified;
}
foreach (EvaluationObject item in evaluation.ResultSet)
{
//I use this block if I am updated the child record
adItem = new AnswerDetail();
adItem.QuestionID = item.QuestionID.Value;
adItem.AnswerOptionKey = item.TeacherAnswerOptionKey.Value;
adItem.Comment = item.TeacherComment;
adItem.CreatedBy = userName;
adItem.CreateStamp = DateTime.Now;
adItem.UpdatedBy = userName;
adItem.UpdateStamp = DateTime.Now;
adItem.AnswerKey = AnswerRecord.AnswerKey;
AnswerRecord.AnswerDetails.Add(adItem);
db.Entry(adItem).State = EntityState.Added;
//This is called at the end of my method:
db.SaveChanges();
}//End of ForEach Loop
</code></pre>
<p><strong>EvaluationVM</strong></p>
<pre><code>public class EvaluationVM
{
public bool IsAdmin { get; set; }
public bool IsLeader { get; set; }
public int TeacherStatus { get; set; }
public int LeaderStatus {get;set;}
public bool IsPublicTeacher { get; set; }
public bool IsFinalTeacher { get; set; }
public bool IsPublicLeader { get; set; }
public bool IsFinalLeader { get; set; }
public List<EvaluationObject> ResultSet {get; set;}
public TeacherInfo CurrentTeacher {get; set;}
public LeaderInfo CurrentLeader { get; set; }
public List<EvaluationRating> RatingSet {get;set;}
}
</code></pre>
<p><strong>EvaluationObject:</strong></p>
<pre><code> public class EvaluationObject : IEvaluationObject
{
public int? QuestionID { get; set; }
public string IndicatorID { get; set; }
public string QuestionDescription { get; set; }
public string TeacherID { get; set; }
public int? TeacherStatusKey { get; set; }
public int? TeacherAnswerKey { get; set; }
public int? TeacherAnswerDetailKey { get; set; }
public int? TeacherAnswerOptionKey { get; set; }
public string TeacherComment { get; set; }
public string LeaderID { get; set; }
public int? LeaderStatusKey { get; set; }
public int? LeaderAnswerKey { get; set; }
public int? LeaderAnswerDetailKey { get; set; }
public int? LeaderAnswerOptionKey { get; set; }
public string LeaderComment { get; set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:15:12.443",
"Id": "84967",
"Score": "0",
"body": "Are all code blocks in the same method? If so, it would be nice if you could add the method's signature; if not, splitting the code block into distinct methods would make it easier to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:17:07.167",
"Id": "84968",
"Score": "0",
"body": "@Mat'sMug - The Method is a controller from a MVC application. So it is the form that got submitted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:21:50.950",
"Id": "84969",
"Score": "0",
"body": "Is there more to the method? I commented that, because right now it's not immediately apparent where `userName`, `evaluation` and `item` come from and what type they are - having the method's signature would help connect the dots ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:27:29.907",
"Id": "84970",
"Score": "0",
"body": "@Mat'sMug - I updated the question with more information. Let me know if you need more?"
}
] | [
{
"body": "<h3>Separation of Concerns</h3>\n<p>I like that you're using EF's built-in unit-of-work implementation. However <code>db</code> (your <code>DbContext</code> class) looks like it's declared at instance level in your controller - make sure it's disposed properly at the end of the request (you could inject the context in the controller's constructor and use an IoC container to ensure per-request instantiation & disposal).</p>\n<p>That doesn't mean the controller's <code>[HttpPost]</code> methods should be doing all the work!</p>\n<p>Looking at the method's code, I think you can extract an entire <em>service class</em> that exposes at least 3 methods!</p>\n<ul>\n<li><code>Answer CreateNewAnswer(string userName)</code></li>\n<li><code>AnswerDetail FindByLeaderId(int leaderId)</code></li>\n<li><code>AnswerDetail CreateNewAnswerDetail(int answerId, AnswerDetailVM item)</code></li>\n</ul>\n<p>Extracting these methods into their own class will make it much easier to follow your controller methods' code, by adding a <em>level of abstraction</em> - the controller shouldn't be dealing with minute details, rather should call into more specialized objects that do their specialized stuff. Shortly put, <em>separate the concerns</em> ;)</p>\n<hr />\n<h3>SaveChanges</h3>\n<p>You don't need to call <code>db.SaveChanges()</code> for every entity you create in the loop - EF's <code>DbContext</code> is a <em>unit-of-work</em> that encapsulates a transaction, so calling <code>SaveChanges</code> is like saying <em>"I'm done, now commit all these pending changes!"</em> - call it once (or, as sparingly as possible - e.g. the <em>parent</em> would typically needs to exist in the db before a <em>child</em> can be added), when you're done.</p>\n<hr />\n<h3>Naming & Other Nitpicks</h3>\n<blockquote>\n<pre><code>Answer AnswerRecord;\nAnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID)).Where(y => y.LeaderID != null).FirstOrDefault<Answer>();\n</code></pre>\n</blockquote>\n<p>For readability, I prefer to split these across multiple lines:</p>\n<pre><code>AnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID))\n .Where(y => y.LeaderID != null)\n .FirstOrDefault<Answer>();\n</code></pre>\n<p>This is confusing, because <code>x</code> and <code>y</code> refer to the same object. Also I'd prefer <code>==</code> over <code>.Equals</code> in most cases, so I'd write it like this instead:</p>\n<pre><code>var answer = db.Answers.Where(answer => answer.TeacherID == evaluation.CurrentTeacher.ID\n && answer.LeaderID != null)\n .FirstOrDefault();\n</code></pre>\n<p>The type parameter for <code>FirstOrDefault</code> is inferred from usage, doesn't need to be specified ;)</p>\n<hr />\n<h3>Comments</h3>\n<p>If these comments are real, in-code comments...</p>\n<blockquote>\n<pre><code>//I use this block if I know the child record is new:\n</code></pre>\n</blockquote>\n\n<blockquote>\n<pre><code>//I use this block if I am updated the child record\n</code></pre>\n</blockquote>\n<p>...then they're both lying - the code blocks under each comment seems to be doing what the other comment is saying! Remove these misleading comments, calling <code>_service.CreateNewAnswerDetail</code> should be clear enough that you're creating a new <code>AnswerDetail</code> entry ;)</p>\n<p>As for this one:</p>\n<blockquote>\n<pre><code>//Add New Parent Record:\n</code></pre>\n</blockquote>\n<p>and this one:</p>\n<blockquote>\n<pre><code>//End of ForEach Loop\n</code></pre>\n</blockquote>\n<p>...they both say nothing that the code doesn't say already, remove them as well, thank yourself later ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T17:04:18.280",
"Id": "86032",
"Score": "0",
"body": "With the db.Save() the way it currently is (inside the for loop), I have a similar method that does the same thing except it does deletes (finds a record then deletes it) and the inserts new records. Like I said the db.save() is currently inside the foreach loop like I have above. Would that possibly cause a deadlock on the table? Let me know if you need further info?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T17:06:13.043",
"Id": "86033",
"Score": "1",
"body": "You cannot garantee the order of operations in `db.Save`, so if you need to first delete records, delete them, `Save()`, and then add the new ones. It would probably be best to *update* than *delete+insert* though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T16:56:29.127",
"Id": "48414",
"ParentId": "48406",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48414",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:58:37.973",
"Id": "48406",
"Score": "2",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Parent/child relationships: adding/updating details to an answer"
} | 48406 |
<p>I've written the following query for SQL server:</p>
<pre><code>SELECT YEAR(Meeting_Date) year, MONTH(Meeting_Date) month, COUNT(project) meetings
FROM
meetings
WHERE Meeting_Date BETWEEN
CAST(DATEPART(year,DATEADD(m,-6,GETDATE())) as varchar(4)) + '-' + CAST(DATEPART(month,DATEADD(m,-6,GETDATE())) as varchar(2)) + '-01'
AND
DATEADD(d,-1,CAST(DATEPART(year,GETDATE()) as varchar(4)) + '-' + CAST(DATEPART(month, GETDATE()) as varchar(2)) + '-01')
GROUP BY YEAR(Meeting_Date), MONTH(Meeting_Date)
ORDER BY YEAR(Meeting_Date), MONTH(Meeting_Date)
</code></pre>
<p>This code counts up how many meetings there were for the six months prior to this one. It works perfectly, but I'm sure there's a better way of figuring the months than I have.</p>
| [] | [
{
"body": "<p>This is one of those things.... date manipulation in SQL.</p>\n\n<p>For performance reasons, it is a pain to cast to <code>NVarchar</code>, etc. For readability reasons, everything is a pain.....</p>\n\n<p>What I have found works best for me, is the following function:</p>\n\n<pre><code>DateAdd(d, 1 - DatePart(d, actualdate), actualdate)\n</code></pre>\n\n<p>The above subtracts the number of days needed to bring a date back to the first-of-the-month.</p>\n\n<p>For example today, (the 28th April), would subtract <code>1 - 28</code> (or 27) days from the 28th, to get the 1st.</p>\n\n<p>You can do your current month-manipulation to move months around once you are back on to the first-of-the-month, and then you don't have to worry about the month overflow problems..</p>\n\n<p>For readability reasons, I would recommend you use variables, if you can:</p>\n\n<pre><code>declare @thismonth as Date = Convert(DateAdd(d, 1 - DatePart(d, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP) as Date);\ndeclare @firstmonth as Date = DateAdd(m, -6, @thismonth);\n\nSELECT YEAR(Meeting_Date) year,\n MONTH(Meeting_Date) month,\n COUNT(project) meetings\nFROM\n meetings\nWHERE Meeting_Date BETWEEN @firstmonth AND @thismonth\nGROUP BY YEAR(Meeting_Date), MONTH(Meeting_Date)\nORDER BY YEAR(Meeting_Date), MONTH(Meeting_Date)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:46:02.807",
"Id": "84962",
"Score": "0",
"body": "here I was writing an answer and then I read your code and it does exactly what I was about to write. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:23:33.867",
"Id": "48408",
"ParentId": "48407",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48408",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:05:37.630",
"Id": "48407",
"Score": "7",
"Tags": [
"sql",
"sql-server",
"datetime",
"t-sql"
],
"Title": "Count and group rows for six months prior"
} | 48407 |
<p>This is part of one of my projects called <a href="https://github.com/fge/largetext" rel="nofollow">largetext</a>, which actually stemmed from a question on Stack Overflow. The goal is to provide access to a very large text file as a <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html" rel="nofollow"><code>CharSequence</code></a> so that it be usable with not only java.util.regex but also <a href="https://github.com/parboiled1/grappa" rel="nofollow">grappa</a>.</p>
<p>In the next version, I want to provide a thread safe version of the main class, <code>LargeText</code>. I have written and tested a thread safe implementation, but now I'd like to know whether it can be done faster... I have a worst case loss of performance of 40% in calls to <code>.charAt()</code>.</p>
<hr>
<p>To give an idea of the impact of this method, looking for all lines more than 10 characters long with a <code>Matcher</code> and the simple <code>Pattern</code> <code>^.{10,}$</code> (in multiline mode) will make <strong>one call to <code>.charAt()</code> for each character in the file</strong>; and the problem is even worse if you use lookarounds, of course. As such this method is pretty critical! On my machine, this method is called more than 80 million times per <em>second</em> with the non thread safe variant below</p>
<hr>
<p>Some explanation on how this all works:</p>
<p>The text file is divided into "text ranges" by a decoding process, mapping one byte range (into the file) to one character range; therefore only the needed text is loaded. This class also handles callers to <code>.charAt()</code> having required a number of characters greater than what has been decoded at a given moment, waking them up when appropriate etc.</p>
<p>The <code>LargeText</code> class uses the principle of locality: when a caller calls <code>.charAt()</code>, it is very likely that the next call to <code>.charAt()</code> will hit the same character range, therefore it keeps the current <code>CharBuffer</code> and text range at hand, and only loads a new one if <code>.charAt()</code> gets out of range.</p>
<p>Note: copyright header and imports omitted for "brevity".</p>
<p>Here is the non thread safe version (<a href="https://github.com/fge/largetext/blob/master/src/main/java/com/github/fge/largetext/NotThreadSafeLargeText.java" rel="nofollow">link</a>):</p>
<pre><code>/**
* A large text file as a {@link CharSequence}: non thread safe version
*
* <p>Despite the not really reassuring name, this is the class you will use the
* most often.</p>
*
* <p>This class's {@code .charAt()} uses regular instance variables to store
* the current text range and text buffer.</p>
*
* @see LargeTextFactory#load(Path)
*/
@NotThreadSafe
@ParametersAreNonnullByDefault
public final class NotThreadSafeLargeText
extends LargeText
{
private IntRange range = EMPTY_RANGE;
private CharBuffer buffer = EMPTY_BUFFER;
NotThreadSafeLargeText(final FileChannel channel, final Charset charset,
final int quantity, final SizeUnit sizeUnit)
throws IOException
{
super(channel, charset, quantity, sizeUnit);
}
@Override
public char charAt(final int index)
{
if (!range.contains(index)) {
final TextRange textRange = decoder.getRange(index);
range = textRange.getCharRange();
buffer = loader.load(textRange);
}
return buffer.charAt(index - range.getLowerBound());
}
}
</code></pre>
<p>And here is the source to the thread safe version (<a href="https://github.com/fge/largetext/blob/master/src/main/java/com/github/fge/largetext/ThreadSafeLargeText.java" rel="nofollow">link</a>):</p>
<pre><code>/**
* A large text file as a {@link CharSequence}: thread safe version
*
* <p>You will need to use an instance of this class, and not the non thread
* safe one, if your {@code LargeText} instance can potentially be used by
* several threads concurrently.</p>
*
* <p>In order to be thread safe, this implementation uses instances of an inner
* class holding both the current text range and buffer in a {@link ThreadLocal}
* variable.</p>
*
* @see LargeTextFactory#loadThreadSafe(Path)
*/
@ThreadSafe
@ParametersAreNonnullByDefault
public final class ThreadSafeLargeText
extends LargeText
{
private static final ThreadLocal<CurrentBuffer> CURRENT
= new ThreadLocal<>();
private static final CurrentBuffer EMPTY_BUF
= new CurrentBuffer(EMPTY_RANGE, EMPTY_BUFFER);
ThreadSafeLargeText(final FileChannel channel, final Charset charset,
final int quantity, final SizeUnit sizeUnit)
throws IOException
{
super(channel, charset, quantity, sizeUnit);
}
@Override
public char charAt(final int index)
{
final CurrentBuffer buf = Optional.fromNullable(CURRENT.get())
.or(EMPTY_BUF);
if (buf.containsIndex(index))
return buf.charAt(index);
final TextRange textRange = decoder.getRange(index);
final IntRange range = textRange.getCharRange();
final CharBuffer buffer = loader.load(textRange);
CURRENT.set(new CurrentBuffer(range, buffer));
return buffer.charAt(index - range.getLowerBound());
}
private static final class CurrentBuffer
{
private final IntRange range;
private final CharBuffer buffer;
private CurrentBuffer(final IntRange range, final CharBuffer buffer)
{
this.range = range;
this.buffer = buffer;
}
private boolean containsIndex(final int index)
{
return range.contains(index);
}
private char charAt(final int index)
{
return buffer.charAt(index - range.getLowerBound());
}
}
}
</code></pre>
<p>Here's a complete example to illustrate the difference. The tested file here is "only" 800 MiB and I have chosen on purpose a small window of 256 KiB.</p>
<p>You can change four things:</p>
<ul>
<li>Path to the tested file (you'll have to, and generate a sufficiently large file, of course)</li>
<li>Window size</li>
<li>The call within the try-with-resources block: this example loads the thread safe version; replace with <code>.load()</code> for a non thread safe version</li>
<li>The tested regex</li>
</ul>
<p></p>
<pre><code>public final class Foo { private static final Pattern PATTERN = Pattern.compile("^.{10,}$", Pattern.MULTILINE);
public static void main(final String... args)
throws IOException
{
final LargeTextFactory factory = LargeTextFactory.newBuilder()
.setWindowSize(256, SizeUnit.KiB).build();
final Path path
= Paths.get("/home/fge/tmp/jsr203/docs/BIGFILE.txt");
final Stopwatch stopwatch = Stopwatch.createUnstarted();
try (
final LargeText largeText = factory.loadThreadSafe(path);
) {
int count = 0;
final Matcher m = PATTERN.matcher(largeText);
stopwatch.start();
while (m.find())
count++;
stopwatch.stop();
System.out.println(count + " matches");
System.out.println(stopwatch);
}
}
}
</code></pre>
<p>You'll have to:</p>
<pre><code>git clone https://github.com/fge/largetext.git
</code></pre>
<p>then:</p>
<pre><code>./gradlew compileJava
# if Windows:
gradlew.bat compileJava
</code></pre>
<p>Or use your IDE. It requires a JDK, nothing else, but version 7 or higher.</p>
<p>So, as you can see, in the thread safe variant, I use an internal class storing both the current range and buffer, and use a <code>ThreadLocal</code> to store it.</p>
<p>Also, the initial values of <code>EMPTY_RANGE</code> and <code>EMPTY_BUFFER</code> are respectively <code>new IntRange(0, 0)</code> and <code>CharBuffer.allocate(0)</code>. The <code>IntRange</code> class is <a href="https://github.com/fge/largetext/blob/master/src/main/java/com/github/fge/largetext/range/IntRange.java" rel="nofollow">here</a>.</p>
<p>Is there a way to improve the thread safe performance?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T16:25:15.240",
"Id": "86380",
"Score": "0",
"body": "It's not standard Java you're using non-standard annotations ( @ThreadSafe etc)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T16:36:49.110",
"Id": "86382",
"Score": "0",
"body": "@EmilyL. This is standard Java... I just have a dependency on `com.googlecode.findbugs:jsr305`"
}
] | [
{
"body": "<p>I'll freely admit that my following suggestions are hunches. I hope they make some difference, but they may be negligible.</p>\n\n<ul>\n<li><p><strong>Override <code>ThreadLocal.initialValue()</code></strong>. This will eliminate calls to <code>Optional.fromNullable</code>: you will always have a non-null value.</p>\n\n<pre><code>private static final ThreadLocal<CurrentBuffer> CURRENT = new ThreadLocal<>() {\n protected CurrentBuffer initialValue() {\n return EMPTY_BUF;\n }\n};\n</code></pre></li>\n<li><p><strong>Cache single last buffer [?].</strong> This may eliminate some calls to <code>CURRENT.get()</code>, but I don't know if the added complexity is worth it. It won't help if there are enough cores to run all threads, but it may improve throughput if there are many more threads. Worth a shot if all else fails?</p>\n\n<pre><code>static class ThreadStash {\n final CurrentBuffer buf;\n final Thread t;\n\n ThreadStash(CurrentBuffer buf, Thread t) {\n this.buf = buf;\n this.t = t;\n }\n}\n\nvolatile ThreadStash stash = new ThreadStash(EMPTY_BUF, Thread.currentThread());\n\n@Override\npublic char charAt(final int index)\n{\n final Thread curThread = Thread.currentThread();\n CurrentBuffer buf;\n ThreadStash stash = this.stash;\n if ( stash.t == curThread ) {\n buf = stash.buf;\n } else {\n buf = CURRENT.get();\n stash = new ThreadStash(buf, curThread);\n }\n if (buf.containsIndex(index))\n return buf.charAt(index);\n final TextRange textRange = decoder.getRange(index);\n final IntRange range = textRange.getCharRange();\n final CharBuffer buffer = loader.load(textRange);\n buf = new CurrentBuffer(range, buffer);\n CURRENT.set(buf);\n stash = new ThreadStash(buf, curThread);\n return buffer.charAt(index - range.getLowerBound());\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:08:50.680",
"Id": "86209",
"Score": "0",
"body": "Actually, I already did the `initialValue` override; this was a very gross oversight from my part. Surprisingly enough I didn't gain as much as I'd have hoped -- in fact, nothing. JIT making too good a job?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:29:49.273",
"Id": "86211",
"Score": "0",
"body": "Yeah, that thing is smart. Whenever I try to outwit it, I end up hours later with little to show for it and missing my wallet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:57:31.597",
"Id": "86216",
"Score": "0",
"body": "I am also trying to make sense of your second suggestion... To be honest I haven't really tried a \"massively parallel\" test, so I'll have to see (in my tests I do test 5 concurrent threads to verify correctness, but 5 is not 1000)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:01:00.167",
"Id": "49087",
"ParentId": "48411",
"Score": "2"
}
},
{
"body": "<p>How large buffer size are you using? What is the hit/miss frequency on your buffer in <code>charAt()</code>?</p>\n\n<p>If the hit frequency is less than 90% and you're doing as you say 80E6 <code>charAt()</code> per second that means you have 8 million buffer allocations per second which is going to cause the GC significant head aches. AFAIR the JVM can stall all threads while doing GC under certain circumstances (I had a similar problem developing a high-performance parallel java application).</p>\n\n<p>So I would change:</p>\n\n<pre><code> CURRENT.set(new CurrentBuffer(range, buffer));\n</code></pre>\n\n<p>to:</p>\n\n<pre><code> buf.range = range;\n buf.buffer = buffer;\n</code></pre>\n\n<p>and change the visibility in <code>CurrentBuffer</code>, it's a private nested class so you're not breaking encapsulation any way. This will put less strain on the GC.</p>\n\n<p>Also, if there is any reason to believe that <code>charAt()</code> is progressing even roughly linearly through the indices, a pre-fetch running in the background would speed things up.</p>\n\n<h3>Edit:</h3>\n\n<p>So with the stats from the comments, the lines executed 99% of the time is:</p>\n\n<p>Not thread safe:</p>\n\n<pre><code> if (!range.contains(index)) {\n // Branch not taken\n }\n return buffer.charAt(index - range.getLowerBound());\n</code></pre>\n\n<p>Thread safe:</p>\n\n<pre><code> final CurrentBuffer buf = CURRENT_BUFFER.get();\n if (buf.containsIndex(index)) // Branch taken\n return buf.charAt(index);\n ... stuff on the stack ...\n</code></pre>\n\n<p><em>Set speculation hat: On</em></p>\n\n<p>The JIT should inline expand the function calls to <code>buf.containsIndex()</code> and <code>buf.charAt</code>, it should also not do anything with the stack variables (not even initializing). So the remaining difference is <code>CURRENT_BUFFER.get()</code> and the book keeping associated with the <code>buf</code> variable which could make or break here as you're only doing a few instructions to fetch the data every time. Adding a few book keeping instructions on the <code>buf</code> variable could have a big impact in your case. I would investigate if I could get rid of it somehow, maybe encapsulate it somehow so the same instance is used in all calls. </p>\n\n<p>Now if you doubt your JVM is good, you can try to inline the two function calls manually and restructure the thread safe variant like this:</p>\n\n<pre><code> final CurrentBuffer buf = CURRENT_BUFFER.get();\n if (!buf.containsIndex(index)){\n final TextRange textRange = decoder.getRange(index);\n final IntRange range = textRange.getCharRange();\n final CharBuffer buffer = loader.load(textRange);\n CURRENT.set(new CurrentBuffer(range, buffer));\n return buffer.charAt(index - range.getLowerBound());\n }\n return buf.charAt(index);\n</code></pre>\n\n<p>just in case the JVM is unable to deduce that those stack variables shouldn't be initialized unless you actually get there. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T17:25:18.237",
"Id": "49089",
"ParentId": "48411",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T15:44:58.590",
"Id": "48411",
"Score": "13",
"Tags": [
"java",
"multithreading",
"thread-safety",
"concurrency"
],
"Title": "Thread-safe large text buffer"
} | 48411 |
<p>So I wrote this code a while ago as a way of seeing how many times it could compute a simple sum in a second (one tick). I was wondering if this gives me valid results or is in fact giving me bogus ones.</p>
<pre><code>from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
def tickscheck(start):
x = 0
count = 0
while millis() - start < 1000:
x = 4+5
#counting up
count = count + 1
print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")
running = True
while(running == True):
tickscheck(millis())
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting")
else:
print("closing Down")
running = False
</code></pre>
| [] | [
{
"body": "<p>No, your benchmark is completely bogus. Let's look at the main loop:</p>\n\n<pre><code>while millis() - start < 1000:\n x = 4+5\n #counting up\n count = count + 1\n</code></pre>\n\n<p>The addition <code>4+5</code> can be constant-folded when the code is compiled. If you are lucky, the assignment remains although a constant assignment might be lifted out of the loop.</p>\n\n<p>But aren't we then still benchmarking the counter increment? Likely, no. The function call <code>millis()</code> in the loop condition is probably at least an order of magnitude more expensive. So essentially, you're benchmarking how fast you can check whether you're done with benchmarking.</p>\n\n<p>The next problem is which time you are measuring. You are currently measuring the elapsed wall clock time (sometimes: “real” time), i.e. the time that you observed passing. However, this is not the same as the time your loop spent executing, because the operating system is free to interrupt execution to schedule other processes in between. The correct time to measure is the “user” time to see how much your program itself worked, and the “system” time to see how much the OS kernel worked on your program's behalf via system calls. The used CPU time is the sum of user and system time. This paragraph uses Unix terminology, but the problem is the same on Windows.</p>\n\n<p>All of this is complicated, so don't do it yourself. Python has a <code>timeit</code> module where you can measure how long a function took to execute a specific number of times. The number of iterations per second is then the inverse of the time spent executing. To prevent the overhead of the function call from affecting the result, the timed function should include a loop itself, e.g. with a million iterations. To execute the body of the loop 10M times, you would then time the function ten times etc.</p>\n\n<h3>Edit: code example</h3>\n\n<p>Assuming Python 3.3 or later, we can use the <code>time.process_time</code> function which measures the used CPU time of our process.</p>\n\n<pre><code>import time\nimport timeit\n\nn = 10000000 # 10M\ntimings = timeit.repeat(\n setup='x, y = 4, 5',\n stmt='z = x + y',\n timer=time.process_time, # comment this line for pre-3.3 pythons\n number=n\n)\nbest_time = max(timings)\nrepetitions_per_second = n/best_time\nprint(\"repetitions per second: %.2E\" % repetitions_per_second)\n</code></pre>\n\n<p>Unfortunately I can't test it right now because I don't have Python 3.3 or later installed. So we might have to use a timer that uses wallclock time instead – this isn't so catastrophic because <code>repeat</code> will take three measurements, and we'll use the best. This does not eliminate the effect of scheduling, but it does minimize it.</p>\n\n<p>Example ballpark results:</p>\n\n<pre><code> 3.2 2.7\nMachine 1 <= 6E6 = 1E7\nMachine 2 <= 2E7 > 2E7\n</code></pre>\n\n<p>So with a back of the envelope-calculation, we can say that machine 2 is roughly 2–3 times as fast as machine 1. This is consistent with their specs (desktop vs. low-end server).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:05:04.330",
"Id": "48421",
"ParentId": "48415",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:11:04.697",
"Id": "48415",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"timer"
],
"Title": "Does this code actually give a valid representation of how quick a system is?"
} | 48415 |
<p>I was wondering which <code>time.time()</code> of <code>from datetime import timedelta</code> was the quickest and best way to find how long a programme had been running for example.</p>
<pre><code>import time
start = time.time()
#do stuff
print(start - time.time())
</code></pre>
<p>or (although longer)</p>
<pre><code>from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
def tickscheck(start):
x = 0
count = 0
while millis() - start < 1000:
x = 4+5
#counting up
count = count + 1
print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")
running = True
while(running == True):
tickscheck(millis())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:23:36.073",
"Id": "85011",
"Score": "0",
"body": "What is your goal here — just to benchmark the Python interpreter on your machine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:59:37.543",
"Id": "85306",
"Score": "0",
"body": "@200_success basically yes"
}
] | [
{
"body": "<p>In Python 3.3 and later you can use one of</p>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\"><code>time.perf_counter()</code></a><br>\n Return the value (in fractional seconds) of a\n performance counter, i.e. a clock with the highest available\n resolution to measure a short duration. It does include time elapsed\n during sleep and is system-wide. The reference point of the returned\n value is undefined, so that only the difference between the results of\n consecutive calls is valid.</p>\n \n <p><a href=\"https://docs.python.org/3/library/time.html#time.process_time\"><code>time.process_time()</code></a><br> Return the value (in fractional seconds) of the\n sum of the system and user CPU time of the current process. It does\n not include time elapsed during sleep. It is process-wide by\n definition. The reference point of the returned value is undefined, so\n that only the difference between the results of consecutive calls is\n valid.</p>\n</blockquote>\n\n<p>Older Python versions offer <a href=\"https://docs.python.org/2/library/timeit.html#timeit.default_timer\"><code>timeit.default_timer()</code></a>, which is now an alias of <code>time.perf_counter()</code>.</p>\n\n<p>The <a href=\"https://docs.python.org/3/library/timeit.html\"><code>timeit</code></a> module offers tools to get more reliable timings by running the code multiple times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T05:48:21.703",
"Id": "48459",
"ParentId": "48416",
"Score": "9"
}
},
{
"body": "<p>For benchmarking process times in Python, you should probably use the <code>timeit</code> module.</p>\n\n<p>It is designed specifically for this purpose and you can keep your code clean by running it from the command-line.</p>\n\n<p>This example is from the docs:</p>\n\n<pre><code>$ python -m timeit '\"-\".join(str(n) for n in range(100))'\n</code></pre>\n\n<p>For example, if the process you want to benchmark is a function <code>foo</code></p>\n\n<pre><code>$ python -m 'timeit --setup 'from my_module import foo' 'foo()'\n</code></pre>\n\n<p>The snippet given with the <code>--setup</code> flag sets up the environment in which you can run your test.</p>\n\n<p>Check out the <a href=\"https://docs.python.org/3.4/library/timeit.html\" rel=\"nofollow\">Python docs</a> for more information</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T11:47:50.937",
"Id": "85755",
"Score": "0",
"body": "thnx ill look into it"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:19:02.987",
"Id": "48785",
"ParentId": "48416",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48785",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:18:21.153",
"Id": "48416",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"timer"
],
"Title": "Measuring Execution Times"
} | 48416 |
<p>After coding this, I was wondering if there are any ways in which I can improve upon it. It generates a random string of characters and symbols the same length as what is entered by the user. It uses a separate list for each char list but I am sure it is using a very long-winded method!</p>
<pre><code>import random, sys
letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
lettersnum = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]
letterssym = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","#","*", "£", "$", "+", "-", "."]
lettersnumsym = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","#", "*", "£", "$", "+", "-", "."]
def generator(length, num, sym, caps):
count = 0
password = ""
try:
test = int(length)
except ValueError:
error("LENGTH NOT VALID NUMBER")
if num.lower() == "yes" and sym.lower() == "yes":
merge = lettersnumsym
elif num.lower() == "yes":
merge = lettersnum
elif sym.lower() == "yes":
merge = letterssym
while count <= int(length):
password = password + merge[random.randint(0, len(merge) - 1)]
count = count + 1
if caps.lower() == "uppercase":
password = password.upper()
elif caps.lower() == "lowercase":
password = password.lower()
print("PASSWORD:",password)
def error(error):
print(error)
sys.exit(0)
running = True
while running == True:
length = input("How long do you want the password?")
numbers = input("Do You Want It to Include Numbers?")
symbols = input("Do You Want It To Include Symbols?")
capital = input("Do You Want It To be uppercase or lowercase??")
generator(length, numbers, symbols, capital)
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
</code></pre>
| [] | [
{
"body": "<p>Python already defines a number of strings of possible characters. See <code>string.ascii_lowercase</code> and <code>string.digits</code> <a href=\"https://docs.python.org/2/library/string.html\">Source</a></p>\n\n<hr>\n\n<p>I would use <code>True</code> and <code>False</code> instead of <code>\"yes\"</code>/<code>\"uppercase\"</code> as arguments to <code>generator()</code>. This function might be used by code that does directly interact with a user, so passing a string would not make sense. Additionally, the restart prompt supports a number of positive responses that are not supported by this function. You should have one layer that controls interaction with the user and one that generates a password. This will make the function cleaner as well as an easier API to work with.</p>\n\n<hr>\n\n<p>Two more point about separation of concerns with <code>generator()</code>:</p>\n\n<ul>\n<li><p>It should return the password instead of printing it. Again, this allows the function to be used when not directly interacting with a command prompt.</p></li>\n<li><p>It should throw an exception instance of calling <code>sys.exit()</code>. <code>exit()</code> will stop the python process and not allow any more execution of code. Your code is written so that multiple passwords can be generated one after another. However, if the user accidentally enters an invalid character to the first question, the application stops running instead asking the user to input a correct value. Throwing an exception would have the same result if you don't change the rest of your code, but allows you to change the code that interacts with the user to handle this case without restarting the application.</p></li>\n</ul>\n\n<hr>\n\n<p>You convert <code>length</code> to an integer repeatedly instead of storing the value. The first validation completely ignores the result and the while loop does the conversion every time it tests if it should continue looping. This can all be solved by having <code>length</code> be passed in as an integer and letting the user layer handle the conversion and error cases.</p>\n\n<hr>\n\n<p><a href=\"https://wiki.python.org/moin/Generators\"><code>Generator</code></a> is already a well defined term with in Python that do something very different. The function should be renamed to <code>generate_password()</code> or something similar.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:10:38.137",
"Id": "48425",
"ParentId": "48417",
"Score": "6"
}
},
{
"body": "<p>You are still not following the advice offered in previous answers to your questions.<br>\nQuoting from <a href=\"https://codereview.stackexchange.com/a/48347/9390\">Edward's great answer</a> on <a href=\"https://codereview.stackexchange.com/questions/48328/are-there-any-bugs-or-ways-to-make-my-divisor-code-better\">\"Are there any bugs or ways to make my divisor code better?\"</a>:</p>\n\n<blockquote>\n <h2>Separate I/O from calculation</h2>\n \n <p>The main purpose of the program is to factor numbers into divisors\n which is something that is potentially reusable. Both to make it more\n clear as to what the program is doing and to allow for future re-use,\n I'd suggest extracting the factoring part into a separate function and\n the have the input from the user be done within the main routine or\n some other input-only function.</p>\n</blockquote>\n\n<p>Your password generating function, sadly, asks the user for input and thus can never be re-used outside the context of this application. Instead, make it take exactly two arguments as the only inputs: a string containing the characters to base the password on, and the length of the password:</p>\n\n<pre><code>def make_password(length, alphabet):\n return ''.join(random.choice(alphabet) for _ in range(length))\n</code></pre>\n\n<p>Here, <code>random.choice(alphabet)</code> replaces <code>merge[random.randint(0, len(merge) - 1)]</code><br>\nin a more readable way.</p>\n\n<p>Another repeat problem, quoting from the same answer:</p>\n\n<blockquote>\n <h2>Think of your user</h2>\n \n <p>Right now, the user has to enter \"yes\" or the equivalent and then\n enter another number to be factored. However, the prompt doesn't\n suggest that \"y\" is a valid answer. Adding that to the prompt would\n help the user understand what the computer is expecting. Better\n still, would be t eliminate that question and to simply ask for the\n next number with a number '0' being the user's way to specify no more\n numbers. Of course the prompt should be changed to tell the user of\n this fact.</p>\n</blockquote>\n\n<p>Your user interface is basically the same: it would drive anyone who used it regularly up the wall. This is a command-line program; throw away all the input prompting and give it a command-line argument interface instead:</p>\n\n<pre>\nusage: makepwd.py [-h] [-d] [-s] [-l | -u] length\n\nGenerates passwords of the specified length, optionally including digits\nand/or symbols.\n\npositional arguments:\n length a positive integer denoting the password length\n\noptional arguments:\n -h, --help show this help message and exit\n -d, --digits include digits in the generated password\n -s, --symbols include symbols in the generated password\n -l, --lower use only lowercase letters\n -u, --upper use only uppercase letters\n</pre>\n\n<p>The <code>argparse</code> module can take care of this for you, but you need to familiarize yourself with its semantics to understand what is going on. Let's take a look at every part individually:</p>\n\n<pre><code>def parse_args():\n parser = argparse.ArgumentParser(description=__doc__, argument_default='')\n parser.set_defaults(letters=string.ascii_letters)\n</code></pre>\n\n<p>We've created an argument parser and provided it the <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><em>docstring</em></a> of our module to use a description. In your original code, lower-case characters were used as a default. This is a <em>bad</em> default, instead use both lower and upper case if nothing else is specified.</p>\n\n<pre><code> parser.add_argument('length', type=int,\n help='a positive integer denoting the password length')\n</code></pre>\n\n<p>The first argument we need is the length of the password. <code>argparse</code> will convert the value to an int and take care of the error handling for us.</p>\n\n<pre><code> add_const_arg = arg_adding_function_for(parser)\n add_const_arg('-d', '--digits', const=string.digits,\n help='include digits in the generated password')\n add_const_arg('-s', '--symbols', const='#*£$+-.',\n help='include symbols in the generated password')\n</code></pre>\n\n<p>Our next two arguments determine the non-alphabetical characters to include in the password.</p>\n\n<pre><code> group = parser.add_mutually_exclusive_group()\n store_letters = arg_adding_function_for(group, dest='letters')\n store_letters('-l', '--lower', const=string.ascii_lowercase,\n help='use only lowercase letters')\n store_letters('-u', '--upper', const=string.ascii_uppercase,\n help='use only uppercase letters')\n</code></pre>\n\n<p>And the final arguments are for overriding the mixed-case default, so it's possible to generate a password containing only lower-case or only upper-case letters (in addition to the digits and symbols). These arguments are mutually exclusive: a password can not be upper-cased and lower-cased at the same time.</p>\n\n<pre><code> return parser.parse_args()\n</code></pre>\n\n<p>And that's it. Almost. You may have noticed I didn't explain the <code>arg_adding_function_for</code> function yet. I defined it as the following <a href=\"http://composingprograms.com/pages/16-higher-order-functions.html\" rel=\"nofollow noreferrer\">higher-order</a> helper function to simplify the above code by using <a href=\"https://docs.python.org/3.4/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a> to pre-set some of the options that are common for each argument. (For flexibility, the <code>*args</code> parameter is included, though not technically necessary - <a href=\"https://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters\">find out more about <code>*args</code> and <code>**kwargs</code></a>).</p>\n\n<pre><code>def arg_adding_function_for(parser, *args, action='store_const', **kwargs):\n return functools.partial(parser.add_argument, action=action, *args, **kwargs)\n</code></pre>\n\n<p>The whole thing in once piece:</p>\n\n<pre><code>\"\"\"\nGenerates passwords of the specified length, optionally including digits and/or symbols.\n\"\"\"\n\nimport argparse\nimport functools\nimport random\nimport string\n\n\ndef main():\n args = parse_args()\n password = make_password(args.length, args.letters + args.digits + args.symbols)\n print(password)\n\n\ndef make_password(length, alphabet):\n return ''.join(random.choice(alphabet) for _ in range(length))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=__doc__, argument_default='')\n parser.set_defaults(letters=string.ascii_letters)\n\n parser.add_argument('length', type=int,\n help='a positive integer denoting the password length')\n\n add_const_arg = arg_adding_function_for(parser)\n add_const_arg('-d', '--digits', const=string.digits,\n help='include digits in the generated password')\n add_const_arg('-s', '--symbols', const='#*£$+-.',\n help='include symbols in the generated password')\n\n group = parser.add_mutually_exclusive_group()\n store_letters = arg_adding_function_for(group, dest='letters')\n store_letters('-l', '--lower', const=string.ascii_lowercase,\n help='use only lowercase letters')\n store_letters('-u', '--upper', const=string.ascii_uppercase,\n help='use only uppercase letters')\n return parser.parse_args()\n\n\ndef arg_adding_function_for(parser, *args, action='store_const', **kwargs):\n return functools.partial(parser.add_argument, action=action, *args, **kwargs)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T07:59:09.910",
"Id": "48462",
"ParentId": "48417",
"Score": "3"
}
},
{
"body": "<p>You are trying to generate a complex password right? Why can't you just use string.py modules built in constants? Something like below. You can take in length or any other parameter as input from user.</p>\n\n<pre><code>import random, string\n\ndef gen_passwrd(length):\n count = 0\n password = \"\"\n while count <= length:\n password = password + random.choice(string.letters + string.digits + string.punctuation)\n count = count +1\nprint password, \"Length = \", length\n\ngen_passwrd(12) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-05T21:03:39.380",
"Id": "177254",
"ParentId": "48417",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:24:32.967",
"Id": "48417",
"Score": "3",
"Tags": [
"python",
"optimization",
"python-3.x",
"random"
],
"Title": "Generating a random string of characters and symbols"
} | 48417 |
<p>I wrote a fizz buzz variation method in Python which prints "fizz", "bang", and "buzz" for 3, 7, and 11 respectively.</p>
<pre><code>def FizzBang():
string = ''
for n in range(1,101):
msg = ""
if not n % 3:
msg += "Fizz"
if not n % 7:
msg += "Bang"
if not n % 11:
msg += "Buzz"
print msg or str(n)
</code></pre>
<p>What can I do to increase the speed of this program? I know the modulus is quite expensive. Also maybe concatenating strings might not be needed as well.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:54:36.760",
"Id": "85021",
"Score": "1",
"body": "You could write it in a native language."
}
] | [
{
"body": "<p>I don't think the modulo operator is as expensive as you think it is, and even if it would be there's no way you can avoid it.</p>\n\n<p>However, instead of doing string concatenation you can write to <code>sys.stdout</code> directly. This however, requires a temporary variable to know if any previous number has been written already.</p>\n\n<p>Also, your <code>string</code> variable has a bad name, and seems to be unused.</p>\n\n<p>If the code in your question is Python2, <a href=\"https://stackoverflow.com/questions/94935/what-is-the-difference-between-range-and-xrange\">use <code>xrange</code> instead of <code>range</code></a> (if it is Python3, no harm done as the <code>range</code> method in Python3 <em>is</em> Python2's <code>xrange</code>)</p>\n\n<p>Python 3 code:</p>\n\n<pre><code>def FizzBang():\n for n in range(1,101):\n written = 0;\n if not n % 3:\n sys.stdout.write(\"Fizz\")\n written = 1\n if not n % 7:\n sys.stdout.write(\"Bang\")\n written = 1\n if not n % 11:\n sys.stdout.write(\"Buzz\")\n written = 1\n if not written:\n print(str(n))\n else:\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:28:02.797",
"Id": "84988",
"Score": "0",
"body": "I've measured this to be about 3% slower than the original (basically a non-issue), and certainly uglier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:33:47.873",
"Id": "84989",
"Score": "0",
"body": "@200_success That explains the downvote. (Well deserved). In that case I think the best suggestion is: Stick to the old code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:41:16.527",
"Id": "84993",
"Score": "0",
"body": "@200_success this answer is slower? Hmm does this answer use less memory? (string concatenations)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:43:20.677",
"Id": "84995",
"Score": "0",
"body": "@200_success would using `print \"Fuzz\",` make things faster? Notice the comma."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:01:34.933",
"Id": "84998",
"Score": "1",
"body": "Indeed, `print \"Fizz\",` makes it about 10% faster than `sys.stdout.write(\"Fizz\")`, probably because `print` is built-in rather than a function call in Python 2. As for any difference in memory usage, I challenge you to find _any_ measurable difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:02:42.600",
"Id": "84999",
"Score": "0",
"body": "I have to admit I did not know about the `print \"Fizz\",` approach. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:14:46.037",
"Id": "85005",
"Score": "0",
"body": "@200_success i'm not sure how to measure this =[ but from reading posts here and there, I've learned that strings are immutable and concatenating them is expensive and a new string object is created for each concatenation. I am not sure how to measure this so all the backup I have is from previous posts that I've read =/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:16:29.397",
"Id": "85008",
"Score": "3",
"body": "@Liondancer We had a recent Python question [about measuring time](http://codereview.stackexchange.com/questions/48416/measuring-execution-times)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:20:47.540",
"Id": "85010",
"Score": "0",
"body": "To measure performance, use [`timeit`](https://docs.python.org/2/library/timeit.html). As for memory, your solution and Simon's solution both use O(1) memory, and the amounts are tiny."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:36:07.560",
"Id": "48427",
"ParentId": "48419",
"Score": "2"
}
},
{
"body": "<p>Indeed, addition is faster than modulo. This implementation runs about 33% faster than the original when counting up to 100. However, I expect that it wouldn't scale as well to larger limits due to its O(<em>n</em>) memory usage.</p>\n\n<pre><code>def fizz_bang(limit=100):\n limit += 1\n strings = [''] * limit\n\n fbb = ((3, 'Fizz'), (7, 'Bang'), (11, 'Buzz'))\n for stride, noise in fbb:\n for n in range(0, limit, stride):\n strings[n] += noise\n for n in range(1, limit):\n print strings[n] or n\n</code></pre>\n\n<p>Also, according to PEP 8 conventions, <code>FizzBang</code> should be named <code>fizz_bang</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:53:16.077",
"Id": "85030",
"Score": "0",
"body": "You could address the memory usage by putting the two `for` loops within a larger loop, that is, compute 1000 or 10000 or some other reasonably large number of output values, print them, and then reuse the memory for the next batch of values. There would be some computational overhead to set values for the inner loops on each iteration of the outermost loop, including three uses of the modulo operation. (On the other hand, in practical terms we would probably all lose interest in the output before memory use became a problem.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:06:40.060",
"Id": "85034",
"Score": "4",
"body": "@DavidK Actually, the array size can be bounded by the LCM of 3, 7, 11, which is 231. After that it cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:39:12.653",
"Id": "85118",
"Score": "0",
"body": "Good point! Yes, of course, so there is still no need to do a modulus."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:55:55.567",
"Id": "48432",
"ParentId": "48419",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48432",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T17:55:57.097",
"Id": "48419",
"Score": "11",
"Tags": [
"python",
"performance",
"python-2.x",
"fizzbuzz"
],
"Title": "\"FIZZ BANG BUZZ!\" 3,7,11 efficiency"
} | 48419 |
<p>I'm new to design patterns and specifically the Service Layer implementation. I need some clarification on where to use Service Layer calls. </p>
<p>Below is an example of what I'm dealing with. I have data from 2 different repositories so I'm not quite certain when/where I'm supposed to call up any additional information that I need to build my Business Model.</p>
<p>I would like for it to do the following:</p>
<ol>
<li>Find Car in Repository</li>
<li>Get Picture from another Repository</li>
<li>Update Url within Model to be used for Presentation Layer.</li>
</ol>
<p>What i'm stuck with is I'm not sure if that logic belongs in the Car Model or it should be handled by a Service layer and within the service layer all of this gets combined. Hopefully this isn't too confusing. Below I added what I thought was relevant.</p>
<p>Business Model/Logic:</p>
<pre><code>public class Car
{
private readonly IFileSystemService _service;
public Car(IFileSystemService service)
{
_service = service;
}
public int id { get; set; }
public string model { get; set; }
public int year { get; set; }
public Image GetImageFile(IGetImageService imgService);
}
</code></pre>
<p>Within the Service Layer:</p>
<pre><code>public void GetImageFile(int carId)
{
Image imgfile = _Repository.GetPhysicalFileLocation(carId);
// ...
}
</code></pre>
<p>Repository 1:</p>
<pre><code>public Car GetCar(int carId)
{
Car myCar = this.GetCar(carId);
// ...
}
</code></pre>
<p>Repository 2:</p>
<pre><code>public Car GetPictureForCar(int carId)
{
Car myCar = this.GetFileForCar(carId);
// ...
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T17:34:48.927",
"Id": "86572",
"Score": "3",
"body": "I can review the \"Business Model/Logic\" part, but everything under it makes no sense, ..why not just post your real code?"
}
] | [
{
"body": "<blockquote>\n <p><em>Business Model/Logic</em></p>\n</blockquote>\n\n<p>These are two distinct things: your <em>model</em> and your <em>logic</em> should be implemented in separate classes - the <em>business model</em> defines a <code>Car</code> class, and the <em>business logic</em> consumes it. In other words, I think your <code>Car</code> class is breaking SRP.</p>\n\n<p>The way I see it (could be wrong) is pretty much like this (assuming MVC):</p>\n\n<p><img src=\"https://i.stack.imgur.com/jNAu2.png\" alt=\"pseudo-uml diagram showing CarController->CarService, CarService->ImageService, CarService->CarRepository, ImageService->Image and CarRepository->Car, and a note saying the CarService gives the controller a model that includes an image and a car.\"></p>\n\n<p>In other words, <code>CarController</code> only needs to know about a <code>CarService</code>, which gives it a <em>model</em> that contains everything the <em>view</em> needs to know - the <code>CarService</code> \"puts the pieces together\" so that the <em>business logic</em> \"layer\" can do its part.</p>\n\n<p>I think having a dependency on <code>IFileSystemService</code> in your <code>Car</code> class makes that class be more than just a <em>model</em>.</p>\n\n<p>Also, in \"repository 2\":</p>\n\n<pre><code>public Car GetPictureForCar(int carId)\n</code></pre>\n\n<p>I don't think it makes much sense to return a whole <code>Car</code> from a method called <code>GetPictureForCar</code> - I'd expect that method to return an <code>Image</code>.</p>\n\n<p>This is even more surprising:</p>\n\n<pre><code>Car myCar = this.GetFileForCar(carId);\n</code></pre>\n\n<p>I'd expect <code>GetFileForCar</code> to return either a <code>File</code> class, or a <code>string</code> with the file's name.</p>\n\n<p>Same here:</p>\n\n<pre><code>Image imgfile = _Repository.GetPhysicalFileLocation(carId);\n</code></pre>\n\n<p>A method that's called <code>GetPhysicalFileLocation</code> should be returning a <code>string</code> with the file's name. And to follow C# naming conventions, <code>_Repository</code> should be <code>_repository</code> (assuming it's a private field).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T18:18:08.143",
"Id": "86577",
"Score": "0",
"body": "Wow! That's and impressive response. Thanks again! This clarifies a great deal! What program are you using for the modeling?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T18:21:41.260",
"Id": "86578",
"Score": "1",
"body": "yuml - see [this meta post](http://meta.codereview.stackexchange.com/a/1830/23788) for more ideas :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T18:11:21.283",
"Id": "49245",
"ParentId": "48420",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "49245",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:02:28.747",
"Id": "48420",
"Score": "4",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Is the following service layer correctly implemented with multiple repositories?"
} | 48420 |
<p>I have few years of experience with web and I recently started learning C++ and I feel a bit lost, so I would like to ask to for some tips how to improve my code overall. This text summarizer should get the sentences with the highest weight (most important ones). </p>
<p>Header file:</p>
<pre><code>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <set>
#include <fstream>
#include <unordered_map>
#include <map>
typedef std::vector<std::set<std::string>> setWords;
class SmartAnalyzer
{
private:
double sentence_intersection(std::set<std::string> const& a, std::set<std::string> const& b);
std::vector<std::string> parseSentences(std::string const& text);
setWords stringSets(std::string const& text);
std::string format(std::string text, bool const& includeDot = false);
public:
SmartAnalyzer() {}
std::string getSummary(std::string title, std::string const& text, int const& limit);
};
</code></pre>
<p>Cpp file:</p>
<pre><code>#include "stdafx.h"
#include "SmartlyParser.h"
double SmartAnalyzer::sentence_intersection(std::set<std::string> const& a, std::set<std::string> const& b)
{
std::vector<std::string> common;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(common));
return (double) common.size() / ((a.size() + b.size()) / 2);
}
std::vector<std::string> SmartAnalyzer::parseSentences(std::string const& text)
{
std::vector<std::string> output;
std::istringstream iss(text);
std::string token;
while (std::getline(iss, token, '.')) {
output.push_back(token);
}
return output;
}
setWords SmartAnalyzer::stringSets(std::string const& text)
{
setWords output;
std::istringstream iss(text), current;
std::string token;
while (std::getline(iss, token, '.')) {
current.clear();
current.str(token);
output.push_back(std::set<std::string>((std::istream_iterator<std::string>(current)), std::istream_iterator<std::string>()));
}
return output;
}
std::string SmartAnalyzer::format(std::string text, bool const& includeDot)
{
text.erase(std::remove_if(text.begin(), text.end(), [includeDot](char c) { return c == ',' || c == '!' || c == '"' || (includeDot && c == '.' ); }), text.end());
std::transform(text.begin(), text.end(), text.begin(), ::tolower);
return text;
}
std::string SmartAnalyzer::getSummary(std::string title, std::string const& text, int const& limit)
{
std::vector<std::string> sentences = parseSentences(text);
int sentLen = sentences.size();
setWords sentencesC = stringSets(format(text));
std::set<std::string> titles = std::set<std::string>((std::istream_iterator<std::string>(std::istringstream(format(title, true)))), std::istream_iterator<std::string>());
double sum;
std::map<double, int> sentencesWeight;
for (int i = 0; i < sentLen; i++)
{
sum = 0;
for (int j = 0; j < sentLen; j++)
{
if (i == j) { /* find intersection with the title, instead of self */
sum += sentence_intersection(sentencesC[i], titles) * 2;
continue;
}
sum += sentence_intersection(sentencesC[i], sentencesC[j]);
}
sentencesWeight.insert({ sum, i });
}
std::string output;
for (std::map<double, int>::reverse_iterator it = sentencesWeight.rbegin(); it != sentencesWeight.rend(); ++it)
{
if (std::string(sentences[it->second] + output).size() > limit) {
break;
}
output += sentences[it->second] + ".";
}
if (output.empty())
{
output = sentences[sentencesWeight.rbegin()->second];
std::size_t pos = output.size();
while ((pos = output.rfind(',', pos)) != std::string::npos && output.size() > limit)
{
output = output.substr(0, pos);
pos--;
}
output += '.';
}
return output;
}
int _tmain()
{
std::ifstream ifs("F:\\Analyzer\\text.txt");
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
std::string title = "Stack, overflow";
SmartAnalyzer a;
std::cout << a.getSummary(title, content, 5 * 36);
getchar();
return 0;
}
</code></pre>
<p><strong>I will really appreciate all kind of tips/improvements and advice on how to start writing in the C++ standards.</strong></p>
<p>Am I using the classes right and not just C with classes? </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:40:26.517",
"Id": "85038",
"Score": "1",
"body": "You should include `<iterator>` and not pass a temporary `istringstream` to an `istream_iterator`. The latter works due to a language extension of MSVC. If you use the MSVC++ compiler, I heavily recommend you disable language extensions (`/Za`) and use warning level 4."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:46:47.353",
"Id": "85039",
"Score": "0",
"body": "Your class looks like a namespace in disguise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:04:45.270",
"Id": "85043",
"Score": "0",
"body": "@dyp Can you give a simple example how I can use iterator, please? Also do you have any suggestions how can I improve my class so it don't look like namespace? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:12:54.867",
"Id": "85044",
"Score": "1",
"body": "@Deepsy minor note, classes are private by default, the the first private in `SmartAnalyzer` is pointless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:01:06.177",
"Id": "85073",
"Score": "1",
"body": "@OMGtechy Some people (me included) like to include it for consistency and clarity."
}
] | [
{
"body": "<ul>\n<li><p>Since any file including a header file is exposed to all its code, it's best to include as few things in a header as possible. All of those libraries but <code><string></code> and <code><set></code> are not used in the header. They should instead be moved to the .cpp file, where they are being used.</p>\n\n<p>Also, <code><unordered_map></code> is not used anywhere, so it should be removed entirely.</p></li>\n<li><p>If you're still going to use <code>std::set<std::string></code> in other places, which is already part of your current <code>typedef</code>, you may add an additional one for that. You can also have your first one in terms of the new one.</p>\n\n<p>New <code>typedef</code>:</p>\n\n<pre><code>typedef std::set<std::string> StringSet;\n</code></pre>\n\n<p>First one updated:</p>\n\n<pre><code>typedef std::vector<StringSet> SetWords;\n</code></pre>\n\n<p><code>sentence_intersection()</code>'s parameters updated:</p>\n\n<pre><code>double sentence_intersection(StringSet const& a, StringSet const& b);\n</code></pre>\n\n<p>Also note that I've started the <code>typedef</code>s with capital letters. Since your variables and functions already use camelCase, the <code>typedef</code>s should probably use a different naming convention (although you don't <em>have</em> to use this one, either).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:05:38.860",
"Id": "48428",
"ParentId": "48424",
"Score": "6"
}
},
{
"body": "<h1>Microsoft Visual C++</h1>\n\n<p>Your code has been written with MSVC and may work with it, but it fails on most of the other compilers. It's not portable at all. Here is what you could do to get rid of this MSVC dependency:</p>\n\n<ul>\n<li>Use <code>main</code> instead of <code>_tmain</code>.</li>\n<li>Don't <code>#include \"stdafx.h\"</code>.</li>\n<li><code>#include <iterator></code> to guarantee that you can access <code>std::istream_iterator</code>.</li>\n<li><p>Follow @dyp's comment and do not pass a temporary <code>std::istringstream</code> to an <code>std::istream_iterator</code>:</p>\n\n<pre><code>std::istringstream iss(format(title, true));\nstd::set<std::string> titles = {\n std::istream_iterator<std::string>(iss),\n std::istream_iterator<std::string>()\n};\n</code></pre></li>\n</ul>\n\n<h1>Order of the headers</h1>\n\n<p>You often want to add/remove headers from your code and/or check whether some header is already included. It's really easier to check whether a header has already been included or not if you keep your <code>#include</code> directives in alphabetical ordering:</p>\n\n<pre><code>#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n</code></pre>\n\n<p>That said, I also agree with @Jamal: most of your headers can be moved to the <code>.cpp</code> and you can get rid of <code><unordered_map></code> which is not used.</p>\n\n<h1>Use C++11</h1>\n\n<p>From what I can see, you are already using C++11. Try to use more of it:</p>\n\n<ul>\n<li><p>Try to replace <code>push_back</code> with <code>emplace_back</code> when it makes sense. For example, in <code>SmartAnalyzer::stringSets</code>:</p>\n\n<pre><code>output.emplace_back(\n std::istream_iterator<std::string>(current),\n std::istream_iterator<std::string>()\n);\n</code></pre></li>\n<li><p>Use <code>std::begin</code> and <code>std::end</code> instead of the corresponding member functions. That way, generic fragments of code may also work with C arrays. For example in <code>SmartAnalyzer::sentence_intersection</code>:</p>\n\n<pre><code>std::set_intersection(std::begin(a), std::end(a),\n std::begin(b), std::end(b),\n std::back_inserter(common));\n</code></pre></li>\n<li><p>In this piece of code:</p>\n\n<pre><code>std::map<double, int>::reverse_iterator it = sentencesWeight.rbegin();\n</code></pre>\n\n<p>Do you honestly care about the full type of <code>it</code>? Generally, you don't, you just want to iterate, use <code>auto</code> to deduce the type:</p>\n\n<pre><code>auto it = sentencesWeight.rbegin(); \n</code></pre></li>\n</ul>\n\n<h1>Other notes</h1>\n\n<p>Some miscellaneous comment:</p>\n\n<ul>\n<li>In <code>std::string format(std::string text, bool const& includeDot = false);</code>, using a <code>bool const&</code> seems to be overkill. Simply pass <code>bool</code>, it will be both simpler and more readable.</li>\n<li>Similarly, there are places where you pass <code>int const&</code> parameters. Honestly, when use use integral or floating point types, passing by <code>const&</code> is really too much. Pass by value.</li>\n<li>Many of your lines are too long. Try to break them as I did in my examples above.</li>\n<li>You used <code>::tolower</code> but did not <code>#include<cctype></code>.</li>\n<li><p>Moreover, <code>std::tolower</code> seems to have overloads for the different <code>char</code> types, contrary to <code>::tolower</code>. You should use the correct overload from <code>std::tolower</code> instead of the generic <code>::tolower</code>:</p>\n\n<pre><code>std::tolower<char>\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T08:51:10.977",
"Id": "48465",
"ParentId": "48424",
"Score": "8"
}
},
{
"body": "<h3> Using a class instead of a namespace </h3>\n\n<pre><code>class SmartAnalyzer\n{\nprivate:\n double sentence_intersection(..);\n std::vector<std::string> parseSentences(..);\n setWords stringSets(..);\n std::string format(..);\n\npublic:\n SmartAnalyzer() {}\n std::string getSummary(..);\n};\n</code></pre>\n\n<p>This class has no data members and therefore no state, nor any invariants to protect. C++ is a \"multi-paradigm\" language, so you can and should choose the \"paradigm\" or <em>programming style</em> that suits best for the problem.</p>\n\n<p>I do not see why a class suits well to house an algorithm, that's why I said in the comments <em>\"Your class looks like a namespace in disguise.\"</em>. Even if you plan to add some state later, the current member functions are just algorithms, so you can just implement them as free functions.</p>\n\n<p>If those algorithms are applicable to a wider set of problems, formulate them generically and make them \"public\" for others to use. If they are private member functions, others cannot reuse them. Otherwise, i.e. if they're not applicable to a wide set of problems, you can put them as free functions in the source file (.cpp) instead of declaring them in the header. In that case, make their linkage internal so their names don't collide with names of functions in other source files.</p>\n\n<hr>\n\n<h3> The O(n²) algorithm </h3>\n\n<p>You used the [optimizations] and [performance] tags. As far as I can see, most time-consuming part here is the weighting algorithm:</p>\n\n<pre><code>for (int i = 0; i < sentLen; i++) \n{\n sum = 0;\n for (int j = 0; j < sentLen; j++)\n {\n if (i == j) { /* find intersection with the title, instead of self */\n sum += sentence_intersection(sentencesC[i], titles) * 2;\n continue;\n }\n sum += sentence_intersection(sentencesC[i], sentencesC[j]);\n }\n sentencesWeight.insert({ sum, i });\n}\n</code></pre>\n\n<p>It should be obvious that this algorithm is in O(n²). To improve the performance of you program, you should try to come up with an algorithm that's asymptotically faster. A first improvement can be achieved by noticing that the correlation is symmetric in <code>i</code> and <code>j</code>. I used a <code>std::vector</code> to store the sentences alongside with the weighting and slightly changed the <code>sentence_intersection</code> algorithm, the new name is <code>intersection_weight</code>:</p>\n\n<pre><code>for (std::size_t i = 0; i < sentLen; i++)\n{\n sentences[i].w += 2 * intersection_weight(sentencesC[i].begin(),\n sentencesC[i].end(),\n titles.begin(), titles.end());\n\n for (auto j = i+1; j < sentLen; j++)\n {\n auto const res = intersection_weight(sentencesC[i].begin(),\n sentencesC[i].end(),\n sentencesC[j].begin(),\n sentencesC[j].end());\n sentences[i].w += res;\n sentences[j].w += res;\n }\n}\n</code></pre>\n\n<p>As this is the most time-consuming part, this optimization halves the total run-time of the program.</p>\n\n<hr>\n\n<h3> Size of the intersection </h3>\n\n<pre><code>double SmartAnalyzer::sentence_intersection(std::set<std::string> const& a,\n std::set<std::string> const& b)\n{\n std::vector<std::string> common;\n std::set_intersection(a.begin(), a.end(), b.begin(), b.end(),\n std::back_inserter(common));\n return (double)common.size() / ((a.size() + b.size()) / 2);\n}\n</code></pre>\n\n<p>This is a most astonishing piece of code. It calculates the <em>size</em> of the intersection between to sets by <em>producing</em> the intersection and then computing its size.</p>\n\n<p>Unfortunately, I couldn't find a Standard Library algorithm to do this. So I split this into two generic algorithms:</p>\n\n<pre><code>template<typename FwdIt0, typename FwdIt1, typename Comp, typename Num>\nNum count_intersection(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1,\n Comp less, Num n)\n// requires:\n// [beg0, end0) is a sorted range wrt less\n// [beg1, end1) is a sorted range wrt less\n// less is a strict weak ordering on *beg0, *beg1 and between *beg0 and *beg1\n// Num is a numerical data type\n// returns:\n// the size of the intersection\n{\n while (beg0 != end0 && beg1 != end1)\n {\n if (less(*beg0, *beg1)) ++beg0;\n else if (less(*beg1, *beg0)) ++beg1;\n else\n {\n ++n;\n ++beg0;\n ++beg1;\n }\n }\n return n;\n}\n</code></pre>\n\n<p>(Even though I've thought that you could use binary search to speed this up, the linear approach is faster in practice; probably because the sets are small and random-access is expensive.)</p>\n\n<pre><code>template<typename FwdIt0, typename FwdIt1>\ndouble intersection_weight(FwdIt0 beg0, FwdIt0 end0, FwdIt1 beg1, FwdIt1 end1)\n{\n auto const mid_size = 0.5 * ( std::distance(beg0, end0)\n + std::distance(beg1, end1));\n auto const intsc = count_intersection(beg0, end0, beg1, end1,\n std::less<>(), int());\n return intsc / mid_size;\n}\n</code></pre>\n\n<p>Note that <code>std::less<></code> is a C++1y feature, but MSVC12 (2013) already supports it.</p>\n\n<p>Since these algorithms are run in a tight loop, they significantly improve performance.</p>\n\n<hr>\n\n<h3>High-level features</h3>\n\n<p>Avoid <code>std::istringstream</code>, <code>std::tolower</code> and <code>std::set</code> in performance-critical applications. Their overhead is typically too high. Additionally, <code>std::tolower</code> is arguably broken: It's locale-aware but works on single characters, which fails e.g. for German <code>BUSSE</code> -> <code>buße</code>. Additionally, there's a <a href=\"https://stackoverflow.com/q/22468086/420683\">problem with language linkage</a>.</p>\n\n<p>If you want speed, provide your own:</p>\n\n<pre><code>inline bool is_dot(char const c)\n{ return c == '.'; }\n\ninline char ascii_tolower(char const c)\n{\n if (c >= 'a' && c <= 'z') return c;\n if (c >= 'A' && c <= 'Z') return c - 'A' + 'a';\n else return c;\n}\n\ninline bool ascii_isspace(char const c)\n{\n return c == ' ' || c == '\\n' || c == '\\r';\n}\n</code></pre>\n\n<p>You can probably further optimize those by using some <code>></code> or <code><</code> comparisons as a first test (most frequent branches first). As I said, the most time-consuming part is the O(n²) algorithm, so you don't actually have to worry about speed here (but the other issues still remain).</p>\n\n<p>Instead of <code>std::istringstream</code>, use a tokenizer (e.g. boost). Instead of <code>std::set</code>, use a <code>std::vector</code>. That's not hard, e.g. if you use</p>\n\n<pre><code>template<class Cont>\ninline void setify(Cont& c)\n{\n std::sort(c.begin(), c.end());\n auto const garbage_beg = std::unique(c.begin(), c.end());\n c.erase(garbage_beg, c.end());\n}\n</code></pre>\n\n<hr>\n\n<h3> The `getSummary` function </h3>\n\n<pre><code>for (std::map<double, int>::reverse_iterator it = sentencesWeight.rbegin();\n it != sentencesWeight.rend();\n ++it)\n</code></pre>\n\n<p>Since the map is only used to get the largest elements, you could use a different comparator (<code>std::greater</code>) instead. Although iterating in reverse isn't that expensive, you could express your intent more clearly if you map was already in descending order.</p>\n\n<p>IMHO, this function is too long. It contains the parsing, the weighting and the output. Split those three parts so they can be reused or exchanged more easily.</p>\n\n<hr>\n\n<h3> Excessive copying </h3>\n\n<p>.. is not inherently bad, since it can increase locality. But some copies are just unnecessary; for example, the whole input text is copied into an <code>istringstream</code> in <code>parseSentences</code> and from there, the individual sentences are copied into a vector.</p>\n\n<p>Similarly, the text is copied in <code>getSummary</code> by passing it to the <code>format</code> function, then the result is passed to <code>stringSets</code> which again copies it into an <code>istringstream</code> to be tokenized and the tokens then copied into a <code>std::vector<std::set<std::string>></code>.</p>\n\n<p>Use iterators or ranges to pass data if you don't need to modify the container. This decouples algorithms from data structures and makes them more easily reusable.</p>\n\n<p>Something similar to the set intersection algorithm is used here:</p>\n\n<pre><code>std::string(sentences[it->second] + output).size()\n</code></pre>\n\n<p>This creates a temporary string just to compute its size. You can replace it with</p>\n\n<pre><code>sentences[it->second].length() + output.length()\n</code></pre>\n\n<hr>\n\n<h3> Run-time measurements </h3>\n\n<p>Using MSVC12 (2013) Update 1, and the complete works of William Shakespeare. Unfortunately, that's too much data for the O(n²) algorithm, so I just used to first 13,000 lines.</p>\n\n<ul>\n<li>Run-time of the original code (at <code>/Ox</code>): 41 s</li>\n<li>Run-time of the modified code (at <code>/Ox</code>): 11 s</li>\n</ul>\n\n<p>Note that I also replaced all the <code>std::set</code>s with <code>std::vector</code>s and used custom lightweight tokenizers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:32:12.057",
"Id": "85116",
"Score": "1",
"body": "Aren't you fed up with giving overly good answers? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:36:26.273",
"Id": "85117",
"Score": "0",
"body": "Nevermind @Morwenn, welcome to CR! (feel free to come say hi in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)/[chat] ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:55:04.837",
"Id": "85201",
"Score": "0",
"body": "By the way, if speed is needed, isn't it faster to implement `aswcii_tolower` as a lookup table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:17:06.250",
"Id": "85208",
"Score": "0",
"body": "@Morwenn Just tried it. Doesn't seem to matter here. It isn't called inside the O(n²) loop, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:19:19.417",
"Id": "85209",
"Score": "0",
"body": "@dyp Ok. Just wanted to make sure :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:20:54.033",
"Id": "85212",
"Score": "0",
"body": "@Morwenn If you can suggest an alternative for the O(n²) algorithm or some improvement there, that'd be great :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:27:15.280",
"Id": "85215",
"Score": "0",
"body": "@dyp I'm rather bad when it comes to reduce the complexity of algorithms (among other things). The only thing I see is that you are computing `sentences[i]` many times in the inner loop. But I guess that a decent compiler should be able to do some loop optimization here, so that's not a real problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:37:37.933",
"Id": "85219",
"Score": "0",
"body": "@Morwenn Hmm yes I tried iterator-based loops now, but they didn't help unfortunately. Without zip iterators, they're also quite ugly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:18:59.573",
"Id": "85289",
"Score": "0",
"body": "Thanks for the great answer! I really appreciate it! More answers like this should exists. You guys are awesome <3"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:12:08.200",
"Id": "48484",
"ParentId": "48424",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "48484",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T18:10:19.897",
"Id": "48424",
"Score": "12",
"Tags": [
"c++",
"optimization",
"performance",
"c++11"
],
"Title": "Text \"analyzer\" in C++"
} | 48424 |
<p>I am trying to use the following form to enter new info into a database. </p>
<p><img src="https://i.stack.imgur.com/zkQfE.png" alt="enter image description here"></p>
<p>I am trying to use the entity framework.</p>
<p>I have the following classes of Interest: </p>
<pre><code>public class InventoryContext : DbContext
{
public DbSet<Item> Items { get; set; }
....Other DbSets follow...
}
[Table("Items")]
public class Item
{
#region Strings
public string Color { get; set; }
public string FullName { get; set; }
[Column(@"Sheet/Roll")]
public string Type { get; set; }
public string PrimaryMachine { get; set; }
public string Alias { get; set; }
public string Brand { get; set; }
public string Finish { get; set; }
#endregion
#region Long
public long ID { get; set; }
public decimal? Weight { get; set; }
#endregion
#region Doubles
public decimal? Size1 { get; set; }
public decimal? Size2 { get; set; }
public decimal? Size3 { get; set; }
#endregion.
}
</code></pre>
<p>And I am stuck on filtering the <code>dgvAllItems</code>, based on the selected drop down values. I think my code is ugly and there is a better way.</p>
<pre><code> private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox s = (ComboBox)sender;
IQueryable<Item> query = c.Items;
foreach (ComboBox cb2 in gbFilters.Controls.OfType<ComboBox>().Where(com => com.Text != ""))
{
string currentpropname = cb2.Name.Substring(2);
if (cb2.Name.Substring(2, 4) == "Size" || cb2.Name == "cbWeight")
{
decimal? currentpropvalue = Convert.ToDecimal(cb2.Text);
PropertyInfo propertyInfo = typeof(Item).GetProperty(currentpropname);
ParameterExpression pe = Expression.Parameter(typeof(Item), "e");
MemberExpression me = Expression.MakeMemberAccess(pe, propertyInfo);
ConstantExpression ce = Expression.Constant(currentpropvalue, typeof(decimal?));
BinaryExpression be = Expression.Equal(me, ce);
Expression<Func<Item, bool>> lambda = Expression.Lambda<Func<Item, bool>>(be, pe);
query = query.Where(lambda);
}
else
{
string currentpropvalue = cb2.Text;
PropertyInfo propertyInfo = typeof(Item).GetProperty(currentpropname);
ParameterExpression pe = Expression.Parameter(typeof(Item), "e");
MemberExpression me = Expression.MakeMemberAccess(pe, propertyInfo);
ConstantExpression ce = Expression.Constant(currentpropvalue, typeof(decimal?));
BinaryExpression be = Expression.Equal(me, ce);
Expression<Func<Item, bool>> lambda = Expression.Lambda<Func<Item, bool>>(be, pe);
query = query.Where(lambda);
}
}
bindingSource1.DataSource = query.ToList();
}
private void ComboBox_DropDown(object sender, EventArgs e)
{
ComboBox cb1 = (ComboBox)sender;
IQueryable<Item> query = c.Items;
foreach (ComboBox cb2 in gbFilters.Controls.OfType<ComboBox>().Where(com => com.Text != ""))
{
string currentpropname = cb2.Name.Substring(2);
if (cb2.Name.Substring(2, 4) == "Size" || cb2.Name == "cbWeight")
{
decimal? currentpropvalue = Convert.ToDecimal(cb2.Text);
PropertyInfo propertyInfo = typeof(Item).GetProperty(currentpropname);
ParameterExpression pe = Expression.Parameter(typeof(Item), "e");
MemberExpression me = Expression.MakeMemberAccess(pe, propertyInfo);
ConstantExpression ce = Expression.Constant(currentpropvalue, typeof(decimal?));
BinaryExpression be = Expression.Equal(me, ce);
Expression<Func<Item, bool>> lambda = Expression.Lambda<Func<Item, bool>>(be, pe);
query = query.Where(lambda);
}
else
{
string currentpropvalue = cb2.Text;
PropertyInfo propertyInfo = typeof(Item).GetProperty(currentpropname);
ParameterExpression pe = Expression.Parameter(typeof(Item), "e");
MemberExpression me = Expression.MakeMemberAccess(pe, propertyInfo);
ConstantExpression ce = Expression.Constant(currentpropvalue, typeof(decimal?));
BinaryExpression be = Expression.Equal(me, ce);
Expression<Func<Item, bool>> lambda = Expression.Lambda<Func<Item, bool>>(be, pe);
query = query.Where(lambda);
}
}
string ActivePropName = cb1.Name.Substring(2);
if (ActivePropName.Substring(0, 4) == "Size" || ActivePropName == "Weight")
{
ParameterExpression arg = Expression.Parameter(typeof(Item), "x");
Expression expr = Expression.Property(arg, ActivePropName);
LambdaExpression lambda = Expression.Lambda(expr, arg);
Expression<Func<Item, decimal?>> expression = (Expression<Func<Item, decimal?>>)lambda;
cb1.DataSource = query.Select(expression).Distinct().ToList();
}
else
{
ParameterExpression arg = Expression.Parameter(typeof(Item), "x");
Expression expr = Expression.Property(arg, ActivePropName);
LambdaExpression lambda = Expression.Lambda(expr, arg);
Expression<Func<Item, string>> expression = (Expression<Func<Item, string>>)lambda;
cb1.DataSource = query.Select(expression).Distinct().ToList();
}
}
</code></pre>
| [] | [
{
"body": "<p>I'm about to watch Vikings so here are a few quick pointers:</p>\n\n<h1>Naming</h1>\n\n<p>Your code contains variables named <code>me</code>, <code>pe</code>, <code>ce</code>, etc. This tells me nothing about what that variable does. </p>\n\n<p>I'm not experienced with <code>Expressions</code> but I assume <code>Expression.Equal</code> refers to an <code>==</code> invocation. Such a variable could then be rewritten as <code>equalsCondition</code>, for example. This tells me a lot more about will also read easier when done everywhere: </p>\n\n<pre><code>expression = equalsCondition(itemValue, constantValue)\n</code></pre>\n\n<h1>Duplication</h1>\n\n<p>Your <code>if</code> statements are very similar to eachother; similar to the point that I'm pretty sure you copy-pasted most of it. This is a sign that you need to factor it out to a method.</p>\n\n<p>An example could be this:</p>\n\n<pre><code>private Expression<Func<Item, bool>> lambda GenerateQuery(object propertyValue)\n{\n PropertyInfo propertyInfo = typeof(Item).GetProperty(currentpropname);\n ParameterExpression pe = Expression.Parameter(typeof(Item), \"e\");\n MemberExpression me = Expression.MakeMemberAccess(pe, propertyInfo);\n ConstantExpression ce = Expression.Constant(currentpropvalue, typeof(decimal?));\n BinaryExpression be = Expression.Equal(me, ce);\n Expression<Func<Item, bool>> lambda = Expression.Lambda<Func<Item, bool>>(be, pe);\n}\n</code></pre>\n\n<p>and used as such:</p>\n\n<pre><code>if (cb2.Name.Substring(2, 4) == \"Size\" || cb2.Name == \"cbWeight\")\n{\n decimal? currentpropvalue = Convert.ToDecimal(cb2.Text); \n query = query.Where(GenerateQuery(currentpropvalue));\n} else {\n string currentpropvalue = cb2.Text;\n query = query.Where(GenerateQuery(currentpropvalue));\n}\n</code></pre>\n\n<hr />\n\n<p>If you push these two changes through to the several places they manifest, you'll find that your code has shrunk a lot and is a lot more readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:14:25.180",
"Id": "85016",
"Score": "0",
"body": "Most of this is psuedo code for my actual program it does follow all standard naming converntion, Underscores, upper lower cases, comments and so. I actually extracted this code out of the methods to make it more clear in my sample (For me trying to follow definitions and references through code on here is a lot harder then just having it in there. But none of this actually helps with the question as I am more looking for performance enhancement or better code conventions ie. not use the field names as the name of the controls how to split my code into generic"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:15:48.097",
"Id": "85017",
"Score": "0",
"body": "classes and not have multiple overloaded methods. Or entire new concepts that maybe avoid the entity framework or allow me to use it in a better way. As I am about 80% sure I am not using it as it was intended, but as I don't know how it was intended I can't tell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:56:14.850",
"Id": "85022",
"Score": "1",
"body": "Sure, I don't see any repositories and you're accessing your datasource (through EF) from a GUI method. For a quick review on EF & repositories, look [here](http://codereview.stackexchange.com/questions/47890/am-i-even-using-the-entity-frameowrk-and-or-linq-the-way-it-is-supposed-to-be-us/47909#47909). Please use the exact code in your question next time, as is requested in the Help Center."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:59:43.360",
"Id": "85023",
"Score": "0",
"body": "My point was that I wasn't asking for how to format my code better, but how to make it perform better. Maybe It is not the correct type of question for the site? Or I asked incorrectly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:24:32.720",
"Id": "85054",
"Score": "1",
"body": "@user2125348 it is - except answerers on this site are free to address anything they see in your code, about any facet one might have thought of.. or not. You may ask about specific performance concerns, so reviewers try to steer their attention in that direction. But if I read code and I'm having a problem with its readability, you can be sure I'm going to make a note about readability in my review! Performance is one thing, but if you're focused on performance and someone points out an important maintainability issue, it's a plus! ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:57:09.510",
"Id": "48437",
"ParentId": "48435",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:30:57.440",
"Id": "48435",
"Score": "4",
"Tags": [
"c#",
"linq",
"entity-framework"
],
"Title": "EntityFramework-based filtering"
} | 48435 |
<p>I was thinking in a way to improve the following query if possible:</p>
<pre><code>SELECT CONCAT(DATE_FORMAT(start_date, '%Y'), ',',
(MONTH(start_date) -1), ',', DATE_FORMAT(start_date, '%d')) as start_date
FROM PROJECTS
</code></pre>
<p>I need <code>start_date</code> in this format: <code>dd/mm-1/yyyy</code>.</p>
<p>Note: I am using an API that use month from 0 to 11, and MySQL uses 1 to 12 – that's why I need <em>month - 1</em>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:04:02.733",
"Id": "85050",
"Score": "2",
"body": "Could you post your application code as well? I think that using SQL to work around the 0-1 mismatch is a bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:16:06.077",
"Id": "85097",
"Score": "0",
"body": "I am working just with database. I don't have access to the code at all. Should I say or ask for the backend programmers that there are better practices? Or even in the code, there's no way to get this code better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:46:41.447",
"Id": "85103",
"Score": "2",
"body": "Where are you running that query from, if it is not embedded in some program? In my opinion, it would be cleaner for the query to return a \"natural\"-looking date (with months 1-12), and for the code that consumes the date to adjust it to the API (months 0-11) as necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:37:43.337",
"Id": "85106",
"Score": "0",
"body": "It's a stored procedure. Anyhow, talking about the query itself, there is some improvement that can I do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:54:37.433",
"Id": "85303",
"Score": "0",
"body": "what are you going to do with this Data after you have queried it? what API are you using?"
}
] | [
{
"body": "<p>If there is no workaround then, bad practice as it may be, what you have is functional. I <a href=\"https://stackoverflow.com/questions/8931106/mysql-my-months-are-current-stored-0-11\">found this post on SO</a> that may allow you to convert the column's <code>date</code> data type to the 0-11 format. Hope this helps. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Removed bad idea. If you really wish to see it just look at the edit history, but it is not a good idea. I'm going back to my original answer. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T04:06:40.573",
"Id": "88526",
"Score": "0",
"body": "I found MySQL raises no error when `CAST` or `CONVERT` as `DATE` is used with the 0-11 format so you should still be able to do date calcs on those too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T04:14:20.120",
"Id": "88528",
"Score": "0",
"body": "Disclaimer: The `CAST(SUBSTRING(` section is almost wholly adapted from the SO link posted above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T09:25:54.877",
"Id": "88545",
"Score": "1",
"body": "Using SQL to produce a weirdly formatted date was bad; storing redundant data is even worse, in my opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T22:07:37.587",
"Id": "88655",
"Score": "0",
"body": "Fair point 200_success"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T22:21:43.697",
"Id": "88657",
"Score": "0",
"body": "I went ahead and rolled it back."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T21:56:16.260",
"Id": "51260",
"ParentId": "48436",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:55:26.853",
"Id": "48436",
"Score": "4",
"Tags": [
"sql",
"datetime",
"mysqli"
],
"Title": "Selecting one MySQL date with month reduced by one"
} | 48436 |
<p>I want to implement the following function:</p>
<pre><code>// Return true if and only if 's' is numeric including
// leading positive/negative sign, decimal point.
bool isnumeric( const char * s );
</code></pre>
<p>It is somewhat similar to <code>strtol()</code> but I don't need to return the number.</p>
<p>My approach is to count various things unless I can bail out:</p>
<pre><code>bool isnumeric( char const * str ) {
if( !str ) { return false; }
int signs = 0;
int decimals = 0;
int digits = 0;
int digitsAfterDecimal = 0;
for( char const * p = str; *p; ++p ) {
if( (*p == '+') || (*p == '-') ) {
if( (decimals > 0) || (digits > 0) ) { return false; }
signs += 1;
if( signs == 2 ) { return false; }
}
else if( *p == '.' ) {
decimals += 1;
if( decimals == 2 ) { return false; }
}
else if( ! isdigit( *p ) ) {
return false;
}
else {
digits += 1;
if( decimals > 0 ) {
digitsAfterDecimal += 1;
}
}
}
return (decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0))
: (digits > 0) ;
}
</code></pre>
<p>I also have the following tests:</p>
<pre><code>void test_isnumeric() {
assert( isnumeric( "42" ) );
assert( isnumeric( "42.0" ) );
assert( isnumeric( "42.56" ) );
assert( isnumeric( "+42" ) );
assert( isnumeric( ".42" ) );
assert( isnumeric( "+.42" ) );
assert( ! isnumeric( "42." ) );
assert( ! isnumeric( "++42" ) );
assert( ! isnumeric( "+." ) );
assert( ! isnumeric( "4+" ) );
}
int main( void ) {
test_isnumeric();
}
</code></pre>
<p>To make it easy to clone and modify, the full code is available <a href="http://ideone.com/qotAhb">here</a>.</p>
<p>Please comment on design, structuring, test coverage etc. Mentioning failing tests are most welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:18:59.323",
"Id": "85018",
"Score": "1",
"body": "Looks like you're using your `int`s mainly as `bool`s, might want to consider to use `bool`s there for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:50:28.840",
"Id": "85020",
"Score": "0",
"body": "@Bobby: Which `int` variable you are referring to? The following `int` variables (`signs`, `decimals`, `digits`, `digitsAfterDecimal`) are used as counters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:26:47.050",
"Id": "85025",
"Score": "0",
"body": "Yes, but you're only testing them for greater than 0, that's basically what a boolean does. F.e. `decimals` might be `bool` called `hasDecimalPoint`, `*p == '.' ... if (hasDecimalPoint) return false; hasDecimalPoint = true;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:59:20.067",
"Id": "85032",
"Score": "0",
"body": "@Bobby: Thanks for the followup comment and clarification, I *now* understand what you are saying. When I applied it, I could simplify the code. [Please feel free to enter your comment as an answer.] With counters, I retained more information as obtained from the scan than it is necessary for this particular problem, which might be helpful if the problem is modified."
}
] | [
{
"body": "<p>State variables are bad. Keep the state explicit, along the lines of:</p>\n\n<pre><code>if (*p == '+' || *p == '-') p++;\nif (!isdigit(*p)) return False;\nwhile (isdigit(*p)) p++;\nif (*p == 0) return True;\nif (*p != '.') return False;\np++;\nwhile (isdigit(*p)) p++;\nreturn *p == 0;\n</code></pre>\n\n<p>Update: few fixes thanks to <a href=\"https://codereview.stackexchange.com/users/39848/edward\">Edward</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:39:21.623",
"Id": "85028",
"Score": "0",
"body": "+1; Thanks for reviewing my code. I would love to write a compact form such as yours. But, in that approach, I had difficulty covering the malformed inputs, for e.g. \"42.\", \"+.\" etc. Perhaps I need to think harder :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T08:15:58.340",
"Id": "85091",
"Score": "0",
"body": "@Arun I find it strange that you consider `42.` not to be a numeric value. In C, `42. == 42.0`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:34:54.300",
"Id": "85163",
"Score": "1",
"body": "I didn't mean the snippet to be working. In fact, it has certain problems in correctness (e.g. returning `True` for a suspicious \"+.\") and design. It is here only to demonstrate a stateless approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:17:25.900",
"Id": "85382",
"Score": "0",
"body": "On line 4 you mean `(*p == 0)` rather than `(*p == '0')` to test for end of string rather than a zero digit and line 2 could be `if (!isdigit(*p)) return False;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:49:42.910",
"Id": "85385",
"Score": "0",
"body": "@Edward You are absolutely right. Fixing."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:05:44.507",
"Id": "48441",
"ParentId": "48438",
"Score": "4"
}
},
{
"body": "<p>Over-all no major problems - just nits.</p>\n\n<ol>\n<li><p>Minor inefficiency. Test for digits <em>first</em>.</p></li>\n<li><p>A simple test for leading sign would do.</p></li>\n<li><p>Decimal point is locale-sensitive.</p>\n\n<pre><code>char dp = localeconv()->decimal_point[0].\n</code></pre></li>\n<li><p>Pedantic (meaning only the crazy care): When counting elements of an array, recommend type <code>size_t</code> rather than <code>int</code> for <code>digits</code>, <code>digitsAfterDecimal</code>. Either that or fail if <code>digits</code> is to exceed <code>INT_MAX</code>. The main issue here is security. If a user can break your code by pasting in insane long string (when <code>INT_MAX < SIZE_MAX</code>) it represents a remote possibility.</p></li>\n<li><p>Pedantic: The <code>bool</code> approach (@Bobby) will not overflow the digit count for insanely high number of digits like the present code. </p></li>\n</ol>\n\n<hr>\n\n<p>Critique of coding goals - not code</p>\n\n<ol>\n<li><p>Do not understand why the coding goal does not allow <strike>\"123\",</strike> \"123.\"<strike>, \".123\"</strike>. </p></li>\n<li><p><code>strtol()</code> will accept leading white-space.</p></li>\n<li><p>Indicating the address of the fail location sounds like a useful enhancement. E. g. return <code>p</code> on failure, <code>NULL</code> on success.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T04:39:16.097",
"Id": "85387",
"Score": "0",
"body": "+1: Good Comments; Thank you. I like the pedantic (A.1) and strtol (B.2) and return NULL (B.3). On B.1, \"123\" and \".123\" are expected to be accepted, only \"123.\" is not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:37:31.917",
"Id": "85446",
"Score": "0",
"body": "Corrected. My mis-read of the program flow, though my mistake, was mis-inteprettting `decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0)) : (digits > 0)`. I like @Bobby idea to use boolean when only 2 states matter. OTOH the end may be `decimals ? (digits && digitsAfterDecimal) : digits;` or even `(decimals && digitsAfterDecimal) || digits`. OT3H, if \"123.\" was OK, then `return digits`. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:40:26.973",
"Id": "85447",
"Score": "0",
"body": "Suggest: To test cases add those pesky empty cases of `assert( ! isnumeric( \"\" ) );`, `assert( ! isnumeric(NULL) );`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:07:39.430",
"Id": "48642",
"ParentId": "48438",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:03:37.170",
"Id": "48438",
"Score": "7",
"Tags": [
"c",
"parsing",
"unit-testing",
"validation",
"fixed-point"
],
"Title": "Test if string is numeric"
} | 48438 |
<p>I have written the same code in Python (NumPy) and in Matlab, and I tried to use the same structure for both language and follow the same procedure. Now my problem is that when I run my code in Python it's very very slow but it runs fast in Matlab.</p>
<p>How can I improve my Python code? I want to work on the Python version of my code.</p>
<p>In the code I am trying to create an MxM matrix (M can vary between 100 to 1000) and trying to fill this matrix 16 times, each time I add the previous value of M[i,j] with the current value. The operation inside the code is simple just some add and divide, and now I wonder why Matlab performs better than Python.</p>
<p><strong>Python:</strong></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
startTime = datetime.now()
bb = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
bb = ['{0:04b}'.format(x) for x in bb]
step_prob=0.01
step = int(1/step_prob)
out_t = np.zeros((step,step), dtype=float)
out_f = np.zeros((step,step), dtype=float)
s = np.zeros((step,step), dtype=float)
improve = np.empty((step,step))
for ii in range(1, step+1):
print ii
pti=ii*step_prob
for jj in range(1, step+1):
pfi=jj*step_prob
improve[ii-1,jj-1]=0
si=(1-pfi+pti)/2
for k in range(len(bb)):
f1 = int(bb[k][0])
f2 = int(bb[k][1])
f3 = int(bb[k][2])
f4 = int(bb[k][3])
for i in range(1, step+1):
for j in range(1, step+1):
ptj=i*step_prob
pfj=j*step_prob
out_t[i-1,j-1] = f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj)
out_f[i-1,j-1] = f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj)
sj=(1-pfj+ptj)/2;
s[i-1,j-1] = ((1-out_f[i-1,j-1]+out_t[i-1,j-1])/2)-max(si,sj);
# temp=s*(s>0)*tril(ones(size(s)));
temp = s*(s>0)*np.tril(np.ones((len(s),len(s))).astype(int))
improve[ii-1,jj-1]=improve[ii-1,jj-1]+sum(sum(temp))
im = plt.imshow(improve*np.tril(np.ones((len(improve),len(improve))).astype(int)),interpolation='bilinear', aspect='auto') # s*[s>0]
# im = plt.imshow(improve, interpolation='bilinear', aspect='auto') # s*[s>0]
plt.colorbar(im, orientation='vertical')
plt.show()
</code></pre>
<p><strong>Matlab:</strong></p>
<pre><code>close all
clear all
clc
bb = de2bi([0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15],4,'left-msb');
% bb = de2bi([1],4);
step_prob=0.01;
for ii=1:1*(1/step_prob)
ii
pti=ii*step_prob;
for jj=1:1*(1/step_prob)
pfi=jj*step_prob;
improve(ii,jj)=0;
si=(1-pfi+pti)/2;
for k=1:size(bb,1)
f1=bb(k,1);
f2=bb(k,2);
f3=bb(k,3);
f4=bb(k,4);
for i=1:1*(1/step_prob)
for j=1:1*(1/step_prob)
ptj=i*step_prob;
pfj=j*step_prob;
out_t(i,j)=f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj);
out_f(i,j)=f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj);
sj=(1-pfj+ptj)/2;
s(i,j)=((1-out_f(i,j)+out_t(i,j))/2)-max(si,sj);
end
end
temp=s.*(s>0).*tril(ones(size(s)));
improve(ii,jj)=improve(ii,jj)+sum(sum(temp));
clear f1 f2 f3 f4
end
end
end
scale=step_prob:step_prob:1;
imagesc(scale,scale,improve.*tril(ones(size(improve))))
xlabel('Pfj')
ylabel('Ptj')
axis xy
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:00:02.820",
"Id": "85024",
"Score": "3",
"body": "Your title should state what your code is for, not that it is slow! What is it's *purpose*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:03:20.220",
"Id": "85033",
"Score": "4",
"body": "To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-14T08:57:13.653",
"Id": "177090",
"Score": "0",
"body": "Coincidentally, I have the exact same problem, except the speeds of the two languages are switched for me..."
}
] | [
{
"body": "<p>You use very short variable names, so its hard to follow what your code is doing.</p>\n\n<p>For speed in numpy, you need to use vector operations. So instead of writing</p>\n\n<pre><code>for ii in range(step):\n out[ii] = ii * x + b\n</code></pre>\n\n<p>You should write:</p>\n\n<pre><code>out = numpy.arange(step)*x + b\n</code></pre>\n\n<p>Individually accessing the elements of numpy array is actually quite slow. You need to write your code to do everything in vector operations.</p>\n\n<p>Here is my rewrite of your inner loop to be vectorized. You could vectorize the outer loop as well, but this should make the biggest difference.</p>\n\n<pre><code> f1 = int(bb[k][0])\n f2 = int(bb[k][1]) \n f3 = int(bb[k][2])\n f4 = int(bb[k][3])\n\n ptj = np.arange(step_prob, 1.0 + step_prob, step_prob)[:, None]\n pfj = np.arange(step_prob, 1.0 + step_prob, step_prob)[None, :]\n\n out_t = f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj)\n out_f = f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj)\n sj = (1 - pfj + ptj) / 2\n\n the_max = np.maximum(sj, [si])\n s = ((1-out_f+out_t)/2)-the_max\n\n temp = s*(s>0)*np.tril(np.ones((len(s),len(s))).astype(int))\n improve[ii-1,jj-1]=improve[ii-1,jj-1]+temp.sum()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:41:46.057",
"Id": "85250",
"Score": "0",
"body": "it's kinda impossible for me to do this, since I need to compute some \"expected value\" individually for different threshold. anyway I don't understand why this way of coding works find in Matlab but not in Numpy"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:52:21.147",
"Id": "85253",
"Score": "5",
"body": "@Am1rr3zA, Python and Matlab are different languages. In Python, manual loops like you've written are rather slow. They used to be slow in Matlab too, but the implementation was improved. Furthermore, I doubt its actually impossible to vectorize, but since I have no idea what you are doing in this code it's hard to give you suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T01:02:59.460",
"Id": "85255",
"Score": "0",
"body": "If I want to explain my code in a simple word I am trying to fill a MxM matrix (improve) each value of matrix is computed as follows: improve[i,j] is sum of 16 times (for all the element in bb array) calculating my formula ( out_t(i,j) and out_f(i,j) ), and my formula try to compute expected value of pti and pfi (outter loop) for all possible range of ptj and pfj (inner loop)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T01:51:54.217",
"Id": "85256",
"Score": "0",
"body": "@Am1rr3zA, I've added some code that vectorizes your inner loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T02:53:51.450",
"Id": "85259",
"Score": "0",
"body": "Tanx for your help but I don't think it's doing the same, first of all ptj = np.arange(step, 1.0 + step, step)[:, None] it's not right it must be ptj = np.linspace(0,1,step), yet after fixing this it's not working as I expected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T02:59:17.860",
"Id": "85260",
"Score": "3",
"body": "@Am1rr3zA, the third parameter to linspace is a count, not a step size. If you want to use linspace, it should be np.linspace(0, 1, steps). But that's not quite what you were doing because your code skipped zero. You do need the [:, None] to make it work. I may well have not gotten it quite right, but hopefully it helps you see what you could do to speed up the poythn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:20:30.933",
"Id": "85379",
"Score": "0",
"body": "actually the other problem I have with your suggestion of removing inner loop is that in my code inner loop supposed to create 2D array but your code will create 1D array, (I am talking about out_t and out_f)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:20:30.643",
"Id": "85445",
"Score": "0",
"body": "@Am1rr3zA, if you really need a 2D array for those, you can use numpy.tile or numpy.repeat. But for most purposes you simply don't need the 2D array, see how I computed s without making the arrays 2d."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T15:50:58.687",
"Id": "85471",
"Score": "0",
"body": "but the s is not what I expected your s contain wrong value"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:23:00.667",
"Id": "85532",
"Score": "1",
"body": "@Am1rr3zA, as I noted, I may not have gotten it quite correct, but the general principle should work. If you fix my arange to refer to step_prob instead of step, I get the correct results at least for the first iteration."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:59:24.980",
"Id": "48533",
"ParentId": "48440",
"Score": "9"
}
},
{
"body": "<p>My observations, in terms of implementing this in Python (without regards to improve the algorithm, that will be later):</p>\n\n<ol>\n<li>You are doing a LOT of unnecessary type conversions in Python that you aren't doing in MATLAB. Type conversions are always slow, so this is going to hurt your performance a lot.</li>\n<li>You shouldn't do <code>for k in range(len(bb)):</code>, always iterate over the sequence directly. You can use unpacking to get the values without needing to index in this case.</li>\n<li>You are iterating over <code>range(1, foo+1)</code>, then subtracting one to put it back into Python 0-based indexing. This is an unnecessary mathematical operation, better to do <code>range(foo)</code>, or in your case <code>enumerate(range(1, foo+1))</code>. Better yet, pre-compute your values, then enumerate over those.</li>\n<li><code>numpy.unpackbits</code> is the equivalent of <code>de2bi</code> and will be much faster.</li>\n<li>Python has in-place operations, which will be faster. So <code>a += 1</code> instead of <code>a = a + 1</code>.</li>\n<li>Numpy sums work of flattened arrays by default. Further, summing is a method of numpy arrays, which is simpler and probably faster.</li>\n<li>Numpy arrays are floats by default if created using <code>ones</code> or <code>zeros</code>, but there is a <code>dtype</code> argument that can set it to whatever you want.</li>\n<li>Numpy has a <code>ones_like</code> and <code>zeros_like</code> to create an array of the same shape as another. By default it also creates one with the same dtype, but you can override that.</li>\n<li>PEP8 is the recommended style for python code.</li>\n</ol>\n\n<p>Now, in terms of improving the algorithm:</p>\n\n<ol>\n<li><code>si</code> and <code>sj</code> are not very big (on the order of tens of megabytes, tops). You can vectorize those and re-use the values. In fact, they are identical, so you only need one.</li>\n<li>You not only never use the other values of <code>out_t</code> and <code>out_f</code> besides the current one, you overwrite them repeatedly. So these are better off as scalars.</li>\n<li>You can vectorize many of the values for the two innermost loops.</li>\n<li>If you put the third loop as the outer loop, you can vectorize <code>out_t</code> and <code>out_f</code>.</li>\n</ol>\n\n<p>So here is my partially-vectorized version:</p>\n\n<pre><code>bb0 = np.arange(16, dtype='uint8')\nbb = np.unpackbits(bb0[None], axis=0)[-4:, :].T\n\nstep_prob = 0.01\nstep = int(1/step_prob)\n\npxx = np.linspace(step_prob, 1, step)\npxxt = pxx[:, None]\n\nsx = (1-pxx+pxxt)/2\n\nimprove = np.zeros((step,step))\nfor f4, f3, f2, f1 in bb:\n out_x = f1*pxx*pxxt + f2*pxx*(1-pxxt) + f3*(1-pxx)*pxxt + f4*(1-pxx)*(1-pxxt)\n for ii, (out_t, sxi) in enumerate(izip(out_x, sx)):\n for jj, (out_f, si) in enumerate(izip(out_x, sxi)):\n s = (1-out_f[:, None]+out_t) - np.maximum(si, sxi)\n temp = s*(s>0)*np.tril(np.ones_like(s))\n improve[ii, jj] = temp.sum()\n</code></pre>\n\n<p>It is orders of magnitude faster than your version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-09T14:35:02.813",
"Id": "239160",
"Score": "0",
"body": "your points all are on point"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-06T19:13:47.257",
"Id": "127730",
"ParentId": "48440",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T21:26:07.493",
"Id": "48440",
"Score": "1",
"Tags": [
"python",
"performance",
"matrix",
"numpy",
"matlab"
],
"Title": "Creation of MxM matrix: Python version much slower than Matlab version"
} | 48440 |
<p>I am trying to implement lock by which I don't want to have reads from happening whenever I am doing a write.</p>
<p>Here is my <code>ClientData</code> class in which I am using <code>CountDownLatch</code>:</p>
<pre><code>public class ClientData {
private static final AtomicReference<Map<String, Map<Integer, String>>> primaryMapping = new AtomicReference<>();
private static final AtomicReference<Map<String, Map<Integer, String>>> secondaryMapping = new AtomicReference<>();
private static final AtomicReference<Map<String, Map<Integer, String>>> tertiaryMapping = new AtomicReference<>();
// should this be initialized as 1?
private static final CountDownLatch hasBeenInitialized = new CountDownLatch(1)
public static Map<String, Map<Integer, String>> getPrimaryMapping() {
try {
hasBeenInitialized.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return primaryMapping.get();
}
public static void setPrimaryMapping(Map<String, Map<Integer, String>> map) {
primaryMapping.set(map);
hasBeenInitialized.countDown();
}
public static Map<String, Map<Integer, String>> getSecondaryMapping() {
try {
hasBeenInitialized.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return secondaryMapping.get();
}
public static void setSecondaryMapping(Map<String, Map<Integer, String>> map) {
secondaryMapping.set(map);
hasBeenInitialized.countDown();
}
public static Map<String, Map<Integer, String>> getTertiaryMapping() {
try {
hasBeenInitialized.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return tertiaryMapping.get();
}
public static void setTertiaryMapping(Map<String, Map<Integer, String>> map) {
tertiaryMapping.set(map);
hasBeenInitialized.countDown();
}
}
</code></pre>
<p>I need to wait on the <code>get</code> calls on three <code>AtomicReferences</code> I have. Once all the writes has been done on the three <code>AtomicReferences</code> I have with the <code>set</code> call, I'll allow making the call to three getters which I have.</p>
<p>I decided to use <code>CountDownLatch</code> which I have initialized as <code>1</code>. Do I need to initialize it to <code>3</code>? And every time before I do the first set on a new update, should I need to reset the countdown latch back to 3? I will be setting those three <code>AtomicReferences</code> in three separate statements.</p>
<p>Is there something wrong here? Some other threads have to read the data from these <code>AtomicReferences</code> once they have been set.</p>
<p>Here is my background thread code which will get the data from the URL, parse it and store it in a <code>ClientData</code>class variable:</p>
<pre><code>public class TempScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void startScheduler() {
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
callServers();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 0, 10, TimeUnit.MINUTES);
}
}
// call the servers and get the data and then parse
// the response.
private void callServers() {
String url = "url";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
parseResponse(response);
}
// parse the response and store it in a variable
private void parseResponse(String response) {
//...
ConcurrentHashMap<String, Map<Integer, String>> primaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> secondaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> tertiaryTables = null;
//...
// store the data in ClientData class variables which can be
// used by other threads
ClientData.setPrimaryMapping(primaryTables);
ClientData.setSecondaryMapping(secondaryTables);
ClientData.setTertiaryMapping(tertiaryTables);
}
}
</code></pre>
<p>Is there any better way of doing this? Also, is there any way I can use one latch instead of three separate latches here?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:39:15.697",
"Id": "85027",
"Score": "0",
"body": "Is this a Bean or something (i.e. why do you need three setters... can't you `setMappings(primary, secondary, tertiary)`) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:59:11.513",
"Id": "85031",
"Score": "0",
"body": "@rolfl: I have updated the question. Can you take a look whether that's what you were suggesting? And with the above code, I can use `countdownlatch` as 1, right? I still doubt whatever I did is right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:13:12.750",
"Id": "85051",
"Score": "0",
"body": "From your code it seems that the background thread will be _overwriting_ the maps every so often. Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:23:03.167",
"Id": "85053",
"Score": "0",
"body": "@David: Not everytime, only whenever there is any change. For the first time, when the code is run, then it will add the values in the map. And then after that, whenever there is any change then only it will update those maps and that change will happen only once in three months max. So that means if the code is running for three months, and if we decide to change something on the service url which my background thread is parsing, and if there is any change, then only it will update those three maps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:27:57.187",
"Id": "85055",
"Score": "0",
"body": "@Webby One change every three months is more than none which means this code must accept a new set of maps at any time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:33:23.827",
"Id": "85057",
"Score": "0",
"body": "@DavidHarkness: By `this code`, you mean to say `ClientData` class. Right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:00:14.730",
"Id": "85072",
"Score": "0",
"body": "For iterative reviews, [please post a separate question](http://meta.codereview.stackexchange.com/questions/1763). I have rolled back to Rev 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:06:54.517",
"Id": "85074",
"Score": "0",
"body": "@200_success: Sure I will do that. Thanks for letting me know."
}
] | [
{
"body": "<p>AtomicReferences are a great construct when you have just one item that needs to be kept in a sane state ina multithreaded environment. Your code is trying to juggle three, and ensure they all have a sane state at the right times, and, for that, you need something bigger than the AtomicReference.</p>\n\n<p>You have elected to use the CountDownLatch. This, frankly, in this situation, is not the right choice. The right choice is to use basic synchronization, or to use a ReentrantLock.</p>\n\n<p>I have taken the liberty of rewriting your class using a Lock, with a dependent Condition, and no other java.util.* components.</p>\n\n<p>This code waits for all three maps to be set, and, when they are, it signals the Condition, and the getters are 'released'.</p>\n\n<pre><code>import java.util.Map;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\n@SuppressWarnings(\"javadoc\")\npublic class ClientData {\n\n private static final class MapContainer {\n private Map<String, Map<Integer, String>> value = null;\n\n public Map<String, Map<Integer, String>> getValue() {\n return value;\n }\n\n public void setValue(Map<String, Map<Integer, String>> value) {\n this.value = value;\n }\n\n }\n\n private static final MapContainer primaryMapping = new MapContainer();\n private static final MapContainer secondaryMapping = new MapContainer();\n private static final MapContainer tertiaryMapping = new MapContainer();\n private static final MapContainer[] containers = {primaryMapping, secondaryMapping, tertiaryMapping};\n private static boolean allset = false;\n private static final Lock lock = new ReentrantLock();\n private static final Condition allsetnow = lock.newCondition();\n\n private static final Map<String, Map<Integer, String>> getMapping(MapContainer container) {\n lock.lock();\n try {\n while (!allset) {\n allsetnow.await();\n }\n return container.getValue();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt(); // reset interruptedd state.\n throw new IllegalStateException(e);\n } finally {\n lock.unlock();\n }\n\n }\n\n private static final void setMapping(MapContainer container, Map<String, Map<Integer, String>> value) {\n if (value == null) {\n throw new IllegalArgumentException(\"Null Map cannot be used\");\n }\n lock.lock();\n try {\n if (allset) {\n throw new IllegalStateException(\"All the maps are already set\");\n }\n if (container.getValue() != null) {\n throw new IllegalArgumentException(\"Cannot change the value in a mapping\");\n }\n container.setValue(value);\n for (MapContainer cont : containers) {\n if (cont.getValue() == null) {\n // not all values are set....\n return;\n }\n }\n allset = true;\n allsetnow.signalAll();\n } finally {\n lock.unlock();\n }\n }\n\n public static Map<String, Map<Integer, String>> getPrimaryMapping() {\n return getMapping(primaryMapping);\n }\n\n public static void setPrimaryMapping(Map<String, Map<Integer, String>> map) {\n setMapping(primaryMapping, map);\n }\n\n public static Map<String, Map<Integer, String>> getSecondaryMapping() {\n return getMapping(secondaryMapping);\n }\n\n public static void setSecondaryMapping(Map<String, Map<Integer, String>> map) {\n setMapping(secondaryMapping, map);\n }\n\n public static Map<String, Map<Integer, String>> getTertiaryMapping() {\n return getMapping(tertiaryMapping);\n } \n\n public static void setTertiaryMapping(Map<String, Map<Integer, String>> map) {\n setMapping(tertiaryMapping, map);\n } \n}\n</code></pre>\n\n<p>It would be better if, instead of three separate <code>set*</code> methods, you had just one method that set all three maps.... if you did, the code would look simpler, like:</p>\n\n<pre><code> public static void setAllMappings(Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary) {\n lock.lock();\n try{\n if (allset) {\n throw new IllegalStateException(\"Maps already set\");\n }\n primaryMapping.setValue(primary);\n secondaryMapping.setValue(secondary);\n tertiaryMapping.setValue(tertiary);\n allset = true;\n allsetnow.signalAll();\n } finally {\n lock.unlock();\n }\n }\n</code></pre>\n\n<p>Other problems in your code are:</p>\n\n<ul>\n<li>your use of the CountDownLatch should have started at <code>3</code></li>\n<li>it is a problem if the same setter is called twice (will reach 0 before all maps are set)</li>\n<li>When handling InterruptedException, you should leave the thread in an appropriate state. In your case, by catching it, and wrapping it in a RuntimeException, you should also reset the interrupted state of the thread.</li>\n</ul>\n\n<p><strong>Edit:</strong></p>\n\n<p>If you were to adjust the way you set the values in the AtomicReference, then the Concerns I have with the CountDownLatch would be mitigated. Consider the following:</p>\n\n<pre><code>public static void setPrimaryMapping(Map<String, Map<Integer, String>> map) {\n if (map != null && primaryMapping.compareAndSet(null, map)) {\n hasBeenInitialized.countDown();\n } else {\n throw new IllegalSateException(\"Map has already been set... cannot double-set it\");\n }\n}\n</code></pre>\n\n<p>The above will mean that each Map can be set only once, and the countdownlatch will work well enough (if initialized with <code>3</code>).</p>\n\n<p>Note that with the CountDown latch, and 3 AtomicReferences, that you have 4 locks that all need to work together, when really, the only one that is important for the actual acess restrictions is the CountDownLatch. That is the reason I don't like the solution with the atomics, and the latch, because the same can be accomplished with just a single lock, which applies the access and concurrency restrictions in a more consistent/logical way.</p>\n\n<p><strong>Edit 2</strong></p>\n\n<p>Simple traditional synchronization mechanism.</p>\n\n<pre><code>import java.util.Map;\n\n@SuppressWarnings(\"javadoc\")\npublic class ClientData {\n\n private static Map<String, Map<Integer, String>> primaryMap = null;\n private static Map<String, Map<Integer, String>> secondaryMap = null;\n private static Map<String, Map<Integer, String>> tertiaryMap = null;\n private static boolean allset = false;\n private static final Object synclock = new Object();\n\n private static final void waitTillSet() {\n try {\n while (!allset) {\n synclock.wait();\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IllegalStateException(e);\n }\n }\n\n public static void setAllMappings(Map<String, Map<Integer, String>> primary, \n Map<String, Map<Integer, String>> secondary, \n Map<String, Map<Integer, String>> tertiary) {\n synchronized (synclock) {\n if (allset) {\n return; // throw exception otherwise.\n }\n primaryMap = primary;\n secondaryMap = secondary;\n tertiaryMap = tertiary;\n allset = true;\n synclock.notifyAll();\n }\n }\n\n public static Map<String, Map<Integer, String>> getPrimaryMapping() {\n synchronized (synclock) {\n waitTillSet();\n return primaryMap;\n }\n }\n\n public static Map<String, Map<Integer, String>> getSecondaryMapping() {\n synchronized (synclock) {\n waitTillSet();\n return secondaryMap;\n }\n }\n\n public static Map<String, Map<Integer, String>> getTertiaryMapping() {\n synchronized (synclock) {\n waitTillSet();\n return tertiaryMap;\n }\n } \n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:37:58.430",
"Id": "85037",
"Score": "0",
"body": "@Webby - the first block of code is compatible with what you originally posted. It has three separate `set*Mapping(Map...)` calls. The second block of code is an alternate mechanism that sets all three at once, and does not need to check if the others have been set.... You should either use the code as it is in the first block, or, replace the three `set*Mapping` methods in the first block with the one `setAllMappings(...)` in the second block"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:53:25.220",
"Id": "85040",
"Score": "0",
"body": "Yup.. I figure that one out after taking a close look at the code. In general what is the benefit of `ReentrantLock` as compared to I was using `CountDownLatch` earlier? And here `ReentrantLock` means, that as soon as the write is done on those three maps, then only you will be able to read the data from those three maps, right? And again, if the writes are happening to those three tables, then the call will be blocked and whenever the writes are done, then the thread will be able to read the data again using the getters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:00:55.750",
"Id": "85042",
"Score": "0",
"body": "@Webby - Hmmm ... those are huge things to answer.... The big problem I have with the countdownLatch is the unsafe setting... you can set the same map 3 times, and trigger the getters... Let me add an update to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:20:17.767",
"Id": "85045",
"Score": "0",
"body": "Thanks. In this case also with `ReentrantLock`, once the first write is done on all three tables, then there won't be any locking happening on the get calls, Right? Only for the first write to those three tables, there will be a locking on `get` calls to those three tables otherwise there won't be any?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:22:12.230",
"Id": "85046",
"Score": "1",
"body": "There will always be locking on the `get*(...)` calls, (whether with the CountdownLatch or the ReentrantLock). There will only be ***blocking*** if the gets are called before all three sets are called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T00:26:22.340",
"Id": "85047",
"Score": "0",
"body": "Thanks a lot for the help. That makes sense. And I am definitely thinking to go with `ReentrantLock` as in my case performance is really really important. So I can safely assume, for the first `set` to all three tables, all three `gets` will be **blocked** for sure. And as soon as the `set` is done on all three tables, then there won't be any **blocking** on the get calls? Right?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:18:55.973",
"Id": "48446",
"ParentId": "48442",
"Score": "4"
}
},
{
"body": "<p>The fact that you must be able to swap in a new set of maps at any time--even if only once every three months--requires a design change. Here are the requirements as I understand them:</p>\n\n<ul>\n<li>Reads block until all three maps have been set the first time.</li>\n<li>Reads receive a consistent set of maps. In other words, you cannot return the old secondary map after returning the new primary map.</li>\n</ul>\n\n<p>Taken together, you really must combine the maps into a new data structure which is returned to clients and replaced in whole by the background thread. Storing it in its own atomic reference allows this new class to avoid concurrency and locks altogether.</p>\n\n<ul>\n<li>Keep the latch to block reads before the first set of maps have been loaded.</li>\n<li>Combine the three maps in a simple data holder.</li>\n<li>Store the data holder in an atomic reference (if necessary) instead of each map individually.</li>\n<li>Set all three maps in one call by storing a new data holder instance. Since all three are stored in one call, the latch can use an initial count of 1.</li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<p>Now let's throw some code behind the above changes.</p>\n\n<pre><code>public class ClientData {\n\n public static class Mappings {\n public final Map<String, Map<Integer, String>> primary;\n public final Map<String, Map<Integer, String>> secondary;\n public final Map<String, Map<Integer, String>> tertiary;\n\n public Mappings(\n Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary\n ) {\n this.primary = primary;\n this.secondary = secondary;\n this.tertiary = tertiary;\n }\n }\n\n private static final AtomicReference<Mappings> mappings = new AtomicReference<>();\n private static final CountDownLatch hasBeenInitialized = new CountDownLatch(1);\n\n public static Mappings getMappings() {\n try {\n hasBeenInitialized.await();\n return mappings.get();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt(); // @rolfl covered this\n throw new IllegalStateException(e);\n }\n }\n\n public static void setMappings(\n Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary\n ) {\n setMappings(new Mappings(primary, secondary, tertiary));\n }\n\n public static void setMappings(Mappings newMappings) {\n mappings.set(newMappings);\n hasBeenInitialized.countDown();\n }\n}\n</code></pre>\n\n<p>There are some other improvements I would suggest but did not implement.</p>\n\n<ul>\n<li>Avoid using static methods when possible to ease testing and alternate implementations.</li>\n<li>The atomic reference may not actually be required since both get and set operations synchronize on <code>hasBeenInitialized</code>.</li>\n<li>If clients of <code>ClientData</code> can handle receiving empty mappings, you can drop the latch and initialize the class with three empty maps. This would reduce all synchronization to the atomic reference.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:46:17.620",
"Id": "85058",
"Score": "0",
"body": "For your second point, Yes, I can still return old map while I am updating the maps second time. But as soon the update is done, I should return new maps value. Sorry for the confusion if I was not clear earlier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:49:58.687",
"Id": "85060",
"Score": "0",
"body": "But is it okay to return the new first map and the old second/third map to the same caller? If they are related, you should return either all old maps or new maps--never a random mix of the two _to the same caller_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:52:00.247",
"Id": "85061",
"Score": "0",
"body": "No. In that case, it should either return all the old maps or all the new maps , not intermix of it. Right now I am using @rolfl suggestion which uses the `ReentrantLock`. Do you think this use case will be solve by that or there will be any problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T02:21:58.360",
"Id": "85062",
"Score": "0",
"body": "@Webby My understanding of rolfl's code is that it doesn't allow setting a new trio of maps. Did I miss something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T02:39:16.927",
"Id": "85063",
"Score": "0",
"body": "He has the set calls right which I can use to set them up?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:10:06.217",
"Id": "85065",
"Score": "0",
"body": "No, this code blocks changing the set of maps once set: `throw new IllegalStateException(\"All the maps are already set\");`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:37:44.510",
"Id": "85150",
"Score": "0",
"body": "@Webby See my update with code. I'll hang out in chat for a bit, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-10T05:36:44.840",
"Id": "155895",
"Score": "0",
"body": "hey are you around? I have a basic question on this solution. It's been a long time and I am still using it in production. I had some confusion so wanted to check on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-10T15:23:05.157",
"Id": "155990",
"Score": "0",
"body": "@lining Sure, what's your question?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T01:42:19.440",
"Id": "48450",
"ParentId": "48442",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48450",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T22:20:38.303",
"Id": "48442",
"Score": "6",
"Tags": [
"java",
"performance",
"multithreading",
"rest",
"atomic"
],
"Title": "Lock for preventing concurrent access in client data"
} | 48442 |
<p>I had a task to create a responsive HTML5/CSS3 page based on PSD layout. I got rejected and when asked for details I got these comments:</p>
<ul>
<li>semantically incorrect HTML</li>
<li>incorrect use of ID selectors in CSS</li>
<li>incorrect general way of solving given CSS problems</li>
</ul>
<p>The link is <a href="http://www.tanadsplinare.com.hr/tmp/v2/">here</a></p>
<p><strong>HTML:</strong></p>
<pre><code><!doctype html>
<html lang="hr">
<head>
<meta charset="utf-8" />
<title>Lorem ipsum</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/style.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans&amp;subset=latin,latin-ext' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="js/jquery.bxslider/jquery.bxslider.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/jquery.bxslider/jquery.bxslider.min.js" type="text/javascript"></script>
<script src="http://maps.googleapis.com/maps/api/js?&sensor=false" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
<!--[if lt IE 8]>
<div style=' clear: both; text-align:center; position: relative;'>
<a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
<img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." />
</a>
</div>
<![endif]-->
<!--[if lt IE 9]>
<script src="js/html5.js"></script>
<link rel="stylesheet" href="css/ie.css" />
<![endif]-->
</head>
<body>
<div id="divMain" class="div_base">
<!-- header -->
<div id="divHeaderHolder" class="div_base">
<header class="div_base">
<div id="divLogo">
<a href="#"><img src="images/logo.png" alt="" title="" /></a>
</div>
<div id="divHeadRight">
<div class="head_tel">Toll Free Number: <a href="tel:0800000000" class="a_head_tel">0800 00 00 00</a></div>
<div class="head_links_holder">
<a href="#" id="aLocate">Locate me</a>
<a href="#" id="aProfil">My Profile</a>
<a href="#" id="aFB"></a>
<a href="#" id="aTW"></a>
</div>
</div>
</header>
<nav class="div_base">
<a href="#" id="aHome" class="underline">Home</a>
<a href="#" class="underline menu_color menu_bg_color">Page Link 1</a>
<a href="#" class="underline menu_color menu_bg_color">Page Link 2</a>
<a href="#" class="underline menu_color menu_bg_color">Page Link 3</a>
<div id="divMenuMobile"><a href="#" id="aMenuMobile"></a></div>
<form>
<input type="search" id="txt_search" placeholder="Search..." class="div_base menu_color" />
</form>
<div id="divAutocomplete"></div>
</nav>
</div>
<!-- /header -->
<!-- main slider -->
<div id="divSliderMainHolder" class="div_base">
<div id="divSliderMain" class="div_base">
<ul id="ulSliderMain">
<li><img src="images/slider1.jpg" alt="" /></li>
<li><img src="images/slider1.jpg" alt="" /></li>
<li><img src="images/slider1.jpg" alt="" /></li>
<li><img src="images/slider1.jpg" alt="" /></li>
</ul>
</div>
</div>
<!-- /main slider -->
<!-- content -->
<div id="divContentHolder" class="div_base">
<section class="div_base">
<div id="divCnt" class="div_base">
<div class="news_item">
<div class="news_imgholder">
<a href="#"><img src="images/news_img1.jpg" alt="" /></a>
</div>
<div class="news_date">17.04.2014.</div>
<div class="news_title"><a href="#" class="underline">Typi non habent claritatem insitam</a></div>
<div class="news_descr">
čćžšđ ČĆŽŠĐ Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed...
</div>
<div class="news_bottom">
<div class="news_bottom_left div_base"></div>
<div class="news_bottom_right">
<a href="#" class="news_more"></a>
</div>
</div>
</div>
<div class="news_item">
<div class="news_imgholder">
<a href="#"><img src="images/news_img2.jpg" alt="" /></a>
</div>
<div class="news_date">02.12.2013.</div>
<div class="news_title"><a href="#" class="underline">Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem.</a></div>
<div class="news_descr">
Lorem ipsum dolor sit amet, <a href="#">consectetuer adipiscing elit</a>, sed
enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
</div>
<div class="news_bottom">
<div class="news_bottom_left div_base"></div>
<div class="news_bottom_right">
<a href="#" class="news_more"></a>
</div>
</div>
</div>
<div class="news_item">
<div class="news_imgholder">
<a href="#"><img src="images/news_img3.jpg" alt="" /></a>
</div>
<div class="news_date">01.12.2013.</div>
<div class="news_title"><a href="#" class="underline">Typi non habent claritatem insitam</a></div>
<div class="news_descr">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed...
</div>
<div class="news_bottom">
<div class="news_bottom_left div_base"></div>
<div class="news_bottom_right">
<a href="#" class="news_more"></a>
</div>
</div>
</div>
</div>
<div id="divSidebar">
<div id="divSideSlider">
<div class="sidebar_item">
<img src="images/sidebar1.jpg" alt="" />
</div>
<div class="sidebar_item">
<img src="images/sidebar2.jpg" alt="" />
</div>
</div>
</div>
</section>
</div>
<!-- /content -->
<!-- footer -->
<div id="divFooterHolder" class="div_base">
<footer class="div_base">
<div id="divFooterLeft">
This site is powered by...
</div>
<div id="divFooterRight">
Design & Technology: D.S.
</div>
</footer>
</div>
</div>
<div id="RWDMenu"></div>
<!-- some general stuff: back to top, custom alert box, ajax preloader... -->
<a href="#top" id="aBackTop"></a>
<div id="divAlertHolder" class="div_base"><div id="divAlert"></div></div>
<div id="divPreloaderholder" class="div_base"><div id="divPreloader"></div></div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>* {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
background: #fff;
}
img, embed, object, video {
max-width: 100%;
}
a {
text-decoration: none;
color: #000;
}
a:hover {
text-decoration: underline;
}
.underline:hover {
border-bottom: 2px solid #C4C8CC;
text-decoration: none;
}
/* for various elements due to OOCSS */
.div_base {
position: relative;
width: 100%;
}
.menu_color {
color: #8F8F8F;
}
.menu_bg_color {
background-color: #F4F4F4;
}
/* ===================================== */
/* all main content, menus, footer... are grouped in divMain in order to slide left navigation */
#divMain {
margin: 0 auto;
z-index: 20;
}
/* this is menu below for smartphones */
#RWDMenu {
position: absolute;
top: 0; left: 0;
z-index: 10;
}
/* ===================================== */
/* Header */
#divHeaderHolder {
height: auto;
background-color: #333333;
-webkit-box-shadow: 0px 18px 20px 0px rgba(0, 0, 0, 0.25);
box-shadow: 0px 18px 20px 0px rgba(0, 0, 0, 0.25);
z-index: 30;
}
header {
margin: 0 auto;
max-width: 1144px;
min-height: 107px;
height: auto;
color: #fff;
font-size: 11px;
}
#divLogo {
position: relative;
display: block;
float: left;
padding-top: 17px;
}
#divHeadRight {
position: relative;
float: right;
padding: 17px 19px 0 0;
font-size: 11px;
color: #fff;
text-transform: uppercase;
}
#divHeadRight a {
color: #fff;
}
.head_tel {
position: relative;
color: #F0F0F0;
text-align: right;
}
.a_head_tel {
position: relative;
top: -5px;
font-size: 16px;
}
.a_head_tel:hover {
text-decoration: none;
}
.head_links_holder {
position: relative;
display: block;
margin-top: 25px;
text-align: right;
}
#aLocate {
display: inline-block;
position: relative;
margin-right: 17px;
background: url(../images/icon_googlemap.png) no-repeat right top;
height: 30px;
padding: 7px 30px 0 0;
}
#aLocate:hover {
background-position: right -30px;
}
#aProfil {
display: inline-block;
margin-right: 42px;
padding-top: 7px;
}
#aFB {
display: inline-block;
position: relative;
background: url(../images/icon_fb.png) no-repeat 0 0;
width: 30px; height: 30px;
margin-right: 14px;
text-indent: -9999px;
}
#aFB:hover {
background-position: 0 -30px;
}
#aTW {
display: inline-block;
position: relative;
background: url(../images/icon_tw.png) no-repeat 0 0;
width: 30px; height: 30px;
text-indent: -9999px;
}
#aTW:hover {
background-position: 0 -30px;
}
nav {
display: table;
max-width: 1144px;
height: 52px;
margin: 0 auto;
}
nav > a {
display: table-cell;
width: 150px;
white-space: nowrap;
height: 52px;
padding: 14px 50px 12px 50px;
border-right: 1px solid #C2C2C2;
font-size: 18px;
text-transform: uppercase;
}
#aMenuMobile {
display: block;
background: url(../images/menu_mobile.png) no-repeat 0 0;
width: 25px; height: 25px;
text-indent: -9999px;
}
#divMenuMobile {
display: none;
}
#aHome {
display: table-cell;
background: url(../images/icon_home.png) no-repeat 0 0;
width: 106px; height: 52px;
text-indent: -9999px;
}
#aHome:hover:after {
content:'';
position: absolute;
top: 0; left: 0;
width: 106px; height: 52px;
background: rgba(0, 0, 0, 0.2);
}
#txt_search {
height: 52px;
background: #EEE9E9;
box-shadow: inset 7px 7px 15px 0px rgba(0, 0, 0, 0.25);
border: 0;
font-style: italic;
font-size: 24px;
padding: 15px;
}
#divAutocomplete {
position:absolute;
display: none;
width: 500px; height: 200px;
border: 1px solid #ccc;
background-color: #fff;
}
.ul_autocomplete {
list-style: none;
padding: 0;
margin: 0;
}
.li_autocomplete {
padding: 5px;
background-color: #ABABAB;
color:#000;
border-bottom: 1px solid #ccc;
cursor: pointer;
}
.li_autocomplete:hover {
background-color: #000;
color:#fff;
}
/* Main Slider */
#divSliderMainHolder {
background-color: #fff;
}
#divSliderMain {
max-width: 1144px;
padding: 31px 28px 44px 28px;
margin: 0 auto;
}
/* Content elements */
#divContentHolder {
margin-top: -50px;
background-color: #F9F8F6;
border-top: 1px solid #D9D9D8;
border-bottom: 1px solid #D9D9D8;
}
section {
display: table;
max-width: 1144px;
padding: 40px 28px 47px 28px;
margin: 0 auto;
}
#divCnt {
display: table-cell;
max-width: 805px;
padding-right: 28px;
}
/* news */
.news_item {
clear: both;
min-height: 176px;
margin-bottom: 29px;
}
.news_imgholder {
float: left;
width: 158px; height: 142px;
margin: 0 27px 10px 0;
padding-left: 16px;
background-color: #EEEEEE;
overflow: hidden;
}
.news_imgholder img:hover {
opacity: .7;
}
.news_date {
color: #ABABAB;
font-size: 13px;
font-weight: bold;
}
.news_title {
color: #000;
font-size: 24px;
line-height: 35px;
margin-bottom: 10px;
}
.news_descr {
color: #6C6C6C;
font-size: 16px;
line-height: 25px;
}
.news_more {
display: block;
position: relative;
background: url(../images/icon_more.png) no-repeat 0 0;
width: 42px; height: 42px;
text-indent: -9999px;
}
.news_more:hover:after {
content:'';
position: absolute;
top: 0; left: 0;
width: 42px; height: 42px;
background: rgba(0, 0, 0, 0.2);
}
.news_bottom {
display: table;
}
.news_bottom_left {
display: table-cell;
height: 42px;
border-bottom: solid 1px #C4C8CC;
}
.news_bottom_right {
display: table-cell;
width: 64px; height: 42px;
padding-left: 22px;
}
/* sidebar */
#divSidebar {
display: table-cell;
width: 251px;
}
.sidebar_item {
margin-bottom: 20px;
width: 251px;
}
/* Footer */
#divFooterHolder {
background-color: #fff;
}
footer {
margin: 0 auto;
display: table;
max-width: 1144px;
height: 66px;
}
#divFooterLeft {
display: table-cell;
vertical-align: middle;
padding-left: 28px;
}
#divFooterRight {
display: table-cell;
vertical-align: middle;
text-align: right;
padding-right: 28px;
}
/* some general stuff: back to top, custom alert box, ajax preloader... */
#aBackTop {
display: none;
position: fixed;
right: 10px; bottom: 50px;
background: url(../images/icon_up.png) no-repeat 0 0;
width: 42px; height: 42px;
text-indent: -9999px;
margin: 0;
z-index: 99;
}
#aBackTop:hover:after {
content:'';
position: absolute;
top: 0; left: 0;
width: 42px; height: 42px;
background: rgba(0, 0, 0, 0.2);
}
#divAlertHolder {
position: fixed;
top: 0; left: 0;
z-index: 99;
}
#divAlert {
display: none;
position: relative;
margin: 100px auto;
width: 80%; height: 400px;
color: #000;
background-color: #fff;
border: 1px solid #C4C8CC;
-webkit-box-shadow: 4px 4px 15px #333;
box-shadow: 4px 4px 15px #333;
text-align: center;
}
#divPreloaderholder {
position: fixed;
top: 0; left: 0;
z-index: 99;
}
#divPreloader {
display: none;
position: relative;
margin: 100px auto;
width: 48px; height: 48px;
background: url(../images/preloader.gif) no-repeat 0 0;
}
@media screen and (max-width: 1024px) {
/* ipad horizontal */
/* menu bar appears for mobile */
nav > a, #aHome {
display: none;
}
#divMenuMobile {
display: table-cell;
width: 52px; height: 52px;
padding: 13px;
}
#txt_search {
display: block;
width: 40%;
min-width: 207px;
}
#RWDMenu a {
display: block;
width: 250px;
white-space: normal;
min-height: 52px; height: auto;
padding: 14px 16px 12px 16px;
border-right: 1px solid #C2C2C2;
border-bottom: 1px solid #C2C2C2;
font-size: 18px;
text-transform: uppercase;
}
}
@media screen and (max-width: 700px) {
/* head right elements go below */
#divLogo {
float: none;
clear: both;
}
#divHeadRight {
float: none;
clear: both;
margin-left: 16px;
}
.head_tel {
text-align: left;
}
.a_head_tel {
font-size: 16px;
}
.head_links_holder {
margin: 10px 0 10px 0;
text-align: left;
}
#aLocate, #aProfil, #aFB, #aTW {
margin-right: 3px;
}
#divCnt {
display: block;
padding-right: 0;
}
#divSidebar {
display: block;
}
footer {
font-size: 12px;
}
#divAlert {
margin-top: 200px;
height: 250px;
}
}
</code></pre>
<p>Maybe I could use <code>article</code> instead of <code>section</code> or within a <code>section</code>, but is it really such a mistake, or I don't see a big picture? Please help me out by pointing out what I do wrong, because obviously I am going in a wrong direction in learning HTML5/CSS3, and if it's not too wide issue, what should I correct?</p>
| [] | [
{
"body": "<p>Several things that would cause me to reject this:</p>\n\n<ul>\n<li><p><strong>Nearly every element on the page is a <code><div></code>.</strong></p>\n\n<p><code><div></code> is semantically void. It says nothing about the structure of the document, other than that \"there's a block here\". (Except that they're not quite even that, cause you've repurposed a few of them as table cells.)</p>\n\n<p>A huge number of those divs could be replaced with elements that are more semantically correct. </p>\n\n<ul>\n<li>Those <code><div class=\"news_item\"></code> could be <code><article></code>s.</li>\n<li>For lists of links (like in your header)...note how i said \"list\". :P <code><nav></code> would work too.</li>\n<li><code><div class=\"news_date\"></code> could be a <code><time></code>.</li>\n</ul>\n\n<p>You also have \"container\" elements that by design only contain one element -- which itself is a container. I tend to consider that broken, except in very rare cases.</p></li>\n<li><p><strong>Your use of IDs and class names is broken.</strong></p>\n\n<ul>\n<li><p>I can almost forgive giving nearly every freaking element in the page an ID and/or class. Not quite, but almost. In my opinion, there should be a reason to distinguish these elements. Don't give stuff an ID or class just because you can. It adds noise.</p>\n\n<p>And the performance argument is an example of premature optimization. You're mucking up the HTML over a couple of milliseconds at best. Was your page slow without all those IDs? (Hint: No.) Don't \"optimize\" for the sake of doing so, or because some schmuck online said this is how $BIG_COMPANY does it, or whatever. Do it because you've determined it matters in your case. <em>When</em> it matters.</p></li>\n</ul>\n\n<p>The whole point of separating content from presentation, though, is so that the two don't get intertwined. HTML structures the document, CSS determines how it looks, and either one can change independently of the other.</p>\n\n<p>And with this code:</p>\n\n<ul>\n<li><p>The class names are often presentational. <code>underline</code>? Really? So if i don't want links to be underlined, i have to edit that class name out of the HTML?</p>\n\n<p>The problem here is that you're embedding assumptions about formatting. There is a <em>reason</em> you want these links underlined. Boil that reason down to a class name and use that instead.</p></li>\n<li><p>What's worse, your IDs embed the actual <em>element names</em> in them. So if i ever do go to make this less of a semantic mess, now i have to go and edit the CSS too.</p></li>\n</ul>\n\n<p>You've largely tossed that separation out the window. Now, any significant change -- to either the structure <em>or</em> the layout -- will probably have to be made in two places.</p>\n\n<p>(By the way, <code>Cnt</code> isn't much of an ID either. Don't abbreviate short single words.)</p></li>\n<li><p>Those conditional chunks of HTML. In your header. I'm not going to say <em>too</em> much about that, cause you're at least trying to help the poor souls still using IE 6-8. But the header is for metadata, scripts, and stylesheets. There shouldn't be any visible content.</p></li>\n<li><p>A minor quibble, because this is obviously a sample. But the logo -- which is solely text -- has no <code>alt</code> text. So a spider or blind person wouldn't even know the company name.</p></li>\n<li><p>Those link-buttons. Let me get this out of the way: it seems broken to me to have a link with no content. Consider what happens if the stylesheet doesn't load, or the user is blind or is actually a search engine's spider. You know what they see? <em>Not a whole lot.</em></p></li>\n</ul>\n\n<hr>\n\n<p>As for the CSS...most of my issues with it are more with the HTML it's trying to style. But:</p>\n\n<ul>\n<li><p>The page links have a hover effect that's not consistent with the rest of the page. Other links like that, you shade them. I was about to call that a bug, til i saw it was intentional. :P Keep it consistent.</p></li>\n<li><p>You do a lot of fiddling around with margins and padding. That'd be OK if the numbers were consistent, or if the reason behind it were obvious, but it looks quite arbitrary -- to the point where in some places, in <code>#divSliderMain</code> for example, it seems like you just tweaked numbers til they fit. That hints to me that this design is quite temperamental, and is going to be a pain if i try to modify it in any significant way.</p></li>\n<li><p>Take a look at the CSS for your header links. All of them share some common properties, and the two social-media icons are nearly identical (the only difference being their background images). Is there really not enough similarity there to come up with some common class?</p></li>\n<li><p><code>height: auto</code> is the default. If you don't override it elsewhere, then setting it doesn't make much sense. Same with <code>display: block</code> for block elements.</p></li>\n<li><p><code>position: relative</code> doesn't make much sense in most of the places where you've used it. You should only need it when (1) you want absolute-positioned children to position themselves relative to that element, and/or (2) you want to position the element relative to its normal place in the flow.</p></li>\n<li><p>As for the header links: You have three 30x60 images, one per link. The background repositions on hover, which implies you know about CSS sprites. So why make the user download three separate images?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:59:39.580",
"Id": "85188",
"Score": "0",
"body": "CHao, thank you very much for your thorough answer! Since my post is deleted, I'll break it down in 3 short comments:\n\"You also have \"container\" elements that by design only contain one element -- which itself is a container.\"\n\nIt's because I have for example a header that is centered and has fixed width, and I have a header background (holder) that stretches horizontally to infinity. What am I doing wrong here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:00:38.140",
"Id": "85189",
"Score": "0",
"body": "\"I can almost forgive...\"\nI put ID on just those elements I'm sure there's just 1 of them. Should I use class instead of ID, even if I'm sure it's just one element on the page?\nI didn't know it's wrong to apply classes to most elements. If I have 2 or more section, 2 or more article, etc... they should have a class, don't they? Even if I have just one article it could share same font with some other element, wouldn't it be redundant to write that property in CSS for article and that other element, instead of applying class with mutual font to both article and other element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:01:03.227",
"Id": "85190",
"Score": "0",
"body": "\"The class names are often presentational. underline? Really?\"\n\nSo is it just wrong naming convention or the logic? My logic is: I wanted to have common definition for links (not to repeat some mutual properties for different links in CSS), and some of the links to be underlined so I added them that class also. Is the logic OK if I change the class name? (I mean, that kind of logic I've learnt in OOCSS - is it wrong?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:40:48.627",
"Id": "85197",
"Score": "0",
"body": "@Dalibor: Updated to address the last comment, and part of the second. As for the first...i haven't looked all that closely at it yet. It just happens to be a code smell to me -- it's a lot like having a list that'll never contain more than one item."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:22:11.077",
"Id": "85213",
"Score": "1",
"body": "As for \"OOCSS\": It started as a good idea, from what i can tell. I rather like the foundational \"media box\" example. (Note how the class names mean something, and the HTML isn't trying to dictate layout. That's how it ought to be.) But at some point it lost its way, and now the way it is practiced/hyped is fundamentally flawed. When someone's adding a class to specifically say \"this div is 6 grid-columns wide\" or \"this text is aligned right\", they either forgot or never really understood the concept of separating content from presentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:49:14.370",
"Id": "85242",
"Score": "0",
"body": "@Dalibor This related CR might be of interest: http://codereview.stackexchange.com/questions/25968/oocss-is-this-broken-down-too-much"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:22:43.480",
"Id": "85247",
"Score": "0",
"body": "@cimmanon: That just about perfectly sums up my thoughts on the matter too. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:48:32.657",
"Id": "85301",
"Score": "0",
"body": "Thank you, cimmanon for the link. Thank you cHao for the advices.\nI'll try to sum up what I've learned so far, please correct me: - don't use IDs in CSS - use as many descriptive elements as possible such as article, section...instead of div -name classes according to the content not appearance - don't use too much classes (I don't know how to achieve this one though) cHao, you said you have some other comments to say, it's not over yet, is it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:31:39.837",
"Id": "85364",
"Score": "0",
"body": "@Dalibor: Not quite over, but it's not going to be much more. I thought the CSS part was going to be huge...but it turns out i covered a bunch of it by talking about names and IDs. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:04:27.530",
"Id": "85411",
"Score": "0",
"body": "I'd like to add that there is a completely random use of newlines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:22:49.553",
"Id": "85414",
"Score": "0",
"body": "I'm sorry I don't know how to use newlines, I made two spaces as help suggested but still it shows inline. (\"End a line with two spaces to add a <br/> linebreak\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:31:40.320",
"Id": "85427",
"Score": "0",
"body": "Thanks again cHao on your excellent comments and useful advices. There is great sense in most you said and I will not go one-by-one item to confirm I agree, I will just ask you questions on 3 items to clarify if you don't mind: \n \"Those link-buttons. Let me get this out of the way: it seems broken to me to have a link with no content.\"; you're absolutely right and I should put text in link. Just what method should I use? Do I set the text-indent to -9999px as I see others do, would I go with Gilder/Levin method, or something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:32:32.050",
"Id": "85428",
"Score": "0",
"body": "\"You do a lot of fiddling around with margins and padding...\" \nAs I use third party component (slider) that has it's own default padding/margin properties, I have to tweak it, especially as I use it more than once in a different shapes. And yes, many times it's \"tweaking until it fits\"; I don't see another way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:33:16.470",
"Id": "85429",
"Score": "0",
"body": "\"Take a look at the CSS for your header links. All of them share some common properties...\": Again you are right and I usually use this guidance (remember my class \"underline\" - although wrong naming).\nHowever! If I have 10 links with common class, let's say that class has background-color green. At one point I decide that one of those links will have yellow background. Now I would be forced to change HTML, to remove common class from that element, wouldn't I? And anyway the separation of content/presentation is broken again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T19:24:59.667",
"Id": "85514",
"Score": "0",
"body": "You could say `text-indent: -9999px`, and it will work, but to me it's always had a dirty keyword-spammer feel to it. There's also that big (un)magic number, whose value hardly even matters as long as it's large...and the browser ends up having to account for content that's thousands of pixels away. You might take a look at http://stackoverflow.com/q/12783419/319403 ; it mentions a couple of better ways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:20:01.863",
"Id": "85521",
"Score": "0",
"body": "For an illustration of what i'm talking about with the padding/margins, inspect `#divSliderMain` using Chrome's dev tools. (Mouse over the HTML for it to highlight the box spacing.) The padding causing issues here is yours. Note how it cuts into `#divContentHolder`'s space. But rather than fix that, you just set a negative margin on `#divContentHolder`. (A margin, by the way, that overcompensates for the padding you added.) See what happens when you simply let both be 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T21:06:51.333",
"Id": "85528",
"Score": "0",
"body": "As for the links: If you want one particular link highlighted differently from the others, there is a reason -- that link has a meaning that's special/different from the others in some way. (If it doesn't, then the CSS is making one up. That's not its job -- it's what HTML is for. CSS is solely for giving that meaning a concrete representation.) Boil the reason down to a class name, and apply it in the HTML. Then you can style it with CSS...and if other such links ever appear, you already have a ready-made class to apply to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-04T14:49:40.397",
"Id": "85898",
"Score": "0",
"body": "@cHao, I summed up some things you thought me (hopefully I understood it right) and could you please look at it if you're interested: http://webmasters.stackexchange.com/questions/61380/basic-semantic-rules-of-css-and-html-right-or-wrong/61383"
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:36:55.773",
"Id": "48455",
"ParentId": "48444",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "48455",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:04:51.803",
"Id": "48444",
"Score": "6",
"Tags": [
"html",
"css",
"html5"
],
"Title": "Why is my page semantically incorrect HTML and incorrect use of CSS?"
} | 48444 |
<p>So I am working through a few different game ideas as I learn programming, and I could definitely use some feedback on my latest project. This is a simple SimCity clone. So far I have created a City made up of City Tiles objects, and a number of Person objects as well. The Persons are passed from the City Tiles to the City and then on to the next City Tile, so each Tile has a certain number of Persons inside of it. Also different terrain types take longer for Persons to move through. The renderer changes the alpha of the sprite that it draws for the Tile based on the number of persons inside. Right now things just move in a random fashion, but later the Game would assign destination tiles to the Persons based on what was happening in the game.</p>
<p>My main concern is firstly whether or not the way I am doing things makes any sense. I am also concerned with the readability of the code, and following Objective-C best practices.</p>
<p>First here is the SKScene class, with the necessary panning and zooming gestures configured.
PCGameScene.h:</p>
<pre><code>#import <SpriteKit/SpriteKit.h>
//set up for 60 frames per second
#define kMinTimeInterval (1.0f / 60.0f)
@interface PCGameScene : SKScene <UIGestureRecognizerDelegate>
@property (nonatomic) NSTimeInterval lastUpdateTimeInterval;
@property (nonatomic) NSTimeInterval countdownInterval;
@property (nonatomic) NSTimeInterval countdownIntervalRender;
@end
</code></pre>
<p>PCGameScene.m</p>
<pre><code>#import "PCGameScene.h"
#import "PCGame.h"
#import "PCCityTile.h"
#import <GLKit/GLKit.h>
@implementation PCGameScene {
//initialization
PCGame *_game;
CGSize _initialScreenSize;
BOOL _contentCreated;
//scene components
SKNode *_world;
SKNode *_sceneCity;
//hud components
SKNode *_selectedNode;
int _selectedFloor;
//gesture components
UIPinchGestureRecognizer *_pinchRecognizer;
UIPanGestureRecognizer *_panRecognizer;
UISwipeGestureRecognizer *_swipeLeft;
UISwipeGestureRecognizer *_swipeRight;
CGPoint _startingButtonLocation;
CGPoint _previousTouchPoint;
}
#pragma mark - Initialization
-(void) didMoveToView:(SKView *)view {
[self createUIAndRenderer];
[self createSceneElements];
if (!_contentCreated) {
[self createSceneContents];
_contentCreated = YES;
}
}
-(void) createUIAndRenderer {
_initialScreenSize = self.size;
//set up the camera
_world = [[SKNode alloc]init];
[self addChild:_world];
_world.position = CGPointMake(_initialScreenSize.width/2, 0);
//set up the backgrounds
self.backgroundColor = [SKColor whiteColor];
//Set up the gesture recognizers
_panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanFrom:)];
[[self view] addGestureRecognizer:_panRecognizer];
_pinchRecognizer = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)];
[[self view] addGestureRecognizer:_pinchRecognizer];
_panRecognizer.delegate = self;
_pinchRecognizer.delegate = self;
_panRecognizer.maximumNumberOfTouches = 1;
//Set up the texture atlases here later
//create the hud
[self buildHud];
}
-(void) createSceneElements {
_sceneCity = [[SKNode alloc]init];
[_world addChild:_sceneCity];
}
-(void) createSceneContents {
_game = [[PCGame alloc]init];
}
#pragma mark - Update Loop
- (void)update:(NSTimeInterval)currentTime {
// Handle time delta.
// If we drop below 60fps, we still want everything to move the same distance.
CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
//update game and hud counters every quarter second
self.countdownInterval += timeSinceLast;
if (self.countdownInterval > 0.25) {
[_game updateCity];
self.countdownInterval = 0;
}
//render more frequently than the game is updated
self.countdownIntervalRender += timeSinceLast;
if (self.countdownIntervalRender > 0.10) {
[self renderCity];
self.countdownIntervalRender = 0;
}
self.lastUpdateTimeInterval = currentTime;
if (timeSinceLast > 1) { // more than a second since last update
//timeSinceLast = kMinTimeInterval;
self.lastUpdateTimeInterval = currentTime;
}
//[self updateWithTimeSinceLastUpdate:timeSinceLast];
}
#pragma mark - Rendering
-(void) renderCity {
[_sceneCity removeAllChildren];
NSArray *tempArray = [_game getChangedTilesForRender];
for (PCCityTile *tempTile in tempArray) {
SKSpriteNode *cityTile = [[SKSpriteNode alloc]init];
cityTile.size = CGSizeMake(1,1);
cityTile.position = tempTile.position;
//the alpha of the tile is based on how many persons are inside it
//multiply it by .30 to make it a little darker than just 0.10
CGFloat tileAlpha = tempTile.personArray.count * 0.30;
cityTile.color = [SKColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:tileAlpha];
[_sceneCity addChild:cityTile];
}
}
#pragma mark - Gesture Handling
-(void) handlePanFrom:(UIGestureRecognizer *)recognizer {
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
if (recognizer.state == UIGestureRecognizerStateBegan) {
_previousTouchPoint = touchLocation;
} else if (recognizer.state == UIGestureRecognizerStateChanged) {
CGPoint tempPosition = CGPointAdd(_world.position, CGPointSubtract(touchLocation, _previousTouchPoint));
_world.position = CGPointMake(tempPosition.x, tempPosition.y);
_previousTouchPoint = touchLocation;
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
}
}
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer {
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
if (recognizer.state == UIGestureRecognizerStateBegan) {
// No code needed for zooming
} else if (recognizer.state == UIGestureRecognizerStateChanged) {
CGPoint anchorPoint = CGPointSubtract(touchLocation, _world.position);
CGPoint mySkNodeShift = CGPointSubtract(anchorPoint, CGPointMultiplyScalar(anchorPoint, recognizer.scale));
[_world runAction:[SKAction group:@[
[SKAction scaleBy:recognizer.scale duration:0.0],
[SKAction moveBy:CGVectorMake(mySkNodeShift.x, mySkNodeShift.y) duration:0.0]
]]];
recognizer.scale = 1.0;
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
// No code needed here for zooming
}
}
#pragma mark - Touch Handling
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
if(touch.tapCount == 1) {
CGPoint positionInScene = [touch locationInNode:self];
[self selectNodeForTouch:positionInScene];
}
}
}
-(void)selectNodeForTouch:(CGPoint)touchLocation {
//we need the touched node
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:touchLocation];
_selectedNode = touchedNode;
//NSLog(@"node name is = %@", touchedNode.name);
//touchLocation = [self convertTouchPointToWorld:touchLocation];
//handle the main hud buttons
if ([touchedNode.name isEqualToString:@"pauseButton"]) {
}
if ([touchedNode.name isEqualToString:@"menuButton"]) {
}
}
#pragma mark - HUD
-(void) buildHud {
SKSpriteNode *pauseButton = [[SKSpriteNode alloc]initWithColor:[SKColor redColor] size:CGSizeMake(_initialScreenSize.width/6, _initialScreenSize.height/10)];
pauseButton.name = @"pauseButton";
pauseButton.position = CGPointMake(_initialScreenSize.width - _initialScreenSize.width/10, _initialScreenSize.height/12);
[self addChild:pauseButton];
SKSpriteNode *menuButton = [[SKSpriteNode alloc]initWithColor:[SKColor greenColor] size:CGSizeMake(_initialScreenSize.width/6, _initialScreenSize.height/10)];
menuButton.name = @"menuButton";
menuButton.position = CGPointMake(_initialScreenSize.width - _initialScreenSize.width/3, _initialScreenSize.height/12);
[self addChild:menuButton];
}
#pragma mark - Helper functions
static inline CGPoint CGPointAdd(CGPoint point1, CGPoint point2) {
return CGPointMake(point1.x + point2.x, point1.y + point2.y);
}
static inline CGPoint CGPointSubtract(CGPoint point1, CGPoint point2) {
return CGPointMake(point1.x - point2.x, point1.y - point2.y);
}
static inline GLKVector2 GLKVector2FromCGPoint(CGPoint point) {
return GLKVector2Make(point.x, point.y);
}
static inline CGPoint CGPointFromGLKVector2(GLKVector2 vector) {
return CGPointMake(vector.x, vector.y);
}
static inline CGPoint CGPointMultiplyScalar(CGPoint point, CGFloat value) {
return CGPointFromGLKVector2(GLKVector2MultiplyScalar(GLKVector2FromCGPoint(point), value));
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(CGPoint) convertTouchPointToWorld:(CGPoint)touchLocation {
CGPoint locationInWorld = [self.scene convertPoint:touchLocation toNode:_world];
return locationInWorld;
}
@end
</code></pre>
<p>Here is the Game class, doesn't do too much yet.<br>
PCGame.h:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface PCGame : NSObject
-(void) updateCity;
-(NSMutableArray *) getChangedTilesForRender;
@end
</code></pre>
<p>PCGame.m:</p>
<pre><code>#import "PCGame.h"
#import "PCCity.h"
@implementation PCGame {
PCCity *_city;
NSArray *_gameChangedTiles;
}
#pragma mark - Initialization
-(id) init {
self = [super init];
if (self) {
_city = [[PCCity alloc]init];
}
return self;
}
#pragma mark - Update loop
-(void) updateCity {
[_city updateCity];
[self updateChangedTiles];
}
-(void) updateChangedTiles {
_gameChangedTiles = _city.changedTiles;
}
#pragma mark - Interface with Renderer
-(NSArray *) getChangedTilesForRender {
return _gameChangedTiles;
}
@end
</code></pre>
<p>Here is the City class, this is the class that ends up determining which City Tile to pass a Person on to.
PCCity.h:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface PCCity : NSObject
-(void) updateCity;
@property NSMutableArray *changedTiles;
@end
</code></pre>
<p>PCCity.m:</p>
<pre><code>#import "PCCity.h"
#import "PCCityTile.h"
#import "PCPerson.h"
#import "PCPersonReporter.h"
#define kMapWidth 100
#define kMapHeight 100
@implementation PCCity {
NSMutableArray *_personArray;
NSMutableDictionary *_cityTiles;
}
-(id) init {
self = [super init];
if (self) {
_cityTiles = [[NSMutableDictionary alloc]init];
_personArray = [[NSMutableArray alloc]init];
self.changedTiles = [[NSMutableArray alloc]init];
[self createCity];
[self createPeople];
[self sendPeopleToTiles];
}
return self;
}
-(void) createCity {
NSMutableDictionary *tempDictionary = _cityTiles;
//how many tiles to create at the start
int mapWidth = kMapWidth;
int mapHeight = kMapHeight;
int mapStartX = 0;
int mapStartY = 0;
int tileX = mapStartX;
int tileY = mapStartY;
while (tileX < mapWidth) {
while (tileY < mapHeight) {
PCCityTile *tempTile = [[PCCityTile alloc]init];
tempTile.position = CGPointMake(tileX,tileY);
NSString *tempTilePosition = NSStringFromCGPoint(tempTile.position);
[tempDictionary setObject:tempTile forKey:tempTilePosition];
tileY++;
}
tileX++;
tileY = mapStartY;
}
_cityTiles = tempDictionary;
}
-(void) createPeople {
for (int i = 0; i < 500; i++) {
int randomStartX = arc4random_uniform(kMapWidth);
int randomStartY = arc4random_uniform(kMapHeight);
PCPerson *tempPerson = [[PCPerson alloc]init];
tempPerson.currentTile = CGPointMake(randomStartX, randomStartY);
//having the destination tile be the same as the current tile will cause a person to pick a new random one
tempPerson.destinationTile = CGPointMake(randomStartX, randomStartY);
[_personArray addObject:tempPerson];
}
//the reporter is a regular person except it NSLogs certain information
PCPersonReporter *reporter = [[PCPersonReporter alloc]init];
reporter.currentTile = CGPointMake(50, 50);
reporter.destinationTile = CGPointMake(20, 20);
[_personArray addObject:reporter];
}
-(void) sendPeopleToTiles {
for (PCPerson *tempPerson in _personArray) {
NSString *sendToTileString = NSStringFromCGPoint(tempPerson.currentTile);
PCCityTile *sendToTile = [_cityTiles objectForKey:sendToTileString];
[sendToTile acceptPerson:tempPerson];
}
[_personArray removeAllObjects];
}
#pragma mark - Update loop
-(void) updateCity {
[self.changedTiles removeAllObjects];
[self updateCityTiles];
[self getPersonsFromTiles];
[self movePersons];
[self createChangedTileArray];
}
-(void) updateCityTiles {
for (id key in _cityTiles) {
PCCityTile *tempTile = [_cityTiles objectForKey:key];
[tempTile updateCityTile];
}
}
-(void) getPersonsFromTiles {
for (id key in _cityTiles) {
PCCityTile *tempTile = [_cityTiles objectForKey:key];
if (tempTile.personsForPickup.count > 0) {
for (PCPerson *person in tempTile.personsForPickup) {
person.isInsideCity = YES;
person.isInsideTile = NO;
[_personArray addObject:person];
}
tempTile.tileHasChanged = YES;
[tempTile.personsForPickup removeAllObjects];
}
}
}
-(void) movePersons {
for (PCPerson *person in _personArray) {
int currentXPos = person.currentTile.x;
int currentYPos = person.currentTile.y;
int destinationXPos = person.destinationTile.x;
int destinationYPos = person.destinationTile.y;
int xDifference = currentXPos - destinationXPos;
int yDifference = currentYPos - destinationYPos;
//moves in the x direction first and then the y if x has not moved
BOOL hasAlreadyMoved = NO;
if (xDifference != 0) {
if (xDifference > 0) {
currentXPos--;
hasAlreadyMoved = YES;
} else if (xDifference < 0) {
currentXPos++;
hasAlreadyMoved = YES;
}
}
if (yDifference != 0 && !hasAlreadyMoved) {
if (yDifference > 0) {
currentYPos--;
} else if (yDifference < 0) {
currentYPos++;
}
}
CGPoint moveToPoint = CGPointMake(currentXPos, currentYPos);
NSString *moveToTileString = NSStringFromCGPoint(moveToPoint);
PCCityTile *moveToTile = [_cityTiles objectForKey:moveToTileString];
[moveToTile acceptPerson:person];
moveToTile.tileHasChanged = YES;
}
[_personArray removeAllObjects];
}
-(void) createChangedTileArray {
for (id key in _cityTiles) {
PCCityTile *tempTile = [_cityTiles objectForKey:key];
if (tempTile.tileHasChanged) {
[self.changedTiles addObject:tempTile];
tempTile.tileHasChanged = NO;
}
}
}
@end
</code></pre>
<p>Here is the City Tile class.
PCCityTile.h:</p>
<pre><code>#import <Foundation/Foundation.h>
#import "PCPerson.h"
#import "TerrainTypes.h"
@interface PCCityTile : NSObject
@property CGPoint position;
@property TerrainType terrainType;
@property NSMutableArray *personArray;
@property NSMutableArray *personsForPickup;
-(void) updateCityTile;
@property BOOL tileHasChanged;
-(void) acceptPerson:(PCPerson *)person;
@end
</code></pre>
<p>PCCityTile.m:</p>
<pre><code>#import "PCCityTile.h"
@implementation PCCityTile
-(id) init {
self = [super init];
if (self) {
self.personArray = [[NSMutableArray alloc]init];
self.personsForPickup = [[NSMutableArray alloc]init];
self.terrainType = arc4random_uniform(7);
}
return self;
}
-(void) acceptPerson:(PCPerson *)person {
person.currentTile = self.position;
person.startCountForTerrain = self.terrainType;
[person startCounting];
person.isInsideTile = YES;
person.isInsideCity = NO;
[self.personArray addObject:person];
}
#pragma mark - Update loop
-(void) updateCityTile {
[self checkPersons];
[self setNewDestinations];
}
-(void) checkPersons {
NSMutableArray *personsToKeep = [[NSMutableArray alloc]init];
NSMutableArray *personsToPickup = [[NSMutableArray alloc]init];
for (PCPerson *person in self.personArray) {
[person checkStatus];
if (!person.isAtDestination) {
if (person.isTerrainCountComplete) {
person.isBeingPickedUp = YES;
person.isStayingAtTile = NO;
[personsToPickup addObject:person];
} else {
person.isStayingAtTile = YES;
person.isBeingPickedUp = NO;
//have to do this here so the tiles show up even when persons are staying put
self.tileHasChanged = YES;
[personsToKeep addObject:person];
}
} else {
person.isStayingAtTile = YES;
person.isBeingPickedUp = NO;
[personsToKeep addObject:person];
}
}
[self.personsForPickup setArray:personsToPickup];
[self.personArray setArray:personsToKeep];
}
-(void) setNewDestinations {
for (PCPerson *person in self.personArray) {
if (person.isAtDestination) {
int randomX = arc4random_uniform(75);
int randomY = arc4random_uniform(75);
person.destinationTile = CGPointMake(randomX, randomY);
}
}
}
@end
</code></pre>
<p>Finally, the Person class itself.
Person.h:</p>
<pre><code>#import <Foundation/Foundation.h>
#import "TerrainTypes.h"
@interface PCPerson : NSObject
@property CGPoint currentTile;
@property CGPoint destinationTile;
@property TerrainType startCountForTerrain;
@property int currentTerrainCount;
@property BOOL isAtDestination;
@property BOOL isBeingPickedUp;
@property BOOL isStayingAtTile;
@property BOOL isInsideCity;
@property BOOL isInsideTile;
@property BOOL isTerrainCounting;
@property BOOL isTerrainCountComplete;
-(void) checkStatus;
-(void) sayStatus;
-(void) startCounting;
@end
</code></pre>
<p>Person.m:</p>
<pre><code>#import "PCPerson.h"
@implementation PCPerson
-(void) checkStatus {
if (self.currentTile.x == self.destinationTile.x && self.currentTile.y == self.destinationTile.y) {
self.isAtDestination = YES;
} else {
self.isAtDestination = NO;
if (self.isTerrainCounting) {
[self doCountdown];
}
}
[self sayStatus];
}
-(void) sayStatus {
//overridden by subclasses
}
-(void) startCounting {
self.isTerrainCounting = YES;
self.isTerrainCountComplete = NO;
switch (self.startCountForTerrain) {
case Impassable:
self.currentTerrainCount = 100;
break;
case Mountain:
self.currentTerrainCount = 90;
break;
case Desert:
self.currentTerrainCount = 80;
break;
case Swamp:
self.currentTerrainCount = 70;
break;
case Forest:
self.currentTerrainCount = 60;
break;
case Hills:
self.currentTerrainCount = 50;
break;
case Grassland:
self.currentTerrainCount = 40;
break;
default:
break;
}
}
-(void) doCountdown {
if (self.currentTerrainCount > 0) {
self.currentTerrainCount-=100;
} else {
self.isTerrainCounting = NO;
self.isTerrainCountComplete = YES;
}
}
@end
</code></pre>
| [] | [
{
"body": "<p><em>Note:</em> I don't have time right out a complete answer, so you'll have to check back this afternoon, but I'll get one started.</p>\n\n<hr>\n\n<p>First, the most glaring problem I see is your use of the <code>self.</code> accessors in the init methods. It seems to be a common problem here (I see it on SO a lot too), but Apple actually explicitly states that you should not be doing this.</p>\n\n<p>You should be accessing the backing variable directly:</p>\n\n<pre><code>-(id) init {\n self = [super init];\n if (self) {\n _personArray = [NSMutableArray array];\n _personsForPickup = [NSMutableArray array];\n _terrainType = arc4random_uniform(7);\n }\n return self;\n}\n</code></pre>\n\n<p>And while it's technically not incorrect, for me, an Objective-C class isn't complete without a public factory method for every public init method.</p>\n\n<pre><code>+ (instancetype)cityTyle {\n return [[self alloc] init];\n}\n</code></pre>\n\n<hr>\n\n<p>Next, I think we need a little mini-lesson on properties and property attributes.</p>\n\n<p>First of all, while getters in other languages are prefixed with <code>getSomeVar</code>, in Objective-C, they are not, and the accessor would just be called <code>someVar</code>.</p>\n\n<p>So, at a minimum, <code>-(NSMutableArray *) getChangedTilesForRender;</code> should be changed to <code>- (NSMutableArray *)changedTilesForRender;</code>.</p>\n\n<p>But the problem for me is the inconsistency between the City and Game class, where one has a property and the other has a method.</p>\n\n<p>Let's look at the Game class first. If we change the method declaration to the following:</p>\n\n<pre><code>@property (nonatomic,strong,readonly) NSMutableArray *changedTilesForRender;\n</code></pre>\n\n<p>Now we have created a getter and a backing instance variable. There is no setter, so the variable can't be changed by outside classes. What's more, the backing variable will by default be called <code>_changedTilesForRender</code>. This is a good thing.</p>\n\n<p>If I'm maintaining this code, whether I didn't write it, or I did write it but it's been 6 months since I wrote it and I just now found a bug, I'm not going to know where all the information for a stand-alone getter method comes from. It might be hard to follow. But when we declare a read-only property, that has a well-defined backing variable.</p>\n\n<p>If you don't want the backing variable to have the same name as the property, you can always <code>@synthesize</code>.</p>\n\n<pre><code>@synthesize changedTilesForRender = fooBarExampleName;\n</code></pre>\n\n<p>And this is still better, because when I Ctrl+F to find the former, it'll take me to a line that clearly redefines it as the latter, and now I can Ctrl+F through the code for that one.</p>\n\n<p>Now, in the City class, <code>changedTiles</code> isn't marked as readonly. Is this intentional?</p>\n\n<hr>\n\n<pre><code>@property BOOL isAtDestination;\n@property BOOL isBeingPickedUp;\n@property BOOL isStayingAtTile;\n@property BOOL isInsideCity;\n@property BOOL isInsideTile;\n@property BOOL isTerrainCounting;\n@property BOOL isTerrainCountComplete;\n</code></pre>\n\n<p>This is a mess. </p>\n\n<p>Any time you need 2 or more <code>BOOL</code>s to describe a single status, you might be better off with an enum.</p>\n\n<p>Your class isn't complete, so I don't know the full meaning or intended use of all of these, but it looks like <code>isTerrainCounting</code> and <code>isTerrainCountComplete</code> are going to be mutually exclusive. The problem with using two <code>BOOL</code>s to describe this single status is that there's nothing you can do to actually make these mutually exclusive as written.</p>\n\n<p>And with multithreading, it's not completely impossible that something else checks the status of <code>PCPerson</code> and come back with both <code>YES</code> or both <code>NO</code>. It may be rare and difficult but not impossible. What's more, this is prone to mistakes. Whether from you or someone else who might look at this code, nothing guarantees that the code will be correctly written to set both.</p>\n\n<p>The only way to make these statuses guaranteed to be mutually exclusive is by making them a single variable. Simply eliminating one of them is an option, and if it's safe to assume that any object that isn't currently terrain counting is thereby count complete--that is to say, there's no status where the object hasn't completed or started counting.</p>\n\n<p>But we can even improve the readability of this single <code>BOOL</code>:</p>\n\n<pre><code>typedef NS_ENUM(BOOL, TerrainCountStatus) {\n TerrainCountStatusCounting = YES,\n TerrainCountStatusCountComplete = NO\n};\n\n@property TerrainCountStatus terrainCountStatus;\n</code></pre>\n\n<p>Now you set it like this:</p>\n\n<pre><code>self.terrainCountStatus = TerrainCountStatusCounting;\n</code></pre>\n\n<p>But what might be even better is an enum that accounts for the third status possibility.</p>\n\n<pre><code>typedef NS_ENUM(NSInteger, TerrainCountStatus) {\n TerrainCountStatusNoCount = -1,\n TerrainCountStatusCounting = 0,\n TerrainCountStatusCountComplete = 1\n}\n</code></pre>\n\n<p>Now you set the values in the same way as the previous example.</p>\n\n<p>But now you can represent three statuses with a single variable and they are guaranteed to be mutually exclusive because it's only a single variable.</p>\n\n<p>What's more, you can still keep the <code>BOOL</code> properties if you want to more easily check YES/NO on a single status.</p>\n\n<pre><code>@property (readonly) BOOL isTerrainCounting;\n</code></pre>\n\n<p>Don't forget the <code>readonly</code>, now override the accessor:</p>\n\n<pre><code>- (BOOL)isTerrainCounting {\n return (self.terrainCountStatus == TerrainCountStatusCounting);\n}\n</code></pre>\n\n<hr>\n\n<p>You don't seem to have included <code>TerrainTypes</code> in this code review, but it seems it's probably an enum? Why not define the values to the starting values you're setting instead of switching and setting a value based on the terrain type?</p>\n\n<hr>\n\n<pre><code>#define kMinTimeInterval (1.0f / 60.0f)\n#define kMapWidth 100\n#define kMapHeight 100\n</code></pre>\n\n<p>These would all be better as <code>const</code> values.</p>\n\n<pre><code>const CGFloat kMinTimeInterval = (1.0f / 60.0f);\nconst NSInteger kMapWidth = 100;\nconst NSInteger kMapHeight = 100;\n</code></pre>\n\n<p>And the latter two could even be an enum instead of a const if you wanted, for example:</p>\n\n<pre><code>typedef NS_ENUM(NSInteger, MapDimensions) {\n kMapWidth = 100,\n kMapHeight = 100\n};\n</code></pre>\n\n<p><code>#define</code> is notoriously hard to debug. It's just preprocessor find & replace, so if there's any sort of bug with it, the compiler won't be too particularly helpful relative to using a <code>const</code> or <code>enum</code>.</p>\n\n<p>The one advantage that <code>#define</code> would even potentially have over anything else is that because the preprocessor finds & replaces, your programming, during run time, might be ever so slightly more efficient. But this is extremely insignificant, and a good compiler will make this completely irrelevant in a lot of cases.</p>\n\n<p>At the end of the day, there aren't a lot of good excuses for using <code>#define</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T17:09:27.317",
"Id": "85788",
"Score": "1",
"body": "Extremely helpful as always! Thank you. Based on some of the recommendations here I am writing radically different code than I was before, which is awesome."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:43:13.080",
"Id": "48476",
"ParentId": "48445",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48476",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:14:09.520",
"Id": "48445",
"Score": "5",
"Tags": [
"game",
"objective-c",
"queue",
"stack",
"simulation"
],
"Title": "Managing People in a SimCity Clone"
} | 48445 |
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/q/47098/37034">this question</a>, which resulted in major confusion on my side regarding forwarding of arguments. <strong>Advice regarding that should probably be given in <a href="https://stackoverflow.com/q/23323547/692359">my question on SO</a>.</strong></p>
<p><strong>Overview</strong></p>
<p>The classes below implement the observer pattern for use in an embedded system. My main need is to be able to connect sources of data (a GPS with position information, for example) to consumers (debugging over a serial line or a position widget). A <code>Signal</code> may have arguments, which are sent to the observers (zero or more <code>Connection</code>s), which call a delegate (free function, static or non-static member).</p>
<p>The return values of any called function are discarded in the interface of <code>AbstractDelegate</code>, because the calling <code>Signal</code> shouldn't need to care about any return values. I didn't use <code>std::function</code> for this because it simply occupied too much the system`s available RAM.</p>
<p>Signals can be copied, because they would be used as object members. A class that contains a <code>Signal</code> member should not be non-copyable just because a <code>Signal</code> is present. I'm not sure if I want to support <code>Connection</code> members, please enlighten me if you have good advice about that.</p>
<p><code>Connection</code>s are created on the heap using two <code>connect</code> functions - one for free functions and static methods, one for non-static methods.</p>
<p>I didn't use an STL container for the <code>Signal</code>'s connection list because I need control over memory allocation, and a <code>Connection</code> must be able to remove itself from the <code>Signal</code>'s list. The result of these two (maybe wrong) thoughts is the intrusive linked list I implemented.</p>
<p><code>Signal</code>s can be blocked (<code>block()</code>, <code>unblock()</code>). If that is the case, no <code>Connection</code> will be notified. <code>Connection</code>s can also be blocked individually.</p>
<p><strong>The header</strong></p>
<pre><code>#ifndef SIGNALS_H
#define SIGNALS_H
#include <utility>
/** Interface for delegates with a specific set of arguments **/
template<typename... args>
class AbstractDelegate
{
public:
virtual void operator()(args...) const = 0;
virtual ~AbstractDelegate() {}
};
/** Concrete member function delegate that discards the function's return value **/
template<typename T, typename ReturnType, typename... args>
class ObjDelegate : public AbstractDelegate<args...>
{
public:
/** member function typedef **/
using ObjMemFn = ReturnType (T::*)(args...);
/** constructor **/
ObjDelegate(T& obj, ObjMemFn memFn)
: obj_(obj), // brace-enclosed initializer list didn't work here
memFn_{memFn} // here the brace-enclosed list works, probably because memFn is _not_ a reference
{
}
/** call operator that calls the stored function on the stored object **/
void operator()(args... a) const override
{
(obj_.*memFn_)(std::forward<args>(a)...);
}
private:
/** reference to the object **/
T& obj_;
/** member function pointer **/
const ObjMemFn memFn_;
};
/** Concrete function delegate that discards the function's return value **/
template<typename ReturnType, typename... args>
class FnDelegate : public AbstractDelegate<args...>
{
public:
/** member function typedef **/
using Fn = ReturnType(*)(args...);
/** constructor **/
FnDelegate(Fn fn)
: fn_{fn}
{
}
/** call operator that calls the stored function **/
void operator()(args... a) const override
{
(*fn_)(std::forward<args>(a)...);
}
private:
/** function pointer **/
const Fn fn_;
};
/** forward declaration **/
template<typename... args>
class Connection;
/** Signal class that can be connected to**/
template<typename... args>
class Signal
{
public:
/** connection pointer typedef **/
using connection_p = Connection<args...>*;
/** constructor **/
Signal()
: connections_(nullptr),
blocked_(false)
{
}
/** copy constructor **/
Signal(const Signal& other)
: connections_(nullptr),
blocked_(other.blocked()) // not sure if this is a good idea
{
}
/** call operator that notifes all connections associated with this Signal.
The most recently associated connection will be notified first **/
void operator()(args... a) const
{
// only notify connections if this signal is not blocked
if (!blocked())
{
auto c = connections_;
while(c)
{
auto c_next = c->next();
if (c_next)
(*c)(a...);
else
(*c)(std::forward<args>(a)...); // last use, can forward
c = c_next;
}
}
}
/** connect to this signal **/
void connect(connection_p p)
{
p->next_ = connections_;
connections_ = p;
p->signal_ = this;
}
/** disconnect from this signal.
Invalidates the connection's signal pointer
and removes the connection from the list **/
void disconnect(connection_p conn)
{
// find connection and remove it from the list
connection_p c = connections_;
if (c == conn)
{
connections_ = connections_->next();
conn->next_ = nullptr;
conn->signal_ = nullptr;
return;
}
while(c != nullptr)
{
if (c->next() == conn)
{
c->next_ = conn->next();
conn->next_ = nullptr;
conn->signal_ = nullptr;
return;
}
c = c->next();
}
}
/** block events from this signal **/
void block()
{
blocked_ = true;
}
/** unblock events from this signal **/
void unblock()
{
blocked_ = false;
}
/** is this signal blocked? **/
bool blocked() const
{
return blocked_;
}
/** destructor. disconnects all connections **/
~Signal()
{
connection_p p = connections_;
while(p != nullptr)
{
connection_p n = p->next();
disconnect(p);
p = n;
}
}
connection_p connections() const {return connections_;}
private:
/** don't allow copy assignment **/
Signal& operator= (Signal& other);
connection_p connections_;
bool blocked_;
};
/** connection class that can be connected to a signal **/
template<typename... args>
class Connection
{
public:
/** template constructor for non-static member functions.
allocates a new delegate on the heap **/
template<typename T, typename ReturnType>
Connection(Signal<args...>& signal, T& obj, ReturnType (T::*memFn)(args...))
: delegate_(new ObjDelegate<T, ReturnType, args...>(obj, memFn)),
signal_(nullptr),
next_(nullptr),
blocked_(false)
{
signal.connect(this);
}
/** template constructor for static member functions and free functions.
allocates a new delegate on the heap **/
template<typename ReturnType>
Connection(Signal<args...>& signal, ReturnType (*Fn)(args...))
: delegate_(new FnDelegate<ReturnType, args...>(Fn)),
signal_(nullptr),
next_(nullptr),
blocked_(false)
{
signal.connect(this);
}
/** get reference to this connection's delegate **/
AbstractDelegate<args...>& delegate() const
{
return *delegate_;
}
/** call this connection's delegate if not blocked **/
void operator()(args... a) const
{
if (!blocked())
{
delegate()(std::forward<args>(a)...);
}
}
/** get pointer to next connection in the signal's list **/
Connection* next() const
{
return next_;
}
/** is this connection connected to a valid signal? **/
bool connected() const
{
return (signal_ != nullptr);
}
/** block events for this connection **/
void block()
{
blocked_ = true;
}
/** unblock events for this connection **/
void unblock()
{
blocked_ = false;
}
/** is this connection blocked? **/
bool blocked() const
{
return blocked_;
}
/** desctructor. If the signal is still alive, disconnects from it **/
~Connection()
{
if (signal_ != nullptr)
{
signal_->disconnect(this);
}
delete delegate_;
}
const Signal<args...>* signal() const {return signal_;}
friend class Signal<args...>;
private:
/** don't allow copy construction **/
Connection(const Connection& other);
/** don't allow copy assignment **/
Connection& operator= (Connection& other);
AbstractDelegate<args...>* delegate_;
Signal<args...>* signal_;
Connection* next_;
bool blocked_;
};
/** free connect function: creates a connection (non-static member function) on the heap
that can be used anonymously **/
template<typename T, typename ReturnType, typename... args>
Connection<args...>* connect(Signal<args...>& signal, T& obj, ReturnType (T::*memFn)(args...))
{
return new Connection<args...>(signal, obj, memFn);
}
/** free connect function: creates a connection (static member or free function) on the heap
that can be used anonymously **/
template<typename ReturnType, typename... args>
Connection<args...>* connect(Signal<args...>& signal, ReturnType (*fn)(args...))
{
return new Connection<args...>(signal, fn);
}
#endif // SIGNALS_H
</code></pre>
<p><strong>And how it's supposed to be used</strong></p>
<pre><code>#include <iostream>
#include "signals.h"
Signal<int> sig; // create a signal
void print(int i) // free function to print an int
{
std::cout << "print(" << i << ")" << std::endl;
}
int get(int i) // a function that returns an int
{
return i;
}
class Foo
{
public:
Foo(const int& i)
: i_(i)
{
std::cout << "Foo(" << i << ")" << std::endl;
}
const int& operator()() const {return i_;}
void addAndPrint(int i)
{
std::cout << "Foo::addAndPrint(" << i + i_ << ")" << std::endl;
}
private:
int i_;
};
int main()
{
connect(sig, print); // when sig is called, print() should be notified
sig(3);
int i = 4;
sig(i);
sig(get(5));
sig(Foo(6)());
Foo foo(8);
sig(foo());
connect(sig, foo, &Foo::addAndPrint);
sig(10);
}
</code></pre>
<p>My main concerns are about copy construction and assignment of <code>Signal</code>s and <code>Connection</code>s. I added those operations because I needed destructors for those classes (rule of three) - taking a look at the desctructors might also be a good idea.</p>
<p>I'm also interested in pitfalls I might have overlooked. I think I have made sure that deleting a <code>Signal</code> or a <code>Connection</code> does not leave any dangling pointers, but that might not be the only thing that can go wrong here.</p>
| [] | [
{
"body": "<p>I will try not to give awful advice like I did last time. Here are a few remarks:</p>\n\n<ul>\n<li><p>First of all, let's come back to <a href=\"http://en.cppreference.com/w/cpp/utility/forward\" rel=\"nofollow noreferrer\"><code>std::forward</code></a>. You should follow the link and read again a little bit more; <code>std::forward</code> is only useful for reference collapsing. In your <code>operator()</code>, you take the arguments by copy (that is fine) and there is no reference collapsing. Therefore, where you use <code>std::forward</code>, you should use <code>std::move</code> instead (from the header <code><algorithm></code>), following the <a href=\"https://stackoverflow.com/q/16724657/1364752\">copy-then-move</a> idiom.</p></li>\n<li><p>You can simplify your default constructor. First of all, you can use in-class initializers to initialize <code>connections_</code> and <code>blocked_</code>:</p>\n\n<pre><code>connection_p connections_ = nullptr;\nbool blocked_ = false;\n</code></pre>\n\n<p>Now, if the values to pass to <code>connections_</code> and <code>blocked_</code> are not specified in a constructor, the compiler will use the values from the in-class initializers instead. That means that you can reduce the implementation of <code>Signal</code>'s default constructor to:</p>\n\n<pre><code>Signal() = default;\n</code></pre></li>\n<li><p>There are too many comments. Try to remove the unneeded comments. Many of your comments do not give more information that what we already know by reading the corresponding line of code. Even worse, if you modify the code and not the comments, they will live. Try to writer <a href=\"http://en.wikipedia.org/wiki/Self-documenting\" rel=\"nofollow noreferrer\">self-documenting code</a> to avoid unneeded and potentially liar comments.</p></li>\n<li><p>However, your comments helped me figure out that you need a C++11 feature here:</p>\n\n<pre><code>private:\n /** don't allow copy construction **/\n Connection(const Connection& other);\n\n /** don't allow copy assignment **/\n Connection& operator= (Connection& other);\n</code></pre>\n\n<p>Instead of making these special functions <code>private</code>, you can <a href=\"http://en.wikipedia.org/wiki/C%2B%2B11#Explicitly_defaulted_and_deleted_special_member_functions\" rel=\"nofollow noreferrer\">explicitely mark them as deleted</a>. In other words, you can write this instead:</p>\n\n<pre><code>Connection(const Connection& other)\n = delete;\nConnection& operator= (Connection& other)\n = delete;\n</code></pre>\n\n<p>And the same holds for copy assignment operator of <code>Signal</code>.</p></li>\n<li><p>Thanks @Jamal for this one: <a href=\"https://stackoverflow.com/a/213977/1364752\">try not to use <code>std::endl</code></a> when it is not needed. Actually, <code>std::endl</code> adds a newline character and flushes the output buffer. You generally don't need the buffer to be flushed, you only want to add a newline character. Moreover, the buffer is automatically flushed when the program ends.</p></li>\n<li><p>There are many places where you can still use <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow noreferrer\">list initialization</a> to avoid potential implicit narrowing conversion. I already mentioned that in my answer to your previous question and forgot to mention the cases where it was not possible (references for example). A better guideline would actually be to use list initialization when you use numbers (integers of floating point numbers) and you know that a loss of precision could be a problem. You can also use it to prevent implicit conversions to <code>bool</code>, which sometimes don't make sense.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-23T23:38:01.000",
"Id": "89140",
"Score": "0",
"body": "It's been a while since I asked this question and I could finally try out your suggestions. The `delete` keyword and in-class initializers were new to me and they certainly simplify things. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T22:31:15.223",
"Id": "49194",
"ParentId": "48447",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "49194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T23:25:36.680",
"Id": "48447",
"Score": "8",
"Tags": [
"c++",
"c++11",
"delegates"
],
"Title": "Delegate and Observer pattern implementation for an embedded system - copy and assignment operations"
} | 48447 |
<p>I'm implementing <code>transpose</code> in Haskell.</p>
<pre><code>-- transpose [[1,2,3],[4,5,6],[7,8,9]]
-- [[1,4,7],[2,5,8],[3,6,9]]
</code></pre>
<p>Please give it a look. Note that I'm trying not to use any built-in functions (excluding <code>map</code> and <code>++</code>):</p>
<pre><code>transpose' :: [[a]] -> [[a]]
transpose' ys
| null $ filter (not . null) ys = []
| otherwise = [flatten' $ map head' ys] ++ transpose' (map tail' ys)
head' :: [a] -> [a]
head' [] = []
head' (x:xs) = [x]
tail' :: [a] -> [a]
tail' [] = []
tail' (x:xs) = xs
flatten' :: [[a]] -> [a]
flatten' as = foldl (\acc x -> acc ++ x) [] as
</code></pre>
<p>Side note - I know that I could look at the Haskell source, but I appreciate the comments & thoughtful insights here.</p>
| [] | [
{
"body": "<p>I see a few problems, mostly similar to my <a href=\"https://codereview.stackexchange.com/a/48104/9357\">remarks in a previous answer</a>:</p>\n\n<ol>\n<li><p>Your definition of <code>head'</code> is unconventional. Its definition should be</p>\n\n<pre><code>head' :: [a] -> a\nhead (x:_) = x\n</code></pre>\n\n<p>Furthermore, your problematic definition of <code>head'</code> is making you define <code>flatten'</code>. If you fix <code>head'</code> as suggested above, then<code>flatten'</code> becomes unnecessary.</p></li>\n<li><p>The definition of <code>tail'</code> is too complicated. It could just be</p>\n\n<pre><code>tail' :: [a] -> [a]\ntail (_:xs) = xs\n</code></pre></li>\n<li><p>For clarity, I would rename the parameter to <code>transpose'</code> from <code>ys</code> to <code>rows</code>.</p></li>\n<li><p>The base case of <code>transpose'</code> is too complicated. Also, it can be done using pattern matching.</p>\n\n<pre><code>transpose' [[]] = []\ntranspose' [[], _] = []\n</code></pre></li>\n<li><p>Prefer <code>x:xs</code> to <code>[x] ++ xs</code>.</p></li>\n<li><p>Scope your helper functions using <code>where</code>.</p></li>\n</ol>\n\n<p>Here's what I came up with:</p>\n\n<pre><code>transpose' :: [[a]] -> [[a]]\ntranspose' [[]] = []\ntranspose' [[], _] = []\ntranspose' rows = (map head' rows) : transpose' (map tail' rows)\n where\n head' (x:_) = x\n tail' (_:xs) = xs\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-28T05:27:37.563",
"Id": "515663",
"Score": "0",
"body": "I tested the code `transpose' [[1,2],[4,4],[8,9]]`, Non-exhaustive patterns in function head'"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T08:20:36.357",
"Id": "48463",
"ParentId": "48451",
"Score": "7"
}
},
{
"body": "<p>Good job doing it the hard way. Definitely take a peek at the implementations of functions in <code>base</code> after you're done rewriting them though, understanding the \"canonical\" implementation will do a lot to help you develop an idiomatic style.</p>\n\n<ol>\n<li><p>Your definition of <code>head'</code> is non-standard. Here's the signature of <code>head</code> from the Prelude.</p>\n\n<pre><code>head :: [a] -> a\n</code></pre>\n\n<p>Your version isn't wrong per se, it's valid to return a list of 0 elements for a computation that may fail, but usually only when success will return 1 <em>or more</em> elements. The standard way to write <code>safeHead</code> is to encode failure using <code>Maybe</code> like so.</p>\n\n<pre><code>head' :: [a] -> Maybe a\nhead' [] = Nothing\nhead' (x:_) = Just x\n</code></pre>\n\n<p>This is the 'smallest' correct definition, in the sense of not including additional unnecessary functionality.</p></li>\n<li><p>Replace the identifiers for unused arguments/patterns with an underscore (like I did just above). This can be helpful in catching some subtle errors early if you compile with <code>-fwarn-unused-matches</code> (included in <code>-Wall</code>). Here's a good <a href=\"https://stackoverflow.com/a/14309605/1722055\">StackOverflow answer</a> about when that might be the case, and it's a good habit to have even for simpler functions like this.</p></li>\n<li><p>Here's where looking at the docs afterward can help, your function <code>flatten'</code> is named <code>concat</code> in the standard <code>List</code> functions. And in fact mapping over a list and then flattening it is so common that there's even a function for that, creatively named <code>concatMap</code>.</p></li>\n<li><p>Consider the lambda you use in the definition of <code>flatten'</code>.</p>\n\n<pre><code>(\\acc x -> acc ++ x)\n</code></pre>\n\n<p>The strength of functional languages is being able to pass functions as values, which is of course what you're doing here with a lambda, but did you know that operators like <code>++</code> can already be used like any other old function? Wrap infix operators in parentheses to treat them like regular functions.</p>\n\n<pre><code>... = foldl (++) [] as -- Identical to the above!\n</code></pre></li>\n<li><p><a href=\"http://www.well-typed.com/blog/90/\" rel=\"nofollow noreferrer\"><code>foldl</code> is broken!</a> This might be more advanced reading than you're comfortable with now, but the bottom line is that <code>foldl</code> typically has unwanted performance characteristics, and to be safe you should use <code>foldl'</code> (<code>import Data.List (foldl')</code> at the start of your file, then change all <code>foldl</code>s to <code>foldl'</code>s) or <code>foldr</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T08:20:50.373",
"Id": "48464",
"ParentId": "48451",
"Score": "3"
}
},
{
"body": "<p>This is a surprisingly tricky function. I played with the solutions provided and realized they were not generic. For instance, the solution that only relies on <code>fmap</code> (a.k.a <code>map</code> if applied to a list), only worked with a list with two lists (i.e., <code>[[],_]</code> only works on a list length of two). </p>\n\n<p>Here is a solution that builds on what was provided to generalize it to a list of <em>any number of lists</em>.</p>\n\n<pre><code>trans :: [[a]] -> [[a]]\ntrans [] = []\ntrans ([]:xss) = trans xss\ntrans ((x:xs):xss) = (x : fmap head' xss) : trans (xs : fmap tail' xss)\n where head' (x:_) = x\n tail' (_:xs) = xs\n</code></pre>\n\n<p>The benefits of this approach: </p>\n\n<ol>\n<li>there is no need to pattern match a list of empty lists; a surprisingly verbose approach that requires the use of a reduction such as <code>concat</code>. Part of the trick to avoiding this is the <code>([]:xss) = trans xss</code> recursion. </li>\n<li>the <code>trans ((x:xs):xss)</code> is key to the solution. This pattern match and subsequent reassembly is a useful idiom worth being familiar with. </li>\n<li>the approach avoids having to define <code>safehead</code>; the safeguard of calling <code>head</code> on an empty list is moot because we have <code>trans [] = []</code> which will pattern match before <code>xss</code> reaches a call to <code>head'</code>.</li>\n</ol>\n\n<p>What made it tricky was my being stuck on trying to pattern match a list of empty lists e.g., <code>[[],[],[]]</code>. I could not find a way to pattern match on a list of empty lists for any number of empty lists <em>without</em> resorting to using <code>concat xss</code> with a pattern match to <code>[]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-25T20:38:43.507",
"Id": "190459",
"ParentId": "48451",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48463",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T02:39:52.127",
"Id": "48451",
"Score": "8",
"Tags": [
"haskell",
"matrix",
"reinventing-the-wheel"
],
"Title": "Implementing Transpose"
} | 48451 |
<p>Below is working code of a semi complete program. Its purpose is to take an input string of any type and modify it based on rules defined for each type. So in this example I pass it a string in CSV format and modify some of the fields. </p>
<p>My questions are</p>
<ol>
<li><p>Can the use of interfaces be improved? </p></li>
<li><p>How can I handle different string modification patterns (I currently make it work by using <code>IStringModificationPattern</code> - but I want to extend this to other types like HTML)?</p></li>
<li><p>What design changes/ additions can I make to integrate the string modification pattern into a configuration class (i.e. using an XML file based settings)?</p></li>
</ol>
<p></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringModificationTest
{
class Program
{
static void Main(string[] args)
{
//usage example
//
string inputText = "CSV,field1,field2,field3,field4,field5,field6,field7,,,,";
StringModifier SM = new StringModifier();
string outputText = SM.ModifyString(inputText);
}
}
</code></pre>
<blockquote>
<p><strong>StringModifier</strong> class</p>
</blockquote>
<pre><code> public class StringModifier
{
private List<IStringType> RegisteredTypes = new List<IStringType>();
private IStringModificationPattern ModificationPattern;
public StringModifier()
{
RegisterTypes();
}
private void RegisterTypes()
{
RegisteredTypes = TypeFactory.GetTypeList();
}
public string ModifyString(string str)
{
///sets the message and sets the Modification pattern
IString detectedStr = DetectStringType(str);
///returns the modified string
return detectedStr.Modify(ModificationPattern);
}
private IString DetectStringType(string str)
{
IString msg = new NullString(str);
for (int i = 0; i < RegisteredTypes.Count; i++)
{
if (str.StartsWith(RegisteredTypes[i].start))
{
//set string type
msg = RegisteredTypes[i].getNewInstance(str);
//set modification pattern
ModificationPattern = RegisteredTypes[i].MODPattern;
}
}
return msg;
}
}
</code></pre>
<blockquote>
<p><strong>TypeFactory</strong> static class</p>
</blockquote>
<pre><code> internal static class TypeFactory
{
public static List<IStringType> GetTypeList()
{
List<IStringType> types = new List<IStringType>();
types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(IStringType))
select Activator.CreateInstance(t) as IStringType);
return types;
}
}
</code></pre>
<blockquote>
<p><strong>IStringType</strong> interface</p>
</blockquote>
<pre><code> public interface IStringType
{
string start { get; }
IString getNewInstance(string STR);
IStringModificationPattern MODPattern { get; }
}
</code></pre>
<blockquote>
<p><strong>IStringType Implementations</strong></p>
</blockquote>
<pre><code> public class CSVType : IStringType
{
public string start { get { return @"CSV,"; } }
public IStringModificationPattern MODPattern { get { return new CSV_StringModificationPattern(); } }
public IString getNewInstance(string str)
{
return (IString)(new CSVString(str));
}
}
public class HTMLStringType : IStringType
{
public string start { get { return @"<HTML>"; } }
public IStringModificationPattern MODPattern { get { return new HTML_StringModificationPattern(); } }
public IString getNewInstance(string str)
{
return (IString)(new HTMLString(str));
}
}
</code></pre>
<blockquote>
<p><strong>IString</strong> interface</p>
</blockquote>
<pre><code> public interface IString
{
string STR { get; }
string Modify(IStringModificationPattern MODPattern);
}
</code></pre>
<blockquote>
<p><strong>IString implementations</strong></p>
</blockquote>
<pre><code> public class CSVString : IString
{
public string STR { get; set; }
public List<string> CSVFields { get; set; }
public CSVString(string str)
{
STR = str;
CSVFields = new List<string>();
CSVFields.AddRange(str.Split(','));
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
foreach (int i in MODPattern.location)
{
CSVFields[i] = "BLAH";
}
//rebuild string
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < CSVFields.Count; i++)
{
sb.Append(CSVFields[i]);
if (i != CSVFields.Count - 1)
sb.Append(',');
}
output = sb.ToString();
return output;
}
}
public class HTMLString : IString
{
public string STR { get; set; }
public HTMLString(string str)
{
STR = str;
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
return output;
}
}
public class NullString : IString
{
public string STR { get; set; }
public NullString(string str)
{
STR = str;
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
//Do nothing
return output;
}
}
</code></pre>
<blockquote>
<p><strong>IStringModificationPattern</strong> interface</p>
</blockquote>
<pre><code> public interface IStringModificationPattern
{
List<int> location { get; set; }
}
</code></pre>
<blockquote>
<p><strong>IStringModificationPattern implementations</strong></p>
</blockquote>
<pre><code> public class CSV_StringModificationPattern : IStringModificationPattern
{
//defines the fields that need to be modified
public List<int> location { get; set; }
public CSV_StringModificationPattern()
{
location = new List<int>();
location.Add(2);
location.Add(5);
}
}
public class HTML_StringModificationPattern : IStringModificationPattern
{
public List<int> location { get; set; }
}
}
</code></pre>
<blockquote>
<p><strong>EDIT:</strong> Revised Code taking into consideration feedback below</p>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringModificationTest2
{
class Program
{
static void Main(string[] args)
{
//usage example
//
string inputText = "CSV,field1,field2,field3,field4,field5,field6,field7,,,,";
StringModifier SM = new StringModifier();
string outputText = SM.Modify(inputText);
}
}
public class StringModifier
{
private readonly List<IStringModificationPattern> _registeredPatterns;
private readonly StringPatternDetector Detector;
public StringModifier()
{
_registeredPatterns = StringModificationPatternFactory.GetTypeList();
Detector = new StringPatternDetector();
}
public string Modify(string inputValue)
{
//get the modification pattern that belongs to this string, and the string object
IStringModificationPattern Modificationpattern = Detector.DetectPattern(this._registeredPatterns, inputValue);
IString StringObject = Detector.StringObject;
//execute correct modification algorithm on the input string
return StringObject.Modify(Modificationpattern); ;
}
}
public class StringPatternDetector
{
private IStringModificationPattern _pattern;
public IString StringObject { get; private set; }
public StringPatternDetector()
{
StringObject = new DEFAULTString(string.Empty);
}
public IStringModificationPattern DetectPattern(List<IStringModificationPattern> registeredPatterns, string value)
{
for (int i = 0; i < registeredPatterns.Count; i++)
{
if (value.StartsWith(registeredPatterns[i].start))
{
_pattern = registeredPatterns[i];
}
}
if (_pattern != null)
StringObject = _pattern.getNewInstance(value);
else
StringObject = new DEFAULTString(value);
return _pattern;
}
}
internal static class StringModificationPatternFactory
{
public static List<IStringModificationPattern> GetTypeList()
{
List<IStringModificationPattern> types = new List<IStringModificationPattern>();
types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(IStringModificationPattern))
select Activator.CreateInstance(t) as IStringModificationPattern);
return types;
}
}
public interface IString
{
string STR { get; }
string Modify(IStringModificationPattern MODPattern);
}
public class CSVString : IString
{
public string STR { get; set; }
public List<string> CSVFields { get; set; }
public CSVString(string str)
{
STR = str;
CSVFields = new List<string>();
CSVFields.AddRange(str.Split(','));
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
foreach (int i in MODPattern.location)
{
CSVFields[i] = "BLAH";
}
//rebuild string
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < CSVFields.Count; i++)
{
sb.Append(CSVFields[i]);
if (i != CSVFields.Count - 1)
sb.Append(',');
}
output = sb.ToString();
return output;
}
}
public class HTMLString : IString
{
public string STR { get; set; }
public HTMLString(string str)
{
STR = str;
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
return output;
}
}
public class DEFAULTString : IString
{
public string STR { get; set; }
public DEFAULTString(string str)
{
STR = str;
}
public string Modify(IStringModificationPattern MODPattern)
{
string output = STR;
//Do nothing
return output;
}
}
public interface IStringModificationPattern
{
string start { get; set; }
List<int> location { get; set; }
IString getNewInstance(string value);
}
public class CSV_StringModificationPattern : IStringModificationPattern
{
public string start { get { return @"CSV,"; } set { this.start = value; } }
//defines the fields that need to be modified
public List<int> location { get; set; }
public CSV_StringModificationPattern()
{
location = new List<int>();
location.Add(2);
location.Add(5);
}
public IString getNewInstance(string value)
{
return (IString)(new CSVString(value));
}
}
}
</code></pre>
| [] | [
{
"body": "<p>The first word that comes to my mind, is <em>over-engineering</em>. This looks like a lot of trouble just to get to work with a CSV string, you turn a 10-liner into a party, happiness ensues and neighbors come too, and their friends also, and before you know it you've got 100 lines of code written, to accomplish the exact same thing.</p>\n\n<p>This answer/review does not care about that.</p>\n\n<hr>\n\n<blockquote>\n <p><strong>StringModifier</strong></p>\n</blockquote>\n\n<p>The <code>RegisteredTypes</code> private field can be made <code>readonly</code>, and its naming doesn't match naming conventions for private types. I'd declare it like this:</p>\n\n<pre><code>private readonly List<IStringType> _registeredTypes;\n</code></pre>\n\n<p>And initialize it directly in the constructor, and remove the private <code>RegisterTypes</code> method altogether:</p>\n\n<pre><code> public StringModifier()\n {\n _registeredTypes = TypeFactory.GetTypeList();\n }\n</code></pre>\n\n<p>While <code>str</code> is a well-understood short for <code>string</code> and I prefer <code>str</code> over <code>@string</code>, I think a better name for that parameter could be, simply, <code>value</code> - also I'd remove <code>String</code> from the method's name, it's in a class called <code>StringModifier</code>, it takes a <code>string</code> parameter and returns a <code>string</code> value. If <code>Modify</code> isn't clear enough, I don't know what is!</p>\n\n<pre><code> public string Modify(string value)\n {\n var detectedString = DetectStringType(value);\n return detectedString.Modify(ModificationPattern);\n }\n</code></pre>\n\n<p>I don't think the comments add anything significant in the <code>ModifyString</code> method. You have descriptive method names, already doing the job of describing what the code does (and that's good!).</p>\n\n<p>The <code>DetectStringType</code> method has opportunities for improvements - the <code>RegisteredTypes</code> needs only to be accessed once, and <code>msg</code> just seems like an arbitrary name - <code>result</code> makes more sense I find:</p>\n\n<pre><code> private IString DetectStringType(string value)\n {\n IString result = new NullString(value);\n\n for (var i = 0; i < _registeredTypes.Count; i++)\n {\n var type = _registeredTypes[i];\n if (value.StartsWith(type.start))\n {\n result = type.GetNewInstance(value);\n ModificationPattern = type.MODPattern;\n }\n\n }\n\n return result;\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><strong>TypeFactory</strong></p>\n</blockquote>\n\n<p>The name is ambiguous, if not overly broad. <code>StringTypeFactory</code> would be a better name. This class is clearly infrastructure code. I don't see a need for it to be <code>static</code> though: by using it in <code>StringModifier</code> the way you are, you have <em>tightly coupled</em> the two classes, essentially making <code>StringModifier</code> responsible for finding all <code>IStringType</code> implementations in the current app domain... which seems like a lot to do for a <code>StringModifier</code>.</p>\n\n<p>I'd move this infrastructure code to infrastructure level, and <em>inject</em> an <code>IEnumerable<IStringType></code> into <code>StringModifier</code>'s constructor:</p>\n\n<pre><code> private readonly IEnumerable<IStringType> _registeredTypes;\n public StringModifier(IEnumerable<IStringType> types)\n {\n _registeredTypes = types;\n }\n</code></pre>\n\n<p>By <em>infrastructure level</em>, I mean this:</p>\n\n<pre><code> var inputText = \"CSV,field1,field2,field3,field4,field5,field6,field7,,,,\";\n\n var factory = new StringTypeFactory();\n var modifier = new StringModifier(factory.GetTypeList());\n\n var outputText = modifier.Modify(inputText);\n</code></pre>\n\n<p>..and I know you're not going to like it. Because you probably want to be able to <code>new</code> up a <code>StringModifier</code> whenever you need to use one - my recommendation is to avoid <code>new</code>ing up <em>anything</em>. With that many abstractions/interfaces, call me crazy but I'll say that <em>you're missing an <code>IStringModifier</code> abstraction</em>:</p>\n\n<pre><code>public interface IStringModifier\n{\n string Modify(string value);\n}\n</code></pre>\n\n<p>Now whenever you have a class that wants to use a <code>StringModifier</code>, you'll <em>inject</em> an <code>IStringModifier</code> through that class' constructor, assign a private readonly field, and use that field. This is called <em>Dependency Injection</em>, and it greatly helps <em>decoupling</em> code and making it more unit-testable. <em>Creating objects</em> is a concern on its own, that belongs to <em>infrastructure code</em>.</p>\n\n<p>This hypothetical <code>SomeClass</code> consumes an <code>IStringModifier</code> and shows how <em>constructor injection</em> works:</p>\n\n<pre><code>public class SomeClass\n{\n private readonly IStringModifier _modifier;\n\n public SomeClass(IStringModifier modifier)\n {\n _modifier = modifier;\n }\n\n public void Foo(string bar)\n {\n var modified = _modifier.Modify(bar);\n // ...\n }\n}\n</code></pre>\n\n<p>But back to your code...</p>\n\n<hr>\n\n<blockquote>\n <p><strong>IStringType</strong></p>\n</blockquote>\n\n<p>The interface members don't follow casing conventions. Should look more like this:</p>\n\n<pre><code>public interface IStringType\n{\n string Start { get; }\n IString GetNewInstance(string value);\n IStringModificationPattern Pattern { get; }\n}\n</code></pre>\n\n<blockquote>\n <p><strong>IString</strong></p>\n</blockquote>\n\n<p>The interface members don't follow casing conventions either:</p>\n\n<pre><code>public interface IString\n{\n string Value { get; }\n string Modify(IStringModificationPattern pattern);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><strong>IStringType Implementations</strong></p>\n</blockquote>\n\n<p>The <code>IStringModificationPattern</code> property smells. All there is to it, is a getter that returns a <code>new</code> instance of a <em>tightly coupled</em> implementation of the <em>modification pattern</em> interface.</p>\n\n<blockquote>\n <p><strong>IString Implementations</strong></p>\n</blockquote>\n\n<p>The naming for <code>NullString</code> is <em>dangerously</em> ambiguous. <code>VanillaString</code> could probably work, ...and actually I can't think of any better names than that at the moment! ;)</p>\n\n<p>The <code>CsvString</code> (PascalCase FTW!) could use an overloaded constructor that takes a custom separator. Handy when you have string values that may contain commas:</p>\n\n<pre><code> public CsvString(string value) \n : this(value, ',')\n { /* no op */ }\n\n public CsvString(string value, char separator)\n {\n Value = value;\n CsvFields = value.Split(separator);\n }\n</code></pre>\n\n<p>Now, your <code>CsvString</code> implementation has serious encapsulation issues:</p>\n\n<pre><code> public string STR { get; set; }\n public List<string> CSVFields { get; set; }\n</code></pre>\n\n<p>Nothing prevents client code from overwriting all the hard work put into coming up with a value for <code>STR</code>. And nothing prevents client code from throwing away the <code>CSVFields</code> and replace it with another <code>List<string></code> reference.</p>\n\n<p>With auto-properties:</p>\n\n<pre><code> public string Value { get; private set; }\n public IEnumerable<string> Fields { get; private set; }\n</code></pre>\n\n<p>Exposing <code>Fields</code> as an <code>IEnumerable<string></code> rather than a <code>List<string></code> allows client code to iterate the fields, but not to <code>Add</code> or <code>Remove</code> anything. In fact, the intent would be made even clearer with a <code>readonly</code> backing field for the fields' reference (no pun intended):</p>\n\n<pre><code> private string _value;\n public string Value { get { return _value; } }\n\n private readonly IEnumerable<string> _fields;\n public string IEnumerable<string> Fields { get { return _fields; } }\n</code></pre>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\"><em>Principle of Least Knowledge</em></a> tells us that if fields are meant to be added or removed from a <code>CsvString</code>, then <code>CsvString</code> should expose methods to do so (and then the backing field would probably be better of as an <code>IList<string></code>), not letting its clients fiddle with it directly: the type of <code>_fields</code> is /<em>should be</em> of no concern to the client code.</p>\n\n<p>I renamed <code>CsvFields</code> to just <code>Fields</code>, because it's a misleading name: there's no separator involved here, it's just ..fields :)</p>\n\n<hr>\n\n<blockquote>\n <p><em>How can I handle different string modification patterns (I currently make it work by using IStringModificationPattern - but I want to extend this to other types like HTML)?</em></p>\n</blockquote>\n\n<p>Before extending this API, I'd secure <em>extensibility</em> as a design concern, and address it with a <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a> response.</p>\n\n<blockquote>\n <p><em>What design changes/ additions can I make to integrate the string modification pattern into a configuration class (i.e. using an XML file based settings)?</em></p>\n</blockquote>\n\n<p>You could probably serialize your <code>IStringModificationPattern</code> implementations to XML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:52:37.833",
"Id": "85366",
"Score": "0",
"body": "Thanks a lot for your feedback. I added a section at the bottom of my original post with revised code based on your feedback. Not sure if I made use of all your recommendations correctly but i tried. My idea now was to work from the configuration settings and bringing that into the application. So the StringModificationpattern classes represent the settings I deserialize from XML (or take from GUI) and I would detect the string and instantiate my objects based on that. I kept the way the user or application calls this 'api' very simple using a wrapper that does everything behind the scenes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:56:18.373",
"Id": "85367",
"Score": "0",
"body": "Additionally I can look into changing to the IEnumerable and encapsulate better my code, I was just trying to get it structured correctly so it works."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T05:26:08.100",
"Id": "48544",
"ParentId": "48452",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:12:59.817",
"Id": "48452",
"Score": "5",
"Tags": [
"c#",
"strings",
".net",
"csv"
],
"Title": "String modification application"
} | 48452 |
<p>I've been trying several styles of validation code for a form. I was wondering if this is good or needs some improvement or just trash it and use jQuery validator code?</p>
<pre><code>$("#registration-form").on("submit", function(e) {
e.preventDefault();
var error_field = "";
$(this).find(".input-field").each(function() {
var field_id = $(this).attr("id");
var value = $.trim($(this).val());
var length = value.length;
var error_value = "";
// Do field checks
if (length == 0) {
error_value = "You missed this field. D:";
} else if (length > 0 && length < 7) {
error_value = capitalize(field_id) + " too short";
} else if (length > 30 && field_id == "username") {
error_value = capitalize(field_id) + " too long";
} else if (length > 50 && field_id == "password") {
error_value = capitalize(field_id) + " too long";
} else if (passwordCombination(value) === false && field_id == "password") {
error_value = capitalize(field_id) + " must contain at least one string, number, and symbol.";
} else if (emailValidate(value) === false && field_id == "email") {
error_value = "Invalid email! :(";
}
// Do show error labels
if (error_value != null) {
$("#registration-form .content-row."+ field_id + " .box-error").text(error_value);
error_field += error_value;
}
});
if (error_field == "") {
var username = $.trim($("#username").val());
var email = $.trim($("#email").val());
var password = $.trim($("#password").val());
$.ajax({ type: "POST", url: "process/app_usage.php",
data: { username: username, email: email, process: "validate_user_email" },
success: function(data) {
// Do stuff
}
});
}
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T05:30:51.730",
"Id": "96196",
"Score": "0",
"body": "Why you don't use [this jQuery Validation plugin](http://jqueryvalidation.org/)!. It offers plenty of customization options."
}
] | [
{
"body": "<blockquote>\n <p>I was wondering if this is good</p>\n</blockquote>\n\n<p>Well, are you just looking to prevent the normal user from messing up during registration? I think it would be fine for that.</p>\n\n<p>I'll see if I can point out flaws in your validation...</p>\n\n<ol>\n<li>First, you check to see if <code>length</code> is 0. If it is, you warn them. Cool. But right after, you check to see if it's greater than 0. This is redundant? It would have to be longer than 0 characters to pass the first conditional!</li>\n<li>Now you check <code>length < 7</code>. But what if my email is <code>a@a.ca</code>? Eeek! But I was lucky and set up my domain www.a.ca with email support and registered with my first initial!</li>\n<li>Why can't the username be longer than 30 characters? Is your database not capable of such long strings? If it truly just cannot handle those awfully long names, fine. If it can, I'd suggest you support long names! Besides, I'd hate to find a new username if I've always used my most favorite 32 characters username!</li>\n<li>Why can't my password be longer than 50 characters either? I might be one of those <a href=\"https://security.stackexchange.com/questions/6095/xkcd-936-short-complex-password-or-long-dictionary-passphrase\">users who has funky passwords</a> that are always has 9 words in their passwords.</li>\n<li>What exactly is <code>passwordCombination()</code>? If I'm one of those funky users I mentioned in point 4, I'd be upset with this rule.</li>\n<li>Use <code><input type=\"email\" /></code> to validate emails on the client-side, not <code>emailValidate()</code>. Then check it again on the server with something such as <a href=\"http://php.net/manual/en/filter.examples.validation.php\" rel=\"nofollow noreferrer\">PHP's <code>filter_var()</code></a>.</li>\n<li><code>\":(\"</code> should really be <code>\"):\"</code> to be consistant with eye placement in <code>\"D:\"</code>.</li>\n</ol>\n\n<p>There's some critique on your validation. So maybe it would be best to find an established validation library and make slight alterations to suit you! <a href=\"https://developers.google.com/web/fundamentals/input/form/provide-real-time-validation\" rel=\"nofollow noreferrer\">Google has some validation standards</a>, and <a href=\"http://dev.w3.org/html5/spec-preview/constraints.html\" rel=\"nofollow noreferrer\">W3C also has some tips and tricks</a> up their sleeve!</p>\n\n<p>But always remember:</p>\n\n<blockquote>\n <p>Servers should not rely on client-side validation. Client-side validation can be intentionally bypassed by hostile users, and unintentionally bypassed by users of older user agents</p>\n</blockquote>\n\n<p>Now I'm not JavaScript maniac, but I might be able to help a little!</p>\n\n<ul>\n<li>I believe you could generalize <code>$(this).find(\".input-field\")</code> into something such as <code>$(this).find(\"input[type=text], input[type=password]\")</code>. This way you don't rely on having that class.</li>\n<li><h2>You just check if <code>error_field</code> is empty, so why not make it simpler and turn it into a counter. Each error increments it. In the end, if it's value is equal to 0, it's all good!</h2></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T01:13:43.923",
"Id": "105182",
"Score": "1",
"body": "@BrianCoolidge I'm glad I was able to answer this, plus the fact that it's months old, yet it got you back here :) Sorry for the wait, it won't happen again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T00:19:04.317",
"Id": "58580",
"ParentId": "48453",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "58580",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:26:27.907",
"Id": "48453",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"validation",
"form"
],
"Title": "Form Validation Evaluation"
} | 48453 |
<p>This is a follow-up to: <a href="https://codereview.stackexchange.com/questions/48442/lock-for-preventing-concurrent-access-in-client-data">Lock for preventing concurrent access in client data</a></p>
<p>I am trying to implement lock by which I want to avoid reads from happening whenever I am doing a write on my three maps.</p>
<p>My requirements are:</p>
<ol>
<li>Reads block until all three maps have been set for the first time.</li>
<li>Now second time, If I am updating the maps, I can still return all the three old maps value(before the updates are done on all three maps) or it should block and return me all the new three maps value whenever the updates are done on all the three maps.</li>
</ol>
<p>As I have three <code>Map</code>s - <code>primaryMapping</code>, <code>secondaryMapping</code> and <code>tertiaryMapping</code>, it should return either all the new values of three updated maps or it should return all the old values of the map. Basically, while updating I don't want to return <code>primaryMapping</code> having old values, <code>secondaryMapping</code> having having new values, and <code>tertiaryMapping</code> with new values.</p>
<p>It should be consistent, either it should return old values or it should return new values after updating the maps. In my case, updating of maps will happen once in three months or four months.</p>
<p>Here is my <code>ClientData</code> class in which I am using <code>ReentrantLock</code> in which the whole logic is there:</p>
<pre><code>public class ClientData {
private static final class MapContainer {
private Map<String, Map<Integer, String>> value = null;
public Map<String, Map<Integer, String>> getValue() {
return value;
}
public void setValue(Map<String, Map<Integer, String>> value) {
this.value = value;
}
}
private static final MapContainer primaryMapping = new MapContainer();
private static final MapContainer secondaryMapping = new MapContainer();
private static final MapContainer tertiaryMapping = new MapContainer();
private static final MapContainer[] containers = {primaryMapping, secondaryMapping, tertiaryMapping};
private static boolean allset = false;
private static final Lock lock = new ReentrantLock();
private static final Condition allsetnow = lock.newCondition();
private static final Map<String, Map<Integer, String>> getMapping(MapContainer container) {
lock.lock();
try {
while (!allset) {
allsetnow.await();
}
return container.getValue();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // reset interruptedd state.
throw new IllegalStateException(e);
} finally {
lock.unlock();
}
}
public static void setAllMappings(Map<String, Map<Integer, String>> primary,
Map<String, Map<Integer, String>> secondary,
Map<String, Map<Integer, String>> tertiary) {
lock.lock();
try{
// how to avoid this?
if (allset) {
throw new IllegalStateException("All the maps are already set");
}
primaryMapping.setValue(primary);
secondaryMapping.setValue(secondary);
tertiaryMapping.setValue(tertiary);
allset = true;
allsetnow.signalAll();
} finally {
lock.unlock();
}
}
public static Map<String, Map<Integer, String>> getPrimaryMapping() {
return getMapping(primaryMapping);
}
public static Map<String, Map<Integer, String>> getSecondaryMapping() {
return getMapping(secondaryMapping);
}
public static Map<String, Map<Integer, String>> getTertiaryMapping() {
return getMapping(tertiaryMapping);
}
}
</code></pre>
<p>Here is my background thread code which will get the data from my service URL and keep on running every 10 minutes once my application has started up. It will then parse the data coming from the URL and store it in a <code>ClientData</code> class variable in those three maps.</p>
<pre><code>public class TempScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void startScheduler() {
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
callServers();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 0, 10, TimeUnit.MINUTES);
}
}
// call the servers and get the data and then parse
// the response.
private void callServers() {
String url = "url";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
parseResponse(response);
}
// parse the response and store it in a variable
private void parseResponse(String response) {
//...
ConcurrentHashMap<String, Map<Integer, String>> primaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> secondaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> tertiaryTables = null;
//...
// store the data in ClientData class variables if anything has changed
// which can be used by other threads
if(changed) {
ClientData.setAllMappings(primaryTables, secondaryTables, tertiaryTables);
}
}
}
</code></pre>
<p>I will be using <code>getPrimaryMapping</code>, <code>getSecondaryMapping</code> and <code>getTertiaryMapping</code> in the <code>ClientData</code> class from the main thread in my main appliction so I want to return either all the new set of values from these three maps or if update is happening, then either block it and return all the new set of values for those three maps after the updates are done.</p>
<p>In the <code>ClientData</code> class, I guess I won't be able to update the maps once it has been set for the first time as this line will cause a problem and throw an exception. Also, how can I implement my second point as shown above?</p>
<pre><code>// how to avoid this?
if (allset) {
throw new IllegalStateException("All the maps are already set");
}
</code></pre>
<p>How can I successfully implement all my above two points? I guess there is something very minor thing which I am missing here. I want to use <code>ReentrantLock</code> here but any other suggestions are also welcome.</p>
<p>Initially, I was thinking to remove this <code>if</code> statement:</p>
<pre><code>// how to avoid this?
if (allset) {
throw new IllegalStateException("All the maps are already set");
}
</code></pre>
<p>Will it still work?</p>
| [] | [
{
"body": "<h1>A simpler approach</h1>\n<p>As far as I can tell from your problem definition, you're overthinking it:</p>\n<ul>\n<li><p><code>ConcurrentMap</code> is overkill because you won't be writing concurrently. As long as you pass a memory barrier of some sort, your other threads will read correctly.</p>\n</li>\n<li><p><code>MapContainer</code> doesn't seem to be serving a purpose, nor does <code>MapContainer[] containers</code>.</p>\n</li>\n</ul>\n<p>Here is a more bare-bones version of your code. (A slightly more cleaned up version is further below.)</p>\n<pre><code>import java.util.Map;\n\npublic class ClientData {\n private static volatile Map<String, Map<Integer, String>> mappings[] = new Map[] {\n Collections.emptyMap(),\n Collections.emptyMap(),\n Collections.emptyMap()\n };\n \n public static void setMappings(\n Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary) {\n // build the array, then assign to volatile reference = memory barrier\n mappings = new Map[] {\n primary, secondary, tertiary\n };\n }\n \n // all these read from volatile reference = memory barrier\n public static Map<String, Map<Integer, String>>[] getMappings() {\n return mappings.clone(); // clone not strictly necessary,\n // but protects from accidental changes\n }\n\n public static Map<String, Map<Integer, String>> getPrimaryMapping() {\n return mappings[0];\n }\n\n public static Map<String, Map<Integer, String>> getSecondaryMapping() {\n return mappings[1];\n }\n\n public static Map<String, Map<Integer, String>> getTertiaryMapping() {\n return mappings[2];\n }\n}\n</code></pre>\n<p>It should meet your needs:</p>\n<ul>\n<li><p>Reader threads will not see incomplete changes if not all changes are already set. All your maps are published simultaneously.</p>\n</li>\n<li><p>It solves your "already set" problem.</p>\n</li>\n<li><p>Bonus: look, ma, no locks!</p>\n</li>\n</ul>\n<hr />\n<h1>Why this works</h1>\n<p>Where's the synchronized? <a href=\"http://www.youtube.com/watch?v=nV59cxMsFnU&t=12\" rel=\"nofollow noreferrer\">Where are the locks, Lebowski</a>? This can't be safe, right?</p>\n<p>Turns out that it is, since <code>volatile</code> semantics were changed in Java 5. From <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp03304/\" rel=\"nofollow noreferrer\" title=\"Java theory and practice: Fixing the Java Memory Model, Part 2\">Brian Goetz</a>:</p>\n<blockquote>\n<p>Under the new memory model, when thread A writes to a volatile variable V, and thread B reads from V, any variable values that were visible to A at the time that V was written are guaranteed now to be visible to B. The result is a more useful semantics of volatile, at the cost of a somewhat higher performance penalty for accessing volatile fields.</p>\n</blockquote>\n<p>Because <code>mappings</code> is a volatile reference, and there is no other reference path way to that array (aliasing), reads from and writes to it are strictly ordered. That means that you could never read the array and have incomplete writes dangling.</p>\n<p><strong>This is not bulletproof.</strong> In particular, if you have code that looks like this:</p>\n<pre><code>// Note that we go through ClientData.mappings twice\nString cafeBar = getPrimaryMapping().get("bar").get(0xCAFE);\nString fooBeef = getTertiaryMapping().get("foo").get(0xBEEF);\n</code></pre>\n<p>...you have no guarantee that those two variables were drawn from the same set of mappings. Another thread may have switched mappings in between.</p>\n<p>What you do to fix this, is fetch and store the array locally for as long as you can both: (1) not tolerate interference, and (2) can tolerate stale data.</p>\n<pre><code>// save a reference, safe for multiple reads\nMap<String, Map<Integer, String>> mappings[] = ClientData.getMappings();\nString cafeBar = mappings[0].get("bar").get(0xCAFE);\nString fooBeef = mappings[2].get("foo").get(0xBEEF);\n</code></pre>\n<p>In that vein, we can make the code safer to use, or at least not accidentally mess up:</p>\n<pre><code>public class ClientData {\n private static volatile ClientData global = new ClientData();\n\n // final guarantees written before publish\n private final Map<String, Map<Integer, String>> primary;\n private final Map<String, Map<Integer, String>> secondary;\n private final Map<String, Map<Integer, String>> tertiary;\n \n private ClientData() {\n this(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());\n }\n \n private ClientData(Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary) {\n this.primary = primary;\n this.secondary = secondary;\n this.tertiary = tertiary;\n }\n \n public static void set(\n Map<String, Map<Integer, String>> primary,\n Map<String, Map<Integer, String>> secondary,\n Map<String, Map<Integer, String>> tertiary) {\n global = new ClientData(primary, secondary, tertiary);\n }\n \n public static ClientData get() {\n return global;\n }\n\n public Map<String, Map<Integer, String>> getPrimaryMapping() {\n return primary;\n }\n\n public Map<String, Map<Integer, String>> getSecondaryMapping() {\n return secondary;\n }\n\n public Map<String, Map<Integer, String>> getTertiaryMapping() {\n return tertiary;\n }\n}\n</code></pre>\n<p>No more shady arrays, magic indices, and no alluring <code>get...Mapping()</code> to use instead of storing <code>ClientData.get()</code> into a local variable first.</p>\n<hr />\n<h1>Concurrent or Immutable?</h1>\n<p><em>Concurrent maps</em> will allow you to do concurrent reads and updates without jeopardising the integrity of your map. This is critical if your mappings will be modified after they are published to other threads. It doesn't look like that's the case in your program.</p>\n<p><em>Immutable maps</em> do not allow changes and are inherently thread-safe... provided they are published in a safe manner (such as through locks, synchronized, or volatile). They are a step up from <code>Collections.synchronizedMap</code> in that they take a copy of the map, which will protect you from aliasing bugs. <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\" title=\"Guava: Google Core Libraries for Java 1.6+\">The Guava library</a> has useful implementations of immutable maps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-03T04:54:27.880",
"Id": "112411",
"Score": "0",
"body": "I have similar question for review [here](http://codereview.stackexchange.com/questions/61536/having-full-atomicity-against-all-the-threads-without-impacting-performance-or-t) as well. Can you please take a look whenever you have some time? I am stuck on that for a while."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T21:18:36.617",
"Id": "49677",
"ParentId": "48457",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "49677",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T04:40:36.530",
"Id": "48457",
"Score": "4",
"Tags": [
"java",
"performance",
"multithreading",
"locking"
],
"Title": "Lock for preventing concurrent access in client data - follow-up"
} | 48457 |
<p>I am learning data structures, and have written an algorithm for insertion sort after learning from some sources. But I am confused which implementation is more correct or appropriate.
<br><br><strong>Code #1</strong> This implementation takes an element and sorts itself with all the elements to its left, one by one, like bubble sort I think. I am just sorting and I think I can not say I am inserting an element to its correct location.</p>
<pre><code>public static int[] insertionSortAsc(int[] elemArr){
int len = elemArr.length;
int temp;
for (int i=0; i<= (len-2); i++){
for (int j=(i+1); j>0; j--){
if (elemArr[j] < elemArr[j-1]){
//swap
temp = elemArr[j];
elemArr[j] = elemArr[j-1];
elemArr[j-1] = temp;
}
}
}
return elemArr;
}
</code></pre>
<p><br><strong>Code #2</strong> This implementation takes an element into a 'temp' variable, compares it with left elements in the array and sorts them by comparing with the 'temp' element. When sorting stops, which means that the left side is sorted corresponding the 'temp' element, then this is element is put into that last location.</p>
<pre><code>public static int[] insertionSort(int[] elements) {
for (int i=1; i<elements.length; i++) {
int j, elem_i = elements[i];
for (j=i; j>0 && elements[j-1] > elem_i; j--) {
elements[j] = elements[j-1];
}
elements[j] = elem_i;
}
return elements;
}
</code></pre>
<p><br>I also have another idea though I have not written the code which I think matches my thought about the meaning of insertion sort.</p>
<ol>
<li>Create an array, sortArr, of same size as that of input array.</li>
<li>Find the minimum element, and put that to sortArr[0]. If more elements with same value, put them into successive locations and maintain the count, means the index to which value is filled into sortArr. Put this minimum element to some tempMin variable.</li>
<li>Now check for another element in the original array which is just greater than tempMin, if found, replace the value of tempMin with this value, and then copy this to sortArr according to the filling count variable, increase the count thereby.</li>
<li>Repeat steps 2 and 3, until filling count variable reaches array length.</li>
<li>Exit.</li>
</ol>
<p>I might be wrong but that is my thought. Please suggest algorithm modifications or my thinking if I am wrong.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T07:49:14.653",
"Id": "85086",
"Score": "0",
"body": "Found a review comment myself. I am modifying original array so there is no need to return the same array, it is already modifying the source. Proper way can be to clone the array and operating on the clone and returning it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T09:04:49.197",
"Id": "85092",
"Score": "0",
"body": "Your code#1 does not sort the whole array.. it only sorts the \"lower\" half of it. Also for the simple bubblesort-swap you implemented, you only need one for-loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T10:57:32.447",
"Id": "85093",
"Score": "0",
"body": "@Vogel612 Thanks for the reply! Are both implementation correct for insertion sort? What changes do you introduce for code#1 for loop, any real optimization?"
}
] | [
{
"body": "<h1>Bubble or Insert?</h1>\n\n<p>#1 and #2 are both implementations of insertion sort (*). The way you insert the element is not so important: whether you copy one by one, use <code>arraycopy</code>, or bubble it down is up to implementation. I'd imagine <code>arraycopy</code> to be the best for larger inputs.</p>\n\n<p>#3 would be closer to <strong>selection sort</strong>, a relative of insertion sort, though there's no advantage in allocating a new array. (Or maybe I misunderstand.)</p>\n\n<p>Both build a sorted part in the array, guaranteeing that at step <code>i</code>, <code>array[0..i]</code> is sorted. Both do their sorting in-line, not requiring extra array allocations. And both select an element from the unsorted part and then insert it. <em>The difference between insertion and selection is in how they select the next element to be inserted.</em></p>\n\n<p>Insertion sort doesn't care which element is next, so it selects whichever.</p>\n\n<p>Selection sort specifically select the littlest element from the rest of the array. This makes it more costly, but adds the additional guarantee that not only is <code>array[0..i]</code> in order, but it also contains the littlest elements of the entire array.</p>\n\n<p><sub>(*) Though #1 is related to bubble sort in a way his parents won't talk about.</sub></p>\n\n<h1>Optimise?</h1>\n\n<p>A strong point of insertion sort is that it performs very well for input that is already (mostly) sorted.</p>\n\n<p>#1 unconditionally runs in quadratic time: <code>i:[0..len-2], j:[i+1..0]</code>, which is in the order of <code>n² - n</code> steps.</p>\n\n<p>#2 is smarter about it, and doesn't run back comparing if it won't need to. This means it has the potential to run in close to linear time. Specifically, it will be in the order of <code>n + d*n</code> steps, with <code>d</code> being the number of elements out of order.</p>\n\n<p>#1 can be 'fixed' with a simple addition:</p>\n\n<pre><code>for (...) { \n for (...) {\n if (cond) {\n swap;\n } else {\n break; // <-- \n }\n }\n}\n</code></pre>\n\n<p>... or, depending on your style preference:</p>\n\n<pre><code>for (...) { \n for (... && cond) { // <-- as in #2\n if (cond) {\n swap;\n }\n }\n}\n</code></pre>\n\n<p>... after which it's pretty much the same as #2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:07:08.923",
"Id": "48490",
"ParentId": "48461",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48490",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T07:43:48.763",
"Id": "48461",
"Score": "1",
"Tags": [
"java",
"algorithm",
"insertion-sort"
],
"Title": "Appropriate insertion sorting algorithm"
} | 48461 |
<p>Building on the older building block, <a href="https://codereview.stackexchange.com/questions/47273/trading-card-games-hand-class-and-tests">Trading Card Game's Hand class and tests</a>, I decided it was time to implement a <code>HandView</code>, which can be implemented by a GUI for example. The view need only be notified if a <em>structural</em> change happens in the "parent" class.</p>
<p>I have taken the following facts into consideration:</p>
<ul>
<li>Loose coupling: I don't want the <code>HandView</code> to be a <em>member</em> of the <code>Hand</code> class</li>
<li>Composition over inheritance</li>
<li>Decoration to provide loose coupling.</li>
<li><code>Hand</code> <strong>is</strong> a collection of cards semanticaly, hence it implements <code>Collection<Card></code>.</li>
</ul>
<p>Needless to say, I am not entirely happy with this approach as it is quite bloated and hence I am looking at an event bus driven approach, one example of such is <a href="http://code.google.com/p/guava-libraries/wiki/EventBusExplained" rel="nofollow noreferrer">Guava Libraries EventBus</a>.</p>
<p>I haven't bothered with the unit tests for these classes yet as they are still all very experimental.</p>
<p><code>HandView</code>:</p>
<pre><code>public interface HandView {
public void onCardAdded(final Card card);
public void onCardPlayed(final int cardIndex);
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
}
</code></pre>
<p><code>Hand</code>:</p>
<pre><code>public interface Hand extends Collection<Card> {
public boolean isFull();
@Override
public boolean add(final Card card);
public Card get(final int index);
public Card play(final int index);
public void swap(final int indexOne, final int indexTwo);
@Override
public String toString();
@Override
public Iterator<Card> iterator();
@Override
public Spliterator<Card> spliterator();
@Override
public int size();
@Override
public void forEach(final Consumer<? super Card> action);
public static Hand newWithCapacity(final int capacity) {
return new HandImpl(capacity);
}
public static Hand decorateHand(final Hand hand, final HandView handView) {
Objects.requireNonNull(hand);
Objects.requireNonNull(handView);
return new Hand() {
@Override
public boolean isFull() {
return hand.isFull();
}
@Override
public boolean add(final Card card) {
boolean result = hand.add(card);
if (result) {
handView.onCardAdded(card);
}
return result;
}
@Override
public Card get(final int index) {
return hand.get(index);
}
@Override
public Card play(final int index) {
Card result = hand.play(index);
handView.onCardPlayed(index);
return result;
}
@Override
public void swap(final int indexOne, final int indexTwo) {
hand.swap(indexOne, indexTwo);
handView.onCardsSwapped(indexOne, indexTwo);
}
@Override
public Iterator<Card> iterator() {
return hand.iterator();
}
@Override
public Spliterator<Card> spliterator() {
return hand.spliterator();
}
@Override
public int size() {
return hand.size();
}
@Override
public void forEach(final Consumer<? super Card> action) {
hand.forEach(action);
}
@Override
public boolean isEmpty() {
return hand.isEmpty();
}
@Override
public boolean contains(final Object object) {
return hand.contains(object);
}
@Override
public Object[] toArray() {
return hand.toArray();
}
@Override
public <T> T[] toArray(final T[] array) {
return hand.toArray(array);
}
@Override
public boolean remove(final Object object) {
return hand.remove(object);
}
@Override
public boolean containsAll(final Collection<?> collection) {
return hand.containsAll(collection);
}
@Override
public boolean addAll(final Collection<? extends Card> collection) {
return hand.addAll(collection);
}
@Override
public boolean removeAll(final Collection<?> collection) {
return hand.removeAll(collection);
}
@Override
public boolean retainAll(final Collection<?> collection) {
return hand.retainAll(collection);
}
@Override
public void clear() {
hand.clear();
}
};
}
}
class HandImpl extends AbstractCollection<Card> implements Hand, Collection<Card> {
private final List<Card> list = new ArrayList<>();
private final int capacity;
protected HandImpl(final int capacity) {
this.capacity = Arguments.requirePositive(capacity, "capacity");
}
@Override
public boolean isFull() {
return (list.size() == capacity);
}
@Override
public boolean add(final Card card) {
Objects.requireNonNull(card);
States.requireFalse(isFull(), "hand is full");
list.add(card);
return true;
}
@Override
public Card get(final int index) {
checkIndex(index);
return list.get(index);
}
@Override
public Card play(final int index) {
checkIndex(index);
return list.remove(index);
}
@Override
public void swap(final int indexOne, final int indexTwo) {
checkIndex(indexOne);
checkIndex(indexTwo);
Collections.swap(list, indexOne, indexTwo);
}
@Override
public String toString() {
return Hand.class.getSimpleName() + "(" + capacity + ", " + list + ")";
}
@Override
public Iterator<Card> iterator() {
return list.iterator();
}
@Override
public Spliterator<Card> spliterator() {
return list.spliterator();
}
@Override
public int size() {
return list.size();
}
@Override
public void forEach(final Consumer<? super Card> action) {
Objects.requireNonNull(action);
list.forEach(action);
}
private void checkIndex(final int index) {
Arguments.requireIndexInRange(index, 0, size());
}
}
</code></pre>
<p>It can be instantiated with:</p>
<pre><code>Hand hand = Hand.newWithCapacity(5);
</code></pre>
<p>or</p>
<pre><code>Hand hand = Hand.decorateHand(Hand.newWithCapacity(5), /* concrete hand view */);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:45:38.000",
"Id": "85099",
"Score": "1",
"body": "\"I haven't bothered with the unit tests for these classes yet as they are still all very experimental.\" If you do not write tests first; tests, instead of verifying some preexisting requirement from that component, just bake in the current implementation. Does `Hand` really need *to extend* `Collection`? Do I really need to implement `spliterator()` for a collection that won't have more than a dozen elements? Let the requirements decide."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:50:04.070",
"Id": "85100",
"Score": "0",
"body": "@abuzittingillifirca The default implementations of `iterator()`, `spliterator()` and `forEach()` are not good enough, therefore it is very much advisory to override them. As the `List` already does this, it is just a minor detail to delegate them explicitely to that list."
}
] | [
{
"body": "<p>I will provide some comments here regarding your code, and at the end I will provide \"My version\" (with some of my comments taken into consideration).</p>\n\n<hr>\n\n<blockquote>\n <p>Composition over inheritance</p>\n</blockquote>\n\n<p>Although I understand that you mean that you want to use composition over inheritance for your <code>HandView</code>, your <code>HandImpl</code> (and your <code>Hand</code> itself) <em>is</em> using inheritance:</p>\n\n<pre><code>class HandImpl extends AbstractCollection<Card>\n</code></pre>\n\n<p>There is a bad aspect of letting your <code>Hand</code> class implement <code>Collection</code>: Completely outside of your class, somewhere far away in your code, would you want code which resides in a galaxy far far away to be allowed to call <code>someHand.clear();</code> ? You probably don't. Which is why implementing <code>Collection</code> can be a bad idea. By not implementing <code>Collection</code>, everything <strong>has to</strong> go through the methods that you provide, such as <code>someHand.play(index)</code>.</p>\n\n<p>You say that <em>Hand is a collection of cards semanticaly, hence it implements Collection.</em> and sure, I agree with that. Hand is a collection of cards, <em>but should it <strong>be used as such</strong> by outside code?</em> Not in my opinion.</p>\n\n<hr>\n\n<p>Because of your <code>capacity</code> in <code>HandImpl</code>, and that you're using an underlying <code>ArrayList</code>, it would be good to initialize the list to a specific capacity:</p>\n\n<pre><code>this.list = new ArrayList<>(capacity);\n</code></pre>\n\n<hr>\n\n<p>Guava provides a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ForwardingCollection.html\" rel=\"nofollow\"><code>ForwardingCollection</code> class</a>, using it would greatly reduce the number of lines in your code.</p>\n\n<hr>\n\n<p>I think that you are over-using your own <code>checkIndex</code> and other validations. You can remove them in the below cases (and probably some others too) to let the default exception be thrown (which will be very similar to the own you throw manually). Removing these additional checks you have added also can remove the need for overriding the method entirely, which will reduce some clutter.</p>\n\n<pre><code>@Override\npublic Card get(final int index) {\n checkIndex(index);\n return list.get(index);\n}\n\n@Override\npublic void forEach(final Consumer<? super Card> action) {\n Objects.requireNonNull(action);\n list.forEach(action);\n}\n</code></pre>\n\n<hr>\n\n<p>Overriding methods in an interface. These lines in your <code>Hand</code> interface can be removed entirely, they don't provide anything extra since <code>Hand</code> <strong>extends</strong> <code>Collection<Card></code>.</p>\n\n<pre><code>@Override\npublic String toString();\n\n@Override\npublic Iterator<Card> iterator();\n\n@Override\npublic Spliterator<Card> spliterator();\n\n@Override\npublic int size();\n\n@Override\npublic void forEach(final Consumer<? super Card> action);\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Loose coupling: I don't want the HandView to be a member of the Hand class</p>\n</blockquote>\n\n<p>IMO, whether or not it's a member of the Hand class does not affect coupling. HandView is an interface, it is already loosely coupled.</p>\n\n<p>This method however, in your <code>Hand</code> interface, provides some coupling:</p>\n\n<pre><code>public static Hand newWithCapacity(final int capacity) {\n return new HandImpl(capacity);\n}\n</code></pre>\n\n<p>I don't think this method belongs in your interface. Perhaps in a <code>HandFactory</code> (which might be a bit overkill). Or in your <code>Game</code> class. Or somewhere else. This is just my opinion though.</p>\n\n<hr>\n\n<p>My version:</p>\n\n<p>This code is still quite similar to your code. The hand still <code>implements Collection<Card></code>, but the number of lines has been reduced by about 25-30 % (I might also have changed a few things to get it to compile, as I don't have some of your other classes, so read and see what I have done, and apply the things you want to your own code).</p>\n\n<pre><code>interface HandView {\n public void onCardAdded(final Card card);\n\n public void onCardPlayed(final int cardIndex);\n\n public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);\n}\n\npublic interface Hand extends Collection<Card> {\n public boolean isFull();\n\n public Card get(final int index);\n\n public Card play(final int index);\n\n public void swap(final int indexOne, final int indexTwo);\n\n public static Hand newWithCapacity(final int capacity) {\n return new HandImpl(capacity);\n }\n\n public static Hand decorateHand(final Hand hand, final HandView handView) {\n Objects.requireNonNull(hand);\n Objects.requireNonNull(handView);\n return new ForwardingHand(hand) {\n @Override\n public boolean add(final Card card) {\n boolean result = hand.add(card);\n if (result) {\n handView.onCardAdded(card);\n }\n return result;\n }\n\n @Override\n public Card play(final int index) {\n Card result = hand.play(index);\n handView.onCardPlayed(index);\n return result;\n }\n\n @Override\n public void swap(final int indexOne, final int indexTwo) {\n hand.swap(indexOne, indexTwo);\n handView.onCardsSwapped(indexOne, indexTwo);\n }\n };\n }\n}\n\nclass HandImpl extends ForwardingCollection<Card> implements Hand {\n private final List<Card> list = new ArrayList<>();\n private final int capacity;\n\n protected HandImpl(final int capacity) {\n this.capacity = capacity;\n }\n\n @Override\n public boolean isFull() {\n return (list.size() == capacity);\n }\n\n @Override\n public boolean add(final Card card) {\n Objects.requireNonNull(card);\n if (isFull())\n throw new IllegalArgumentException();\n list.add(card);\n return true;\n }\n\n @Override\n public Card get(final int index) {\n return list.get(index);\n }\n\n @Override\n public Card play(final int index) {\n return list.remove(index);\n }\n\n @Override\n public void swap(final int indexOne, final int indexTwo) {\n Collections.swap(list, indexOne, indexTwo);\n }\n\n @Override\n public String toString() {\n return Hand.class.getSimpleName() + \"(\" + capacity + \", \" + list + \")\";\n }\n\n @Override\n protected Collection<Card> delegate() {\n return list;\n }\n}\n\nclass ForwardingHand extends ForwardingCollection<Card> implements Hand {\n\n private final Hand delegate;\n\n public ForwardingHand(Hand hand) {\n this.delegate = hand;\n }\n\n @Override\n public boolean isFull() {\n return delegate.isFull();\n }\n\n @Override\n public Card get(int index) {\n return delegate.get(index);\n }\n\n @Override\n public Card play(int index) {\n return delegate.play(index);\n }\n\n @Override\n public void swap(int indexOne, int indexTwo) {\n delegate.swap(indexOne, indexTwo);\n }\n\n @Override\n protected Collection<Card> delegate() {\n return delegate;\n }\n}\n</code></pre>\n\n<p>I should add though that your code is very readable and understandable, so don't think of this as a \"your code is crap\" review. Think about this as a \"Have you thought about this?\" / \"What about this way?\" review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:32:40.227",
"Id": "48472",
"ParentId": "48466",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48472",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T09:12:05.217",
"Id": "48466",
"Score": "10",
"Tags": [
"java",
"game",
"community-challenge"
],
"Title": "Trading Card Game's Hand and HandView implementation using composition and decoration"
} | 48466 |
<h2>Initial problem</h2>
<p>For a project I found myself in the need to search for elements in a container that are the closest neighbours to another precise element I have. In my case it was points in any dimension, but it can apply to various other things that we are not used to compute "distance" for.</p>
<p>So I decided to write a generic function to perform this search, so I can use it for whatever type I want, provided that I can compute the "distance" between two elements of this type. I tried to make it in the style of standard library's algorithm.</p>
<h2>My solution</h2>
<pre><code>template<typename T, class Distance>
struct Comp
{
using result_type = typename std::result_of<Distance(const T&, const T&)>::type;
using type = std::less<result_type>;
};
template<class InputIt, typename T, class Distance,
class Compare = typename Comp<T, Distance>::type>
std::vector<T> find_n_nearest(
InputIt start,
InputIt end,
const T& val,
size_t n,
Distance dist,
Compare comp = Compare())
{
std::vector<T> result{start, end};
std::sort(std::begin(result), std::end(result),
[&] (const T& t1, const T& t2)
{
return comp(dist(val, t1), dist(val, t2));
});
result.erase(std::begin(result) + n, std::end(result));
return result;
}
</code></pre>
<p>What this (the function) basically does is :</p>
<ul>
<li>create a copy of the range we want to look in</li>
<li>sort it, by comparing values returned from the <code>distance</code> function between <code>val</code> and the element of the range, so that we have the nearest neighbours of <code>val</code> at the begining of our vector</li>
<li>compare the distances with a custom operator if provided, <code>std::less</code> if not</li>
<li>only keep the <code>n</code> elements we want</li>
</ul>
<p>Now about the boilerplate :</p>
<p>I want to default the <code>Compare</code> type to <code>std::less</code>, which needs a type parameter. So we need to find the return type of the <code>Distance</code> object provided, and my solution here is what I found to work with both functions and lambdas.</p>
<h2>Examples</h2>
<p>Simple use case : retrieve the nearest values to an int. Distance between two ints will be the absolute value of their substraction.</p>
<pre><code>const auto distance_int =
[] (int i, int j)
{
return std::abs(i-j);
};
std::vector<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
auto res = {0, 10, 23, -20, 36};
auto found = find_n_nearest(std::begin(v), std::end(v), 4, 5, distance_int);
if(std::equal(std::begin(res), std::end(res), std::begin(found)))
std::cout << "Success !" << std::endl;
</code></pre>
<p>To illustrate the use of the comparator, let's say I now define my "neighbourhood" of ints as being as distant as possible. In a word, the opposite of the precedent example.</p>
<pre><code>std::list<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
auto res = {79841651, -3256, 68, 59, 56};
auto found = find_n_nearest(std::begin(v), std::end(v), 4, 5, distance_int, std::greater<int>());
if(std::equal(std::begin(res), std::end(res), std::begin(found)))
std::cout << "Success !" << std::endl;
</code></pre>
<h2>Review</h2>
<p>When I used this function, it was convenient to me to receive the results as a <code>std::vector<T></code> but this is not very good as a generic algorithm.</p>
<p>There are two problems with this : I think we should not alter the original range, so sorting it is not an option. Then we have to copy it elsewhere, and for that I used my cache vector (not that much time to think about it during the project, and it was not a critical piece of code). I thought of replacing this by providing an <code>OutputIt</code> to the function, indicating where to put the results (for example an user-provided vector or whatever container), but I don't think I could sort the range in my algorithm, because the <code>Output Iterator</code> concept is used only to ... output things.</p>
<p>If there are more efficient algorithms (instead of sorting from distance) to do it feel free to tell me, but that's not my main concern. I'd like to have an elegant solution, and pieces of advice on anything you think is not quite good in my code.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:15:57.160",
"Id": "85159",
"Score": "0",
"body": "I am afraid you are overcomplicating things. With a proper comparator, `std::partial_sort` does exactly what you need. And I don't think it is a great burden for the caller to make an alterable copy prior to the call."
}
] | [
{
"body": "<p>From a design point of view, when the standard library algorithms have to return a <code>[begin, end)</code> range of values, they don't return a container but take an additional <a href=\"http://en.cppreference.com/w/cpp/concept/OutputIterator\" rel=\"nofollow\"><code>OutputIterator</code></a> iterator (<em>e.g.</em> <a href=\"http://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"nofollow\"><code>std::copy</code></a>). Therefore, you function declaration should be along these lines:</p>\n\n<pre><code>template<\n typename T,\n typename InputIt,\n typename OutputIt,\n typename Distance,\n typename Compare = typename Comp<T, Distance>::type\n>\nvoid find_n_nearest(\n InputIt first,\n InputIt last,\n OutputIt d_first,\n const T& val,\n std::size_t n,\n Distance dist,\n Compare comp = Compare());\n</code></pre>\n\n<p>That said, the standard library algorithms also tend to return the first iterator of the output range, so the declaration would become:</p>\n\n<pre><code>template<\n typename T,\n typename InputIt,\n typename OutputIt,\n typename Distance,\n typename Compare = typename Comp<T, Distance>::type\n>\nOutputIt find_n_nearest(\n InputIt first,\n InputIt last,\n OutputIt d_first,\n const T& val,\n std::size_t n,\n Distance dist,\n Compare comp = Compare());\n</code></pre>\n\n<p>That way, your code and the client's one do no rely on a particular container type, but work with any compatible range. That's how genericity is achieved in the standard library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:57:24.533",
"Id": "85352",
"Score": "0",
"body": "So I was heading in the right direction, thanks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:06:12.220",
"Id": "85353",
"Score": "0",
"body": "@tehinternetsismadeofcatz Probably. But look at iavr's answer. They tend to give incredibly good advice :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:06:44.223",
"Id": "85354",
"Score": "0",
"body": "Yeah I'm reading through all of your answers !"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:23:07.760",
"Id": "48478",
"ParentId": "48470",
"Score": "4"
}
},
{
"body": "<p>You have a function which is performing three steps:</p>\n\n<ol>\n<li>Copy the input range</li>\n<li>Sort the copied range by distance to a given element</li>\n<li>Erase elements from the result range</li>\n</ol>\n\n<p>I would omit the first and last step. These are convenience elements providing no real functionality. In addition, the third step is erasing possible useful information and involves undefined behavior if the input range has not the number of requested elements (<code>result.erase(std::begin(result) + n, std::end(result);</code>).</p>\n\n<p>Leaving the second step:\nHere we have a std::sort with a custom comparator operating on distances. Your comparator depends on the result type of a distance function and is not more than a type trait. You might avoid that.</p>\n\n<p>An alternative implementation might be:</p>\n\n<pre><code>#include <algorithm>\n#include <iterator>\n\n// Distance\n// ========\n\ntemplate <typename T>\nstruct Distance {\n T operator () (const T& a, const T& b) {\n return std::abs(a - b);\n }\n};\n\n// Compare Distance\n// ================\n\ntemplate <\n typename T,\n typename DistanceFunctor = Distance<T>,\n typename CompareFunctor = std::less<decltype(\n std::declval<DistanceFunctor>()(std::declval<T>(), std::declval<T>()))>>\nstruct CompareDistance\n{\n T pivot;\n DistanceFunctor distance;\n CompareFunctor compare;\n CompareDistance(T&& pivot)\n : pivot(std::move(pivot))\n {}\n\n CompareDistance(T&& pivot, DistanceFunctor&& distance)\n : pivot(std::move(pivot)),\n distance(std::move(distance))\n {}\n\n CompareDistance(T&& pivot, DistanceFunctor&& distance, CompareFunctor&& compare)\n : pivot(std::move(pivot)),\n distance(std::move(distance)),\n compare(std::move(compare))\n {}\n\n bool operator () (const T& a, const T& b) {\n return compare(distance(a, pivot), distance(b, pivot));\n }\n};\n\n// Distance Sort\n// =============\n\ntemplate <typename Iterator, typename T>\ninline void distance_sort(\n Iterator first,\n Iterator last,\n T&& pivot)\n{\n typedef typename std::iterator_traits<Iterator>::value_type value_type;\n CompareDistance<value_type> compare_distance(std::move(pivot));\n std::sort(first, last, compare_distance);\n}\n\ntemplate <typename Iterator, typename T, typename Distance>\ninline void distance_sort(\n Iterator first,\n Iterator last,\n T&& pivot,\n Distance&& distance)\n{\n typedef typename std::iterator_traits<Iterator>::value_type value_type;\n CompareDistance<value_type, Distance> compare_distance(\n std::move(pivot),\n std::move(distance));\n std::sort(first, last, compare_distance);\n}\n\ntemplate <typename Iterator, typename T, typename Distance, typename Compare>\ninline void distance_sort(\n Iterator first,\n Iterator last,\n T&& pivot,\n Distance&& distance,\n Compare&& compare)\n{\n typedef typename std::iterator_traits<Iterator>::value_type value_type;\n CompareDistance<value_type, Distance, Compare> compare_distance(\n std::move(pivot),\n std::move(distance),\n std::move(compare));\n std::sort(first, last, compare_distance);\n}\n\n// Test\n// ====\n\n#include <iostream>\n\nint main() {\n std::vector<int> original = { 56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256 };\n\n // Find closest neighbours [less]:\n std::vector<int> elements(original);\n distance_sort(begin(elements), end(elements), 4);\n\n for(const auto& e : elements)\n std::cout << e << ' ';\n std::cout << '\\n';\n\n // Find closest neighbours [greater]:\n distance_sort(begin(elements), end(elements), 4, Distance<int>(), std::greater<int>());\n\n for(const auto& e : elements)\n std::cout << e << ' ';\n std::cout << '\\n';\n\n // Without distance_sort, but with existing tools\n std::sort(\n begin(elements),\n end(elements),\n [](int a, int b) {\n const int pivot = 4;\n return std::abs(a - pivot) < std::abs(b - pivot);\n }\n );\n\n for(const auto& e : elements)\n std::cout << e << ' ';\n std::cout << '\\n';\n}\n</code></pre>\n\n<p>Please notice the option not to provide anything and rely on existing tools.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:19:12.340",
"Id": "85347",
"Score": "1",
"body": "If I started from some code and it ended up four times longer for the same functionality, I would ask myself if something has gone wrong. Plus, why is everything `move`d and not `forward`ed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:14:56.743",
"Id": "85356",
"Score": "0",
"body": "@iavr Any advice on when to use rvalue references for template parameters ? If I refer to the standard lib's algorithms, they never use them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:02:24.347",
"Id": "85362",
"Score": "0",
"body": "@tehinternetsismadeofcatz (you mean *function* parameters?) Depends on expected input and algorithm. Iterators typically contain just a pointer, and function objects are empty; in both cases it's better to pass by value, so this is common in STL. Typically iterators need to be copied, so pass-by value is the only option. Function objects may be non-empty (like a `compare` containing a data point) or have mutable state. In such cases, the most generic option is rvalue (universal) references that are `std::forward`ed unless used more than once (in which case `std::forward` only on last use)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T09:47:28.267",
"Id": "85407",
"Score": "0",
"body": "@iavr I meant function parameters that depend on a template, like for example `Distance&& distance` in Dieter's answer. In fact I was wondering if the compiler can deduce that the `Distance` type passed is a (rvalue) reference or not. But I bet it's clearer to specify it with `&&` in the function parameters anyway. I think I'll have a deeper read on type deduction for templates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:06:13.347",
"Id": "85412",
"Score": "0",
"body": "@tehinternetsismadeofcatz With `&&` it's not just clearer: skipping `&&` means \"pass-by-value\". You can check [universal references](https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers) and pages 7-8 of [perfect forwarding](http://thbecker.net/articles/rvalue_references/section_07.html)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:25:27.943",
"Id": "48532",
"ParentId": "48470",
"Score": "3"
}
},
{
"body": "<p>I think all you need is <a href=\"http://en.cppreference.com/w/cpp/algorithm/nth_element\"><code>std::nth_element</code></a>:</p>\n\n<pre><code>template<typename Q, typename I, typename Distance>\nvoid find_n_nearest(const Q& q, I first, I nth, I last, Distance dist)\n{\n using T = decltype(*first);\n auto compare = [&q, &dist] (T i, T j) { return dist(i, q) < dist(j, q); };\n std::nth_element(first, nth, last, compare);\n std::sort(first, last, compare);\n}\n\nint main()\n{\n auto distance = [] (int i, int j) { return std::abs(i-j); };\n std::vector<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};\n auto res = {0, 10, 23, -20, 36};\n\n find_n_nearest(4, v.begin(), v.begin() + 5, v.end(), distance);\n assert(std::equal(v.begin(), v.begin() + 5, res.begin()));\n}\n</code></pre>\n\n<p>If you just need the <code>n</code> nearest elements but not necessarily sorted, you can skip <code>std::sort</code>. Then complexity is linear in <code>n</code>.</p>\n\n<p>I have skipped the initial copy part, because it's not always needed. Feel free to add it if you like.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:10:35.603",
"Id": "85355",
"Score": "0",
"body": "Clever, I feel ashamed that I looked quickly at `nth_element` but did not see the use for it. One thing to say, we drop the modularity of the comparator here. Not that it would be incredibly useful though (well idk, but I wanted to achieve it while writing my function)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:38:08.533",
"Id": "85361",
"Score": "0",
"body": "If you want the modularity of the comparator, then I would suggest to drop dependence on `dist` and point `q` as well. Then you have a new and more generic function that is actually just `nth_element` followed by `sort`. You could name this `nth_sorted` and have `find_n_nearest` call that one after constructing `compare`, which encapsulates `q` and `dist`. This way you are just splitting `find_n_nearest` into two steps. I think that's much cleaner."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:44:38.173",
"Id": "48619",
"ParentId": "48470",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48619",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T10:16:10.400",
"Id": "48470",
"Score": "8",
"Tags": [
"c++",
"c++11",
"template",
"clustering"
],
"Title": "Std lib-like C++ function to find nearest elements in a container"
} | 48470 |
<p>I tried to write <a href="https://github.com/tomilov/variant" rel="nofollow noreferrer">my own</a> <code>variant</code> class, that is fully move-semantics enabled. WRT to implemented visitors, they don't require any policy and like to be derived from <code>boost::static_visitor</code> or to contain <code>typedef</code>ed <code>result_type</code>. The result type of the visitor deduced by means of <code>std::result_of</code> and also can be <a href="https://stackoverflow.com/a/3601661/1430927">prvalue, rref, lref or const lref</a>. The only requirement is that all the returning types for all possible invocations of visitor must be of the same type exactly. It can be improved using <code>std::common_type</code> or something alike but better (to keep referenceness). Multivisitor provides the ability to pass some (non-visitable, i.e. not derived from <code>variant<></code> class) of the arguments to visitor. It is very useful (for me).</p>
<p>Forward substitution of partial visitors (is a part of implementation details) of multivisitor is perfectly inlining. But backstroke is evidently no, due to type erasure points facing. It is non-avoidable anyways.</p>
<p>The following code (5<sup>5</sup> = 3125 functions generated for visitor functor) compiles 20.9s vs 51.2s for <code>boost::variant</code>:</p>
<pre><code>struct P
: boost::static_visitor< void >
{
template< typename ...T >
result_type
operator () (T &&...) const
{
//return __PRETTY_FUNCTION__;
}
};
int main()
{
struct A {};
struct B {};
struct C {};
struct D {};
struct E {};
using V = boost::variant< A, B, C, D, E >;
P p;
V v0(A{}), v1(B{}), v2(C{}), v3(D{}), v4(E{});
boost::apply_visitor(p, v0, v1, v2, v3, v4);
return 0;
}
</code></pre>
<p>The compilation time of the code for my variant class significantly depends on lengths of symbol names (both on type names provided as template parameters to <code>variant<></code>, and, say, on enclosing my variant machinery into own namespace). Dependence have nonlinear character and such behaviour is very strange. Definitely, there is the matter for issue. Compilation time for <code>boost::variant</code> does not depend on indicated above.</p>
<p>On my mind the <strong>never-empty-guarantee</strong> observed completely.</p>
<p><a href="https://github.com/tomilov/variant" rel="nofollow noreferrer">Following</a> code works on <strong>gcc</strong> perfectly. <a href="http://coliru.stacked-crooked.com/a/c1cc1799598d3f03" rel="nofollow noreferrer">Live example on Coliru</a>.</p>
<p>Code of the variant implementation part itself:</p>
<pre><code>#pragma once
#include "traits.hpp"
#include "recursive_wrapper.hpp"
#include <exception>
#include <memory>
#include <utility>
#include <type_traits>
#include <typeinfo>
namespace insituc
{
struct bad_get
: std::exception
{
~bad_get() noexcept = default;
bad_get() = default;
bad_get(const char * const _what)
: what_(_what)
{ ; }
virtual
const char *
what() const noexcept
{
return what_;
}
private :
const char * const what_ = "bad_get: failed value get using get()";
};
template< typename ...types >
struct variant
{
static_assert((0 < sizeof...(types)),
"type list should not be empty");
static_assert(and_< !std::is_reference< types >::value... >::value,
"type list should not contain a reference");
static_assert(and_< !std::is_const< types >::value... >::value,
"type list should not contain a const");
static_assert(and_< !std::is_volatile< types >::value... >::value,
"type list should not contain a volatile");
template< typename type >
using which_type = get_offset< 0, is_same< type, unwrap_type< types > >::value... >;
template< int _which >
using type = typename nth_type< _which, unwrap_type< types >... >::type;
using types_count = int_< sizeof...(types) >;
private :
template< typename type >
using is_this_type = bool_< !(which_type< unrefcv< type > >::value < 0) >;
template< int _which >
using internal_type = typename nth_type< _which, types... >::type;
template< typename ...arguments >
using which_is_constructible_from = get_offset< 0, std::is_constructible< unwrap_type< types >, arguments... >::value... >;
template< typename type >
using which_is_assignable_from = get_offset< 0, std::is_assignable< unwrap_type< types > &, type >::value... >;
template< typename ...arguments >
using is_there_constructible = or_< std::is_constructible< unwrap_type< types >, arguments... >::value... >;
template< typename type >
using is_there_assignable = or_< std::is_assignable< unwrap_type< types > &, type >::value... >;
constexpr static std::size_t const size = max_value< std::size_t, sizeof(types)... >::value;
constexpr static std::size_t const align = max_value< std::size_t, alignof(types)... >::value;
using storage_type = typename std::aligned_storage< size, align >::type; // std::aligned_union would be better to use
std::unique_ptr< storage_type > storage_ = std::make_unique< storage_type >();
int which_ = -1;
template< typename storage, typename visitor, typename type, typename ...arguments >
static
result_of< visitor, unwrap_type< type >, arguments... >
caller(storage && _storage, visitor && _visitor, arguments &&... _arguments)
{
//static_assert(std::is_same< unrefcv< storage >, storage_type >::value, "!");
return std::forward< visitor >(_visitor)(unwrap(reinterpret_cast< type >(_storage)), std::forward< arguments >(_arguments)...);
}
struct destroyer
{
template< typename type >
void
operator () (type & _value) const
{
_value.~type();
}
};
template< typename rhs >
enable_if< is_this_type< unrefcv< rhs > >::value >
construct(rhs && _rhs)
{
static_assert(std::is_constructible< unrefcv< rhs >, rhs >::value, "type selected, but it cannot be constructed");
constexpr int _which = which_type< unrefcv< rhs > >::value;
::new (storage_.get()) internal_type< _which >(std::forward< rhs >(_rhs));
which_ = _which;
}
template< typename ...arguments >
void
construct(arguments &&... _arguments)
{
constexpr int _which = which_is_constructible_from< arguments... >::value;
static_assert(!(_which < 0), "no one type can be constructed from specified parameter pack");
// -Wconversion warning here means, that construction or assignmnet may imply undesirable type conversion
::new (storage_.get()) internal_type< _which >(std::forward< arguments >(_arguments)...);
which_ = _which;
}
struct constructor
{
template< typename rhs >
void
operator () (rhs && _rhs) const
{
destination_.construct(std::forward< rhs >(_rhs));
}
variant & destination_;
};
struct assigner
{
template< int _which, typename rhs >
void
assign(rhs && _rhs) const
{
if (lhs_.which() == _which) {
// -Wconversion warning here means, that assignment may imply undesirable type conversion
lhs_.get< type< _which > >() = std::forward< rhs >(_rhs);
} else {
variant backup_(std::forward< rhs >(_rhs));
lhs_.swap(backup_);
}
}
template< typename rhs >
enable_if< is_this_type< unrefcv< rhs > >::value >
operator () (rhs && _rhs) const
{
static_assert(std::is_assignable< unrefcv< rhs > &, rhs >::value, "type selected, but it cannot be assigned");
static_assert(std::is_constructible< unrefcv< rhs >, rhs >::value, "type selected, but it cannot be constructed");
assign< which_type< unrefcv< rhs > >::value >(std::forward< rhs >(_rhs));
}
template< typename rhs >
enable_if< (!is_this_type< unrefcv< rhs > >::value && (is_there_assignable< rhs >::value && is_there_constructible< rhs >::value)) >
operator () (rhs && _rhs) const
{
assign< which_is_assignable_from< rhs >::value >(std::forward< rhs >(_rhs));
}
template< typename rhs >
enable_if< (!is_this_type< unrefcv< rhs > >::value && (is_there_assignable< rhs >::value && !is_there_constructible< rhs >::value)) >
operator () (rhs && _rhs) const
{
constexpr int _which = which_is_assignable_from< rhs >::value;
if (lhs_.which() == _which) {
// -Wconversion warning here means, that assignment may imply undesirable conversion
lhs_.get< type< _which > >() = std::forward< rhs >(_rhs);
} else {
throw bad_get();
}
}
template< typename rhs >
enable_if< (!is_this_type< unrefcv< rhs > >::value && (!is_there_assignable< rhs >::value && is_there_constructible< rhs >::value)) >
operator () (rhs && _rhs) const
{
constexpr int _which = which_is_constructible_from< rhs >::value;
if (lhs_.which() == _which) {
throw bad_get();
} else {
variant backup_(std::forward< rhs >(_rhs));
lhs_.swap(backup_);
}
}
template< typename rhs >
enable_if< (!is_this_type< unrefcv< rhs > >::value && !(is_there_assignable< rhs >::value || is_there_constructible< rhs >::value)) >
operator () (rhs &&) const
{
throw bad_get();
}
variant & lhs_;
};
struct reflect
{
template< typename type >
std::type_info const &
operator () (type const &) const noexcept
{
return typeid(type);
}
};
public :
~variant() noexcept
{
apply_visitor(destroyer{});
}
void
swap(variant & _other) noexcept
{
storage_.swap(_other.storage_);
std::swap(which_, _other.which_);
}
int
which() const
{
return which_;
}
template< typename visitor, typename ...arguments >
result_of< visitor, type< 0 > const &, arguments... >
apply_visitor(visitor && _visitor, arguments &&... _arguments) const &
{
static_assert(is_same< result_of< visitor, unwrap_type< types > const &, arguments... >... >::value,
"non-identical return types in visitor");
using result_type = result_of< visitor &&, type< 0 > const &, arguments... >;
using caller_type = result_type (*)(storage_type const & _storage, visitor && _visitor, arguments &&... _arguments);
constexpr static caller_type const dispatcher_[sizeof...(types)] = {&variant::caller< storage_type const &, visitor &&, types const &, arguments... >...};
return dispatcher_[which_](*storage_, std::forward< visitor >(_visitor), std::forward< arguments >(_arguments)...);
}
template< typename visitor, typename ...arguments >
result_of< visitor, type< 0 > &, arguments... >
apply_visitor(visitor && _visitor, arguments &&... _arguments) &
{
static_assert(is_same< result_of< visitor, unwrap_type< types > &, arguments... >... >::value,
"non-identical return types in visitor");
using result_type = result_of< visitor &&, type< 0 > &, arguments... >;
using caller_type = result_type (*)(storage_type & _storage, visitor && _visitor, arguments &&... _arguments);
constexpr static caller_type const dispatcher_[sizeof...(types)] = {&variant::caller< storage_type &, visitor &&, types &, arguments... >...};
return dispatcher_[which_](*storage_, std::forward< visitor >(_visitor), std::forward< arguments >(_arguments)...);
}
template< typename visitor, typename ...arguments >
result_of< visitor, type< 0 > &&, arguments... >
apply_visitor(visitor && _visitor, arguments &&... _arguments) &&
{
static_assert(is_same< result_of< visitor, unwrap_type< types > &&, arguments... >... >::value,
"non-identical return types in visitor");
using result_type = result_of< visitor &&, type< 0 > &&, arguments... >;
using caller_type = result_type (*)(storage_type && _storage, visitor && _visitor, arguments &&... _arguments);
constexpr static caller_type const dispatcher_[sizeof...(types)] = {&variant::caller< storage_type &&, visitor &&, types &&, arguments... >...};
return dispatcher_[which_](std::move(*storage_), std::forward< visitor >(_visitor), std::forward< arguments >(_arguments)...);
}
variant()
{
static_assert(is_there_constructible<>::value, "no one type is default constructible");
construct();
}
variant(variant const & _rhs)
{
_rhs.apply_visitor(constructor{*this});
}
variant(variant && _rhs)
{
std::move(_rhs).apply_visitor(constructor{*this});
}
template< typename ...other_types >
variant(variant< other_types... > const & _rhs)
{
_rhs.apply_visitor(constructor{*this});
}
template< typename ...other_types >
variant(variant< other_types... > & _rhs)
{
_rhs.apply_visitor(constructor{*this});
}
template< typename ...other_types >
variant(variant< other_types... > && _rhs)
{
std::move(_rhs).apply_visitor(constructor{*this});
}
template< typename ...arguments >
variant(arguments &&... _arguments)
{
construct(std::forward< arguments >(_arguments)...);
}
variant &
operator = (variant const & _rhs)
{
_rhs.apply_visitor(assigner{*this});
return *this;
}
variant &
operator = (variant && _rhs)
{
std::move(_rhs).apply_visitor(assigner{*this});
return *this;
}
template< typename ...other_types >
variant &
operator = (variant< other_types... > const & _rhs)
{
_rhs.apply_visitor(assigner{*this});
return *this;
}
template< typename ...other_types >
variant &
operator = (variant< other_types... > & _rhs)
{
_rhs.apply_visitor(assigner{*this});
return *this;
}
template< typename ...other_types >
variant &
operator = (variant< other_types... > && _rhs)
{
std::move(_rhs).apply_visitor(assigner{*this});
return *this;
}
template< typename rhs >
variant &
operator = (rhs && _rhs)
{
static_assert((is_this_type< unrefcv< rhs > >::value || (is_there_assignable< rhs >::value || is_there_constructible< rhs >::value)),
"no one underlying type is proper to assignment");
assigner{*this}(std::forward< rhs >(_rhs));
return *this;
}
template< typename type >
type const &
get() const &
{
constexpr int _which = which_type< type >::value;
static_assert(!(_which < 0), "type is not listed");
if (which_ != _which) {
throw bad_get();
} else {
return unwrap(reinterpret_cast< internal_type< _which > const & >(*storage_));
}
}
template< typename type >
type &
get() &
{
constexpr int _which = which_type< type >::value;
static_assert(!(_which < 0), "type is not listed");
if (which_ != _which) {
throw bad_get();
} else {
return unwrap(reinterpret_cast< internal_type< _which > & >(*storage_));
}
}
template< typename type >
type &&
get() &&
{
constexpr int _which = which_type< type >::value;
static_assert(!(_which < 0), "type is not listed");
if (which_ != _which) {
throw bad_get();
} else {
return unwrap(reinterpret_cast< internal_type< _which > && >(*storage_));
}
}
std::type_info const &
get_type_info() const
{
return apply_visitor(reflect{});
}
};
template< typename type >
struct is_variant
: bool_< false >
{
};
template< typename first, typename ...rest >
struct is_variant< variant< first, rest... > >
: bool_< true >
{
};
template< typename ...types >
void
swap(variant< types... > & _lhs, variant< types... > & _rhs) noexcept
{
_lhs.swap(_rhs);
}
template< typename variant, typename ...arguments >
variant
make_variant(arguments &&... _arguments)
{
return variant(std::forward< arguments >(_arguments)...);
}
template< typename type, typename ...types >
type const &
get(variant< types... > const & _variant)
{
return _variant.template get< type >();
}
template< typename type, typename ...types >
type &
get(variant< types... > & _variant)
{
return _variant.template get< type >();
}
template< typename type, typename ...types >
type &&
get(variant< types... > && _variant)
{
return std::move(_variant).template get< type >();
}
} // namespace insituc
</code></pre>
<p>And code of the visitor implementation part (all the rest is on <a href="http://coliru.stacked-crooked.com/a/c1cc1799598d3f03" rel="nofollow noreferrer">Coliru</a>):</p>
<pre><code>#pragma once
#include "traits.hpp"
#include "variant.hpp"
#include <utility>
namespace insituc
{
namespace details
{
template< typename visitable >
using cvref_qualified_first_type = copy_cvref< visitable, typename unref< visitable >::template type< 0 > >;
template< typename supervisitor, typename type, bool = is_variant< unrefcv< type > >::value >
struct subvisitor;
template< typename supervisitor, typename visitable >
struct subvisitor< supervisitor, visitable, true >
{ // visitation
template< typename ...visited >
result_of< supervisitor, cvref_qualified_first_type< visitable >, visited... >
operator () (visited &&... _visited) const
{
return std::forward< visitable >(visitable_).apply_visitor(std::forward< supervisitor >(supervisitor_), std::forward< visited >(_visited)...);
}
supervisitor && supervisitor_;
visitable && visitable_;
};
template< typename supervisitor, typename type >
struct subvisitor< supervisitor, type, false >
{ // forwarding
template< typename ...visited >
result_of< supervisitor, type, visited... >
operator () (visited &&... _visited) const
{
return std::forward< supervisitor >(supervisitor_)(std::forward< type >(value_), std::forward< visited >(_visited)...);
}
supervisitor && supervisitor_;
type && value_;
};
template< typename ...visitables >
struct visitor_partially_applier;
template<>
struct visitor_partially_applier<>
{ // backward
template< typename visitor >
result_of< visitor >
operator () (visitor && _visitor) const
{
return std::forward< visitor >(_visitor)();
}
};
template< typename first, typename ...rest >
struct visitor_partially_applier< first, rest... >
: visitor_partially_applier< rest... >
{ // forward
using base = visitor_partially_applier< rest... >;
template< typename visitor >
result_of< base, subvisitor< visitor, first >, rest... >
operator () (visitor && _visitor, first && _first, rest &&... _rest) const
{
subvisitor< visitor, first > const subvisitor_{std::forward< visitor >(_visitor), std::forward< first >(_first)};
return base::operator () (subvisitor_, std::forward< rest >(_rest)...);
}
};
} // namespace details
template< typename visitor, typename first, typename ...rest >
//constexpr // C++14 // body of constexpr function not a return-statement
result_of< details::visitor_partially_applier< first, rest... > const, visitor, first, rest... >
apply_visitor(visitor && _visitor, first && _first, rest &&... _rest) // visitables can contain non-visitor types
{
details::visitor_partially_applier< first, rest... > const apply_visitor_partially_;
return apply_visitor_partially_(std::forward< visitor >(_visitor), std::forward< first >(_first), std::forward< rest >(_rest)...);
}
namespace details
{
template< typename visitor >
struct delayed_visitor_applier
{
/*static_assert(std::is_lvalue_reference< visitor >::value || !std::is_rvalue_reference< visitor >::value,
"visitor is not lvalue reference or value");*/
delayed_visitor_applier(visitor && _visitor)
: visitor_(std::forward< visitor >(_visitor))
{ ; }
result_of< visitor >
operator () () const
{
return visitor_();
}
result_of< visitor >
operator () ()
{
return visitor_();
}
template< typename visitable,
typename = enable_if< is_variant< unrefcv< visitable > >::value > >
result_of< visitor, cvref_qualified_first_type< visitable > >
operator () (visitable && _visitable) const
{
return std::forward< visitable >(_visitable).apply_visitor(visitor_);
}
template< typename visitable,
typename = enable_if< is_variant< unrefcv< visitable > >::value > >
result_of< visitor, cvref_qualified_first_type< visitable > >
operator () (visitable && _visitable)
{
return std::forward< visitable >(_visitable).apply_visitor(visitor_);
}
template< typename ...visitables >
result_of< details::visitor_partially_applier< visitables... > const, visitor, visitables... >
operator () (visitables &&... _visitables) const
{
return apply_visitor(visitor_, std::forward< visitables >(_visitables)...);
}
template< typename ...visitables >
result_of< details::visitor_partially_applier< visitables... > const, visitor, visitables... >
operator () (visitables &&... _visitables)
{
return apply_visitor(visitor_, std::forward< visitables >(_visitables)...);
}
private :
visitor visitor_;
};
} // namespace details
template< typename visitor >
constexpr
details::delayed_visitor_applier< visitor >
apply_visitor(visitor && _visitor)
{
return details::delayed_visitor_applier< visitor >(std::forward< visitor >(_visitor));
}
} // namespace insituc
</code></pre>
<p>Main cons are totally non-guaranteed <strong>exception safety</strong> on construction, copying, moving and so on. The implementation is based on smart pointers, and, thus, on dynamic memory allocation.</p>
<p>How can I improve exception safety? How can I get rid of using smart pointers and use different type of storage from the heap?</p>
<p>ADDITIONAL:</p>
<p>Recently I performed the test of compilation time for multivisitation. Three-dimentional results are presented as two cartesian projections. Upper one is dependence of compilation time (in seconds) on number of variant's bounded types for different <code>apply_visitor</code> arities (different lines). Bottom one is dependence of compilation time (in seconds) on <code>apply_visitor</code> arities for different numbers of variant's bounded types (different lines).</p>
<p><img src="https://i.stack.imgur.com/KLiwg.png" alt="dependencies of ct on task dimensionalities"></p>
<p>It is notable that compilation time have close to exponential dependence with respect to any dimesionality (<code>apply_visitor</code> arity or number of variant's bounded types).</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:27:48.127",
"Id": "85105",
"Score": "0",
"body": "It seems, that bloating of the symbol tables may be signinfically decreased using `decltype(auto)` as return type in **C++14**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:49:37.440",
"Id": "85130",
"Score": "0",
"body": "Why are you mixing the `Variant` pattern and `Visitor` pattern into a single low level class `insituc::variant<T...>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T10:40:00.107",
"Id": "86317",
"Score": "0",
"body": "@LokiAstari I think, that internal visitation is integral part of the variant (used at least in d-tor). Thus, we can't avoid to implement it as a part of the variant anyways. We should to separate headers for non-member function `apply_visitor` and member one (and variant class itself)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T10:30:04.263",
"Id": "88369",
"Score": "4",
"body": "Normally, editing the code in the question is disallowed. However, since this question is old and has no answers, I don't see any harm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T09:05:45.820",
"Id": "89403",
"Score": "0",
"body": "When lately I tried to compile the code with using of the `decltype(auto)` feature, then I met unobvious effect (just at first glance): `decltype(auto)` introduces few additional degrees of complexity in sense of O-notation, which is dramatically increases compilation time even on small dimensionalities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T09:07:39.310",
"Id": "89404",
"Score": "0",
"body": "So **C++14** does not introduce any usefull feature to improve above variant class multivisitation properties at my mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-02T03:27:05.153",
"Id": "154322",
"Score": "0",
"body": "There is memory leak on destruction for recursive_wrapper-ed bounded types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-20T06:19:38.170",
"Id": "171489",
"Score": "0",
"body": "@LokiAstari I found out multivisitation 1.5x faster in test 5x5 if member-function `apply_visitor` used instead of free function analog."
}
] | [
{
"body": "<h1>The things you did right</h1>\n\n<p>Almost all of your code:</p>\n\n<ul>\n<li>Correct use of rvalue references, move semantics and perfect forwarding.</li>\n<li>You provided namespace-level functions that help with ADL (even though namespace-level <code>get</code> will probably not be found by ADL, but you can't do anything about that).</li>\n<li>You ensured that <code>swap</code> was <code>noexcept</code>.</li>\n<li>You gave meaningful names to your types and variables.</li>\n<li>You did some \"concept check\" with <code>static_assert</code>, which helps avoiding horrible error messages.</li>\n</ul>\n\n<p>Basically, what you did is really good, especially since your edit. There's almost nothing left to say. Almost...</p>\n\n<h1>Naming stuff</h1>\n\n<blockquote>\n <p><em>There are only two hard things in Computer Science: cache invalidation, naming things and of-by-one errors.</em></p>\n</blockquote>\n\n<p>Your variable names have generally good names. However, for some reason, you seem to hate capital letters. You could use some, at least for you template parameter names. That would also allow you to drop many underscores. This piece of code:</p>\n\n<pre><code>template< typename storage, typename visitor, typename type, typename ...arguments >\nstatic\nresult_of< visitor, unwrap_type< type >, arguments... >\ncaller(storage && _storage, visitor && _visitor, arguments &&... _arguments)\n{\n // ...\n}\n</code></pre>\n\n<p>would probably be easier to read written as:</p>\n\n<pre><code>template< typename Storage, typename Visitor, typename Type, typename ...Arguments >\nstatic\nresult_of< Visitor, unwrap_type< Type >, Arguments... >\ncaller(Storage && storage, Visitor && visitor, Arguments &&... arguments)\n{\n // ...\n}\n</code></pre>\n\n<p>I also almost got lost when I read this:</p>\n\n<pre><code>which_ = _which;\n</code></pre>\n\n<p>I understand the logic (leading underscore for class members), but I think that I would still make errors hard to detect if I wrote code with names so close from each other.</p>\n\n<h1>Exceptions</h1>\n\n<p>While I like the name <code>bad_get</code> for your exception (close to the names of the exceptions in the standard library), there are still some things that you can change in that class so that it looks even more like a standard library exception:</p>\n\n<ul>\n<li>You can make the destructor explicitly <code>virtual</code>.</li>\n<li>You can add a <code>std::string</code> overload to the constructor.</li>\n<li><p>You could also add an explicit <code>override</code> qualifier to the method <code>what</code> to clarify your intent (even though the standard library does not do it):</p>\n\n<pre><code>virtual const char * what() const noexcept override { /* .... */ }\n</code></pre>\n\n<p>I have to admit that there are many keywords on the same line. You can find information about why you should use the <code>override</code> keyword <a href=\"https://stackoverflow.com/a/18198377/1364752\">here</a>. But basically, remember that sometimes, you want to override a function in a derived class, but write a function with a slightly different signature. Sometimes, this kind of error can be really hard to spot (because of implicit base class name hiding for example). If you add <code>override</code> to make it clear that you intend to override a base class function, the compiler will tell you if you messed the signature and ended up not overriding anything. In short, it helps to prevent silent errors.</p></li>\n</ul>\n\n<h1>Dead code</h1>\n\n<p>You have some pieces of dead code left:</p>\n\n<pre><code>/*static_assert(std::is_lvalue_reference< visitor >::value || !std::is_rvalue_reference< visitor >::value,\n \"visitor is not lvalue reference or value\");*/\n</code></pre>\n\n<p>You should simply remove it. Dead code will not help you, and revision control software can help you to find old code that you may need but already removed.</p>\n\n<h1>Simplify your return statements</h1>\n\n<p>You can use <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow noreferrer\">list initialization</a> to make some of your return statements more readable provided the return type is already known by the function:</p>\n\n<pre><code>template< typename visitor >\nconstexpr\ndetails::delayed_visitor_applier< visitor >\napply_visitor(visitor && _visitor)\n{\n return details::delayed_visitor_applier< visitor >(std::forward< visitor >(_visitor));\n}\n</code></pre>\n\n<p>The code above can be reduced to:</p>\n\n<pre><code>template< typename visitor >\nconstexpr\ndetails::delayed_visitor_applier< visitor >\napply_visitor(visitor && _visitor)\n{\n return { std::forward< visitor >(_visitor) };\n}\n</code></pre>\n\n<p>That said, list initialization won't work if the constructor of <code>details::delayed_visitor_applier< visitor ></code> is marked <code>explicit</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T09:53:54.343",
"Id": "89579",
"Score": "0",
"body": "Can you clarify your sentence about method `what` - do you mean `which` instead? WRT simplification of `return` statements, I had already did it (in repository). I follow the guideline to not change the question text, so there is not actual version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T09:56:50.173",
"Id": "89582",
"Score": "0",
"body": "I'll take note about naming. I think that capital letters is better choise for template parameters naming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:00:56.627",
"Id": "89583",
"Score": "0",
"body": "Please clarify also about `std::string` overloading. Do you mean, that there will be separate `char *` to `std::string` conversion constructor, if `std::string` is presented as one of bounded types?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:02:51.617",
"Id": "89584",
"Score": "0",
"body": "The `bad_get` name chosen, because it is the routine in *Boost.Variant*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:03:35.503",
"Id": "89585",
"Score": "0",
"body": "I don't know exactly why there are two constructors to standard exception classes ([example](http://en.cppreference.com/w/cpp/error/logic_error)). The `const char*` one was added to C++11 but I don't know whether the `std::string` one is still helpful. They continue to add both of them to the classes that are currently developped though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:06:55.187",
"Id": "89587",
"Score": "0",
"body": "Sorry, I didn't note that all said is concerned to particularily exception part of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:10:08.263",
"Id": "89588",
"Score": "0",
"body": "What do you think, should I to change the code in original question? Or it is sufficient to add the link to public repository to the end of the **Q**?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T10:14:31.853",
"Id": "89590",
"Score": "0",
"body": "Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14746/discussion-between-morwenn-and-orient)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T08:17:54.327",
"Id": "51807",
"ParentId": "48471",
"Score": "9"
}
},
{
"body": "<p>Have you tried the assignment? Using clang3.5, I get the following if I just add <code>v3 = v0;</code> near the end of your main function posted above (I got your latest version of your code from your web site):</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>In file included from main.cpp:53:\n./traits.hpp:33:28: error: no matching function for call to object of type 'insituc::variant<A, B, C, D>::assigner'\nusing result_of = decltype(std::declval< type >()(std::declval< arguments >()...));\n ^~~~~~~~~~~~~~~~~~~~~~\n./variant/variant.hpp:275:32: note: in instantiation of template type alias 'result_of' requested here\n static_assert(is_same< result_of< visitor &&, unwrap_type< types > &, arguments &&... >... >,\n ^\n./variant/variant.hpp:351:14: note: in instantiation of function template specialization 'insituc::variant<A, B, C, D>::apply_visitor<insituc::variant<A, B, C, D>::assigner>' requested here\n _rhs.apply_visitor(assigner{*this});\n ^\nmain.cpp:89:8: note: in instantiation of member function 'insituc::variant<A, B, C, D>::operator=' requested here\nv3 = v0;\n ^\n./variant/variant.hpp:176:9: note: candidate template ignored: substitution failure [with rhs = A &]: non-type template argument is not a constant expression\n operator () (rhs && _rhs) const\n ^\n./variant/variant.hpp:205:9: note: candidate template ignored: substitution failure [with rhs = A &]: non-type template argument is not a constant expression\n operator () (rhs && _rhs) const\n ^\n./variant/variant.hpp:218:9: note: candidate template ignored: substitution failure [with rhs = A &]: non-type template argument is not a constant expression\n operator () (rhs && _rhs) const\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-10T01:18:05.977",
"Id": "139647",
"Score": "0",
"body": "Please provide exact link to repository you use (I suspect your revision is outdated)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-10T09:25:59.680",
"Id": "139672",
"Score": "0",
"body": "Can't find `main.cpp` in new repository location."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-12T18:45:17.360",
"Id": "139970",
"Score": "0",
"body": "repository is from here, latest version: https://bitbucket.org/insituc/insituc/src and main.cpp is from your original post (fist code snipped / your coliru example). From what I gather, the issue is that you are defining which_type, is_this-type, aliases etc in the variant class and then try to use them in the assigner local class, but those definitions are not supposed to be available until variant is fully defined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-13T05:49:02.703",
"Id": "140069",
"Score": "0",
"body": "The problem is in the version of `clang++`. I use `clang++` of version `3.6`. All works fine. But when tried to compile same code on `clang++ v3.5` on coliru, then I got failure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-14T04:20:05.180",
"Id": "140273",
"Score": "0",
"body": "Seems this is [the bug of clang++ 3.5](http://llvm.org/bugs/show_bug.cgi?id=17030#c1)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-10T00:57:46.873",
"Id": "77139",
"ParentId": "48471",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "51807",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T10:59:38.433",
"Id": "48471",
"Score": "18",
"Tags": [
"c++",
"c++11",
"error-handling",
"variant-type"
],
"Title": "Variant class with full move support"
} | 48471 |
<p>I need comments on the below code:</p>
<pre><code>Thread.new {EM.run do
IpamAgent::Amqp.run
end}
module IpamAgent
class Amqp
class << self
def run
begin
$connection = AMQP.connect(RMQ_CONFIGURATIONS)
$connection.on_tcp_connection_loss do |conn, settings|
Rails.logger.info "<<<<<<<<<<<<<<<< [network failure] Trying to reconnect...>>>>>>>>>>>>>>>>>>>>>>>>"
conn.reconnect(false, 2)
end
Rails.logger.info "<<<<<<<<<<<<<<<<<<<<<<<<AMQP listening>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
worker = IpamAgent::MessageHandler.new
worker.start
Rails.logger.info "<<<<<<<<<<<<<<<<<<<<<<<<Message handler started>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
rescue Exception => e
Rails.logger.info "<<<<<<<<<<<<<<<<<<<<<<<<Message handler Exception>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
Rails.logger.info "[error] Could not handle event of type #{e.inspect}"
Rails.logger.info "<<<<<<<<<<<<<<<<<<<<<<<<Message handler Exception>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
end
end
end
end
end
module IpamAgent
class MessageHandler
attr_accessor :ns_exchange, :sc_exchange, :ns_queue, :sc_queue, :service_location, :service_version, :service_name, :message_sequence_id, :presto_exchange, :presto_queue
def initialize
# Profile the code
@ns_exchange = CONFIGURATIONS["ns_exchange"]
@sc_exchange = CONFIGURATIONS["sc_exchange"]
@presto_exchange = CONFIGURATIONS["presto_exchange"]
@ns_queue = CONFIGURATIONS["ns_queue"]
@sc_queue = CONFIGURATIONS["sc_queue"]
@presto_queue = CONFIGURATIONS["presto_queue"]
end
# Create the channels, exchanges and queues
def start
ch1 = AMQP::Channel.new($connection)
ch2 = AMQP::Channel.new($connection)
ch3 = AMQP::Channel.new($connection)
@ns_x = ch1.direct(ns_exchange, :durable => true)
@ns_queue = ch1.queue(ns_queue, :auto_delete => false)
@ns_queue.bind(@ns_x, :routing_key => @ns_queue.name).subscribe(:ack => true, &method(:handle_ns_message))
@sc_x = ch2.topic(sc_exchange, :durable => true)
@sc_queue = ch2.queue(sc_queue, :auto_delete => false)
@sc_queue.bind(@sc_x, :routing_key => "#").subscribe(:ack => true, &method(:handle_sc_message))
@presto_x = ch3.direct(presto_exchange, :durable => true)
@presto_queue = ch3.queue(presto_queue, :auto_delete => false)
@presto_queue.bind(@presto_x, :routing_key => @presto_queue.name).subscribe(:ack => true, &method(:handle_presto_message))
end
# Handle the messages from Network service component
def handle_ns_message(headers, payload)
message_headers = JSON.parse(headers.to_json)["headers"]
payload = eval(payload)
headers.ack
Rails.logger.info ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MESSAGE FROM NS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
Rails.logger.info message_headers
Rails.logger.info payload
Rails.logger.info ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MESSAGE FROM NS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
tenant_detail = IpamAgent::TenantDetail.where(service_instance: payload["orgId"]).first
if(payload && payload.keys.include?(:responseCode))
new_tenant_detail = IpamAgent::TenantDetail.create(message: ({"header" => message_headers, "payload" => payload}), status: "waiting_for_sc", service_instance: payload["orgId"])
if tenant_detail && tenant_detail.service_group
publish_sgid_to_presto(tenant_detail)
else
get_sgid_from_sc(new_tenant_detail)
end
else
Rails.logger.info("Payload: #{payload}, routing key is #{message_headers}")
end
end
# Retrieve the Service Group ID from Service controller
def get_sgid_from_sc(tenant_detail)
message = tenant_detail.get_sc_message
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>PUBLISHING TO SC<<<<<<<<<<<<<<<<<<<<<<<")
Rails.logger.info(message)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>PUBLISHING TO SC<<<<<<<<<<<<<<<<<<<<<<<")
@sc_x.publish(message.last, :routing_key => @sc_queue.name, :headers => message.first, :mandatory => true)
end
# Handle the messages from Service controller
def handle_sc_message(headers, payload)
message_headers = JSON.parse(headers.to_json)
headers.ack
payload = eval(payload)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>MESSAGE FROM SC<<<<<<<<<<<<<<<<<<<<<<<")
Rails.logger.info(message_headers)
Rails.logger.info(payload)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>MESSAGE FROM SC<<<<<<<<<<<<<<<<<<<<<<<")
if(payload && payload["serviceInstanceGroupId"])
tenant_detail = IpamAgent::TenantDetail.find_or_save(payload)
publish_sgid_to_presto(tenant_detail)
end
end
# Shovel the NS request to PMP with Service Group ID
def publish_sgid_to_presto(tenant_detail)
tenant_details = TenantDetail.where(service_instance: tenant_detail.service_instance, status: "waiting_for_sc")
tenant_details.each do |sc|
sc.update(status: "success")
message = sc.get_pmp_message
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>PUBLISHING TO PRESTO<<<<<<<<<<<<<<<<<<<<<<<")
Rails.logger.info(message.first)
Rails.logger.info(message.last)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>PUBLISHING TO PRESTO<<<<<<<<<<<<<<<<<<<<<<<")
@presto_x.publish(message.last, :routing_key => @presto_queue.name, :headers => message.first, :mandatory => true)
end
end
# Receive the message from PMP presto and publsih it to Network Service
def handle_presto_message(headers, payload)
message_headers = JSON.parse(headers.to_json)
payload = eval(payload)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>MESSAGE FROM PRESTO<<<<<<<<<<<<<<<<<<<<<<<")
Rails.logger.info(headers.to_json)
Rails.logger.info(payload)
Rails.logger.info(">>>>>>>>>>>>>>>>>>>>MESSAGE FROM PRESTO<<<<<<<<<<<<<<<<<<<<<<<")
headers.ack
@ns_x.publish(payload, :routing_key =>@ns_queue.name, :headers => headers, :mandatory => true) if (message_headers && payload)
end
end
end
</code></pre>
| [] | [
{
"body": "<p><strong>Don't use global variables</strong><br>\nUsing <code>$connection</code> as a holder for your AMQP connection is a bad idea. <code>connection</code> being such a generic name, it might be used somewhere else for something completely different, and you may end up breaking your code with someone else's.</p>\n\n<p>A better idea would be to use class variables - this way you get your namespace for free:</p>\n\n<pre><code>module IpamAgent\n class Amqp\n class << self\n attr_reader connection\n\n def run\n begin\n @connection = AMQP.connect(RMQ_CONFIGURATIONS)\n connection.on_tcp_connection_loss do |conn, settings|\n # ...\nend\n</code></pre>\n\n<p>And now your usage will be:</p>\n\n<pre><code>def start\n ch1 = AMQP::Channel.new(IpamAgent::Amqp.connection)\n # ...\nend\n</code></pre>\n\n<p><strong>Don't change the meaning of a variable</strong><br>\nWhen you set a variable with one type, for one usage, but then set <em>the same</em> variable with another type, for a different usage - you are confusing yourself, and future code-readers, and make your code very brittle. This goes double for instance variables, and <em>triple</em> for instance variables exposed to the outside - what do you think a user will expect from this code:</p>\n\n<pre><code> worker = IpamAgent::MessageHandler.new\n queue = worker.ns_queue\n worker.start\n same_queue = worker.ns_queue\n</code></pre>\n\n<p><strong>Avoid noisy code, and noisy logs</strong><br>\nYour code is filled with <code><</code> and <code>></code> characters, which are meant to highlight sections in your log files, but since it is used so much, your log file will be filled with marquees, and will be painful to read (just like you code right now, only much worse).</p>\n\n<p>You should differentiate between events in the log using log levels - exceptions and errors should be logged using <code>Rails.logger.error</code>, production-level events should be logged using <code>Rails.logger.info</code>. All other events and debug data should be logged only using <code>Rails.logger.debug</code>, and maybe not at all.</p>\n\n<p><strong>Variable naming</strong><br>\nUsing names such as <code>ch</code>, <code>ns</code>, <code>sc</code>, etc. is very discouraged, unless it is part of your domain's nomenclature. For example, <code>ns</code> for a lot of people coming from XML, means <code>namespace</code>. Be verbal - use full names (<code>network_service</code>).</p>\n\n<p><strong>If it needs a comment - you probably have to rename it or refactor it</strong><br>\nYou have many methods with comments explaining what they do. Comments are generally a bad idea, since they tend to \"rot\" - when you change the code, most often than not, you neglect to maintain the comments (For example what does <code># Profile the code</code> refer to?).</p>\n\n<p>There are two types of method comments in your code - those which repeat the name of the method, and don't add much (<code>handle_network_service_message</code> is enough, you don't need to say <code># Handle the messages from Network service component</code>...), and those which explain things which are not explained by the method name.</p>\n\n<p>Delete the ones which repeat the name of the method.</p>\n\n<p>The other kind hints that you probably need to either rename the method, or break it down to its parts. You could either rename <code>start</code> to <code>create_channels</code>, or (probably better) have a <code>create_channel</code> method which <code>start</code> will call 3 times - it will make your code DRYier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:11:20.383",
"Id": "48657",
"ParentId": "48473",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T11:36:01.460",
"Id": "48473",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Implementation on AMQP in Ruby"
} | 48473 |
<p>I want to inform the Receivers about new contracts we have this week. After I sent the Emails, the Information about sent contracts are stored in MS SQL Database.</p>
<p>To avoid that someone become the same Email about contract more than one time I perform this steps:</p>
<ol>
<li>I have the Collection with new contracts as the input</li>
<li>I read the information from DB using Entity Framework about sent Emails</li>
<li>If the Emails was already sent I add new Instance to the sent Emails Collection</li>
</ol>
<p>After that, I remove the contracts from input collection that are already in sent collection:</p>
<pre><code>public Collection<Contract> GiveContractsThatWereNotSent(Collection<Contract> newThisWeekContracts)
{
var contractsWereSent = new Collection<Contract>();
using (var accountingEntities = new AccountingEntities())
{
foreach (Contract newContract in newThisWeekContracts)
{
bool found = (from sent in accountingEntities .Tbl_SentProtocol
where
sent.CONTRACT_NO == newContract.ContractNo
&& sent.CONTRACT_NO_ALT == newContract.ContractNoAlt
select sent ).Any();
if (found)
{
contractsWereSent.Add(newContract);
}
}
}
foreach (Contract contract in contractsWereSent)
{
newThisWeekContracts.Remove(contract);
}
return newThisWeekContracts;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:26:32.117",
"Id": "85115",
"Score": "1",
"body": "You're doing `N` queries to the database, where `N = newThisWeekContracts.Count`. Would probably be *better* [citation needed] to do just one query with two `IN` clauses. On the other hand, having two `IN` clauses with thousands of items each would *probably* be not so great either and would require further restructuring."
}
] | [
{
"body": "<p>Several points:</p>\n\n<ul>\n<li>Write your code against <em>abstractions</em>. <code>Collection</code> is a specific <em>implementation</em>.\n<ul>\n<li>You don't need <code>newThisWeekContracts</code> to be specifically a <code>Collection</code>. I'd take in any <code>IEnumerable<Contract></code> instead.</li>\n<li>By returning a <code>Collection</code>, the caller can <em>add</em> to it, or <em>remove</em> from it, which probably isn't the intended behavior. I'd return an <code>IEnumerable<Contract></code>, or, if adding/removing is ok, I'd return an <code>IList<Contract></code> or <code><ICollection<Contract></code> (i.e. an <em>abstraction</em>, not a specific <em>implementation</em>).</li>\n</ul></li>\n<li>I like the descriptive naming, casing is correct and all, but the names read a little bit awkward still.</li>\n</ul>\n\n<p>It looks like the number of queries can be reduced, haven't profiled this but I would think it consumes fewer resources; the main thing is combining <code>.Where()</code> with <code>.Any()</code> and <code>!.Any()</code> as needed:</p>\n\n<pre><code>public IEnumerable<Contract> GiveContractsThatWereNotSent(IEnumerable<Contract> newContracts)\n{\n using (var entities = new AccountingEntities())\n {\n var sentContracts =\n entities.Tbl_SentProtocol\n .Where(sent => \n newContracts.Any(contract => \n sent.CONTRACT_NO == contract.ContractNo\n && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))\n .ToList();\n\n }\n\n // ...\n}\n</code></pre>\n\n<p>That gives you <em>sent contracts</em> (/ <code>contractsWereSent</code>), but that's not what you're after. Now you need to return the contracts in <code>newContracts</code> (/ <code>newThisWeekContracts</code>) that are <em>not</em> in <code>sentContacts</code>.</p>\n\n<p>What you have here:</p>\n\n<pre><code>foreach (Contract contract in contractsWereSent)\n{\n newThisWeekContracts.Remove(contract);\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms132413%28v=vs.110%29.aspx\" rel=\"nofollow\">Involves calling <code>EqualityComparer<T>.Default</code> on each <code>contract</code></a>, which verifies whether <code>Contract</code> implements <code>IEquatable<T></code>, otherwise uses overrides of <code>.Equals</code> and <code>.GetHashCode</code> if <code>Contract</code> overrides them, otherwise uses <em>reference equality</em>... which doesn't sound very neat, since if a contract is \"equal\" when its <code>ContractNo</code> and <code>ContractNoAlt</code> exists in <code>sendContracts</code> when comparing in <code>Tbl_SentProtocol</code>, then I'd use the same equality comparison when I want to \"remove\" items from the <code>newContracts</code>.</p>\n\n<p>In fact, I wouldn't remove anything from <code>newContracts</code>. Keep inputs for inputs!</p>\n\n<p>How about this?</p>\n\n<pre><code>IEnumerable<Contract> sentContracts;\nusing (var entities = new AccountingEntities())\n{\n sentContracts = // trying to prevent horizontal scrolling...\n entities.Tbl_SentProtocol\n .Where(sent => \n newContracts.Any(contract => \n sent.CONTRACT_NO == contract.ContractNo\n && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))\n .ToList(); \n}\n\nreturn newContracts.Where(contract => !sentContracts.Any(sent =>\n sent.CONTRACT_NO == contract.ContractNo\n && sent.CONTRACT_NO_ALT == contract.ContractNoAlt))\n .ToList();\n</code></pre>\n\n<hr>\n\n<p>One more thing, the entities should be named so as to read like normal code - entity type <code>SentContract</code> can be mapped to table <code>tbl_SentProtocol</code>, and properties <code>ContractNumber</code> and <code>ContractAltNumber</code> can map to columns <code>CONTRACT_NO</code> and <code>CONTRACT_NO_ALT</code> ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:38:36.913",
"Id": "85646",
"Score": "0",
"body": "thank you for the very good explanation :) Upvote + Accept"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:35:37.817",
"Id": "48494",
"ParentId": "48477",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48494",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:14:37.347",
"Id": "48477",
"Score": "2",
"Tags": [
"c#",
"linq",
"entity-framework"
],
"Title": "Compare Collection with the information in DB using EF and LINQ"
} | 48477 |
<p>I need to generate a minimum and maximum value for a range of speeds (slow, medium, fast), the user can specify any combination of the 3 values, and receive a range that encompasses all.</p>
<p>Given any combination of <code>"slow"</code>, <code>"medium"</code>, <code>"fast"</code>, <code>getRange()</code> will return a <code>[min, max]</code> range.</p>
<p>The function can be called in the following ways:</p>
<pre><code>// Any combination of the values
getRange(['slow', 'medium', 'fast']); // [0, 100]
getRange(['medium', 'fast']); // [36, 100]
getRange(['slow']); // [0, 35]
// Or just a single string
getRange('fast'); // [76, 100]
// No string specified
getRange(); // [0, 100]
</code></pre>
<p>Is there any way to simplify my code? It seems a bit clunky and there's probably a simpler way of writing this:</p>
<pre><code>function getRange(speed){
var min, max;
if(speed && speed.length){
var obj = {};
if(Array.isArray(speed)){
speed.forEach(function(s){
obj[s] = true;
});
}
else{
obj[speed] = true;
}
if(obj.slow){
min = 0;
max = 35;
}
if(obj.medium){
if(typeof min == 'undefined'){
min = 36;
}
max = 75;
}
if(obj.fast){
if(typeof min == 'undefined'){
min = 76;
}
max = 100;
}
}
if(typeof min == 'undefined'){
min = 0;
}
if(typeof max == 'undefined'){
max = 100;
}
return [min, max];
};
</code></pre>
| [] | [
{
"body": "<p>I do believe this could be done easier. You could use the <code>||</code> shortcut to set <code>min</code> and <code>max</code> if you could not find a speed range, and you could extract the numbers into a data structure and go from there.</p>\n\n<p>Something like this:</p>\n\n<pre><code>function getRange(speed){\n //Speed range config, in array to preserve order\n var speedRanges = [\n { name: 'slow', min: 1 , max : 35 },\n { name: 'medium', min: 36 , max : 75 },\n { name: 'fast', min: 76 , max : 100 }\n ],\n min, max, i, range;\n //Build logic once for arrays, if we are not dealing with an array,\n //then turn speed into an array\n if (!Array.isArray(speed))\n speed = [speed];\n //Check for each speed range, apply if applicable \n for (i = 0; i < speedRanges.length; i++) {\n range = speedRanges[i];\n if (~speed.indexOf(range.name)) {\n min = min || range.min;\n max = range.max;\n }\n }\n\n min = min || 1;\n max = max || 100;\n return [min, max];\n}\n</code></pre>\n\n<p>If you absolutely need <code>slow</code> to be <code>0</code> to <code>35</code> then you will have to enhance <code>min = min || range.min;</code> since <code>0</code> counts as not set..</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:39:02.013",
"Id": "85107",
"Score": "0",
"body": "Thanks, `min = 0` is not really important."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:59:23.377",
"Id": "48480",
"ParentId": "48479",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48480",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T12:37:23.437",
"Id": "48479",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"interval"
],
"Title": "Generate [min, max] range from strings"
} | 48479 |
<p>What do you think of this piece of code ? This is an implementation of quick sort in C, but I'm not sure about the quality and correctness.</p>
<pre><code>#include <stdio.h>
void swap(int tab[], int a, int b)
{
int temp = tab[a];
tab[a] = tab[b];
tab[b] = temp;
}
void quickSort(int tab[], int begin, int end)
{
int left = begin-1;
int right = end+1;
const int pivot = tab[begin];
if(begin >= end)
return;
while(1)
{
do right--; while(tab[right] > pivot);
do left++; while(tab[left] < pivot);
if(left < right)
swap(tab, left, right);
else break;
}
quickSort(tab, begin, right);
quickSort(tab, right+1, end);
}
int main(void)
{
int tab[5] = {5, 3, 4, 1, 2};
int i;
quickSort(tab, 0, 4);
for(i = 0; i < 5; i++)
{
printf("%d ", tab[i]);
}
putchar('\n');
return 0;
}
</code></pre>
<p>Is it the standard way of implementing a quick sort in C ?</p>
| [] | [
{
"body": "<p>The code is not a bad implementation of Quicksort but it has a flaw, inherent to the Quicksort algorithm, that you can easily fix. I tested the code with this main:</p>\n\n<pre><code>const int testsize = 100000;\n\nint main(void)\n{\n int tab[testsize];\n int i;\n\n for(i = 1; i < testsize; i++)\n tab[i] = i;\n\n tab[0] = testsize+1;\n quickSort(tab, 0, testsize-1);\n return 0;\n}\n</code></pre>\n\n<p>As you can see, this is deliberately the worst case scenario for Quicksort in which it takes \\$O(n^2)\\$ time to sort. This code took 11.85 seconds on my machine. Quicksort works best on randomly arranged data, so paradoxically, you can often actually <em>improve</em> sorting time by randomly shuffling the data before you start. I wrote this rather simple-minded shuffle routine:</p>\n\n<pre><code>void shuffle(int tab[], int begin, int end)\n{\n for (; begin < end/2; ++begin)\n swap(tab, begin, rand()%end);\n}\n</code></pre>\n\n<p>When I inserted a call to <code>shuffle()</code> just before the call to <code>quickSort()</code> in <code>main</code>, the time to sort the same data dropped to 0.026 seconds. By comparison, the standard <code>qsort()</code> sorts in 0.006 seconds on this same machine.</p>\n\n<p>Also, more generally, I'd be inclined to pass two pointers to <code>swap</code> rather than an array and two indices. The code may be very slightly faster, but it's certainly more general. </p>\n\n<p>The code could also be made more general by using the same parameters as the <code>qsort()</code> routine in <code><stdlib.h></code> but then, that's already written. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:40:35.000",
"Id": "85119",
"Score": "0",
"body": "Isn't rand()%end a bad practice (modulo bias..) ? I know it's irrelevant in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:42:27.953",
"Id": "85120",
"Score": "1",
"body": "@user3585425: yes, it is, but as you say, it really doesn't matter in this case. Even if that were fixed, it's still a simple-minded shuffle. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:13:54.493",
"Id": "85143",
"Score": "2",
"body": "I don't think shuffling is a solution. The probability of getting the worst case _before_ shuffling is exactly equal to the probability to end up with the worst case _after_ it. A little better remedy is using more sophisticated pivot selection strategy (such as a median of 3 or 5 elements)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:02:44.860",
"Id": "85158",
"Score": "1",
"body": "@vnp: in theory, your assertion about probabilities may be valid, but in practice it definitely is not. In the real world, nearly ordered lists are actually quite common. Also, rather than tinkering with modifications to Quicksort, one could simply use a heap sort. Which is \"better\" depends mostly on the requirements of the problem at hand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:25:54.557",
"Id": "85161",
"Score": "0",
"body": "@Edward: 100% agree with our definition of better. Most politely disagree with all the rest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:43:47.560",
"Id": "85168",
"Score": "0",
"body": "@vnp: it probably has to do with our different experiences. Quicksort is fine if you're interested in average time, but if you need a time guarantee, as with real-time systems, other algorithms perform better in that context. See, for, example, [this paper](http://www.researchgate.net/publication/3706941_Which_sorting_algorithms_to_choose_for_hard_real-time_applications/file/9fcfd50ff15599c760.pdf) and [this one on soft real-time](http://www.researchgate.net/publication/220414433_Real-Time_Performance_of_Sorting_Algorithms/file/9fcfd50ad3f528d9e7.pdf)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T10:11:13.053",
"Id": "85288",
"Score": "0",
"body": "This is slightly unrelated, but is there a way to prove that my function actually sorts its input ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T16:37:42.020",
"Id": "85328",
"Score": "0",
"body": "@user3585425: Here's how I would prove it: `for(i=1; i<testsize; ++i) assert(tab[i] >= tab[i-1]);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:42:53.977",
"Id": "85500",
"Score": "0",
"body": "As `qsort()` is mentioned here, wanted to add for clarity: The standard function `qsort()` does not define the algorithm used to do sorting. `qsort()` may used the \"Quick Sort\" algorithm, it may not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T19:51:09.213",
"Id": "88303",
"Score": "0",
"body": "@Edward You realize I'm asking if it's possible to prove that this function actually sorts its input for every possible input, not if one run of this function sorts one particular input."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:28:02.763",
"Id": "48485",
"ParentId": "48481",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>I'd recommend to use pointers instead of indices. It is one less parameter to pass down the recursion.</p></li>\n<li><p>Algorithms on ranges are somewhat simpler if they are given semi-open ranges (that is, <code>begin</code> <em>is</em> the first element, and <code>end</code> is the first element beyond the range).</p></li>\n<li><p>No raw loops. Factor out the <code>while</code> loop into a function on its own. Now not only the code becomes cleaner, but you also get a very important <code>partition</code> algorithm for free. You may also want to make one step deeper, and recognize that <code>do... while</code> loops are also important algorithms (namely, <code>find_forward</code> and find_backward`).</p></li>\n<li><p>Once the <code>partition</code> is factored out, you may want to eliminate one of the recursions. The actual recursive call shall go into the smaller partition.</p></li>\n<li><p>Terminating a recursion early is a serious optimization, but it is beyond the scope of this review.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:44:46.847",
"Id": "48503",
"ParentId": "48481",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T13:29:06.307",
"Id": "48481",
"Score": "4",
"Tags": [
"c",
"reinventing-the-wheel",
"quick-sort"
],
"Title": "Correctness of quick sort in C"
} | 48481 |
<p>I am very new to Ruby and building my first game. To be honest I did it this way because I was lazy to type so much. My friend told me that the correct way was to do this with case statement i.e. for scissor we have three cases, for rock we have three cases and similarly for paper.</p>
<pre class="lang-ruby prettyprint-override"><code>puts "Rock, paper or scissor"
w = 0 and l =0 and t =0 and j=0
loop{
choice = ["paper" , "rock" , "scissor" ]
i=0
if j ==10
puts "wins : #{w}\nlosses : #{l}\ndraw: #{t}"
if w > l
puts "You won the game"
elsif w<l
puts "You lost!"
else
puts "The game is a draw"
end
gets
break
end
while i == 0
human = gets.chomp.downcase
choice.each {
|x|
if human == x
i+=1 and j+=1
break
end
}
puts "-----------------please enter rock paper or scissor-----------------" if i == 0
end
computer = rand(3)
com = choice[computer]
if (com == "scissor" and human != "rock") or (human == "scissor" and computer !=1)
v = human <=> com
else
v = com <=> human
end
puts "You chose #{human}, computer choose #{com}"
case v
when 1
puts "---->You win"
w +=1
when -1
puts "---->Computer wins"
l+=1
else
puts "---->draw"
t+=1
end
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:39:50.960",
"Id": "85129",
"Score": "0",
"body": "can you fix the indenting?"
}
] | [
{
"body": "<p>You can initialize the score's var this way : <code>w = l = t = j = 0</code>.</p>\n\n<p>Choices could be initilize with the literal string array : <code>choice = %w( rock paper scissor )</code>.</p>\n\n<p>Don't use the <code>and</code> reserved key word to inline code, you can use the <code>;</code> but multilines is better. Same for boolean <code>and</code> and <code>or</code>, use <code>&&</code> and <code>||</code>.</p>\n\n<p>When you wrote a multilines block, use the <code>do ... end</code> syntax :</p>\n\n<pre><code>choice.each {\n |x| \n if human == x\n i+=1 and j+=1\n break\n end\n}\n</code></pre>\n\n<p>Becomes :</p>\n\n<pre><code>choice.each do |x| \n if human == x\n i+=1\n j+=1\n break\n end\nend\n</code></pre>\n\n<p>And you can use the <a href=\"http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-include-3F\" rel=\"nofollow\">Array#include?</a> method to check the player's input :</p>\n\n<pre><code>if choice.include?(human)\n i += 1\n j += 1\nend\n</code></pre>\n\n<p>Instead of doing this :</p>\n\n<pre><code>computer = rand(3)\ncom = choice[computer]\n</code></pre>\n\n<p>You can use the <a href=\"http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-sample\" rel=\"nofollow\">Array#sample</a> method like that : <code>com = choice.sample</code></p>\n\n<p>You should use <a href=\"http://www.ruby-doc.org/core-2.1.1/Symbol.html\" rel=\"nofollow\">Symbol</a> instead of String for choices : <code>\"scissor\" become :scissor</code>.</p>\n\n<p>Here's my version :</p>\n\n<pre><code>puts \"Rock, paper or scissor\"\nw = l = t = j = 0 # inline instanciation\n# instanciate choice outside the loop otherwise it is recreate each turn\nchoice = %i(paper rock scissor) # use a literal symbols array to define choices\n\nloop do # use do...end instead of {} for multilines\n if j == 10\n puts \"wins : #{w}\\nlosses : #{l}\\ndraw: #{t}\"\n if w > l \n puts \"You won the game\"\n elsif w < l \n puts \"You lost!\"\n else \n puts \"The game is a draw\"\n end\n\n gets\n break\n end \n\n human = nil\n until choice.include?(human) # use of until and choice.include? to loop since human make a valid choice\n puts \"Do your choice (paper, rock, scissor) :\"\n human = gets.chomp.downcase.to_sym # String#to_sym convert string in symbol\n end\n\n com = choice.sample # use of Array#sample to make a random choice between all\n puts \"You chose #{human}, computer choose #{com}\"\n # use a simple if..else to check result which is more readable\n if (com == human)\n t += 1\n puts \"---->draw\"\n elsif (com == :scissor && human == :paper) || # details all com's wins is more expressif\n (com == :paper && human == :rock) || \n (com == :rock && human == :scissor)\n l += 1\n puts \"---->Computer wins\"\n else\n w += 1\n puts \"---->You win\"\n end\n\n j+=1 # the end of turn is here, so increment here\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:45:00.883",
"Id": "48495",
"ParentId": "48483",
"Score": "2"
}
},
{
"body": "<p><strong>Indentation</strong><br>\nBe sure to indent your code properly. Indentation helps the reader understand where he is in the code (how deep). Some languages actually <em>depend</em> on correct indentation.</p>\n\n<p><strong>Meaningful names</strong><br>\nYou should give your variable names which will have meaning, and will help the reader of your code understand what each one is responsible for. Names like <code>w</code>, <code>t</code>, <code>j</code> should not be used for any variable other than immediate throw-away variables like if <code>for(i = 1;...</code>.</p>\n\n<p>A variable name <code>l</code> should <em>never ever</em> be used, since it is too easily confused with the digit <code>1</code>, so in some fonts you will never know the difference between <code>l+=1</code> and <code>l+=l</code>...</p>\n\n<p><strong>Your code should tell a story</strong><br>\nTry to design your code in a way that a reader will be able to follow your logic. In your code, there is an endless loop, and in the first <code>if</code> you check whether a mysterious <code>j</code> is <code>10</code>, and if it is you end the game... The story starts with the ending!</p>\n\n<p>A more pleasing option might be:</p>\n\n<pre><code>while number_of_turns_played < 10 do\n\n # play a turn...\n number_of_turns_played += 1\n\nend\n\nif number_of_wins > number_of_losses\n puts \"You won the game\"\nelsif number_of_wins < number_of_losses\n puts \"You lost the game\"\nelse\n puts \"The game is a draw\"\nend\n</code></pre>\n\n<p>This way the story has a beginning, and an end, and it easier to follow.</p>\n\n<p><strong>Choose your types</strong><br>\nWhat is <code>i</code> used for? As far as I can see it can have only two values - <code>0</code> and <code>1</code>, and it is used to flag the get input loop that a valid input has been received. The name <code>i</code> is cryptic enough - why not at least make it a <code>boolean</code>?</p>\n\n<p><strong>Block format conventions</strong><br>\nIt is idiomatic in ruby to use <code>{}</code> syntax for one liner blocks, and <code>do end</code> syntax for multiline blocks.<br>\nInstead of writing:</p>\n\n<pre><code>choice.each {\n |x|\n # do something\n}\n</code></pre>\n\n<p>You should write:</p>\n\n<pre><code>choice.each do |x|\n # do something\nend\n</code></pre>\n\n<p><strong>Too sophisticated for your own good</strong><br>\nLet's look at the condition you worked so hard on for being lazy:</p>\n\n<blockquote>\n<pre><code>if (com == \"scissor\" and human != \"rock\") or (human == \"scissor\" and computer !=1)\n v = human <=> com\nelse \n v = com <=> human\nend\n</code></pre>\n</blockquote>\n\n<ol>\n<li>First - be consistent - on one side check <code>com</code> and on the other you check <code>computer</code> - choose!</li>\n<li>Using esoteric operators - the \"spaceship\" operator (<code>a<=>b</code>) is used when sorting arrays, and returns <code>-1</code> if <code>a</code> is smaller than <code>b</code>, <code>1</code> if <code>a</code> is larger than <code>b</code>, and <code>0</code> if they are equal. It is very rarely used, and your usage, while cute, might be very unclear for most (I know <em>I</em> had to double check what it returns). Is it really needed?</li>\n<li>Assumptions - you rely on the fact that <code>\"paper\"</code> is <em>smaller</em> than <code>\"rock\"</code>, which is <em>smaller</em> than <code>\"scissor\"</code>, and you write your algorithm around that assumption. You are relying on an incidental fact, which might change when, say, you translate it to another language! Don't make incidental assumptions, use your code to define your rules.</li>\n<li>When there are too many exceptions to the rule - so you found a cool rule, which is good for [almost] all your cases. That is all but two, out of six... which is four... which is just about half the cases... Which you will need to explain to anybody who reads the code, since it is not apparent from how the code is written... Maybe it is not that good a rule?</li>\n</ol>\n\n<p>So, what would I suggest?</p>\n\n<p>Say I set the choices to <code>%w(rock paper scissors)</code>, where each choice beats the one prior to it, now I can ask:</p>\n\n<pre><code>computer_choice_idx = rand(3)\nif human_choice == choices[computer_choice_idx]\n # draw!\nelsif human_choice == choices[computer_choice_idx - 1]\n # computer beats human!\nelse\n # human beats computer!\nend\n</code></pre>\n\n<p>Since in ruby <code>choice[-1]</code> returns the last element in the array (<code>\"scissors\"</code>), there is no exception! If the computer chose <code>\"rock\"</code>(id <code>0</code>) and the human chose <code>\"scissors\"</code> - computer will beat human, since <code>\"scissors\" == choices[-1]</code>.</p>\n\n<p>In short:</p>\n\n<pre><code>Choices = %w(rock paper scissors)\n\nputs 'Rock, paper or scissors'\ndraws = wins = losses = 0\n10.times do\n begin\n puts \"-----------------please enter rock paper or scissors-----------------\"\n human_choice = gets.chomp.downcase\n end until Choices.include?(human_choice)\n\n computer_choice_idx = rand(3)\n\n puts \"You chose #{human_choice}, computer choose #{Choices[computer_choice_idx]}\"\n\n if human_choice == Choices[computer_choice_idx]\n puts \"---->draw\"\n draws += 1\n elsif human_choice == Choices[computer_choice_idx - 1]\n puts \"---->Computer wins\"\n losses += 1\n else\n puts \"---->You win\"\n wins += 1\n end\nend\nputs \"wins : #{wins}\\nlosses : #{losses}\\ndraw: #{draws}\"\nif wins > losses\n puts \"You won the game\"\nelsif wins < losses\n puts \"You lost!\"\nelse\n puts \"The game is a draw\"\nend\n</code></pre>\n\n<p>Enjoy!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:35:23.480",
"Id": "48618",
"ParentId": "48483",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48618",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:00:08.623",
"Id": "48483",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"game",
"rock-paper-scissors"
],
"Title": "Rock, Paper, Scissors game"
} | 48483 |
<p>I wrote this code where I trap <code>InterruptedException</code>'s in a blocking queue and try again to consume from the same queue thinking of spurious wakeups. I don't know if in this case I should be thinking of spurious wakeups since I am not calling <code>wait()</code> directly.</p>
<p>Basically, the worry that someone raised is that if the <code>take</code> throws an <code>InterruptedException</code>, I should stop processing (so the <code>while</code> should be inside the <code>try</code>, the opposite of what I did). There is already a mechanism to stop processing by calling a public method in the class, but I don't know if processing should also be stopped by an <code>InterruptedException</code>.</p>
<p>Does anyone have any thoughts?</p>
<pre><code>private BlockingQueue<MyMessage> queue;
...
@Override
public void run() {
log.debug("[run] Starting processing");
while (runningController.isRunning()) {
try {
MyMessage message = queue.take(); // will block if empty
assert message != null; // a blocking queue can never return null
RuntimeMessage parsedMsg = processMessage(message);
if (parsedMsg != null) {
outputConsumer.messageArrived(parsedMsg);
} else {
log.warn("[run] Unparsed message 0x" + Integer.toHexString(message.getCommandType()));
}
} catch (InterruptedException exc) {
log.error("[run] Interrupted while reading from queue", exc);
} catch (MessageConfigurationException exc) {
log.error("[run] Error finding structure configuration for received message", exc);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>When you write, that message <strong>cannot</strong> be <code>null</code>, why are you asserting for it then?\nThat code is IMO noise. I'd rather remove it. Other than that, the comment on it is even more noisy. Your assert says exactly what your comment says. Why keep it?</p>\n\n<p>Same should go for the <code>//will block if empty</code>. It's noise, as it adds no value to the understanding of the code. It's clear that <code>BlockingQueue.take()</code> <strong>will</strong> block when there's no messages, why would there be a need to write a comment on that?</p>\n\n<p>Currently you catch inside your while loop. this means your execution continues, even when <code>InterruptedException</code> or <code>MessageConfigurationException</code> is thrown. You should keep that, given the case it is desired behavior. You have to decide on a case to case basis. We miss the context to decide on that, that's why its <strong>your</strong> job, isn't it ;)</p>\n\n<p>If you want to stop execution when you caught an exception, just call that public method you mentioned. It's not like calls from other public members are forbidden ;)</p>\n\n<p>Oh and a minor nitpick, the name for your <code>BlockingQueue</code> could be better, I'd probably go for <code>messages</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:11:23.087",
"Id": "85141",
"Score": "0",
"body": "i know the execution continues, the question is if that makes sense. If say, an InterruptedException has the intent of terminating a thread then I should not ignore it and continue processing in the thread, but that's what i don't know. The javadoc says \"InterruptedException - if interrupted while waiting\" but i don't know if I can just ignore it and try taking again or I should terminate ASAP. My reasoning was that because of spurious wakeups it was ok to ignore it. Someone else in my team disagrees and thinks I should kill the thread ASAP after an InterruptedException"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:13:32.617",
"Id": "85142",
"Score": "0",
"body": "@Hilikus As I said in my answer, I don't have enough context to judge that. Personally, I *guess* you should keep executing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:15:08.237",
"Id": "85144",
"Score": "0",
"body": "ok, if the answer is open to context then i guess it is not automatically wrong to ignore a InterruptedException, that partially answers my question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-16T15:46:19.363",
"Id": "87875",
"Score": "1",
"body": "\"Interruption is usually the most sensible way to implement interruption\". (Brian Goetz: Java Concurrency in Practice, 2006)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:13:14.060",
"Id": "48498",
"ParentId": "48488",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T14:46:57.437",
"Id": "48488",
"Score": "4",
"Tags": [
"java",
"multithreading",
"synchronization"
],
"Title": "Spurious wakeups in Java's BlockingQueue.take()"
} | 48488 |
<p>I'm new to HTML coding and have created a basic webpage structure for a basic website with 5 pages.</p>
<p>Can anyone suggest any improvements that could help with the structure, layout and design for the pages?</p>
<p>Code for one of the pages is below (all the same except for the names):</p>
<pre><code><!DOCTYPE html>
<html lang="en-GB">
<Head>
<title>Fellows and Fullwood LTD</title>
<meta Charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles.css" />
</Head>
<body>
<div id="container">
<div id="Header">
<h1 align="center"><img src="Images/fellows.gif" width="150" height="39" longdesc="Images/fellows.gif"><font size="12">Fellows and Fullwood</font></h1>
</div>
<div id="nav">
<u1><!--
--><li><a href="#">Home</a></li><!--
--><li><a href="#">About Us</a></li><!--
--><li><a href="#">News</a></li><!--
--><li><a href="#">Careers</a></li><!--
--><li><a href="#">Contact Us</a></li>
</u1>
</div>
<div id="Main">
<h2>Contact us</h2><form action="" method="POST" enctype="multipart/form-data">
<div align="center">
<p>
<input type="hidden" name="action" value="submit"/>
</p>
<p>Your name:<br>
<input name="name" type="text" value="" size="30"/>
<br />
Your email:<br>
<input name="email" type="text" value="" size="30"/>
<br /> Your message:<br />
<textarea name="message" rows="7" cols="30"> </textarea>
<br /><input type="submit" value="Send email"/>
</p>
</div>
</form>
<p>lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here
</p>
</div>
<div id="Sidebar">
<h2>Sidebar</h2>
<u1>
<li><a href="#">Home</a> </li>
<br></br>
<li><a href="#">About Us</a></li>
<br></br>
<li><a href="#">News</a></li>
<br></br>
<li><a href="#">Careers</a></li>
<br></br>
<li><a href="#">Contact Us</a></li>
<br></br>
</u1>
</div>
<div id="Footer">
<p>&copy;Copyright Fellows and Fullwood 2014.</p>
</div>
</div>
</body>
</code></pre>
<p></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:59:40.537",
"Id": "85243",
"Score": "1",
"body": "Use [Lorem Ipsum](http://www.lipsum.com/) instead of lots and lots of text. ;)"
}
] | [
{
"body": "<pre><code> <div id=\"Header\">\n</code></pre>\n\n<p>HTML 5 introduces the <a href=\"http://www.w3.org/TR/html5/sections.html#the-header-element\" rel=\"nofollow\"><code><header></code></a> element.</p>\n\n<pre><code> <h1 align=\"center\">\n</code></pre>\n\n<p>Don't use presentational attributes, like <code>align</code>, use CSS. </p>\n\n<pre><code> <img src=\"Images/fellows.gif\" width=\"150\" height=\"39\" longdesc=\"Images/fellows.gif\">\n</code></pre>\n\n<p>The alt attribute is mandatory. If the text that follows it duplicates the information in the image, then use <code>alt=\"\"</code>.</p>\n\n<p>The <code>longdesc</code> attribute has been removed from HTML 5. In HTML 4 it should point to an HTML document that describes the image (for people who cannot see it), not the image itself.</p>\n\n<pre><code> <font size=\"12\">Fellows and Fullwood</font>\n</code></pre>\n\n<p>The <code><font></code> element is <a href=\"http://www.w3.org/TR/html5/obsolete.html#obsolete\" rel=\"nofollow\">obsolete</a> and should not be used (and I'm pretty sure <code>12</code> isn't a valid size for it anyway). Use CSS. </p>\n\n<pre><code> </h1>\n </div>\n <div id=\"nav\">\n</code></pre>\n\n<p>HTML 5 introduces the <a href=\"http://www.w3.org/TR/html5/sections.html#the-nav-element\" rel=\"nofollow\"><code><nav></code></a> element.</p>\n\n<pre><code> <u1><!--\n</code></pre>\n\n<p>An Unordered List is <code>ul</code> not <code>u1</code>.</p>\n\n<p>Use <a href=\"http://validator.w3.org\" rel=\"nofollow\">a validator</a>.</p>\n\n<pre><code> --><li><a href=\"#\">Home</a></li><!--\n --><li><a href=\"#\">About Us</a></li><!--\n --><li><a href=\"#\">News</a></li><!--\n --><li><a href=\"#\">Careers</a></li><!--\n --><li><a href=\"#\">Contact Us</a></li>\n </u1>\n </div>\n <div id=\"Main\">\n</code></pre>\n\n<p>HTML 5 introduces <a href=\"http://www.w3.org/TR/html5/grouping-content.html#the-main-element\" rel=\"nofollow\"><code><main></code></a></p>\n\n<pre><code> <h2>Contact us</h2><form action=\"\"\n</code></pre>\n\n<p>You can omit the action attribute entirely if you want to resolve to the current URI.</p>\n\n<pre><code> method=\"POST\" enctype=\"multipart/form-data\">\n <div align=\"center\">\n <p>\n <input type=\"hidden\" name=\"action\" value=\"submit\"/> \n </p>\n</code></pre>\n\n<p>Most of the paragraphs in this form at dubious at best but this is just wrong. There is no content for the user at all, and certainly no paragraph.</p>\n\n<pre><code> <p>Your name:<br>\n</code></pre>\n\n<p>Please <a href=\"http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/\" rel=\"nofollow\">learn to love labels</a> </p>\n\n<pre><code> <input name=\"name\" type=\"text\" value=\"\" size=\"30\"/>\n <br /> \n</code></pre>\n\n<p>In general, prefer container elements and CSS margins/paddings to hard line breaks. <code><br></code> is most useful when line breaks are a significant part of content which is otherwise continuous (such as street addresses or poetry). </p>\n\n<pre><code> <div id=\"Footer\">\n <p>&copy;Copyright Fellows and Fullwood 2014.</p>\n </div>\n</code></pre>\n\n<p>HTML 5 introduces the <a href=\"http://www.w3.org/TR/html5/sections.html#the-footer-element\" rel=\"nofollow\"><code><footer></code></a> element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:11:43.013",
"Id": "48491",
"ParentId": "48489",
"Score": "15"
}
},
{
"body": "<p>For later you can always visit this site for help : <a href=\"http://validator.w3.org/check\" rel=\"nofollow\">http://validator.w3.org/check</a></p>\n\n<p>Here are the errors I found by pasting your code into the validator:</p>\n\n<ol>\n<li>The align attribute on the h1 element is obsolete. Use CSS instead. It is better to separate content from style.</li>\n<li>An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images.</li>\n<li>The font element is obsolete: again use css. </li>\n<li>Element u1 not allowed as child of element div in this. You really don't need that div :)</li>\n<li>Using <code></br></code> is wrong: it doesn't have a closing tag use this instead : <code><br/></code></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:12:30.093",
"Id": "48492",
"ParentId": "48489",
"Score": "3"
}
},
{
"body": "<p>I say you are using <code><Head>..</Head></code> and <code><body>..</body></code> that is not very consistent. I suggest you replace it with just lower-case letters, so: <code><head>..</head></code>. </p>\n\n<p>Another tip: if you want dummy text have a look on Google for \"Lorem ipsum\" </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:29:30.253",
"Id": "85184",
"Score": "0",
"body": "Same goes for the IDs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:20:01.903",
"Id": "48493",
"ParentId": "48489",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T15:02:28.150",
"Id": "48489",
"Score": "7",
"Tags": [
"beginner",
"html"
],
"Title": "Basic webpage structure"
} | 48489 |
<p>I have the need to search a directory containing 1000+ files on remote servers where I only have access to SQL Server Management Studio and Explorer. I have written the below SQL statement which does what I need, only incredibly slowly. I fear using this many temp tables and the cursor is the main issue. Any ideas on how I can speed this up?</p>
<p><strong>EDIT:</strong> I forgot to mention that I need to keep this query based. I will not necessarily have full permissions regarding jobs and/or SSIS packages.</p>
<pre><code>--Drop temp table if it already exists
IF OBJECT_ID('tempdb..#tempFileContents') IS NOT NULL
DROP TABLE #tempFileContents
DECLARE @FindText AS VARCHAR(255)
DECLARE @FileDir AS VARCHAR(255)
--Directory to search
SET @FileDir = 'C:\Users\*********\Desktop\TEMP\'
--Text to search
SET @FindText = '1234'
----------------------
----------------------
--Crete temp table to store output lines from text file
CREATE TABLE #tempFileContents
(
lineText TEXT
)
--Create declared table to store found file names in the directory
DECLARE @files table
(
filename VARCHAR(255)
,depth INTEGER
,files BIT
)
--Create declared table to store the text the string ws found in along with the filpath of the file.
DECLARE @foundText table
(
LineNum INT
,foundText TEXT
,filename VARCHAR(255)
)
--Create table of files in the directory
INSERT INTO @files
EXEC xp_dirtree @FileDir, 10, 1
--Update file names to include filepath
UPDATE @files SET filename = @FileDir + filename
--Varchar used to store the derived SQL string
DECLARE @sql NVARCHAR(1000);
--Create cursor for file searching
DECLARE @text VARCHAR(255)
DECLARE @ID VARCHAR(255)
DECLARE IDs CURSOR LOCAL FOR select filename from @files
--Open cursor
OPEN IDs
FETCH NEXT FROM IDs into @ID
WHILE @@FETCH_STATUS = 0
BEGIN
--Truncate temp table prior to searching a file
TRUNCATE TABLE #tempFileContents
SET @sql = 'BULK INSERT #tempFileContents FROM "' + @ID + '"'
EXEC(@sql);
--Insert into results table
INSERT INTO @foundText
(LineNum, foundText, filename)
SELECT ROW_NUMBER() OVER( ORDER BY @ID ) AS 'rownumber', lineText, @ID FROM #tempFileContents
DELETE FROM @foundText
WHERE foundText NOT LIKE '%' + @FindText + '%'
OR foundText IS NULL
FETCH NEXT FROM IDs into @ID
END
--Close off and dispose of unneeded resources
CLOSE IDs
DEALLOCATE IDs
DROP TABLE #tempFileContents
--Display results
SELECT * FROM @foundText
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:19:26.827",
"Id": "85160",
"Score": "0",
"body": "I've fixed the formatting, which was due to your mixture of spaces and tabs."
}
] | [
{
"body": "<p>SSIS jobs are the most appropriate for this usecase</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:22:59.623",
"Id": "85135",
"Score": "0",
"body": "I forgot to mention that i need to keep this query based. as i will not necessarily have full permissions regarding jobs and/or SSIS packages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:30:05.900",
"Id": "85136",
"Score": "0",
"body": "@LexWebb if *you* won't have the required permissions, have the job run under a user that does. SQL Server *Integration* Services is indeed the best-suited solution for data *integration* from disparate sources IMHO. A possible alternative could be a PowerShell script, maybe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:54:55.557",
"Id": "85140",
"Score": "0",
"body": "I should have been more specific. This will not be run regularly. It will be used on a support bases. We will not be able to use integration services for that reason."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:14:04.693",
"Id": "48499",
"ParentId": "48496",
"Score": "2"
}
},
{
"body": "<p>Although the approach is 'peculiar in choice of tools', doing what you do should work just fine. The only part that I would definitely want to change is the loading of the results. Currently you are <code>BULK INSERT</code>ing a file into a temp-table, then copy all that data into a table-variable, followed by deleting everything from the freshly (and the old!) copied data where it does not match a given criteria.</p>\n\n<p>I would propose the following changes:</p>\n\n<ul>\n<li>do not use Table-variables for this. They're fine for (very) small data-sets that don't require a lot of manipulation but will confuse the Query Optimizer when you do lots of inserts and deletes on them</li>\n<li>do not use the TEXT datatype, rather use varchar(max)</li>\n<li>use IDENITITY instead of RowNumber(). RownNumber works great, but it requires sorting the data. Also be very careful with this: doing RowNumber() ordered over a 'constant' might return different results than you originally anticipated and most certainly does <strong>not</strong> guarantee that you'll get things in the order they were originally in the file !!!!!</li>\n<li>variable naming: @filename is much more readable than @ID</li>\n</ul>\n\n<p>Doing some cleaning I ended up with below which in my tests on a couple of 100 small files ran slightly faster than the original. There might be a nicer way than the tempdb..stagingTable approach which will cause issues when the script is run in parallel, but I didn't see an easier way out to be able to use LineNum as an identity which in my opinion is must for what you're trying to achieve!</p>\n\n<pre><code>--Drop temp table if it already exists\nIF OBJECT_ID('tempdb..tempdb..stagingTable') IS NOT NULL\n DROP TABLE tempdb..stagingTable\n\nIF OBJECT_ID('tempdb..#files') IS NOT NULL\n DROP TABLE #files\n\nIF OBJECT_ID('tempdb..#foundText') IS NOT NULL\n DROP TABLE #foundText\n\n----------------------\n----------------------\nGO\n--Crete temp table to store output lines from text file\nCREATE TABLE tempdb..stagingTable\n(\n LineNum int IDENTITY(1, 1) PRIMARY KEY,\n LineText varchar(max),\n)\n\nGO\n-- since we can't tell BULK-insert to skip the LineNum column, we create a view without it\nCREATE VIEW vtempFileContents AS SELECT LineText FROM tempdb..stagingTable\nGO\n\n--Create declared table to store found file names in the directory\nCREATE TABLE #files\n(\n filename VARCHAR(255)\n ,depth INTEGER\n ,files BIT\n)\n\n--Create declared table to store the text the string ws found in along with the filpath of the file.\nCREATE TABLE #foundText\n(\n LineNum int\n ,foundText TEXT\n ,filename VARCHAR(255),\n PRIMARY KEY (filename, LineNum)\n)\n\nGO\n\nDECLARE @FindText AS VARCHAR(255)\nDECLARE @FileDir AS VARCHAR(255)\n\n--Directory to search\nSET @FileDir = 'C:\\temp\\test\\'\n--Text to search\nSET @FindText = 'common'\n\n--Create table of files in the directory\nINSERT INTO #files \nEXEC xp_dirtree @FileDir, 10, 1\n\n--Varchar used to store the derived SQL string\nDECLARE @sql NVARCHAR(1000);\n\n--Create cursor for file searching\nDECLARE @text VARCHAR(255)\nDECLARE @filename VARCHAR(255)\n\nDECLARE files_loop CURSOR LOCAL FAST_FORWARD FOR SELECT @FileDir + filename FROM #files\n\n--Open cursor\nOPEN files_loop\nFETCH NEXT FROM files_loop into @filename\nWHILE @@FETCH_STATUS = 0\nBEGIN\n --Truncate temp table prior to searching a file\n TRUNCATE TABLE tempdb..stagingTable\n SET @sql = 'BULK INSERT vtempFileContents FROM \"' + @filename + '\"'\n EXEC(@sql);\n\n --Insert matching records in results table\n INSERT INTO #foundText (LineNum, foundText, filename)\n SELECT LineNum, LineText, @filename \n FROM tempdb..stagingTable\n WHERE LineText IS NOT NULL\n AND LineText LIKE '%' + @FindText + '%'\n\n FETCH NEXT FROM files_loop into @filename\nEND\n\n--Close off and dispose of unneeded resources\nCLOSE files_loop\nDEALLOCATE files_loop\n\n--Display results\nSELECT * FROM #foundText\n\nGO\n-- cleanup\nDROP VIEW vtempFileContents\nDROP TABLE tempdb..stagingTable\nDROP TABLE #foundText\nDROP TABLE #files\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-12T11:03:18.290",
"Id": "87078",
"Score": "0",
"body": "Great! thanks for taking the time to look into this. I never thought of using a view, having discovered the BULK INSERT i could only get it to work with a table-variable style query. I have tested it and it seems to run a decent amount faster, i appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-12T09:35:49.023",
"Id": "49503",
"ParentId": "48496",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "49503",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:03:30.910",
"Id": "48496",
"Score": "1",
"Tags": [
"performance",
"sql",
"sql-server",
"search",
"file"
],
"Title": "Text file searching using SQL"
} | 48496 |
<p>I want to find the corresponding hash in an array from a string that contains a criterion defined in a hash of the array.</p>
<p>I do something like that :</p>
<pre><code>types = [
{key: 'type_1', criteria: ['type_1a', 'type_1b']},
{key: 'type_2', criteria: ['type_2a', 'type_2b']},
...
]
def find_type(str)
types.each do |type|
type[:criteria].each do |criterion|
return type if str =~ /#{criterion}/i
end
end
nil
end
</code></pre>
<p>I'm sure it could be more ruby but don't find how...</p>
| [] | [
{
"body": "<p>The orthodox (and functional) approach in Ruby is:</p>\n\n<pre><code>def find_type(types, str)\n types.detect do |type|\n type[:criteria].any? do |criterion|\n str =~ /#{criterion}/i # or Regexp.new(criterion, \"i\")\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T05:21:25.130",
"Id": "85266",
"Score": "0",
"body": "To guard against the possibility that any of the hashes to not have the key `:criteria`, you may want to replace `h[:criteria]` with `(h[:criteria] || [])`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T05:22:42.323",
"Id": "85267",
"Score": "0",
"body": "You forgot that the method needs `types` as an argument. I'll be deleting this comment..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:45:08.690",
"Id": "85279",
"Score": "0",
"body": "I guess `types` was not really a local variable but something accessible by the method. Anyway, added as an argument."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:02:24.740",
"Id": "48507",
"ParentId": "48497",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T16:05:26.187",
"Id": "48497",
"Score": "1",
"Tags": [
"ruby",
"search"
],
"Title": "Search a value across 2 array"
} | 48497 |
<p>I'm changing the inner implementation of a project. In order to do so, I've created an interface that will be implemented in 2 different ways.</p>
<p>One of this ways is by class <code>A</code>, which is a wrapper for an outside class (class "<code>B</code>") from a .dll file (a product of other team).</p>
<p>Class <code>B</code> is a private a member of class <code>A</code>. Class <code>B</code> ctor takes an argument, which does not change during the run of my application. It needed to be created only once, and to stay available for class <code>A</code> everywhere in the code.</p>
<p>Class <code>A</code> is an implementation of interface. It use the capabilities of class <code>B</code> in order to implement it's functions, and obviously needed to be available also everywhere in the code. </p>
<p>I've concluded that:</p>
<p>Class <code>A</code> has to be:</p>
<ol>
<li>explicitly created once (hence, not static) </li>
<li>only once, (because I need <code>B</code> to be created only once.) </li>
<li>accessible from anywhere in the code</li>
<li>have a member (<code>B</code>) that must initialized once, and only once (private member, needed only inside class <code>A</code>)</li>
</ol>
<p>Concerning condition #4, ideally I would like to initialize <code>B</code> in the constructor.</p>
<p>A bit similar to singleton pattern, with the exception of wanting to initialize a member in the constructor.</p>
<p>I've come to a solution, and would like to get feedback.</p>
<pre><code>public sealed class A
{
private static SomeClass B = null; // the "must initialized only once" member
// setting B:
private void setB(int i)
{
B = new SomeClass(i);
}
// ctor
public A(int i)
{
if(B == null)
setB(i);
else throw new Exception("An instance of A can be created only once");
}
}
</code></pre>
<p>The idea is to assign the class to static object at the beginning of the code. It's not very neat, but it compiles and seems to do the job just right. I don't use singleton since it won't be possible to initialize the member in the ctor. By the way, thread safety is not a concern here. </p>
<p><code>SomeClass</code> needed only inside class <code>A</code>. <code>SomeClass</code> comes from dll, and class <code>A</code> kind of wrapping it. <code>A</code> does answering cross-cutting concern, it is an implementation of Interface used all over the code. I've tried to implement singleton, but as much as I tried it didn't answer my needs.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:26:46.157",
"Id": "85146",
"Score": "0",
"body": "How are you going to access your SomeClass object from outside of class A?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:32:11.037",
"Id": "85147",
"Score": "2",
"body": "Why not go with a real, full-blown *Singleton* implementation? Thread safety not being an issue *now* might become an issue *later*... Why does it need to be *accessible from anywhere in the code*? Is it addressing a cross-cutting concern? Have you considered any alternative approaches?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:38:32.927",
"Id": "85151",
"Score": "0",
"body": "You've passed off the Singleton handling responsibility to `A`, which is not a Singleton, and then thrown an exception when calling code creates an instance of A because it's actually a roundabout Singleton."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:42:14.917",
"Id": "85152",
"Score": "0",
"body": "Is the project only starting, or it's well under way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:42:43.180",
"Id": "85153",
"Score": "0",
"body": "true, but I can't change SomeClass, and making A singleton will make it difficult to initialize B in the ctor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:45:39.907",
"Id": "85154",
"Score": "0",
"body": "It's an big project I've to maintain, and now I'm changing some major inner implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:45:58.210",
"Id": "85155",
"Score": "3",
"body": "Welcome to Code Review! If possible, please add some more context to your question. The more you tell us about what your **real** code does and what the purpose of doing that is, the easier it will be for reviewers to give you better help. **Why** do you need a singleton in your code? What is it's real purpose?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:50:33.860",
"Id": "85156",
"Score": "3",
"body": "Simon is right, this is pretty much impossible to review as is. You would get much better (and more applicable) answers with real code and more context ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:57:06.143",
"Id": "85157",
"Score": "2",
"body": "My way of handling this would be to simply never create an instance of the class directly, and let the same instance be injected to everything that needs it (through a MEF import in my case). It won't stop other programmers from misusing your code by newing up more instances, but that isn't really your problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:58:36.570",
"Id": "85178",
"Score": "1",
"body": "You have the beginnings of a good question, but [hypothetical code lacks sufficient detail to be reviewed](http://meta.codereview.stackexchange.com/q/1709/9357). We have therefore closed this question as off-topic, but would love to see you ask another question with real identifiers and a real use case so that we can give it a proper review."
}
] | [
{
"body": "<p>If you need to wrap <code>SomeClass</code>, make your wrapper an <em>abstraction</em>:</p>\n\n<pre><code>public interface ISomeClassWrapper\n{\n // expose the methods and properties you want to wrap\n}\n</code></pre>\n\n<p>Then everywhere it's needed in the code, replace static method calls like this:</p>\n\n<pre><code>public void DoSomething()\n{\n SomeClass.Xyz();\n}\n</code></pre>\n\n<p>With something like this:</p>\n\n<pre><code>public class MyOtherClass\n{\n private readonly ISomeClassWrapper _wrapper;\n\n public MyOtherClass(ISomeClassWrapper wrapper)\n {\n _wrapper = wrapper;\n }\n\n public void DoSomething()\n {\n _wrapper.Xyz();\n }\n}\n</code></pre>\n\n<p>Now, if you're worried about how many instances of <code>SomeClassWrapper</code> (which implements <code>ISomeClassWrapper</code> but <code>MyOtherClass</code> doesn't need to know that), <strong>don't instantiate it. ever.</strong></p>\n\n<p>How do you ensure there's only 1 instance of it?</p>\n\n<p>When you've replaced <code>SomeClass.Xyz();</code> with <code>_wrapper.Xyz();</code>, you've done several things:</p>\n\n<ul>\n<li><code>MyOtherClass</code> is now <em>decoupled</em> from <code>SomeClass</code>, and even from <code>SomeClassWrapper</code>.</li>\n<li>The <code>ISomeClassWrapper</code> dependency is now <em>statically declared as such</em>, so just by looking at <code>MyOtherClass</code>'s constructor you <em>know</em> it needs an implementation for <code>ISomeClassWrapper</code> to carry out its tasks.</li>\n<li>You can now provide a fake/mock implementation of <code>ISomeClassWrapper</code>, and write a test for <code>DoSomething()</code> without worrying about side-effects in code that you have no control over.</li>\n<li>The code that's responsible for providing the <code>ISomeClassWrapper</code> instance/implementation, is also responsible for passing <em>everyone that wants an <code>ISomeClassWrapper</code> instance</em>, the same instance. Most IoC containers can do this very, very easily.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:33:25.267",
"Id": "85162",
"Score": "0",
"body": "look promising, i'll try it and report back"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:41:56.467",
"Id": "85165",
"Score": "0",
"body": "Good! If you're going to use an IoC container, make sure *no code depends in it*, otherwise you'll fall into the Service Locator trap; also if you're taking the Dependency Injection route, make sure you go *all the way* about it; I'd recommend Mark Seemann's *Dependency Injection in .net*, an excellent read on the subject ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:48:08.483",
"Id": "85172",
"Score": "0",
"body": "What class implements `ISomeClassWrapper`? You still need to create an instance of whatever it is to pass to `MyOtherClass`, which in and of itself means you can create more than one instance of it anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:50:08.677",
"Id": "85174",
"Score": "1",
"body": "The hardest part about avoiding a service locator is how similar it looks to proper dependency injection in some cases. The primary reason I've started using MEF is that it offers an attributed model, which allows you to avoid resolving your dependencies in code altogether; the attributed properties and constructors are simply fulfilled as available. @Brandon: While more than one instance *can* be created, if injected, it won't be. If someone does make another instance in your project, punch them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:50:47.130",
"Id": "85176",
"Score": "1",
"body": "@Brandon the wrapper itself! And yes, nothing *prevents* `new`ing up another instance somewhere else, except following the DI pattern and sticking to it (hence \"going all the way about it\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:58:41.460",
"Id": "85179",
"Score": "0",
"body": "@Mat'sMug I don't want to cloud up this question so I'll stick to the chat after this: I assumed it was the wrapped class implementing, but I guess I was just hoping that it wasn't \"Well, hopefully other developers don't do this\", speaking of creating new instances. I like the idea of the DI pattern, but from past experience (and Magus' comment), I'd be doing more punching than developing."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:23:38.900",
"Id": "48508",
"ParentId": "48502",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:13:17.380",
"Id": "48502",
"Score": "0",
"Tags": [
"c#",
"singleton"
],
"Title": "Singleton-like pattern for a project"
} | 48502 |
<p>Following code is supposed generate a new ID (PID) for a new client based on the client name's first letter and the existing IDs in the range which are stored in a database. </p>
<p>For ex lets say if the new client's name is "Abc" and if last ID in the database starting from letter A, is A200. Then the new ID should be A201.</p>
<p>This code compiles and runs giving the desired out put but I hope this could be optimized further.</p>
<p>Expecting your suggestions on improving this...</p>
<pre><code>private void GeneratePIDforNewPoint(string pointName)
{
string firstLetterOfPointName; // variable to hold first letter of "point name" being passed to this method
string lastExistingPID; // variable to hold the last PID (most recent hence largest) from the list of PIDs retrieved from the database
int lastDigitOfExistingPID; // variable to hold last digit of the "lastPID" (ex- digit '2' from PID 'F002')
string finalPID; // variable to hold out put (the generated new PID for the new point)...
firstLetterOfPointName = pointName[0]; // Get the fist letter of the point name...
List<string> pidList=_ds.GetPIDs(firstLetterOfPointName); // Calling method to get the pid list from database
if (pidList.Count >=1) // At the end of this if block, numeric part of the new PID will be desided
{
pidList.Sort();
lastExistingPID = pidList[pidList.Count - 1];
lastDigitOfExistingPID = int.Parse(lastExistingPID[lastExistingPID.Length - 1].ToString());
}
else
{
lastDigitOfExistingPID = 0;
}
lastDigitOfExistingPID += 1;
// Found digit will be converted to the pid format by attaching the starting letter and zeros to make the length.(format --> A001/ B099 / C100 etc.)
finalPID= firstLetterOfPointName + String.Format("{0:000}", lastDigitOfExistingPID );
_view.PID = finalPID;
}
public List<string> GetPIDs(string firstLetterOfPointName)
{
string selectStatement = @"SELECT PID FROM point WHERE PID like @PID";
List<string> pidList = new List<string>(); // List to store all retrived PIDs from the database...
// Retrieve all existing PIDs starting with "letter" from the database
using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
{
sqlCommand.Parameters.Add("@PID", SqlDbType.VarChar).Value = firstLetterOfPointName + '%';
sqlConnection.Open();
using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
{
// If reader has data, are added to the list
while (dataReader.Read())
{
pidList.Add(dataReader.GetString(0).Trim());
}
return pidList;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:43:06.277",
"Id": "85252",
"Score": "1",
"body": "Create a table `create table charid { id char, count long }`. Search for `pointName[0]` as `id` in the table, increment `count` and write it back while locking the row. If `pointName[0]` is not in the table, add it and set the `count` to 1 while locking the table."
}
] | [
{
"body": "<p>First, I would expect from a function named GeneratePID to return the generated ID and not to set it. (Nobody likes side-effects)</p>\n\n<pre><code>private string GeneratePIDforNewPoint(string pointName)\n{\n if(pointName == null)\n return \"error\"; \n\n var storedPIDs = _ds.GetPIDs(pointName[0]);\n var newPID = 0; \n if(storedPIDs.Count > 0) {\n var maximumStoredPID = _ds.GetPIDs(pointName[0]).Max();\n newPID = Int32.Parse(maximumStoredPID.substring(1)) + 1;\n }\n return pointName[0] + String.Format(\"{0:000}\", newPID); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:38:52.013",
"Id": "85249",
"Score": "0",
"body": "Lack of side effects destroys the utility. Unless this code is single-threaded and non-reentrant, somehow you have to increment a count and/or store the new ID."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T03:26:51.870",
"Id": "85262",
"Score": "0",
"body": "I think when using the count, problem might be, if a record deleted accidentally in the table? Ex: Lets say it had A001,A002 and A003. Now A002 was deleted. The above code will generate A003 as new PID and would raise an error( violation of key constrain). How to avoid this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:02:41.807",
"Id": "85270",
"Score": "1",
"body": "Okay, in that case you have to find the maximum PID. I've edited the code above."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:24:41.510",
"Id": "48515",
"ParentId": "48505",
"Score": "4"
}
},
{
"body": "<p>It's been an old question, just thought to add an alternative to a name-with-counter solution already offered above.</p>\n\n<h1>ID using CRC32</h1>\n\n<h2>ID based on data</h2>\n\n<p>Usually when I need an ID that is based on user's full name or some other type of data, I'd do something like this:</p>\n\n<h3>php example</h3>\n\n<pre class=\"lang-php prettyprint-override\"><code>class myUtils {\n static public function genID( $firstName, $lastName ) {\n $strDesc = $firstName . \"-\" . $lastName;\n return \"\".dechex(crc32($strDesc));\n }\n}\n</code></pre>\n\n<p>This will return an 8-character long string representation of a 32-bit integer, for example: <code>a072c35b</code></p>\n\n<p>This is then simple and fast to use:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$id = myUtils::genID(\"First name\",\"Last name\");\n</code></pre>\n\n<p>This way you can generate ID that represents bunch of data grouped together, for example instead of just providing first and last name, you can add his passport number into the mix etc. to generate ID that is unique to that user. </p>\n\n<p>However, if you just require a unique ID number, there's even simpler way:</p>\n\n<h2>Just a Unique ID</h2>\n\n<p>If I need to generate a unique ID that is just that - unique, I'd go for something like this:</p>\n\n<h3>php example</h3>\n\n<pre class=\"lang-php prettyprint-override\"><code>class myUtils {\n static public function uid_32bit() {\n return \"\".dechex(crc32(date(\"YdmHis\").bin2hex(openssl_random_pseudo_bytes(10))));\n }\n static public function uid_64bit() {\n return self::uid_32bit().self::uid_32bit();\n }\n}\n</code></pre>\n\n<p>This way I could get 8-character long unique string - representing 32-bit integer:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$id = myUtils::uid_32bit();\n</code></pre>\n\n<p>or, I could get 16-character long unique string, representing 64-bit integer value:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$id = myUtils::uid_64bit();\n</code></pre>\n\n<p>Main advantage of this approach is that is easily read by humans, as it contains only lowercase letters (a...f) and numbers (0...9), and can be used for instance invoice unique numbers that are shown to user, or some other client-facing output, without revealing any information about how you have structured your data in the back-end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T08:04:44.233",
"Id": "450102",
"Score": "0",
"body": "Why do you use `date($strDesc)` like this? What does it do? (I believe I know why, but I'd like to hear your reasoning.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T11:37:58.350",
"Id": "450280",
"Score": "0",
"body": "Ahhh crap, that was copy-paste error. I copied function from the 2nd code snippet that uses date, but missed to remove date part. In the first code snippet It's supposed to calculate crc32 from generated string. I've edited the code snippet to fix this bug. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T04:13:45.977",
"Id": "230933",
"ParentId": "48505",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48515",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T17:56:44.720",
"Id": "48505",
"Score": "3",
"Tags": [
"c#",
"optimization",
".net"
],
"Title": "Algorithm generating a unique ID based on client name"
} | 48505 |
<p>Not sure if this is the right board for this topic but since it will affect my SEO i guess it's not that wrong to ask about this in here.</p>
<p>I just took on a website that lists some stores around your location.
You can enter some conditions and it will return a list of nearby stores.</p>
<p>I noticed that the List of stores will be returned as a <code><section></code> and each store is represented by an <code><article></code>.</p>
<pre><code><section class="stores">
<article>
<header>
<h1>
<a href="http://foo.com/store1"> Ice Cream Store 1</a> </h1>
</header>
<div class="objekt_image">
<div class="image_wrapper">
foo
</div>
</div>
<div class="about">
foo </div>
<div class="clear"></div>
</article>
<article>
<header>
<h1>
<a href="http://foo.com/store2"> Ice Cream Store 2</a> </h1>
</header>
<div class="objekt_image">
<div class="image_wrapper">
foo2
</div>
</div>
<div class="about">
foo </div>
<div class="clear"></div>
</article>
....
</code></pre>
<p>Is this good code style? I thought <code><article></code> should be represent ...well...articles about some topic like news or articles about a specific topic. Instead these articles are some stores which will change every few weeks. Whats the best way to represent a list like this?</p>
| [] | [
{
"body": "<p><a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-article-element\" rel=\"nofollow\">Spec</a>:</p>\n\n<blockquote>\n <p>The article element represents a complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.</p>\n</blockquote>\n\n<ul>\n<li>Complete and self-contained? Yes - it has information about foostore which doesn't require the rest of the document to make sense.</li>\n<li>Composition? A work of music, literature, or art? Not really. It would work better if it included a review.</li>\n<li><p>One of the below:</p>\n\n<ul>\n<li>A post? No.</li>\n<li>An article? No.</li>\n<li>Blog entry? No.</li>\n<li>User-submitted content? Is it?</li>\n<li>Interactive? No.</li>\n</ul></li>\n</ul>\n\n<p>So probably not, as long as it isn't user-generated reviews.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:31:05.277",
"Id": "85773",
"Score": "0",
"body": "thats what I thought, thanks for your review. So should I just use some <div> tags or is there a better way to represent a foostore"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:29:38.607",
"Id": "85807",
"Score": "0",
"body": "It looks like `<div>` is the best way. There are no elements specifically made for foostores..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T21:25:15.207",
"Id": "85834",
"Score": "0",
"body": "Well, who knows what the next html specification update will bring us. So far I'll change it to <div> thanks mate."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:58:32.273",
"Id": "48516",
"ParentId": "48506",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T19:45:04.607",
"Id": "48506",
"Score": "3",
"Tags": [
"html",
"html5"
],
"Title": "Should I return an object wrapped by an article tag?"
} | 48506 |
<p>This question continues on my previous implementations of the <code>Hand</code> class of a Trading Card Game, earlier questions can be found here:</p>
<ul>
<li>Earlier model: <a href="https://codereview.stackexchange.com/questions/47273/trading-card-games-hand-class-and-tests">Trading Card Game's Hand class and tests</a></li>
<li>Older model having similar functionality as this one, likely deprecated for current one: <a href="https://codereview.stackexchange.com/questions/48466/trading-card-games-hand-and-handview-implementation-using-composition-and-decor">Trading Card Game's Hand and HandView implementation using composition and decoration</a></li>
</ul>
<p>I have tried to implement as much of the old reviews as I thought was neccessary, except the point about the unit test method names, I haven't had time to do that yet.</p>
<p>The goal of this implementation is to allow concrete instances of a <code>HandView</code> to listen for add, play and swap events on the <code>Hand</code> class. I expect concrete implementations to work together with for example the console or a GUI to relay the information back to the user.</p>
<p>I will first list some dependency classes without unit tests, and then my implementations with unit tests.</p>
<p>Dependencies:</p>
<pre><code>public final class Arguments {
private Arguments() {
throw new UnsupportedOperationException();
}
public static int requirePositive(final int value) throws IllegalArgumentException {
return requirePositive(value, "value");
}
public static int requirePositive(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value <= 0) {
throw new IllegalArgumentException("the " + name + " must be positive: " + value);
}
return value;
}
public static int requireNegative(final int value) throws IllegalArgumentException {
return requireNegative(value, "value");
}
public static int requireNegative(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value >= 0) {
throw new IllegalArgumentException("the " + name + " must be negative: " + value);
}
return value;
}
public static int requirePositiveOrZero(final int value) throws IllegalArgumentException {
return requirePositiveOrZero(value, "value");
}
public static int requirePositiveOrZero(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value < 0) {
throw new IllegalArgumentException("the " + name + " must be positive or zero: " + value);
}
return value;
}
public static int requireNegativeOrZero(final int value) throws IllegalArgumentException {
return requireNegativeOrZero(value, "value");
}
public static int requireNegativeOrZero(final int value, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (value > 0) {
throw new IllegalArgumentException("the " + name + " must be negative or zero: " + value);
}
return value;
}
public static int requireInRange(final int value, final int lowInclusive, final int highExclusive) throws IllegalArgumentException {
return requireInRange(value, lowInclusive, highExclusive, "value");
}
public static int requireInRange(final int value, final int lowInclusive, final int highExclusive, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (lowInclusive >= highExclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher exclusive bound: " + lowInclusive + " >= " + highExclusive);
}
if (value < lowInclusive || value >= highExclusive) {
throw new IllegalArgumentException("the " + name + " must be in range: " + value + ", expected: [" + lowInclusive + ", " + highExclusive + ")");
}
return value;
}
public static int requireInRangeClosed(final int value, final int lowInclusive, final int highInclusive) throws IllegalArgumentException {
return requireInRangeClosed(value, lowInclusive, highInclusive, "value");
}
public static int requireInRangeClosed(final int value, final int lowInclusive, final int highInclusive, final String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
if (lowInclusive > highInclusive) {
throw new IllegalArgumentException("the lower inclusive bound is greater or equal to the higher inclusive bound: " + lowInclusive + " >= " + highInclusive);
}
if (value < lowInclusive || value > highInclusive) {
throw new IllegalArgumentException("the " + name + " must be in range: " + value + ", expected: [" + lowInclusive + ", " + highInclusive + ")]");
}
return value;
}
public static int requireIndexInRange(final int index, final int lowInclusive, final int highExclusive) throws IndexOutOfBoundsException {
if (index < lowInclusive || index >= highExclusive) {
throw new IndexOutOfBoundsException("the index must be in range: " + index + ", expected: [" + lowInclusive + ", " + highExclusive + ")");
}
return index;
}
public static int requireIndexInRangeClosed(final int index, final int lowInclusive, final int highInclusive) throws IndexOutOfBoundsException {
if (index < lowInclusive || index > highInclusive) {
throw new IndexOutOfBoundsException("the index must be in range: " + index + ", expected: [" + lowInclusive + ", " + highInclusive + "]");
}
return index;
}
public static String requireMinimalLength(final String value, final int minimum) throws IllegalArgumentException {
return requireMinimalLength(value, minimum, "value");
}
public static String requireMinimalLength(final String value, final int minimum, final String name) throws IllegalArgumentException {
Objects.requireNonNull(value);
Arguments.requirePositive(minimum, "minimum");
Objects.requireNonNull(name);
if (value.length() < minimum) {
throw new IllegalArgumentException("the length of the " + name + " must be at least the minimum: " + value.length() + ", expected: " + minimum);
}
return value;
}
}
</code></pre>
<hr>
<pre><code>public final class States {
private States() {
throw new UnsupportedOperationException();
}
public static boolean requireTrue(final boolean condition) throws IllegalStateException {
return requireTrue(condition, "condition must be true");
}
public static boolean requireTrue(final boolean condition, final String message) throws IllegalStateException {
Objects.requireNonNull(message);
if (!condition) {
throw new IllegalStateException(message);
}
return condition;
}
public static boolean requireFalse(final boolean condition) throws IllegalStateException {
return requireFalse(condition, "condition must be false");
}
public static boolean requireFalse(final boolean condition, final String message) throws IllegalStateException {
Objects.requireNonNull(message);
if (condition) {
throw new IllegalStateException(message);
}
return condition;
}
public static <E, C extends Collection<E>> C requireEmpty(final C collection) throws IllegalStateException {
return requireEmpty(collection, "collection");
}
public static <E, C extends Collection<E>> C requireEmpty(final C collection, final String name) throws IllegalStateException {
Objects.requireNonNull(name);
if (!collection.isEmpty()) {
throw new IllegalStateException(name + " must be empty");
}
return collection;
}
public static <E, C extends Collection<E>> C requireNonEmpty(final C collection) throws NoSuchElementException {
return requireNonEmpty(collection, "collection");
}
public static <E, C extends Collection<E>> C requireNonEmpty(final C collection, final String name) throws NoSuchElementException {
Objects.requireNonNull(name);
if (collection.isEmpty()) {
throw new NoSuchElementException(name + " must be non-empty");
}
return collection;
}
public static <T, E extends RuntimeException> T requireNonNull(final T object, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (object == null) {
throw exceptionSupplier.get();
}
return object;
}
public static <T, E extends RuntimeException> T requireNonNull(final T object, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(exceptionFunction);
Objects.requireNonNull(message);
if (object == null) {
throw exceptionFunction.apply(message);
}
return object;
}
}
</code></pre>
<p>Interfaces for the <em>View</em> implementation:</p>
<pre><code>/**
* A marker interface to denote that an object implements a view on some other object.
*
* @author Frank van Heeswijk
* @param <T> The type of object that is viewed
*/
public interface View<T extends Viewable<T, ? extends View<T>>> {
}
</code></pre>
<hr>
<pre><code>/**
* An interface for objects that are viewable via a view.
*
* @author Frank van Heeswijk
* @param <T> The type of viewable object
* @param <V> The concrete view on the viewable object
*/
public interface Viewable<T extends Viewable<T, V>, V extends View<T>> {
public void addViewCallback(final V view);
public void removeViewCallback(final V view);
}
</code></pre>
<p>Concrete implementations:</p>
<pre><code>public interface HandView extends View<Hand> {
public void onCardAdded(final Card card);
public void onCardPlayed(final int cardIndex);
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
}
</code></pre>
<hr>
<pre><code>public class Hand extends AbstractCollection<Card> implements Collection<Card>, Viewable<Hand, HandView> {
private final Collection<HandView> views = new HashSet<>();
private final int capacity;
private final List<Card> list;
public Hand(final int capacity) {
this.capacity = Arguments.requirePositive(capacity, "capacity");
this.list = new ArrayList<>(capacity);
}
@Override
public void addViewCallback(final HandView view) {
views.add(Objects.requireNonNull(view));
}
@Override
public void removeViewCallback(final HandView view) {
if (!views.remove(Objects.requireNonNull(view))) {
throw new IllegalStateException("the requested view to remove must be present in the views: " + view);
}
}
public boolean isFull() {
return (list.size() == capacity);
}
@Override
public boolean add(final Card card) {
Objects.requireNonNull(card);
States.requireFalse(isFull(), "hand is full");
list.add(card);
views.forEach(view -> view.onCardAdded(card));
return true;
}
public Card get(final int index) {
checkIndex(index);
return list.get(index);
}
public Card play(final int index) {
checkIndex(index);
Card result = list.remove(index);
views.forEach(view -> view.onCardPlayed(index));
return result;
}
public void swap(final int indexOne, final int indexTwo) {
checkIndex(indexOne);
checkIndex(indexTwo);
Collections.swap(list, indexOne, indexTwo);
views.forEach(view -> view.onCardsSwapped(indexOne, indexTwo));
}
@Override
public String toString() {
return Hand.class.getSimpleName() + "(" + capacity + ", " + list + ")";
}
@Override
public Iterator<Card> iterator() {
return list.iterator();
}
@Override
public Spliterator<Card> spliterator() {
return list.spliterator();
}
@Override
public int size() {
return list.size();
}
@Override
public void forEach(final Consumer<? super Card> action) {
Objects.requireNonNull(action);
list.forEach(action);
}
private void checkIndex(final int index) {
Arguments.requireIndexInRange(index, 0, size());
}
}
</code></pre>
<p>Unit test for <code>Hand</code>:</p>
<pre><code>public class HandTest {
static {
assertTrue(true);
}
@Test
public void testConstructor() {
new Hand(1);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorIAE() {
new Hand(0);
}
@Test
public void testAddViewCallback() {
Hand hand = new Hand(5);
hand.addViewCallback(createHandView());
}
@Test(expected = NullPointerException.class)
public void testAddViewCallbackViewNull() {
Hand hand = new Hand(5);
hand.addViewCallback(null);
}
@Test
public void testRemoveViewCallback() {
Hand hand = new Hand(5);
HandView handView = createHandView();
hand.addViewCallback(handView);
hand.removeViewCallback(handView);
}
@Test(expected = NullPointerException.class)
public void testRemoveViewCallbackViewNull() {
Hand hand = new Hand(5);
hand.removeViewCallback(null);
}
@Test(expected = IllegalStateException.class)
public void testRemoveViewCallbackViewNotPresent() {
Hand hand = new Hand(5);
hand.removeViewCallback(createHandView());
}
@Test
public void testIsFull() {
Hand hand = new Hand(2);
hand.add(createCard());
assertFalse("hand should not be full", hand.isFull());
hand.add(createCard());
assertTrue("hand should be full", hand.isFull());
hand.play(1);
assertFalse("hand should not be full anymore", hand.isFull());
}
@Test
public void testAdd() {
Hand hand = new Hand(1);
assertTrue(hand.add(createCard()));
}
@Test(expected = NullPointerException.class)
public void testAddNPE() {
Hand hand = new Hand(1);
hand.add(null);
}
@Test(expected = IllegalStateException.class)
public void testAddISE() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.add(createCard());
}
@Test
public void testGet() {
Hand hand = new Hand(1);
Card card = createCard();
hand.add(card);
assertEquals("card should be equal", card, hand.get(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetIOOBE() {
Hand hand = new Hand(1);
hand.get(0);
}
@Test
public void testPlay() {
Hand hand = new Hand(1);
Card card = createCard();
hand.add(card);
assertEquals("card should be equal", card, hand.play(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOBE1() {
Hand hand = new Hand(1);
hand.play(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOBE2() {
Hand hand = new Hand(1);
hand.play(0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOB3() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.play(1);
}
@Test
public void testSwap() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
hand.add(card);
hand.add(card2);
assertNotSame("card should be unequal to card2", card, card2);
hand.swap(0, 1);
assertEquals("card should be equal", card, hand.play(1));
assertEquals("card2 should be equal", card2, hand.play(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOBE1() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(-1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOBE2() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOBE3() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(0, -1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOBE4() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(0, 1);
}
@Test
public void testToString1() {
Hand hand = new Hand(1);
assertEquals(Hand.class.getSimpleName() + "(1, [])", hand.toString());
}
@Test
public void testToString2() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
assertNotSame("card should be unequal to card2", card, card2);
hand.add(card);
hand.add(card2);
assertEquals(Hand.class.getSimpleName() + "(2, [" + card + ", " + card2 + "])", hand.toString());
}
@Test
public void testIterator() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
hand.add(card);
hand.add(card2);
assertNotSame("card should be unequal to card2", card, card2);
Iterator<Card> iterator = hand.iterator();
assertTrue(iterator.hasNext());
assertEquals("first element should equal card", card, iterator.next());
assertTrue(iterator.hasNext());
assertEquals("second element should equal card2", card2, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
public void testSpliterator() {
assertNotNull(createFilledHand().spliterator());
}
@Test
public void testSize() {
Hand hand = new Hand(2);
assertEquals("empty hand", 0, hand.size());
hand.add(createCard());
assertEquals("one card", 1, hand.size());
hand.add(createCard2());
assertEquals("two cards", 2, hand.size());
}
@Test
public void testForEach() {
createFilledHand().forEach(Assert::assertNotNull);
}
private Card createCard() {
return new MonsterCard("Test", 10, 100, MonsterModus.OFFENSIVE);
}
private Card createCard2() {
return new MonsterCard("Test2", 15, 150, MonsterModus.HEALING);
}
private Hand createFilledHand() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
assertNotSame("card should be unequal to card2", card, card2);
hand.add(card);
hand.add(card2);
return hand;
}
private HandView createHandView() {
return new HandView() {
@Override
public void onCardAdded(final Card card) { }
@Override
public void onCardPlayed(final int cardIndex) { }
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
};
}
}
</code></pre>
<hr>
<p>Integration test for <code>Hand</code>, integrating with <code>HandView</code>:</p>
<pre><code>public class HandIT {
static {
assertTrue(true);
}
@Test
public void testAdd() {
Hand hand = new Hand(5);
final AtomicInteger counter = new AtomicInteger(0);
final AtomicReference<Card> cardReferenceOne = new AtomicReference<>();
final AtomicReference<Card> cardReferenceTwo = new AtomicReference<>();
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) {
counter.incrementAndGet();
cardReferenceOne.set(card);
}
@Override
public void onCardPlayed(final int cardIndex) { }
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
});
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) {
counter.incrementAndGet();
cardReferenceTwo.set(card);
}
@Override
public void onCardPlayed(final int cardIndex) { }
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
});
Card card = new MonsterCard("Test", 5, 5, MonsterModus.HEALING);
hand.add(card);
assertEquals(2, counter.get());
assertEquals(card, cardReferenceOne.get());
assertEquals(card, cardReferenceTwo.get());
}
@Test
public void testPlay() {
Hand hand = new Hand(5);
hand.add(new MonsterCard("Test", 5, 5, MonsterModus.HEALING));
final AtomicInteger counter = new AtomicInteger(0);
final AtomicInteger indexReferenceOne = new AtomicInteger(-1);
final AtomicInteger indexReferenceTwo = new AtomicInteger(-1);
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) { }
@Override
public void onCardPlayed(final int cardIndex) {
counter.incrementAndGet();
indexReferenceOne.set(cardIndex);
}
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
});
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) { }
@Override
public void onCardPlayed(final int cardIndex) {
counter.incrementAndGet();
indexReferenceTwo.set(cardIndex);
}
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
});
hand.play(0);
assertEquals(2, counter.get());
assertEquals(0, indexReferenceOne.get());
assertEquals(0, indexReferenceTwo.get());
}
@Test
public void testSwap() {
Hand hand = new Hand(5);
hand.add(new MonsterCard("Test", 5, 5, MonsterModus.HEALING));
hand.add(new MonsterCard("Random", 3, 7, MonsterModus.OFFENSIVE));
final AtomicInteger counter = new AtomicInteger(0);
final AtomicInteger indexOneReferenceOne = new AtomicInteger(-1);
final AtomicInteger indexTwoReferenceOne = new AtomicInteger(-1);
final AtomicInteger indexOneReferenceTwo = new AtomicInteger(-1);
final AtomicInteger indexTwoReferenceTwo = new AtomicInteger(-1);
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) { }
@Override
public void onCardPlayed(final int cardIndex) { }
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
counter.incrementAndGet();
indexOneReferenceOne.set(cardIndexOne);
indexTwoReferenceOne.set(cardIndexTwo);
}
});
hand.addViewCallback(new HandView() {
@Override
public void onCardAdded(final Card card) { }
@Override
public void onCardPlayed(final int cardIndex) { }
@Override
public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
counter.incrementAndGet();
indexOneReferenceTwo.set(cardIndexOne);
indexTwoReferenceTwo.set(cardIndexTwo);
}
});
hand.swap(0, 1);
assertEquals(2, counter.get());
assertEquals(0, indexOneReferenceOne.get());
assertEquals(1, indexTwoReferenceOne.get());
assertEquals(0, indexOneReferenceTwo.get());
assertEquals(1, indexTwoReferenceTwo.get());
}
}
</code></pre>
<p>The unit tests hit 100% coverage as intended, and they also all pass.</p>
<p>Reviews about every aspect are welcome. Extra attention would be nice for the integration tests, as they are my first integration tests ever.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:27:58.583",
"Id": "85309",
"Score": "1",
"body": "Where's the assertion in `testRemoveViewCallback`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:34:30.983",
"Id": "85311",
"Score": "0",
"body": "@abuzittingillifirca Can you please elaborate on what you exactly mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:47:20.160",
"Id": "85315",
"Score": "3",
"body": "Every test should have an assertion, otherwise it is useless. A remove listener test scenario should be something like \"**When** I remove a listener **and** raise an event **(then)** the listener should not be notified anymore.\" The part after **then** is the assertion. You should make each test fail first, to ensure *it does something useful*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:48:54.173",
"Id": "85316",
"Score": "0",
"body": "@abuzittingillifirca It's a fair point to have in a review, I do think it would be more suited for the integration tests though, as in the unit test (`testRemoveViewCallback`), all dependencies should be mocked and should not influence the unit test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:56:10.843",
"Id": "85319",
"Score": "0",
"body": "Look at here [`EventBus.unregister`](http://code.google.com/p/guava-libraries/source/browse/guava-tests/test/com/google/common/eventbus/EventBusTest.java#216) for an example."
}
] | [
{
"body": "<pre><code>public interface Viewable<T extends Viewable<T, V>, V extends View<T>> {\n public void addViewCallback(final V view);\n\n public void removeViewCallback(final V view);\n}\n</code></pre>\n\n<p>Drop the <code>public</code> keywords from the methods. Methods in interfaces are automatically <code>public</code>. See <a href=\"https://stackoverflow.com/questions/161633/should-methods-in-a-java-interface-be-declared-with-or-without-a-public-access-m\">this SO thread</a> for reference.</p>\n\n<pre><code>@Test(expected = IllegalArgumentException.class)\n</code></pre>\n\n<p>As mentioned in another review, there are good reasons to choose <code>ExpectedException</code> rules over <code>@Test(expected = …)</code>.</p>\n\n<pre><code>public void testConstructorIAE() {\n</code></pre>\n\n<p>Maybe a matter of taste, but I don't like these acronyms for exceptions. If you read it for the first time, it's definitely something you have to think about for half a second.</p>\n\n<pre><code>@Test(expected = NullPointerException.class)\npublic void testAddViewCallbackViewNull() {\n Hand hand = new Hand(5);\n hand.addViewCallback(null);\n}\n</code></pre>\n\n<p>I still think your job should be preventing internal NPEs to shoot back to the caller. <code>NullPointerException</code> is uselessly generic. Your method knows what went wrong, so give the caller better feedback.</p>\n\n<p>I also agree with what was said in the comments: A test that doesn't assert is useless. I know it seems like \"but it's okay here\" – I used to think like that and wrote tests like that. Granted, I work with a larger code base, but I ended up finding my own tests that had slightly changed over time to be useless because of this.</p>\n\n<p>I also agree with the other thing from the comments – <code>testXyz</code> is a good name for simple unit tests. Integration tests should have clear, descriptive names. In our project, we use a <code>givenXyzWhenXyzThenXyz</code> pattern. Of course you don't have to stick to this, it's just one of many possibilites.</p>\n\n<p>The nice thing about this pattern is that it forces you to state the abstraction of what is to be asserted in the test name. And really, that is what integration tests do: they don't test the tiny little innards of the system – they test the big picture. On top of that, such proper test names – again, speaking heavily from experience here – make it drastically easier to quickly understand what a test does.</p>\n\n<p>Really, the problem with integration tests is that they are more complex than unit tests and therefore need time to be understood. And just like you want clear method names in the production code to <em>abstract</em> the implementation details away, you should go for clear names in tests that do the same.</p>\n\n<p>Just FYI, our test names can be really long. Really long. Something along the lines of</p>\n\n<pre><code>@Test\npublic void givenTwoBusinessRequestsViaSoapWithSameDataWhenExecuteRequestProcessingThenSecondRequestIsignored() {\n // …\n}\n</code></pre>\n\n<p>is common and by far not the longest. So don't feel bad giving your tests long names – descriptive is more important.</p>\n\n<p>The last thing in the comment mentions that you should write tests first, make sure they fail and then work on making them pass. While I agree that this is an effective approach, this so-called <em>Test-Driven Development</em> (TDD) is not \"mandatory\". But I definitely do recommend it!</p>\n\n<p>Other than these things, it looks solid to me. I didn't look at the dependency/helper classes since I assume they didn't change.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:44:44.173",
"Id": "85664",
"Score": "1",
"body": "I agree, except one thing: a `@Test` without assertion is not always useless. It verifies that the operations succeed and don't throw exceptions. If nothing else, it confirms the setup is sane (no exceptions in `@Before*`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:59:11.520",
"Id": "48617",
"ParentId": "48509",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48617",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:25:00.583",
"Id": "48509",
"Score": "11",
"Tags": [
"java",
"game",
"community-challenge"
],
"Title": "Trading Card Game's Hand and HandView implementation and unit tests"
} | 48509 |
<p>Is there a more elegant and Pythonic way to handle counters in this solution to an exercise from the NLTK book? The exercise asks to print out the context (one word forward and one word back) for every verb of a particular type (tagged VN).</p>
<pre><code>import nltk
wsj = nltk.corpus.treebank.tagged_words(simplify_tags=True)
cdf = nltk.ConditionalFreqDist((tag, word) for (word, tag) in wsj)
wordlist = cdf['VN'].keys()
# Bug 1: strange exceptions in the for loop when iterating over wsj
# Solution: wsj is a custom NLTK type "ConcatenatedCorpusView"
# cast wsj into a native python type "list" for better iteration.
# I am guessing ConcatenatedCorpusView chokes on empty tuples
wsj_list = list(wsj)
# Bug 2: repeated words return index of the first word only
# Solution: to deal with repeated words
# we keep indexing from the last location. The index method
# takes a second parameter
starts_at = 0
for t in wsj_list:
if t[0] in wordlist and t[1] == 'VN':
ndx = wsj_list.index(t,starts_at)
starts_at = ndx + 1
print wsj_list[ndx-1:ndx+1], ndx
</code></pre>
| [] | [
{
"body": "<p>You could use <code>enumerate</code> to get the index. It makes the code both simpler and more efficient, as the linear search of <code>index</code> is avoided. I would also suggest unpacking <code>t</code> to <code>(word, tag)</code> to improve readability.</p>\n\n<pre><code>for ndx, (word, tag) in enumerate(wsj_list):\n if word in wordlist and tag == 'VN':\n print wsj[ndx-1:ndx+1], ndx\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:53:57.317",
"Id": "48512",
"ParentId": "48510",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T18:32:50.037",
"Id": "48510",
"Score": "2",
"Tags": [
"python"
],
"Title": "A more Pythonic way to iterate over a list with duplicate items"
} | 48510 |
<p>In my method I have something like this:</p>
<pre><code>returnValue = null;
if (!string.IsNullOrEmpty(pa.Phone))
{
if (pa.Length != 10 && member == Schema.Phone.Name)
{
returnValue = new stuff;
}
}
if (!string.IsNullOrEmpty(pa.OtherPhone))
{
if (pa.OtherPhone.Length != 10 && member == Schema.OtherPhone.Name)
{
returnValue = new stuff;
}
}
if (!string.IsNullOrEmpty(pa.Fax))
{
if (pa.Fax.Length != 10 && member == Schema.Fax.Name)
{
returnValue = new stuff
}
}
// even more similar ifs...
// at the end of method: return returnValue;
</code></pre>
<p>How can I refactor this logic? Note that new stuff is always the same for all the <code>if</code>s.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:28:44.357",
"Id": "85183",
"Score": "0",
"body": "Is the first nested if supposed to be `Pa.Phone.Length` rather than `Pa.Length`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:50:54.293",
"Id": "85186",
"Score": "5",
"body": "It would be nice if you included the entire method (even if it's long), so we have actual context and don't have to guess about what `pa` and `member` might be. Also `new stuff` should probably be `new Stuff();` ...and then we can help you come up with a more descriptive title ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:32:52.000",
"Id": "85196",
"Score": "0",
"body": "@Mat'sMug Ulugbek Umirov got it right with the info I had posted."
}
] | [
{
"body": "<p>If <code>member</code> is <code>string</code>.</p>\n\n<pre><code>Func<string, string, bool> f = (p, m) => !string.IsNullOrEmpty(p) && p.Length != 10 && member == m;\nif (f(pa.Phone, Schema.Phone.Name) ||\n f(pa.OtherPhone, Schema.OtherPhone.Name) ||\n f(pa.Fax, Schema.Fax.Name))\n{\n return new stuff;\n}\nelse\n{\n return null;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:23:20.067",
"Id": "85182",
"Score": "0",
"body": "yes, member is a string."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:21:10.230",
"Id": "48514",
"ParentId": "48513",
"Score": "5"
}
},
{
"body": "<p>A little improve to the previous post ?</p>\n\n<pre><code>Func<string, string, bool> f = (p, m) => !string.IsNullOrEmpty(p) && p.Length != 10 && member == m;\nFunc<dynamic[], bool> inFunc = o => o.Any(k => k);\n\nreturn inFunc(new []{f(pa.Phone, Schema.Phone.Name), f(pa.OtherPhone, Schema.OtherPhone.Name),f(pa.Fax, Schema.Fax.Name)}) \n ? (object) new stuff()\n : null;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:23:14.527",
"Id": "48550",
"ParentId": "48513",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48514",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T19:17:39.997",
"Id": "48513",
"Score": "-2",
"Tags": [
"c#",
"null"
],
"Title": "Refactoring the logic of a return value"
} | 48513 |
<p>I've been working to create a game in Python similar to <a href="http://www.ndemiccreations.com/en/22-plague-inc">Plague Inc.</a> and instead of just writing one big clump of code and then getting it reviewed, I wanted to do it stage-by-stage and make it a little easier. Also, reviews might possibly help me later on in the development process.</p>
<pre><code>import datetime
import random
countries = [
dict(Name = "China", Population = "1,363,560,000"),
dict(Name = "India", Population = "1,242,070,000"),
dict(Name = "United States", Population = "317,768,000"),
dict(Name = "Indonesia", Population = "249,866,000"),
dict(Name = "Brazil", Population = "201,032,714"),
dict(Name = "Pakistan", Population = "186,015,000"),
dict(Name = "Nigeria", Population = "173,615,000"),
dict(Name = "Bangladesh", Population = "152,518,015"),
dict(Name = "Russia", Population = "143,700,000"),
dict(Name = "Japan", Population = "127,120,000"),
dict(Name = "Mexico", Population = "119,713,203"),
dict(Name = "Philippines", Population = "99,329,000"),
dict(Name = "Vietnam", Population = "89,708,900"),
dict(Name = "Egypt", Population = "86,188,600"),
dict(Name = "Germany", Population = "80,716,000"),
dict(Name = "Iran", Population = "77,315,000"),
dict(Name = "Turkey", Population = "76,667,864"),
dict(Name = "Thailand", Population = "65,926,261"),
dict(Name = "France", Population = "65,844,000"),
dict(Name = "United Kingdom", Population = "63,705,000"),
dict(Name = "Italy", Population = "59,996,777"),
dict(Name = "South Africa", Population = "52,981,991"),
dict(Name = "South Korea", Population = "50,219,669"),
dict(Name = "Colombia", Population = "47,522,000"),
dict(Name = "Spain", Population = "46,609,700"),
dict(Name = "Ukraine", Population = "45,410,071"),
dict(Name = "Kenya", Population = "44,354,000"),
dict(Name = "Argentina", Population = "40,117,096"),
dict(Name = "Poland", Population = "38,502,396"),
dict(Name = "Sudan", Population = "37,964,000"),
dict(Name = "Uganda", Population = "35,357,000"),
dict(Name = "Canada", Population = "35,344,962"),
dict(Name = "Iraq", Population = "34,035,000"),
]
current_date = datetime.datetime.strftime(datetime.date.today(), "%m-%d-%Y")
print "Welcome to a Python version of Plague Inc."
user = raw_input('\nWhat is your name? ').title() # for later on in the game
print '\nCountries to choose from are\n'
print "Country".ljust(15),"Population\n"
for country in countries:
print country["Name"].ljust(15), country["Population"]
startcountry = raw_input('\nWhat country would you like to start in? ').title()
if startcountry == 'Random': # random.sample can be used for more than one country later on
startcountry = random.choice(countries)
diseasename = raw_input('\nWhat would you like to name your disease? ').title()
print '\nNews Bulletin'.ljust(45), current_date
print '-' * 55
print 'An unknown disease named', diseasename, 'has struck', startcountry, 'by storm.'
print 'Doctors and scientists will need to collaborate to find out more information about this disease.'
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:56:43.897",
"Id": "96299",
"Score": "0",
"body": "I suggest you put static game information in a text file and import the information at runtime."
}
] | [
{
"body": "<p>Store the population as a number. If you want to include comas when the numbers are presented to the user, the UI code can add those in. When people start dying, trying to decrement a number stored in a string, that contains comas, is going to be a pain.</p>\n\n<hr>\n\n<p>I would use a <a href=\"https://docs.python.org/2/library/collections.html#collections.namedtuple\">named tuple</a> instead of a dictionary to store the data. You get access to all of the data with just <code>.name</code> instead of <code>[\"name\"]</code>. Additionally, your code will go bang sooner if you misspell a value's name. For example, you used <code>Name</code> and <code>Population</code> as the keys, so my attempt to use your dictionary look up would return <code>None</code> instead of telling me the property is not defined.</p>\n\n<hr>\n\n<p>You have some magic numbers in you UI code. If you add another country with a much larger name, you need to adjust your text padding in multiple places.</p>\n\n<hr>\n\n<p>You don't tell the user that <code>Random</code> is a valid option when selecting a country. You also don't validate that the entered country name is valid.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:32:25.137",
"Id": "85230",
"Score": "0",
"body": "Did you mean a *list* of namedtuples or a namedtuple *with two lists*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:37:42.480",
"Id": "85232",
"Score": "1",
"body": "@codesparkle: Make one `namedtuple` to represent a country. Then make as many instances of that as needed, one for each country."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:48:30.930",
"Id": "48527",
"ParentId": "48517",
"Score": "12"
}
},
{
"body": "<p>Some thoughts:</p>\n\n<ul>\n<li><p>As the game goes on, you’ll need to record more information about the countries. Whether they’re doing medical research, border closures, infection/mortality rates, etc. Rather than storing all this information in a list of dictionaries, I’d suggest creating objects for each country. Here’s a simple example:</p>\n\n\n\n<pre><code>class Country(object):\n def __init__(self, name, population):\n self.name = name\n self.population = population\n\nchina = Country(\"China\", 1363560000)\n</code></pre>\n\n<p>Also follow martijnn2008’s advice, and load the countries from an external file (probably a CSV). Keeping the data separate from the code is generally good practice. You’d probably be better off having a small dataset in the program to start with, as you build the basic logic, then start using the full data set later.</p>\n\n<p>As unholysampler suggests, use an int for the population; this will make your life much easier later when chunks of the population start dying. You can always define a function that does nice comma-printing on your population data later.</p></li>\n<li><p>Have different functions for parts of the game. For example, a <code>start_game()</code> function which just includes the code for setting up a new game, then another function <code>news_bulletin()</code> which prints a random news bulletin.</p>\n\n<p>This will make it easier to reuse this code later – for example, if the user gets to the end of the game and you want to ask \"Play again?\", you can just redirect them to <code>start_game()</code> rather than jumping through hoops.</p></li>\n<li><p>Rather than expecting the user to enter a name that’s formatted exactly as it’s stored in your data, you could:</p>\n\n<ul>\n<li><p>Do something to clean up messy input. For example, right now, \"china\" is an invalid input, but any reasonable person can see what they meant. Perhaps do something like</p>\n\n<pre><code>if start_country.lower() in list_of_countries:\n # more code here\n</code></pre>\n\n<p>And weirdness happens if I choose a country name which isn't on your list. You could perhaps just ask again and again until you get an answer, or just pick one at random for me. I just want to get on with the game!</p></li>\n<li><p>Just offer them a choice from a numbered list. Here’s a very crude mockup of how that might work:</p>\n\n<pre><code>Which country would you like to choose?\n1 China\n2 India\n3 United States\nType the corresponding number: # wait for input\n3\nYou have chosen \"United States\"\n</code></pre></li>\n</ul></li>\n<li><p>Magic numbers as arguments to <code>ljust()</code> throughout your code. Icky and fragile. Pull them out and make them variables, or better try to compute the necessary values on the fly.</p>\n\n<p><strong>ETA:</strong> The problem arises because you’re assuming that the window is 55 characters wide (for example, the <code>print '-' * 55</code> line). You should pull this out into a <code>window_width</code> variable, so you don't have problems later on (and if necessary, can adapt it for wider or narrower windows).</p>\n\n<p>What if, later, you want to add the Independent Former Republic of New South Nebelsbad? Stuff like that might cause you problems if you’re rigid about the width.</p></li>\n<li><p>In your import statements, I would write</p>\n\n\n\n<pre><code>from datetime import datetime\n</code></pre>\n\n<p>Cuts out <code>datetime.datetime</code> statements, which just look weird. Also note that your MM-DD-YY may confuse players for whom that isn’t their default date system. How about</p>\n\n\n\n<pre><code>>>> current_date = datetime.datetime.strftime(datetime.date.today(), \"%d %B, %Y\")\n>>> print current_date\n29 April, 2014\n</code></pre>\n\n<p>That looks much more natural, and is unambiguous.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T02:05:27.377",
"Id": "85257",
"Score": "0",
"body": "Can you just explain a little more on magic numbers, as I'm not quite sure what you mean. I just looked up formatting in python and used what was found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T02:15:32.600",
"Id": "85258",
"Score": "0",
"body": "Btw, changing the datetime import statement breaks the code, as I've tried this in early development."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T06:31:16.967",
"Id": "85269",
"Score": "0",
"body": "@TjF: Huh, okay. Usually I use `from datetime import datetime` and then `datetime.strftime`, but it’s only a minor point. I’ll edit to clarify the magic number statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:36:38.870",
"Id": "85337",
"Score": "1",
"body": "The only suggestion I would make it to save the external information in XML form rather than csv, if only for easier serialization and visualization tools. I don't know much about python, but googling `python xml` makes xml look promising. It's certainly not the most efficient method of saving information, but it can be used to initialize data(countries) as well as saving game states. Then, optimizing memory usage can be worried about later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T01:37:33.583",
"Id": "85375",
"Score": "0",
"body": "Thanks guys. I'll work on updating this and adding more to the game and post an update in a few weeks."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:02:53.183",
"Id": "48529",
"ParentId": "48517",
"Score": "20"
}
},
{
"body": "<p>As a someone who learnt to code in BASIC, your Python code in this question and a couple of others looks a lot like you also have experience of BASIC. A lot of former BASIC users find they can write things in Python which are pretty close to what they are used to, especially if they are familiar with a structured form of BASIC like QBasic or early VB (more recent versions of VB are quite different).</p>\n\n<p>There is nothing wrong with this - Python was influenced by BASIC, including in its desire to be an easy-to-learn language for programming beginners. You should also ignore anyone who looks down on BASIC or on you for having started in BASIC. However, to most Python programmers this code looks quite weird and hard to read. This is because you are structuring your code in a way which is fairly unusual for Python, but normal for BASIC. This means you aren't using many of the language features in Python which make Python powerful and useful and friendly.</p>\n\n<p>To imagine why the 'feel' of your code seems weird to Python programmers, imagine translating a sentence into another language, by translating each word in a dictionary, and keeping them in the same order. For some very short sentences, this might work:</p>\n\n<pre><code>Donde esta la biblioteca ?\nWhere is the library ?\n</code></pre>\n\n<p>For slightly longer sentences, the sentence will sound strange but will probably be understandable:</p>\n\n<pre><code>Die Proletarier haben nichts in ihr zu verlieren als ihre Ketten.\nThe proletarians have nothing in them to lose as their chains.\n</code></pre>\n\n<p>Compare with the correct translation: \"The proletarians have nothing to lose but their chains.\"</p>\n\n<p>If the sentence is too complicated or long, it might become almost incomprehensible:</p>\n\n<pre><code>Le bon sens est la chose du monde la mieux partagée : car chacun pense en être si bien pourvu, que ceux même qui sont les plus difficiles à contenter en toute autre chose, n'ont point coutume d'en désirer plus qu'ils en ont.\nThe good sense is the thing of the world the best shared : coach each one thinks in to be if well supplied, that those same who are the more difficult at to content in all other thing, not have point custom of in to desire more that they in have.\n</code></pre>\n\n<p>Now, first of all, you don't need to worry all the time about 'feel' or 'style'. While you are learning, and especially if you are writing toy programs or experiments only for yourself, you can write how you like. Ultimately it is more important that your code does what you want it to do, than that it is elegant or easy to read. As you try and code new things, you will pick up some ways of writing things that work in Python and make your code neater and better structured.</p>\n\n<p>However, you are on CR because you want to write better code. One part of this is structure and another part is style. (There are many other important parts.) These are kind of linked - structure is kind of the style of whole programs, and style is kind of the structure of single lines, or things like variable names and spacing. Together they form <em>readability</em>. When you improve this, you will make it easier for others to read and discuss your code, but you will also make it easier for yourself to edit and maintain your code. You will often see readability mentioned on CR and on StackOverflow and Programmers.SE, including lots of places where people put forward different code solutions <em>just</em> to improve readability, without affecting at all how the code works.</p>\n\n<p>I think you have already picked up lots of style things since your first questions on CR. PEP8, the Python style guide which has been recommended to you is an important tool, as is a good editor which highlights syntax and does indenting for you. If you look at a few lines of your code, you should be able to see quickly what the different elements of the code are - where the lines start and end, what is a definition, what are arguments to functions, etc.</p>\n\n<p>As for structure, the most important element you should be using is the function. Functions are fundamental to most programming languages. A function in Python can be used to take an argument and modify it or return a derived object, it could allow some piece of code to be repeated exactly the same each time (essentially a subroutine), it could take several arguments and vary what it does depending on them, or anything in between. You should use functions to get rid of pieces of code which are repeated in several places, whether with variations or not, but you can also move code which is only used once into a function.</p>\n\n<p>It allows top-down programming, where you write a program like this:</p>\n\n<pre><code>setup()\nprint_intro()\nuser_info = get_user_choices()\nplay_game(user_info)\n</code></pre>\n\n<p>with all those functions left to be filled in later:</p>\n\n<pre><code>def setup():\n # todo\n\ndef print_intro():\n # todo\n\n...\n</code></pre>\n\n<p>When you do fill them in, you will use further unwritten functions.</p>\n\n<pre><code>def setup():\n countries = load_country_data()\n initialize_timer()\n initialize_save_file()\n</code></pre>\n\n<p>and so on, until you get down to functions which do a single simple thing, which you just write.</p>\n\n<p>Once you've mastered functions in your code, you can start looking at how to use <code>class</code> and other Python constructs. As you do this, you will go from thinking of a certain program structure in your head, and then translating it into Python properly, to thinking in Python automatically. You will see that Python users have a specific term for the ways they like the style, structure and appearance of Python code to be: 'Pythonic'. Eventually you will have an instinct for what is and isn't Pythonic, and will even start to disagree with others as to what truly Pythonic code should be like.</p>\n\n<p>The most important resource by far is reading other people's code. Code on CR is an ok place to start, but lots of it might be written by other beginners. Questions on SO or Programmers.SE might give more examples of good code, and lots of discussion of how to write good code. There are lots of other places you can find examples of Python code, written to illustrate things or as short working programs, probably including many simple games like the ones you have been working on. github is definitely a place to start looking for code to read. You can even try and read things which you don't understand what they do - library code or pieces of big programs. Though you won't get all of it, you will see (if the code is decent and decently commented) how it is structured and be able to follow the flow of execution and data.</p>\n\n<p>Finally some of the whole concept of different styles and structures between languages might seem unintuitive and frustrating to you, as if your code was being picked apart for no good reason. If you go on to learn further programming languages, you will see that each has a slightly different (sometimes very different) 'feel' and 'style'. This actually affects how people use the tools so much that people choose between languages not because of differences in what they do, but based on how things can be expressed, and whether this chimes with their personality and how they like to write. Coders who speak a few languages know how to pick up the 'idioms' in a new language quickly, and start writing in a new style which fits it well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:06:49.213",
"Id": "48571",
"ParentId": "48517",
"Score": "6"
}
},
{
"body": "<p>I would recommend to try to use a windowed programme for this by either using <code>pygame</code> or <code>tkinter</code>. That way you could include an interactive map and then capture mouse clicks on each country just like in the real game. This is easier in pygame that tkinter in my opinion but u need to install pygame.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T20:15:20.427",
"Id": "85520",
"Score": "0",
"body": "I would, but I am using Pythonista for iPad, and they don't have these modules yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:46:27.413",
"Id": "48587",
"ParentId": "48517",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "48529",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:26:42.010",
"Id": "48517",
"Score": "8",
"Tags": [
"python",
"game",
"python-2.x"
],
"Title": "Plague Inc. in Python - Extremely Early Stage"
} | 48517 |
<p>I've implemented DFS and BFS implementations. I want to check if the code is readable, contains any issues, and can be improved.</p>
<p><strong>GraphImplementation</strong></p>
<pre><code>package graphs;
import java.util.*;
import graphs.State;
public class GraphImplementation
{
public void dfs(Node root)
{
//Avoid infinite loops
if(root == null) return;
System.out.print(root.getVertex() + "\t");
root.state = State.Visited;
//for every child
for(Node n: root.getChild())
{
//if childs state is not visited then recurse
if(n.state == State.Unvisited)
{
dfs(n);
}
}
}
public void bfs(Node root)
{
//Since queue is a interface
Queue<Node> queue = new LinkedList<Node>();
if(root == null) return;
root.state = State.Visited;
//Adds to end of queue
queue.add(root);
while(!queue.isEmpty())
{
//removes from front of queue
Node r = queue.remove();
System.out.print(r.getVertex() + "\t");
//Visit child first before grandchild
for(Node n: r.getChild())
{
if(n.state == State.Unvisited)
{
queue.add(n);
n.state = State.Visited;
}
}
}
}
public static Graph createNewGraph()
{
Graph g = new Graph();
Node[] temp = new Node[8];
temp[0] = new Node("A", 3);
temp[1] = new Node("B", 3);
temp[2] = new Node("C", 1);
temp[3] = new Node("D", 1);
temp[4] = new Node("E", 1);
temp[5] = new Node("F", 1);
temp[0].addChildNode(temp[1]);
temp[0].addChildNode(temp[2]);
temp[0].addChildNode(temp[3]);
temp[1].addChildNode(temp[0]);
temp[1].addChildNode(temp[4]);
temp[1].addChildNode(temp[5]);
temp[2].addChildNode(temp[0]);
temp[3].addChildNode(temp[0]);
temp[4].addChildNode(temp[1]);
temp[5].addChildNode(temp[1]);
for (int i = 0; i < 7; i++)
{
g.addNode(temp[i]);
}
return g;
}
public static void main(String[] args) {
Graph gDfs = createNewGraph();
GraphImplementation s = new GraphImplementation();
System.out.println("--------------DFS---------------");
s.dfs(gDfs.getNode()[0]);
System.out.println();
System.out.println();
Graph gBfs = createNewGraph();
System.out.println("---------------BFS---------------");
s.bfs(gBfs.getNode()[0]);
}
}
</code></pre>
<p><strong>Graph.java:</strong></p>
<pre><code>package graphs;
public class Graph {
public int count; // num of vertices
private Node vertices[];
public Graph()
{
vertices = new Node[8];
count = 0;
}
public void addNode(Node n)
{
if(count < 10)
{
vertices[count] = n;
count++;
}
else
{
System.out.println("graph full");
}
}
public Node[] getNode()
{
return vertices;
}
}
</code></pre>
<p><strong>Node.java:</strong></p>
<pre><code>package graphs;
import graphs.State;
public class Node {
public Node[] child;
public int childCount;
private String vertex;
public State state;
public Node(String vertex)
{
this.vertex = vertex;
}
public Node(String vertex, int childlen)
{
this.vertex = vertex;
childCount = 0;
child = new Node[childlen];
}
public void addChildNode(Node adj)
{
adj.state = State.Unvisited;
if(childCount < 30)
{
this.child[childCount] = adj;
childCount++;
}
}
public Node[] getChild()
{
return child;
}
public String getVertex()
{
return vertex;
}
}
</code></pre>
<p><strong>State.java:</strong></p>
<pre><code>package graphs;
public enum State {
Unvisited,Visiting,Visited;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:03:45.130",
"Id": "85204",
"Score": "0",
"body": "Is this code for learning/assignment purpose or for working software/app ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:05:42.683",
"Id": "85205",
"Score": "0",
"body": "@Xiang m trying to learn graphs on my own and various search algorithms to become efficient in trees & graphs"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-03T11:09:53.770",
"Id": "188188",
"Score": "0",
"body": "I find it useful - http://opendatastructures.org/ods-java/12_3_Graph_Traversal.html . Explains everything clearly with pseudo code."
}
] | [
{
"body": "<p>I'd use lists instead of a arrays and public counter. \neg.:</p>\n\n<pre><code>public class Graph\n{\n private List<Node> vertices = new LinkedList<Node>(); \n\n public void addNode(Node n)\n { \n if(vertices.length >= 10){\n System.out.println(\"graph full\");\n return;\n } \n vertices.add(n); \n }\n\n public Node[] getNode()\n {\n return vertices.toArray;\n }\n}\n</code></pre>\n\n<p>There is also a bug in your Graph-class, since your array is limited to 8 entries, but you are filling it until your is counter >= 10.</p>\n\n<p>Your Node-class contains public members with getters? I'd make them private ;)</p>\n\n<p>I'd also remove redundant comments. \ne.g.: \"for every child\" at a for loop. Since everybody knows what an for loop does.</p>\n\n<p>Let your code be the description:</p>\n\n<pre><code>for(Node child: root.getChild())\n if(child.state == State.Unvisited)\n dfs(n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:14:21.083",
"Id": "85207",
"Score": "0",
"body": "why would you use lists instead of arrays? whats the tradeoff?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:19:37.830",
"Id": "85210",
"Score": "0",
"body": "Arrays are continuous allocated memory and in list there is no guarantee. So accessing objects in array is much faster. *Arrays are not dynamic in size but list are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:19:45.110",
"Id": "85211",
"Score": "2",
"body": "For me Lists are easier to handle. They dont throw nasty overflow errors. You dont need a counter, because the list already contains those informations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:44:44.280",
"Id": "85221",
"Score": "0",
"body": "if I use getter methods as private then how would I use it in main class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:48:08.043",
"Id": "85222",
"Score": "2",
"body": "No, the getters have to be public. The member fields should be private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:15:49.527",
"Id": "85226",
"Score": "2",
"body": "@Xiang `ArrayList` uses a contiguous array under the hood while `LinkedList` uses a non-contiguous chain of nodes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:16:19.537",
"Id": "85244",
"Score": "0",
"body": "Yes I was talking about LinkedList which is used in the code above."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:12:54.397",
"Id": "48523",
"ParentId": "48518",
"Score": "3"
}
},
{
"body": "<p>Overall a good design. However there are few points which you should pay attention to. </p>\n\n<p><strong>Access Modifiers:</strong>\nYou code has some properties as public and also public getter. This makes no sense. You should choose the access modifiers carefully. Anybody can access the child (NodeArray) and set to null if this code is used as an API by some user.</p>\n\n<pre><code>public Node[] child;\n\npublic Node[] getChild()\n{\n return child;\n}\n</code></pre>\n\n<p>This should be</p>\n\n<pre><code>private Node[] child;\n\npublic Node[] getChild()\n{\n return child;\n}\n\npublic void setChild(Node node){\n // set Node to first empty location in Node array\n if(node != null)\n child[nonEmptyLocation] = node;\n}\n\n// if you want to set whole array\npublic void setChildren(Node[] nodes){\n if(nodes!= null && nodes.length > 0)// check that the data is valid\n this.nodes = nodes;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class Graph {\n\n public int count; // num of vertices\n</code></pre>\n\n<p><strong>Static Functions:</strong>\nYour DFS and BFS functions are not static. I can think of no reason to do that when you have create function as static. Better make it consistent. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:25:25.667",
"Id": "85214",
"Score": "0",
"body": "so you are saying I should use private in those methods and import class in main program to use the methods? what could be another way of doing it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:29:24.643",
"Id": "85217",
"Score": "0",
"body": "No, the way this should be done is make the class properties as private and then provide public setters/getters. This way you will have control on how the data is changed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:35:25.403",
"Id": "85218",
"Score": "0",
"body": "Can you edit my code and show me few examples of what you are saying?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:24:39.133",
"Id": "85248",
"Score": "0",
"body": "Code edited. Should be easy to understand now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:31:55.077",
"Id": "85341",
"Score": "0",
"body": "In general, it's a good idea to provide getters and setters to prevent others from meddling with your object's internal state. However, these particular getters and setters add complexity but don't provide much protection over `public Node[] child`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:13:42.147",
"Id": "85346",
"Score": "0",
"body": "I agree. Code provided in the post is to demonstrate the concept and not to achieve any major data blunder. The data setting rules depends a lot on the context of the problem and technical design of the module."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:15:21.433",
"Id": "48524",
"ParentId": "48518",
"Score": "1"
}
},
{
"body": "<h3>Data Structure</h3>\n\n<p>Your terminology is a bit off. Trees have roots and children. Arbitrary graphs, on the other hand… I think \"origin\" and \"neighbors\" would be more appropriate.</p>\n\n<ul>\n<li><p><strong>Visited flag:</strong> Storing the visited/unvisited flag in the <code>Node</code> hurts flexibility. Once you perform a <code>dfs()</code> or <code>bfs()</code>, that graph is \"ruined\". You won't be able to reset all nodes to the unvisited state. (Well, you <em>could</em> do it manually, since <code>Node.state</code> is a public field, after all. But that's nasty too.) Instead, I suggest that <code>dfs()</code> and <code>bfs()</code> keep a <code>HashSet</code> of visited nodes. Once the traversal is done, just discard the set.</p></li>\n<li><p><strong>State.Visiting:</strong> That value is never used.</p></li>\n<li><p><strong>Node.getNode():</strong> The name suggests that it would return a single node, but it doesn't. Also, by returning the entire array, and the <em>original</em> of the array rather than a copy, you would be letting the caller alter the graph's connections in unapproved ways. Better to offer ways to iterate through all neighbours and to fetch a specific neighbour.</p></li>\n<li><p><strong>Child vertex array:</strong> The <code>Node</code> constructor says: <code>vertices = new Node[8];</code> However, <code>addNode()</code> checks <code>if (count < 10)</code>. You should test against <code>vertices.length</code> instead.</p>\n\n<p>If the capacity is exceeded, you should't print to <code>System.out</code> as a side-effect. Throw an exception instead, so that the caller can decide how to handle it.</p>\n\n<p>Better yet, use an expandable data structure so that you don't have to deal with capacity limits. A simple substitution would be to use an <code>ArrayList<Node></code>, but read on…</p></li>\n<li><p><strong>Graph.vertices <em>vs.</em> Node.child:</strong> Those arrays seem to serve the same purpose, redundantly.</p></li>\n<li><p><strong>Graph.createNewGraph():</strong> It's cumbersome. Wouldn't it be nice to be able to write</p>\n\n<pre><code>Graph g = new Graph();\ng.addEdge(\"A\", \"B\");\ng.addEdge(\"B\", \"C\");\n…\nreturn g;\n</code></pre></li>\n</ul>\n\n<p>My suggestion:</p>\n\n<pre><code>public class Graph {\n // Alternatively, use a Multimap:\n // http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html\n private Map<String, List<String>> edges = new HashMap<String, List<String>>();\n\n public void addEdge(String src, String dest) {\n List<String> srcNeighbors = this.edges.get(src);\n if (srcNeighbors == null) {\n this.edges.put(src,\n srcNeighbors = new ArrayList<String>()\n );\n }\n srcNeighbors.add(dest);\n }\n\n public Iterable<String> getNeighbors(String vertex) {\n List<String> neighbors = this.edges.get(vertex);\n if (neighbors == null) {\n return Collections.emptyList();\n } else {\n return Collections.unmodifiableList(neighbors);\n }\n }\n}\n</code></pre>\n\n<h3>Traversal</h3>\n\n<p>Your <code>dfs()</code> and <code>bfs()</code> methods can only ever print the node names. You can't reuse the code for anything else, since the <code>System.out.print()</code> calls are mingled with the graph traversal code. It would be better to implement an <code>Iterator</code> so that the caller can decide what to do with each node.</p>\n\n<p>Also, DFS and BFS are two different strategies for accomplishing a similar task. Therefore, they should be implemented in two classes with a shared interface. I suggest an <code>Iterator<String></code>.</p>\n\n<p>The breadth-first iterator is a pretty straightforward translation of your original code, with the main difference being that the iterator is now responsible for keeping track of which vertices have been visited.</p>\n\n<pre><code>public class BreadthFirstIterator implements Iterator<String> {\n private Set<String> visited = new HashSet<String>();\n private Queue<String> queue = new LinkedList<String>();\n private Graph graph;\n\n public BreadthFirstIterator(Graph g, String startingVertex) {\n this.graph = g;\n this.queue.add(startingVertex);\n this.visited.add(startingVertex);\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean hasNext() {\n return !this.queue.isEmpty();\n }\n\n @Override\n public String next() {\n //removes from front of queue\n String next = queue.remove(); \n for (String neighbor : this.graph.getNeighbors(next)) {\n if (!this.visited.contains(neighbor)) {\n this.queue.add(neighbor);\n this.visited.add(neighbor);\n }\n }\n return next;\n }\n}\n</code></pre>\n\n<p>Unfortunately, you'll find that you can no longer use recursion for depth-first traversal. Instead, you'll have to rewrite it as an iterative solution using an explicit stack, which makes the code more complicated. (Alternatively, if you abandon the idea of making an <code>Iterator</code> and use the <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern#Java_example\">visitor pattern</a> instead, then you could keep the same recursive code structure).</p>\n\n<pre><code>public class PreOrderDFSIterator implements Iterator<String> {\n private Set<String> visited = new HashSet<String>();\n private Deque<Iterator<String>> stack = new LinkedList<Iterator<String>>();\n private Graph graph;\n private String next;\n\n public PreOrderDFSIterator(Graph g, String startingVertex) {\n this.stack.push(g.getNeighbors(startingVertex).iterator());\n this.graph = g;\n this.next = startingVertex;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean hasNext() {\n return this.next != null;\n }\n\n @Override\n public String next() {\n if (this.next == null) {\n throw new NoSuchElementException();\n }\n try {\n this.visited.add(this.next);\n return this.next;\n } finally {\n this.advance();\n }\n }\n\n private void advance() {\n Iterator<String> neighbors = this.stack.peek();\n do {\n while (!neighbors.hasNext()) { // No more nodes -> back out a level\n this.stack.pop();\n if (this.stack.isEmpty()) { // All done!\n this.next = null;\n return;\n }\n neighbors = this.stack.peek();\n }\n\n this.next = neighbors.next();\n } while (this.visited.contains(this.next));\n this.stack.push(this.graph.getNeighbors(this.next).iterator());\n }\n}\n</code></pre>\n\n<h2>Tests</h2>\n\n<p>This problem deserves better testing. With the original code, which always printed its output to <code>System.out</code>, there was no good way to write unit tests. Now, you can do anything you want with the results, so it is possible to write proper unit tests.</p>\n\n<pre><code>import static org.junit.Assert.*;\n\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.*;\n\n// javac -cp .:junit.jar GraphTest.java\n// java -cp .:junit.jar:hamcrest-core.jar org.junit.runner.JUnitCore GraphTest\n\n@RunWith(JUnit4.class)\npublic class GraphTest {\n\n public static Graph graph1;\n\n @BeforeClass\n public static void makeGraphs() {\n Graph g = graph1 = new Graph();\n g.addEdge(\"A\", \"B\");\n g.addEdge(\"B\", \"C\");\n g.addEdge(\"B\", \"D\");\n g.addEdge(\"B\", \"A\");\n g.addEdge(\"B\", \"E\");\n g.addEdge(\"B\", \"F\");\n g.addEdge(\"C\", \"A\");\n g.addEdge(\"D\", \"C\");\n g.addEdge(\"E\", \"B\");\n g.addEdge(\"F\", \"B\");\n }\n\n private void expectIteration(String answer, Iterator<String> it) {\n StringBuilder sb = new StringBuilder();\n while (it.hasNext()) {\n sb.append(' ').append(it.next());\n }\n assertEquals(answer, sb.substring(1));\n }\n\n @Test\n public void preOrderIterationOfIsolatedVertex() {\n expectIteration(\"Z\", new PreOrderDFSIterator(graph1, \"Z\"));\n }\n\n @Test\n public void preOrderIterationFromA() {\n expectIteration(\"A B C D E F\", new PreOrderDFSIterator(graph1, \"A\"));\n }\n\n @Test\n public void preOrderIterationFromB() {\n expectIteration(\"B C A D E F\", new PreOrderDFSIterator(graph1, \"B\"));\n }\n\n @Test\n public void BreadthFirstIterationOfIsolatedVertex() {\n expectIteration(\"Z\", new BreadthFirstIterator(graph1, \"Z\"));\n }\n\n @Test\n public void BreadthFirstIterationFromA() {\n expectIteration(\"A B C D E F\", new BreadthFirstIterator(graph1, \"A\"));\n }\n\n @Test\n public void BreadthFirstIterationFromB() {\n expectIteration(\"B C D A E F\", new BreadthFirstIterator(graph1, \"B\"));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:42:17.753",
"Id": "85236",
"Score": "0",
"body": "What would be better to use: Graph.vertices vs. Node.child?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:44:48.680",
"Id": "85237",
"Score": "0",
"body": "Neither! Store `Graph.edges` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:47:08.063",
"Id": "85240",
"Score": "0",
"body": "Whats with the tradeoff of Iterators? just to avoid 2 lines of code, using iterator would be good enough?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:25:38.000",
"Id": "85340",
"Score": "0",
"body": "The main benefit of implementing an `Iterator` is that everyone can immediately tell how to use it. The `Iterator` provides a very convenient interface for the caller, at the expense of complicating your depth-first traversal code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-21T09:50:43.147",
"Id": "230093",
"Score": "0",
"body": "hey @200_success why do you suggest edges to be of the type private Map<String, List<String>> edges = new HashMap<String, List<String>>();\n ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-21T15:21:41.197",
"Id": "230154",
"Score": "0",
"body": "@MonaJalal The keys are node names. The values are a list of the node's neighbours."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:24:23.450",
"Id": "48530",
"ParentId": "48518",
"Score": "42"
}
},
{
"body": "<p>As I mentioned in my <a href=\"https://codereview.stackexchange.com/a/48530/9357\">other answer</a>, hard-coding <code>System.out.println()</code> as the action for each node hurts code reusability. To let the caller specify the action to be performed on each node, without unrolling the recursion in the depth-first iterator, you can use the <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern#Java_example\" rel=\"nofollow noreferrer\">visitor pattern</a>.</p>\n\n<pre><code>import java.util.*;\n\npublic class Graph<T> {\n\n public static interface Visitor<T> {\n void visit(T vertex);\n }\n\n // Alternatively, use a Multimap:\n // http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html\n private Map<T, List<T>> edges = new HashMap<T, List<T>>();\n\n public void addEdge(T src, T dest) {\n List<T> srcNeighbors = this.edges.get(src);\n if (srcNeighbors == null) {\n this.edges.put(src,\n srcNeighbors = new ArrayList<T>()\n );\n }\n srcNeighbors.add(dest);\n }\n\n public Iterable<T> getNeighbors(T vertex) {\n List<T> neighbors = this.edges.get(vertex);\n if (neighbors == null) {\n return Collections.emptyList();\n } else {\n return Collections.unmodifiableList(neighbors);\n }\n }\n\n public void preOrderTraversal(T vertex, Visitor<T> visitor) {\n preOrderTraversal(vertex, visitor, new HashSet<T>());\n }\n\n private void preOrderTraversal(T vertex, Visitor<T> visitor, Set<T> visited) {\n visitor.visit(vertex);\n visited.add(vertex);\n\n for (T neighbor : this.getNeighbors(vertex)) {\n // if neighbor has not been visited then recurse\n if (!visited.contains(neighbor)) {\n preOrderTraversal(neighbor, visitor, visited);\n }\n }\n }\n\n public void breadthFirstTraversal(T vertex, Visitor<T> visitor) {\n Set<T> visited = new HashSet<T>();\n Queue<T> queue = new LinkedList<T>();\n\n queue.add(vertex); //Adds to end of queue\n visited.add(vertex);\n\n while (!queue.isEmpty()) {\n //removes from front of queue\n vertex = queue.remove(); \n visitor.visit(vertex);\n\n //Visit child first before grandchild\n for (T neighbor : this.getNeighbors(vertex)) {\n if (!visited.contains(neighbor)) {\n queue.add(neighbor);\n visited.add(neighbor);\n }\n }\n }\n }\n\n}\n</code></pre>\n\n<p>I've made the node type generic, just because it's possible.</p>\n\n<p>Here are tests to demonstrate its usage.</p>\n\n<pre><code>import static org.junit.Assert.*;\n\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.*;\n\n// javac -cp .:junit.jar Graph.java GraphTest.java\n// java -cp .:junit.jar:hamcrest-core.jar org.junit.runner.JUnitCore GraphTest\n\n@RunWith(JUnit4.class)\npublic class GraphTest {\n private static class CrumbtrailVisitor implements Graph.Visitor<String> {\n private StringBuilder sb = new StringBuilder();\n\n public void visit(String vertex) {\n sb.append(' ').append(vertex);\n }\n\n public String toString() {\n return sb.substring(1);\n }\n };\n\n public static Graph<String> graph1;\n\n @BeforeClass\n public static void makeGraphs() {\n Graph<String> g = graph1 = new Graph<String>();\n g.addEdge(\"A\", \"B\");\n g.addEdge(\"B\", \"C\");\n g.addEdge(\"B\", \"D\");\n g.addEdge(\"B\", \"A\");\n g.addEdge(\"B\", \"E\");\n g.addEdge(\"B\", \"F\");\n g.addEdge(\"C\", \"A\");\n g.addEdge(\"D\", \"C\");\n g.addEdge(\"E\", \"B\");\n g.addEdge(\"F\", \"B\");\n }\n\n @Test\n public void preOrderVisitorFromA() {\n Graph.Visitor<String> crumbtrailVisitor = new CrumbtrailVisitor();\n graph1.preOrderTraversal(\"A\", crumbtrailVisitor);\n assertEquals(\"A B C D E F\", crumbtrailVisitor.toString());\n }\n\n @Test\n public void breadthFirstVisitorFromB() {\n Graph.Visitor<String> crumbtrailVisitor = new CrumbtrailVisitor();\n graph1.breadthFirstTraversal(\"B\", crumbtrailVisitor);\n assertEquals(\"B C D A E F\", crumbtrailVisitor.toString());\n }\n}\n</code></pre>\n\n<p>As you can see, the inversion of control makes things more awkward for the caller. But you still gain the ability to specify an arbitrary action. Also, with Java 8 method references, the simple case is easy — you can just write <code>graph1.preOrderTraversal(\"A\", System.out::println)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T06:42:14.093",
"Id": "48545",
"ParentId": "48518",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48530",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T20:44:52.173",
"Id": "48518",
"Score": "24",
"Tags": [
"java",
"graph",
"breadth-first-search",
"depth-first-search"
],
"Title": "Depth First Search & Breadth First Search implementation"
} | 48518 |
<p>The <a href="http://www.spoj.com/problems/GSS1/" rel="nofollow">problem is presented here</a> as follows:</p>
<blockquote>
<p>You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1
≤ N ≤ 50000 ). A query is defined as follows: Query(x,y) = Max {
a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }. Given \$M\$ queries, your program
must output the results of these queries.</p>
<p><strong>Input</strong></p>
<ul>
<li>The first line of the input file contains the integer \$N\$. </li>
<li>In the second line, \$N\$ numbers follow. </li>
<li>The third line contains the integer \$M\$. </li>
<li>\$M\$ lines follow, where line \$i\$ contains 2 numbers \$x_i\$ and \$y_i\$. </li>
</ul>
<p><strong>Output</strong></p>
<p>Your program should output the results of the \$M\$ queries, one query per
line. </p>
<p><strong>Example</strong></p>
<p><em>Input</em>: </p>
<p>3 </p>
<p>-1 2 3 </p>
<p>1
1 2 </p>
<p><em>Output</em>: </p>
<p>2</p>
</blockquote>
<p>I'm solving the problem by using a segment tree - I am saving the sum, the max ,leftmost max, and the right most max at every node. I then search the graph to find the answer to a specific interval. How could I increase the speed of this code?</p>
<pre><code>import java.util.Scanner;
//TLE
class GSS1 {
static class Node{
int max;
int MaxL;
int MaxR;
int sum;
public Node(int max, int MaxL, int MaxR, int sum){
this.max=max;
this.MaxL=MaxL;
this.MaxR=MaxR;
this.sum=sum;
}
public Node(){
}
}
static class SegmentTree{
private Node[] tree;
private int maxsize;
private int height;
private final int STARTINDEX = 0;
private final int ENDINDEX;
private final int ROOT = 0;
Node s;
public SegmentTree(int size){
height = (int)(Math.ceil(Math.log(size) / Math.log(2)));
maxsize = 2 * (int) Math.pow(2, height) - 1;
tree = new Node[maxsize];
for(int i=0;i<tree.length;i++){
tree[i]=new Node();
}
ENDINDEX = size - 1;
s=new Node();
s.MaxL=Integer.MIN_VALUE;
s.MaxR=Integer.MIN_VALUE;
s.sum=Integer.MIN_VALUE;
s.max=Integer.MIN_VALUE;
}
private int leftchild(int pos){
return 2 * pos + 1;
}
private int rightchild(int pos){
return 2 * pos + 2;
}
private int mid(int start, int end){
return (start + (end - start) / 2);
}
private Node constructSegmentTreeUtil(int[] elements, int startIndex, int endIndex, int current){
if (startIndex == endIndex)
{
tree[current].max=tree[current].MaxL=tree[current].MaxR=tree[current].sum=elements[startIndex];
return tree[current];
}
int mid = mid(startIndex, endIndex);
Node left=constructSegmentTreeUtil(elements, startIndex, mid, leftchild(current));
Node right=constructSegmentTreeUtil(elements, mid + 1, endIndex, rightchild(current));
tree[current].max = Math.max(left.max, right.max);
tree[current].MaxL = Math.max(left.MaxL , left.sum+right.MaxL);
tree[current].MaxR = Math.max(right.MaxR , right.sum+left.MaxR);
tree[current].sum = left.sum+right.sum;
return tree[current];
}
public void constructSegmentTree(int[] elements){
constructSegmentTreeUtil(elements, STARTINDEX, ENDINDEX, ROOT);
}
private Node getSumUtil(int startIndex, int endIndex, int queryStart, int queryEnd, int current){
if (queryStart <= startIndex && queryEnd >= endIndex ){
return tree[current];
}
if (endIndex < queryStart || startIndex > queryEnd){
return s;
}
int mid = mid(startIndex, endIndex);
Node left=getSumUtil(startIndex, mid, queryStart, queryEnd, leftchild(current));
Node right=getSumUtil( mid + 1, endIndex, queryStart, queryEnd, rightchild(current));
Node current_Node=new Node();
current_Node.max = Math.max(left.max, right.max);
current_Node.MaxL = Math.max(left.MaxL , left.sum+right.MaxL);
current_Node.MaxR = Math.max(right.MaxR , right.sum+left.MaxR);
current_Node.sum = left.sum+right.sum;
return current_Node;
}
public int getMaxSum(int queryStart, int queryEnd){
if(queryStart < 0 || queryEnd > tree.length)
{System.out.println("inside negative");
return Integer.MIN_VALUE;
}
return getMax(getSumUtil(STARTINDEX, ENDINDEX, queryStart, queryEnd, ROOT));
}
public int getMax(Node r){
return Math.max(Math.max(r.max, r.MaxL),Math.max(r.MaxR, r.sum));
}
public int getFirst(){
return tree[0].MaxL;
}
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int numbers[]=new int [input.nextInt()];
for(int i=0;i<numbers.length;i++){
numbers[i]=input.nextInt();
}
SegmentTree tree=new SegmentTree(numbers.length);
tree.constructSegmentTree(numbers);
int cases=input.nextInt();
int x;
int y;
int query;
for(int i=0;i<cases;i++){
x=input.nextInt()-1;
y=input.nextInt()-1;
System.out.println(tree.getMaxSum(x, y));
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I can't suggest any optimization. The complexity of the algorithm is N*logN in both setup and execution time. The task however has a (sub)linear solution.</p>\n\n<p>Since this is a competitive problem, I am sure it is unethical to show the code; I am not even sure it is ethical to describe an algorithm. Besides the fact that a linear solution exists, I can afford one more hint:</p>\n\n<p>View the data set as a sequence of runs of positive and negative values. Notice that each run either completely belongs to an optimal range, or is completely excluded from it. Given a current best, and a sequence CNP (C being a current candidate, N a next run of negatives, followed by the run P of positives) figure out the conditions when restarting at P is better than accepting CNP as next candidate.</p>\n\n<p>Please forgive me, I am intentionally vague. Yet again, the mere fact that a linear algorithm exists is a very strong hint.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T05:02:22.557",
"Id": "48542",
"ParentId": "48525",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:22:08.900",
"Id": "48525",
"Score": "2",
"Tags": [
"java",
"performance",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "GSS1 SPOJ problem Time Limit Exceeding"
} | 48525 |
<p>I am trying to implement lock by which I want to avoid reads from happening whenever I am doing a write on my three maps.</p>
<p>Requirements:</p>
<ul>
<li>Reads block until all three maps have been set for the first time.</li>
<li>Now second time, If I am updating the maps, I can still return all the three old maps value(before the updates are done on all three maps) or it should block and return me all the new three maps value whenever the updates are done on all the three maps.</li>
</ul>
<p>As I have three Maps - <code>primary</code> , <code>secondary</code> and <code>tertiary</code> so it should return either all the new values of three updated maps or it should return all the old values of the map. Basically, while updating I don't want to return primary having old values, secondary having having new values, and tertiary with new values.</p>
<p>It should be consistent, either it should return old values or it should return new values after/while updating the maps. In my case, updating of maps will happen once in three months or four months.</p>
<p>And from the main application thread, reads will be happening on the getter of those three maps at a rate of <code>1000 requests per second</code>. So the get call on the three maps are really performance critical. I was thinking to use <code>ReentrantLock</code> or <code>ReentrantReadWriteLock</code> but got stick to CountDownLatch because of simplicity-</p>
<p>Below is my <code>ClientData</code> class in which I am using <code>CountDownLatch</code> -</p>
<pre><code>public class ClientData {
public static class Mappings {
public final Map<String, Map<Integer, String>> primary;
public final Map<String, Map<Integer, String>> secondary;
public final Map<String, Map<Integer, String>> tertiary;
public Mappings(
Map<String, Map<Integer, String>> primary,
Map<String, Map<Integer, String>> secondary,
Map<String, Map<Integer, String>> tertiary
) {
this.primary = primary;
this.secondary = secondary;
this.tertiary = tertiary;
}
}
private static final AtomicReference<Mappings> mappings = new AtomicReference<>();
private static final CountDownLatch hasBeenInitialized = new CountDownLatch(1);
public static Mappings getMappings() {
try {
hasBeenInitialized.await();
return mappings.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
public static void setMappings(
Map<String, Map<Integer, String>> primary,
Map<String, Map<Integer, String>> secondary,
Map<String, Map<Integer, String>> tertiary
) {
setMappings(new Mappings(primary, secondary, tertiary));
}
public static void setMappings(Mappings newMappings) {
mappings.set(newMappings);
hasBeenInitialized.countDown();
}
}
</code></pre>
<p>And below is my background thread code. It will get the data from my service URL and keep on running every 10 minutes once my application has started up. It will then parse the data coming from the URL and store it in a <code>ClientData</code> class variable in those three maps as shown above.</p>
<pre><code>public class TempScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void startScheduler() {
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
callServers();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 0, 10, TimeUnit.MINUTES);
}
}
// call the servers and get the data and then parse
// the response.
private void callServers() {
String url = "url";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
parseResponse(response);
}
// parse the response and store it in a variable
private void parseResponse(String response) {
//...
ConcurrentHashMap<String, Map<Integer, String>> primaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> secondaryTables = null;
ConcurrentHashMap<String, Map<Integer, String>> tertiaryTables = null;
//...
// store the data in ClientData class variables if anything has changed
// which can be used by other threads
if(changed) {
ClientData.setMappings(primaryTables, secondaryTables, tertiaryTables);
}
}
}
</code></pre>
<p><strong>Problem Statement:</strong></p>
<p>Is there any way I can improve the above <code>ClientData</code> class somehow? Any kind of performance improvements? Or by using any other ways instead of <code>CountDownLatch</code>?</p>
<p>I will be using <code>ClientData</code> class in main application thread like this -</p>
<pre><code>Mappings mappings = ClientData.getMappings();
// use mappings.primary
// use mappings.secondary
// use mappings.tertiary
</code></pre>
<p>I am suspecting, I can avoid <code>AtomicReference</code> here -</p>
<blockquote>
<p>The atomic reference may not actually be required since both get and set operations synchronize on <code>hasBeenInitialized</code>. </p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:00:13.093",
"Id": "85224",
"Score": "0",
"body": "I had assumed in [your previous question](http://codereview.stackexchange.com/questions/48442/how-to-prevent-reads-before-initialization-is-complete/48450#48450) that the maps couldn't be modified once set. If that's the case, there's no need for `ConcurrentHashMap` here since they are written by a single thread and safely published before being read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:14:11.470",
"Id": "85225",
"Score": "0",
"body": "@DavidHarkness: You talking about inside `TempScheduler` class? Right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:18:03.147",
"Id": "85227",
"Score": "0",
"body": "Correct. If those maps created in a single background thread, there's no need for a concurrent map."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:24:40.530",
"Id": "85228",
"Score": "0",
"body": "Yeah. good point. I will replace that with LinkedHashMap then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:32:51.147",
"Id": "85231",
"Score": "0",
"body": "If you don't need insertion-order traversal you can use `HashMap` instead of `LinkedHashMap` to save some memory. `ConcurrentHashMap` didn't provide this feature, so I doubt you're depending on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T03:15:47.687",
"Id": "85261",
"Score": "0",
"body": "@DavidHarkness: Thanks for another tip. I added that change as well. Let's see if I can get any other suggestion."
}
] | [
{
"body": "<p>Going through some smaller items in your code. Your <code>Mappings</code> class is public, which is fine, but it should also be final. There is no reason for people to extend your class. The constructor should be private, and all the Map fields should be private as well, but you should have getters for those maps... <code>getPrimary()</code>, <code>getSecondary()</code>, etc.</p>\n\n<p>On the <code>ClientData</code> class, the method <code>setMappings(Mappings...)</code> content should be merged in to the <code>setMappings(Map ..., Map.. Map)</code> method, and that method should not be public either, assuming the background thread is defined in the same package as you.</p>\n\n<p>Restricting these permissions will make your application better defined.</p>\n\n<p>The remaining concern with your code is whether the Map instances themselves are Mutable (well, they <em>are</em> mutable, but should they be?). I would recommend making them readonly using <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableMap-java.util.Map-\" rel=\"nofollow\">Collections.unmodifiableMap()</a> which will prevent the actual Map content from becoming corrupted by some thread polluting the data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-04T23:22:38.997",
"Id": "52482",
"ParentId": "48526",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "52482",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:39:53.143",
"Id": "48526",
"Score": "5",
"Tags": [
"java",
"optimization",
"performance",
"multithreading",
"locking"
],
"Title": "Using CountDownLatch for blocking the reads if writes are happening"
} | 48526 |
<p>I have the below MySQL query that does exactly what I need, but I am sure there are better queries that do the same thing.</p>
<p>If you see something very ugly or bad and have any suggestions, I will be very glad to hear them.</p>
<pre><code>SELECT c.`ID_COURIER`, c.`NAME`,
c.`NICKNAME`, c.`AREA_CODE`,
c.`PHONE_NUMBER`, d.`ID_DELIVERY`,
d.`DESCRIPTION`, d.`START_DATE`,
d.`END_DATE`, d.`CANCELED`,
r.`LAT`, r.`LNG`,
(SELECT COUNT(DISTINCT `ID_ORDER`) FROM `ORDERS` WHERE `ID_DELIVERY` = d.`ID_DELIVERY` AND `DELIVERY_DATE` IS NULL AND `CANCELED` = false) as REMAINING_ORDERS
FROM `COURIER` as c
LEFT JOIN `DELIVERY` as d USING (`ID_COURIER`)
LEFT JOIN `GEOLOCATIONS` as r ON r.`ID_DELIVERY` = d.`ID_DELIVERY`
WHERE c.`ID_COMPANY` = ? AND c.`DISABLED` = false
AND (
CASE WHEN (SELECT MAX(`START_DATE`)
FROM `DELIVERY`
WHERE `ID_COURIER` = c.`ID_COURIER`)
IS NULL THEN d.`START_DATE` IS NULL
ELSE d.`START_DATE` = (SELECT MAX(`START_DATE`)
FROM `DELIVERY`
WHERE `ID_COURIER` = c.`ID_COURIER`)
END )
AND (
CASE WHEN (SELECT MAX(`ID_GEOLOCATION`)
FROM `GEOLOCATIONS`
WHERE `ID_DELIVERY` = d.`ID_DELIVERY`)
IS NULL THEN r.`ID_GEOLOCATION` IS NULL
ELSE r.`ID_GEOLOCATION` = (SELECT MAX(`ID_GEOLOCATION`)
FROM `GEOLOCATIONS`
WHERE `ID_DELIVERY` = d.`ID_DELIVERY`)
END)
GROUP BY c.`ID_COURIER`
ORDER BY d.`START_DATE` DESC
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:57:34.130",
"Id": "85223",
"Score": "1",
"body": "If you would like help with an SQL performance issue, please post the output of `EXPLAIN SELECT`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T22:27:39.917",
"Id": "85229",
"Score": "0",
"body": "Welcome to Code Review! To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:19:21.637",
"Id": "85245",
"Score": "0",
"body": "Some context regarding database structure and example rows in the table along with example results from the query would be helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T18:53:30.023",
"Id": "88444",
"Score": "0",
"body": "I agree more context would help tremendously. You have a lot of nested subquries and aggregate functions within them and I could see that causing issues, I would try to avoid that as much as you can. I'll try and come up with an answer shortly based on what you provided."
}
] | [
{
"body": "<p>Top to bottom, here we go.</p>\n\n<ul>\n<li><p><code>COUNT(DISTINCT <code>ID_ORDER</code>)</code> </p>\n\n<p>This <code>DISTINCT</code> aggregation seems superfluous, if <code>ID_ORDER</code> is a true identity column then there should not be duplicates. This will improve performance.</p></li>\n<li><p><code>LEFT JOIN <code>DELIVERY</code> AS d USING (<code>ID_COURIER</code>)</code></p>\n\n<p>I'm not a big fan of the <code>USING</code> keyword as I find it ambiguous. Agreed it's a useful shorthand but to the next person going back to read your code they would have to go and check that both tables have a <code>ID_COURIER</code> column. Plus if one of the columns got renamed at any point it would be more difficult to find the bug.</p>\n\n<p>My suggestion:</p>\n\n<pre><code>LEFT JOIN `DELIVERY` AS d ON c.ID_DELIVERY = d.ID_DELIVERY\n</code></pre></li>\n<li><p><code>WHERE c.<code>ID_COMPANY</code> = ?</code></p>\n\n<p>This doesn't seem to have any purpose I'm sure you could take it out with no difference. </p></li>\n<li><p><code>CASE WHEN (SELECT MAX(<code>START_DATE</code>)</code> and the rest of the statement. </p>\n\n<p>This I find very unusual and not optimal for performance. I'm not sure I completely understand what you are trying to do but I'll give it my best shot. You may want to instead build this into your select. Here is what I suggest for the complete script. I made some edits to the layout to make it easier to read. If I misunderstood the intention of your <code>CASE</code> statements let me know and I can revise. </p></li>\n</ul>\n\n<p></p>\n\n<pre><code>SELECT \n c.ID_COURIER, \n c.NAME,\n c.NICKNAME, \n c.AREA_CODE, \n c.PHONE_NUMBER, \n-- This will return NULL if ID_GEOLOCATION is NULL\n (SELECT MAX(ID_GEOLOCATION) FROM GEOLOCATIONS) AS 'ID_GEOLOCATION',\n d.DESCRIPTION, \n-- This will return NULL if START_DATE is NULL\n (SELECT MAX(START_DATE) FROM ORDERS) AS 'START_DATE',\n d.END_DATE,\n d.CANCELED,\n r.LAT, \n r.LNG, \n-- Subquery JOIN moved to FROM and WHERE statements\n COUNT(ID_ORDER) AS 'REMAINING ORDERS' \nFROM COURIER AS c \n LEFT JOIN DELIVERY AS d ON c.ID_DELIVERY = d.ID_DELIVERY\n LEFT JOIN GEOLOCATIONS AS r ON r.ID_DELIVERY = d.ID_DELIVERY \n LEFT JOIN ORDERS AS o ON d.ID_DELIVERY = o.ID_DELIVERY\nWHERE c.DISABLED = false\nAND o.DELIVERY_DATE IS NULL AND o.CANCELED = false\nGROUP BY c.ID_COURIER\nORDER BY d.START_DATE DESC;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T21:07:15.097",
"Id": "51255",
"ParentId": "48528",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "51255",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:51:08.110",
"Id": "48528",
"Score": "2",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Delivery geolocations query"
} | 48528 |
<p>This code works fine, but I believe it has optimization problems. Please review this.</p>
<p>Also, please keep in mind that it stops after each iteration of the loop <code>foreach($mascow_sub_area as $subway)</code>.</p>
<pre><code> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<?php
set_time_limit(0);
ini_set('memory_limit', '-1');
require_once("../../dom/dom.php");
$connection = mysqli_connect("localhost", "root", "", "delivery_clud");
mysqli_set_charset($connection, "utf8");
function spider($url){
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$url = "select * from html where url = '$url'";
$yql_query_url = $yql_base_url . "?q=" . urlencode($url);
$yql_query_url .= "&format=json";
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
curl_close($session);
return $json;
}
$mascow_sub_area = array(//'Aviamotornaya','Avtozavodskaya','Akademicheskaya','Aleksandrovskiy_Sad',
'Alekseevskaya',
'Alma-Atinskaya','Altufevo','Annino','Arbatskaya','Aeroport','Babushkinskaya','Bagrationovskaya','Barrikadnaya','Baumanskaya','Begovaya','Belorusskaya','Belyaevo','Bibirevo','Biblioteka_imeni_Lenina','Borisovo','Borovitskaya','Botanicheskiy_Sad','Bratislavskaya','Bulvar_Admirala_Ushakova','Bulvar_Dmitriya_Donskogo','Buninskaya_Alleya','Varshavskaya','VDNKh','Vladykino','Vodnyy_Stadion','Voykovskaya','Volgogradskiy_Prospekt','Volzhskaya','Volokolamskaya','Vorobevy_Gory','Vystavochnaya','Vykhino','Delovoy_Tsentr','Dinamo','Dmitrovskaya','Dobryninskaya','Domodedovskaya','Dostoevskaya','Dubrovka','Zhulebino','Zyablikovo','Izmaylovskaya','Kaluzhskaya','Kantemirovskaya','Kakhovskaya','Kashirskaya','Kievskaya','Kitay-gorod','Kozhukhovskaya','Kolomenskaya','Komsomolskaya','Konkovo','Krasnogvardeyskaya','Krasnopresnenskaya','Krasnoselskaya','Krasnye_Vorota','Krestyanskaya_Zastava','Kropotkinskaya','Krylatskoe','Kuznetskiy_Most','Kuzminki','Kuntsevskaya','Kurskaya','Kutuzovskaya','Leninskiy_prospekt','Lermontovskij_prospekt','Lubyanka','Lyublino','Marksistskaya','Marina_roshcha','Marino','Mayakovskaya','Medvedkovo','Mezhdunarodnaya','Mendeleevskaya','Mitino','Molodezhnaya','Myakinino','Nagatinskaya','Nagornaya','Nakhimovskiy_prospekt','Novogireevo','Novokosino','Novokuznetskaya','Novoslobodskaya','Novoyasenevskaya','Novye_Cheremushki','Oktyabrskaya','Oktyabrskoe_Pole','Orekhovo','Otradnoe','Okhotnyy_Ryad','Paveletskaya','Park_Kultury','Park_Pobedy','Partizanskaya','Pervomayskaya','Perovo','Petrovsko-Razumovskaya','Pechatniki','Pionerskaya','Planernaya','Ploshchad_Ilicha','Ploshchad_Revolyutsii','Polezhaevskaya','Polyanka','Prazhskaya','Preobrazhenskaya_Ploshchad','Proletarskaya','Prospekt_Vernadskogo','Prospekt_Mira','Profsoyuznaya','Pushkinskaya','Pyatnickoe_shosse','Rechnoy_Vokzal','Rizhskaya','Rimskaya','Ryazanskiy_Prospekt','Savelovskaya','Sviblovo','Sevastopolskaya','Semenovskaya','Serpukhovskaya','Slavyanskiy_Bulvar','Smolenskaya','Sokol','Sokolniki','Sportivnaya','Sretenskiy_bulvar','Strogino','Studencheskaya','Sukharevskaya','Skhodnenskaya','Taganskaya','Tverskaya','Teatralnaya','Tekstilshchiki','Teletsentr','Teplyy_Stan','Timiryazevskaya','Tretyakovskaya','Trubnaya','Tulskaya','Turgenevskaya','Tushinskaya','Ulitsa_1905_goda','Ulitsa_Akademika_Koroleva','Ulitsa_Akademika_Yangelya','Ulitsa_Gorchakova','Ulitsa_Milashenkova','Ulitsa_Podbelskogo','Ulitsa_Sergeya_Eyzenshteyna','Ulitsa_Skobelevskaya','Ulitsa_Starokachalovskaya','Universitet','Filevskiy_Park','Fili','Frunzenskaya','Tsaritsyno','Tsvetnoy_bulvar','Cherkizovskaya','Chertanovskaya','Chekhovskaya','Chistye_Prudy','Chkalovskaya','Shabolovskaya','Shipilovskaya','Shosse_Entuziastov','Shchelkovskaya','Shchukinskaya','Elektrozavodskaya','Yugo-Zapadnaya','Yuzhnaya','Yasenevo');
$categories = array(1=>"1",2=>"2");//array(1=>array('pizza','sushi','shashliki','pirogi','burger'),2=>array('farm','dairy','delicatessen','confectionery','gastronomy'));
foreach($categories as $key => $cati){
{
if($key == 2){
$url = "http://www.delivery-club.ru/entities/groceries/farm/#group=%D0%93%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%BD%D0%BE%D0%BC%D0%B8%D1%8F&group=%D0%A4%D0%B5%D1%80%D0%BC%D0%B5%D1%80%D1%81%D0%BA%D0%B8%D0%B5+%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B&group=%D0%9C%D0%BE%D0%BB%D0%BE%D1%87%D0%BD%D1%8B%D0%B5+%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B&group=%D0%94%D0%B5%D0%BB%D0%B8%D0%BA%D0%B0%D1%82%D0%B5%D1%81%D1%8B&group=%D0%9A%D0%BE%D0%BD%D0%B4%D0%B8%D1%82%D0%B5%D1%80%D1%81%D0%BA%D0%B8%D0%B5+%D0%B8%D0%B7%D0%B4%D0%B5%D0%BB%D0%B8%D1%8F&group=%D0%92%D0%BE%D0%B4%D0%B0%2C+%D0%A7%D0%B0%D0%B9%2C+%D0%9A%D0%BE%D1%84%D0%B5&show=all";
get_data("Goods", str_get_html(file_get_contents($url)));
}
else{
foreach($mascow_sub_area as $subway){
//echo "Key: $key----Category: $sub.<br />";
$url = "http://www.delivery-club.ru/ajax/entities/?mode=food&cat_id=$cati&mo_mode=null&district=null&okrug=null&cuisine=region&params=null&ajax_changer_subway=$subway";
$html = str_get_html(file_get_contents($url));
//echo $html;return;
//$html = "";
//echo "test<hr />";
get_data($subway, $html);
}
}
}
}
function get_data($subway, $html){
$data = array();
$data['subway'] = $subway;
$val = ($html->find('.dum'));
foreach($html->find('.dum') as $one){
foreach($one->find(".full_link") as $link){
$data['name'] = (trim(strip_tags("$link->innertext")));
$data['link'] = trim(strip_tags("http://www.delivery-club.ru$link->href"));
// print_r($data);
//
}
foreach($one->find('.info') as $main){
foreach($main->find('.min_sum') as $min_sum){
$data['min_order'] = (trim(strip_tags("$min_sum->innertext")));
}//
foreach($main->find('.distanse') as $dis){
$d = explode(":", strip_tags($dis->innertext));
$data['distance'] = (trim($d[1]));
}
foreach($main->find('.specialization') as $main_cat){
$d = explode(":", strip_tags($main_cat->innertext));
$data['specialization'] = (trim($d[1]));
}
//$ul = $main->find('ul');
$price ;
foreach($main->find('.price') as $li){ $price[] = trim(strip_tags($li->innertext));}
$data['delivery_cost'] = end($price);$price = array();
foreach($main->find('.categories') as $cat){
$d = explode(":", strip_tags($cat->innertext));
$data['categories'] = (trim($d[1]));
}
// foreach($main->find('.price', 0) as $extra){
// echo "----Delivery Charges".$extra->innertext;
// }
foreach($main->find('.time') as $time){
$data['delivery_time'] =(trim(strip_tags($time->innertext)));
}
foreach($main->find('.plus') as $plus){
$data['plus'] = trim(strip_tags($plus->innertext));
}
foreach($main->find('.minus') as $minus){
$data['minus'] = trim(strip_tags($minus->innertext));
}
foreach($main->find('.hint') as $minus){
$data['description'] = (trim(strip_tags($minus->innertext)));
}
$u = ( parse_url($data['link']));
$u['fragment'] = str_replace(end($u),"info/#".end($u), end($u));
$data['city'] = 'Moscow';
$next_scrap = $u['scheme']."://".$u['host'].$u['path'].$u['fragment'];
sleep(3);
$minified = str_get_html(file_get_contents($next_scrap));
if(!$minified || $minified == "") continue;
foreach($minified->find('.tabs') as $tabs){
preg_match('/[0-9]+/', $tabs->innertext, $found);
if(count($found)){
$data['reviews'] = $found[0];
}
}
foreach($minified->find(".thumb") as $plus){
$p_r = str_replace('%', "", $plus->innertext);
$data['positive_reviews'] = ceil($data['reviews']*($p_r/100));
$data['negative_reviews'] = $data['reviews']-$data['positive_reviews'];
break;
}
$i = 0;
$address = array();
foreach($minified->find('.default_list') as $ul){
foreach($ul->find('li') as $li){
$address[$i]['address'] = trim(strip_tags($li->innertext));
foreach($li->find('meta') as $meta){
$address[$i][] = strip_tags($meta->content);
}
// echo $li->innertext."<br />";
$i+=1;
}
}
//print_r($address);
$data['address'] = '';
foreach($address as $val){
$data['address'] .= "( address=>".(trim($val['address']));
$data['address'] .= " --- longitude=>".trim($val[1]);
$data['address'] .= " --- latitude=>".trim($val[0])." ) || ";
}
}
//file_put_contents("output.txt",
//print_r($data);
insert($data);
}
}
function insert($data)
{
//open connection from the connection file
//it'll reccieve table as a String and data in the form of array(key value pair) and adjust those key values to a query
// $where is an array that will take array as first one and impose that as an 'WHERE' clause and will set its values.
global $connection;
$fields = array();
$values = array();
foreach ($data as $key => $value) {
$fields[] = $key;
$values[] = "'" . mysqli_real_escape_string($connection, $value) . "'";
}
if (count($fields) == count($values)) {
$insert = implode(",", $fields);
$val = implode(",", $values);
}
$sql = "INSERT INTO data($insert) VALUES($val)";
$sql .= " ON DUPLICATE KEY UPDATE link = '".mysqli_real_escape_string($connection,$data['link'])."'";
mysqli_query($connection, ($sql))or die(mysqli_error($connection)."<br />".print($sql));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:39:42.817",
"Id": "85291",
"Score": "0",
"body": "You have up to five levels of nesting in foreach loop. Its Big O can't be good. http://stackoverflow.com/questions/21372927/big-o-and-nested-loops"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T00:10:32.857",
"Id": "88671",
"Score": "0",
"body": "I only found about 2 lines of MySQLi at the very end, perhaps you should not have tagged that as MySQLi question... for all it's worth they look fine."
}
] | [
{
"body": "<p>I want to focus principally on this section of your code:</p>\n\n<pre><code>$mascow_sub_area = array(//'Aviamotornaya','Avtozavodskaya','Akademicheskaya','Aleksandrovskiy_Sad',\n'Alekseevskaya',\n'Alma-Atinskaya','Altufevo','Annino','Arbatskaya','Aeroport','Babushkinskaya','Bagrationovskaya','Barrikadnaya','Baumanskaya','Begovaya','Belorusskaya','Belyaevo','Bibirevo','Biblioteka_imeni_Lenina','Borisovo','Borovitskaya','Botanicheskiy_Sad','Bratislavskaya','Bulvar_Admirala_Ushakova','Bulvar_Dmitriya_Donskogo','Buninskaya_Alleya','Varshavskaya','VDNKh','Vladykino','Vodnyy_Stadion','Voykovskaya','Volgogradskiy_Prospekt','Volzhskaya','Volokolamskaya','Vorobevy_Gory','Vystavochnaya','Vykhino','Delovoy_Tsentr','Dinamo','Dmitrovskaya','Dobryninskaya','Domodedovskaya','Dostoevskaya','Dubrovka','Zhulebino','Zyablikovo','Izmaylovskaya','Kaluzhskaya','Kantemirovskaya','Kakhovskaya','Kashirskaya','Kievskaya','Kitay-gorod','Kozhukhovskaya','Kolomenskaya','Komsomolskaya','Konkovo','Krasnogvardeyskaya','Krasnopresnenskaya','Krasnoselskaya','Krasnye_Vorota','Krestyanskaya_Zastava','Kropotkinskaya','Krylatskoe','Kuznetskiy_Most','Kuzminki','Kuntsevskaya','Kurskaya','Kutuzovskaya','Leninskiy_prospekt','Lermontovskij_prospekt','Lubyanka','Lyublino','Marksistskaya','Marina_roshcha','Marino','Mayakovskaya','Medvedkovo','Mezhdunarodnaya','Mendeleevskaya','Mitino','Molodezhnaya','Myakinino','Nagatinskaya','Nagornaya','Nakhimovskiy_prospekt','Novogireevo','Novokosino','Novokuznetskaya','Novoslobodskaya','Novoyasenevskaya','Novye_Cheremushki','Oktyabrskaya','Oktyabrskoe_Pole','Orekhovo','Otradnoe','Okhotnyy_Ryad','Paveletskaya','Park_Kultury','Park_Pobedy','Partizanskaya','Pervomayskaya','Perovo','Petrovsko-Razumovskaya','Pechatniki','Pionerskaya','Planernaya','Ploshchad_Ilicha','Ploshchad_Revolyutsii','Polezhaevskaya','Polyanka','Prazhskaya','Preobrazhenskaya_Ploshchad','Proletarskaya','Prospekt_Vernadskogo','Prospekt_Mira','Profsoyuznaya','Pushkinskaya','Pyatnickoe_shosse','Rechnoy_Vokzal','Rizhskaya','Rimskaya','Ryazanskiy_Prospekt','Savelovskaya','Sviblovo','Sevastopolskaya','Semenovskaya','Serpukhovskaya','Slavyanskiy_Bulvar','Smolenskaya','Sokol','Sokolniki','Sportivnaya','Sretenskiy_bulvar','Strogino','Studencheskaya','Sukharevskaya','Skhodnenskaya','Taganskaya','Tverskaya','Teatralnaya','Tekstilshchiki','Teletsentr','Teplyy_Stan','Timiryazevskaya','Tretyakovskaya','Trubnaya','Tulskaya','Turgenevskaya','Tushinskaya','Ulitsa_1905_goda','Ulitsa_Akademika_Koroleva','Ulitsa_Akademika_Yangelya','Ulitsa_Gorchakova','Ulitsa_Milashenkova','Ulitsa_Podbelskogo','Ulitsa_Sergeya_Eyzenshteyna','Ulitsa_Skobelevskaya','Ulitsa_Starokachalovskaya','Universitet','Filevskiy_Park','Fili','Frunzenskaya','Tsaritsyno','Tsvetnoy_bulvar','Cherkizovskaya','Chertanovskaya','Chekhovskaya','Chistye_Prudy','Chkalovskaya','Shabolovskaya','Shipilovskaya','Shosse_Entuziastov','Shchelkovskaya','Shchukinskaya','Elektrozavodskaya','Yugo-Zapadnaya','Yuzhnaya','Yasenevo');\n$categories = array(1=>\"1\",2=>\"2\");//array(1=>array('pizza','sushi','shashliki','pirogi','burger'),2=>array('farm','dairy','delicatessen','confectionery','gastronomy'));\nforeach($categories as $key => $cati){\n {\n if($key == 2){\n $url = \"http://www.delivery-club.ru/entities/groceries/farm/#group=%D0%93%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%BD%D0%BE%D0%BC%D0%B8%D1%8F&group=%D0%A4%D0%B5%D1%80%D0%BC%D0%B5%D1%80%D1%81%D0%BA%D0%B8%D0%B5+%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B&group=%D0%9C%D0%BE%D0%BB%D0%BE%D1%87%D0%BD%D1%8B%D0%B5+%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B&group=%D0%94%D0%B5%D0%BB%D0%B8%D0%BA%D0%B0%D1%82%D0%B5%D1%81%D1%8B&group=%D0%9A%D0%BE%D0%BD%D0%B4%D0%B8%D1%82%D0%B5%D1%80%D1%81%D0%BA%D0%B8%D0%B5+%D0%B8%D0%B7%D0%B4%D0%B5%D0%BB%D0%B8%D1%8F&group=%D0%92%D0%BE%D0%B4%D0%B0%2C+%D0%A7%D0%B0%D0%B9%2C+%D0%9A%D0%BE%D1%84%D0%B5&show=all\";\n get_data(\"Goods\", str_get_html(file_get_contents($url)));\n }\n</code></pre>\n\n<p><strong>Commented out code</strong></p>\n\n<p>There are some values and some code commented out. Why? If it's not needed, just remove it. </p>\n\n<p>Values:</p>\n\n<pre><code>$mascow_sub_area = array(//'Aviamotornaya','Avtozavodskaya','Akademicheskaya','Aleksandrovskiy_Sad',\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>$categories = array(1=>\"1\",2=>\"2\");//array(1=>array('pizza','sushi','shashliki','pirogi','burger'),2=>array('farm','dairy','delicatessen','confectionery','gastronomy')); $categories = array(1=>\"1\",2=>\"2\");//array(1=>array(\n</code></pre>\n\n<p><strong>Hard-coded arbitrary values</strong></p>\n\n<p>You hard-coded dozens of arbitrary areas into the massive <code>$mascow_sub_area</code> array, then you make PHP iterate over each value in multiple arrays to check for conditions. I would suggest that you make use of MySQL more and store your values there. This would have certain advantages:</p>\n\n<ol>\n<li><p>Easy to add, update and remove values from a table without having to change the PHP script at all.</p></li>\n<li><p>Takes advantage of the speed of SQL query optimizer to fetch and compare data. </p></li>\n<li><p>Then just pass the result set back to PHP.</p></li>\n</ol>\n\n<p>And that brings me to...</p>\n\n<h1><strike><strong>Wrong tool for the job.</strong></strike></h1>\n\n<h1><strong>Use your database!</strong></h1>\n\n<p>What you are doing, I'm sure you realize, is iterating through arrays multiple levels deep, comparing data. I can't imagine that being very fast at all. As was commented:</p>\n\n<blockquote>\n <p>You have up to five levels of nesting in foreach loop. Its Big O can't be good. – CodeWorks Apr 30 at 11:39 </p>\n</blockquote>\n\n<p><strike>\nYou can calculate with up to 5 levels of nesting you would get up to \\$O(n^5)\\$. I have not counted all those area names but it must be at least 30, probably a lot more... going through 3 levels of nesting \\$O(30^3) = 27 000\\$</p>\n\n<p>Granted, this is oversimplified and probably not <em>that</em> bad, in concept it's a pretty scary <em>Big O</em>. \n</strike></p>\n\n<p>I try to keep this in mind:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ng3Sk.jpg\" alt=\"hammer\"></p>\n\n<p>To a RDBMS like MySQL, comparing multiple arrays worth of data using tables is trivial, because it does so <em>as a set</em> rather than one by one. I've had a <a href=\"https://codereview.stackexchange.com/questions/51603/modifying-sakila-database\">similar problem, but in reverse</a> using loops in SQL, and once I had the code reviewed someone suggested to do it by set instead, and it sped it up dramatically. </p>\n\n<p>To me, I would see <code>$mascow_sub_area</code>, <code>$categories</code>, and maybe even your URL concatenation logic be set-based in SQL, though I'm not sure that specifically would be best tool for the job.</p>\n\n<p>Example:</p>\n\n<pre><code>create table mascow_sub_area(\n area_id int not null identity,\n area_name varchar(255) not null\n);\ninsert into mascow_sub_area(area_name) values\n('Atinskaya'),('Altufevo'),('Annino') -- etc.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T22:38:58.180",
"Id": "113853",
"Score": "1",
"body": "The database suggestion is good, but I would not say that the loop is a *real* O(n) as it's not looping through the same array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T22:51:27.807",
"Id": "113856",
"Score": "0",
"body": "The performance analysis is sloppy. The runtime will likely be dominated by the fetching and inserting, both of which are probably unavoidable. The HTML parsing and descent into the DOM tree is fine — each inner loop will only look at the relevant portion of the document. Runtime should be nowhere near \"\\$O(n^5)\\$\" — whatever \\$n\\$ means (you didn't specify). It's probably more like \\$O(N(S+L))\\$, where \\$S\\$ is the number of subway stations, \\$L\\$ is the total number of store locations, and \\$N\\$ is the average number of DOM nodes per page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T23:14:17.537",
"Id": "113866",
"Score": "0",
"body": "@200_success would you mind to edit that into the answer properly? I was thinking of \\$n\\$ as being the number of values in the `$mascow_sub_area` array, who knows how many that is so I made a conservative guess of 30. I just don't understand what you commented enough to do it justice..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T23:19:29.377",
"Id": "113869",
"Score": "0",
"body": "Consider striking out the complexity analysis from your answer then. Probably the only thing remarkable to say about the code's complexity is that the code is structured in a way that makes it hard to see where the complexity lies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T23:49:25.807",
"Id": "113871",
"Score": "0",
"body": "Fair enough. I did that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T22:02:13.020",
"Id": "62467",
"ParentId": "48531",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "62467",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:10:24.283",
"Id": "48531",
"Score": "8",
"Tags": [
"php",
"mysqli",
"curl",
"geospatial",
"web-scraping"
],
"Title": "Optimize web-scraping of Moscow grocery website"
} | 48531 |
<p>I'm working on a framework that will be used to create simple 2D grid based games. It is using an Entity-Component-System pattern with corresponding manager classes used to control the lifespan of objects and construct them polymorphically based on an ID.</p>
<p>In addition to general improvements to my code, I'm asking for feedback on the implementation of the ECS model specifically. Things I would like to change are:</p>
<ul>
<li>Remove Manager classes (if possible)</li>
<li>Decouple Systems and Components keys from base classes (<a href="https://stackoverflow.com/questions/23417874/creating-hashable-non-copyable-objects-and-static-classes-using-inheritance">related post</a>).</li>
</ul>
<p>I don't like the use of my manager classes, I created them out of necessity to ensure the proper constructors are called on my abstract base classes, and would like to redesign the framework without them if possible.</p>
<p>I would appreciate any advice on decoupling the Systems and Components id's from their base classes. (Possibly create a generic key class that can be used for both base classes?) <a href="https://stackoverflow.com/questions/23417874/creating-hashable-non-copyable-objects-and-static-classes-using-inheritance">Related post</a>.</p>
<p>Using the ECS:</p>
<pre><code>SystemsManager* sysMan = new ConcreteSystemsManager();
EntitiesManager* entMan = new ConcreteEntitiesManager();
sysMan->createSystem("ExampleSystem");
entMan->createEntity("ExampleEntity");
sysMan->getSystemPtr("ExampleSystem")->registerEntity(
entMan->getEntityPtr("ExampleEntity");
GameState* gameState = new ConcreteGameState(entMan, sysMan);
gameState->run();
</code></pre>
<p>I've only included the declarations of the classes used in my framework, I didn't feel it was necessary since my request for feedback is about my overall design, however I'll post the implementation files upon request.</p>
<p><strong>State.hpp</strong></p>
<pre><code>#pragma once
#include "EntitiesManager.hpp"
#include "SystemsManager.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
// Forward Declarations
class GameSystem;
// Base class for concrete GameState classes to
// inherit from.
class State
{
public:
State();
State(EntitiesManager*, SystemsManager*);
~State();
void setEntitiesManager(EntitiesManager*);
void setSystemsManager(SystemsManager*);
virtual int run() = 0;
protected:
private:
std::shared_ptr<EntitiesManager> entitiesManager;
std::shared_ptr<SystemsManager> systemsManager;
};
};
};
};
</code></pre>
<p><strong>IManager.hpp</strong></p>
<pre><code>#pragma once
namespace drj
{
namespace gfw
{
namespace core
{
class IManager
{
public:
virtual ~IManager();
virtual int create(std::string const&) = 0;
virtual int destroy(std::string const&) = 0;
protected:
IManager();
private:
};
};
};
};
</code></pre>
<p><strong>EntitiesManager.hpp</strong></p>
<pre><code>#pragma once
#include <string>
#include <memory>
#include <unordered_map>
#include "Entity.hpp"
#include "IManager.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
class EntitiesManager : public IManager
{
public:
EntitiesManager();
virtual ~EntitiesManager();
// Returns nullptr if the entity doesn't exist.
// This EntitiesManager still owns the pointer.
Entity* getEntityPtr(std::string const&) const;
// Returns -1 if the entity already exists.
int create(std::string const&);
// Returns -1 if the entity didn't exist.
int destroy(std::string const&);
protected:
private:
std::unordered_map<
std::string,
std::unique_ptr<Entity>> entities;
};
};
};
};
</code></pre>
<p><strong>SystemsManager.hpp</strong></p>
<pre><code>#pragma once
#include <string>
#include <memory>
#include <unordered_map>
#include "System.hpp"
#include "IManager.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
class SystemsManager : public IManager
{
public:
virtual ~SystemsManager();
// Returns nullptr if the system doesn't exist.
System* getSystemPtr(std::string const&) const;
// Returns -1 if the system already exists.
virtual int create(std::string const&) = 0;
// Returns -1 if the system didn't exist.
virtual int destroy(std::string const&) = 0;
protected:
SystemsManager();
private:
std::unordered_map<
std::string,
std::unique_ptr<System>> systems;
};
};
};
};
</code></pre>
<p><strong>ComponentsManager.hpp</strong></p>
<pre><code>#pragma once
#include <string>
#include <memory>
#include <unordered_map>
#include "Component.hpp"
#include "IManager.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
class ComponentsManager : public IManager
{
public:
virtual ~ComponentsManager();
// Returns nullptr if the component doesn't exist.
Component* getComponentPtr(std::string const&) const;
// Returns -1 if the component already exists.
virtual int create(std::string const&) = 0;
// Returns -1 if the component didn't exist.
virtual int destroy(std::string const&) = 0;
protected:
ComponentsManager();
std::unordered_map<
std::string,
std::unique_ptr<Component>> components;
private:
};
};
};
};
</code></pre>
<p><strong>Entity.hpp</strong></p>
<pre><code>#pragma once
#include <list>
#include <memory>
#include <string>
#include "ComponentsManager.hpp"
//#include "GameComponent.hpp"
#include "System.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
// GameObjects are used as Entities in the ECS model
// of the core GameEngine module.
class Entity
{
friend class System;
public:
Entity();
~Entity();
// Returns true if the provided key is in this
// objects systemsRegistry.
bool hasSystemKey(std::string const&) const;
// Adding a key is not the same as registering
// an entity, however it is a process in that.
void addSystemKey(std::string const&);
void removeSystemKey(std::string const&);
ComponentsManager* getComponentsManager() const;
void setComponentsManager(ComponentsManager*);
protected:
private:
std::list<std::string> systemsRegistry;
std::unique_ptr<ComponentsManager> componentsManager;
};
};
};
};
</code></pre>
<p><strong>Component.hpp</strong></p>
<pre><code>#pragma once
#include <string>
#include <list>
namespace drj
{
namespace gfw
{
namespace core
{
// Base class for specialized GameComponent
// classes to inherit from.
class Component
{
friend class System;
public:
std::string const& getKey() const;
virtual ~Component();
protected:
Component(std::string const&);
private:
Component();
std::list<std::string> systemsUsing;
const std::string key;
size_t getSystemsUsingSize() const;
bool hasSystemKey(std::string const&) const;
// Used by GameSystem when registering
// entities and components.
void addSystemKey(std::string const&);
void removeSystemKey(std::string const&);
};
};
};
};
</code></pre>
<p><strong>System.hpp</strong></p>
<pre><code>#pragma once
#include <string>
#include "Component.hpp"
namespace drj
{
namespace gfw
{
namespace core
{
// Forward Declarations
class Entity;
// Base class used to create specialized Systems
// that use registered GameObjects as their
// input and output data.
class System
{
public:
virtual ~System();
std::string const& getKey() const;
// Returns true if the provided entity
// has this systems key in its systemsRegistry.
//
// The same as calling GameObject::hasKey(GameSystem::key)
bool isRegistered(Entity const&) const;
// Adds this systems key to the provided
// entities systemsRegistry and adds the
// necessary components to its ComponentsManager.
void registerEntity(Entity&) const;
void unregisterEntity(Entity&) const;
virtual int run(Entity&) = 0;
protected:
// Prevents users from creating non-specialized
// GameSystem objects.
//
// @arg[0] The key used to identify this
// system apart from other systems.
//
// @arg[1] The list of component keys that
// are required for concrete systems.
System(std::string const&,
std::list<std::string> const&);
private:
System();
const std::list<std::string> componentsRegistry;
const std::string registryKey;
};
};
};
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-30T04:08:12.813",
"Id": "104968",
"Score": "1",
"body": "This is surprisingly very pointer heavy for no apparent reason."
}
] | [
{
"body": "<p>There is nothing to redesign. This is (rudely speaking) a lot of scaffolding, with no concrete usage to validate whether this is a good design.</p>\n\n<p>I suggest that you first try to implement a real <code>System</code> (like the video <code>System</code> for instance), which will unequivocally tell you how exactly it expects to use <code>Entities</code> and <code>Components</code>. Then there will be something to review and make progress on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-05T08:40:54.423",
"Id": "372454",
"Score": "0",
"body": "This is in short the best answer to me. I added some more in depth thoughts but I think this can be accepted as well :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-17T09:46:33.563",
"Id": "54482",
"ParentId": "48536",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>The flat <code>namespace</code>s seem a little weird to me, but the answers to <a href=\"https://stackoverflow.com/questions/11358425/is-there-a-better-way-to-express-nested-namespaces-in-c-within-the-header\">this question</a> and <a href=\"https://stackoverflow.com/questions/713698/c-namespaces-advice\">this question</a> offer mixed suggestions on the preferred usage. They also seem to suggest that you may not need more than two <code>namespace</code>s, but I'm not familiar enough with this design to know for sure.</p></li>\n<li><p>Some of your comments are unnecessary, such as this one:</p>\n\n<blockquote>\n<pre><code>// Forward Declarations\n</code></pre>\n</blockquote>\n\n<p>It's already pretty clear that this is a forward declaration, and you don't need to tell us anyway. Comments should best be used to document something <em>unobvious</em> for others.</p></li>\n<li><p>In some places you do this:</p>\n\n<blockquote>\n<pre><code>protected: \nprivate:\n // code here...\n</code></pre>\n</blockquote>\n\n<p>and in other places you do this:</p>\n\n<blockquote>\n<pre><code>private:\n // no code here...\n</code></pre>\n</blockquote>\n\n<p>If you don't currently have anything after such a keyword, simply leave it out. Keeping them there anyway doesn't really help with maintenance, and can still leave others confused about why it's left there anyway. It's especially unneeded for <code>private</code>, as classes are <code>private</code> by default. It is okay (usually preferred) to keep the keyword there anyway, but it should still have some code.</p></li>\n</ul>\n\n<p>Side-note: as @Laurent has mentioned, there's not much to review here as all you've given us are headers. On the other hand, there's already much code here, so any additional code for review should be posted as a separate question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-15T23:39:30.717",
"Id": "57135",
"ParentId": "48536",
"Score": "3"
}
},
{
"body": "<p><strong>Please, resist the temptation to write your own ECS system</strong>, I've been in you and it is a no-go. But if you have to do so, do it right!</p>\n\n<ul>\n<li>You need to understand <strong>why you need ECS pattern</strong> (you entered dependency hell at least once)</li>\n<li>You need to <strong>start from good examples</strong> of ECS in your language (and I fear, for C++ there are actually no good examples, nor usefull articles)</li>\n</ul>\n\n<p>Let's me make a premise, I'm actually a consultant, helping a small indie team of quitting dependency hell, I'm basically re-writing a small game (30k lines of code). Turning it into a full-fledged ECS game. And I'm using an already existing ECS framework, not a mine framework. Explaining it is the most difficult part.</p>\n\n<p>I'm actually learning new things with every-day problems I face, so I'm not speaking to you as \"expert\", but as person that is learning. Sometimes I ask questions to the author of the framework I use and he is very willingly to help me and find better solutions to certain problems.</p>\n\n<p>Believe me, I come from a C++ programming background, so I always struggled to make my custom engine, dealing with allocation etc. I even started a 3D engine once, I would never do that again.</p>\n\n<p>What you are trying to achieve already however:</p>\n\n<blockquote>\n <p>Remove Manager classes (if possible)</p>\n \n <p>Decouple Systems and Components keys from base classes</p>\n</blockquote>\n\n<p>suggests me that you already spent a good amount of time digging into the topic. While your first point indicates you are on the right way, your second point gives me the impression that you have been hijacked by articles written by people that do not really use the ECS pattern or do not understand the pattern at all (Unity, Unreal and Lumberyard are NOT Using the ECS pattern, neither in its old conception).</p>\n\n<p><strong>To directly address your question</strong>, I think the best suggestion comes from @Laurent La RIZZA's answer:</p>\n\n<blockquote>\n <p>I suggest that you first try to implement a real System (like the video System for instance), which will unequivocally tell you how exactly it expects to use Entities and Components. Then there will be something to review and make progress on</p>\n</blockquote>\n\n<p>but let me explain why his suggestions arepure gold. ECS pattern is about decoupling all the game logic (yet seems most articles put focus on components, the point is deocupling the logic).</p>\n\n<ul>\n<li>If your design is right then your logic is decoupled.</li>\n<li>That means you can design \"random\" pieces of logic.</li>\n<li>Design functionalities of your game first (Player shooting to enemies, player jumping, opening a door)</li>\n<li>Each functionality becomes at least 1 System.</li>\n</ul>\n\n<p>Once you have pieces of logic, working on Components, then you finally just need one further step to link that logic togheter, and what you need is actually a ECS framework. </p>\n\n<ul>\n<li><p><strong>Therefore the correct way to do ECS, is by designing Systems first</strong>, </p></li>\n<li><p>In <a href=\"https://eagergames.wordpress.com/category/ecs/\" rel=\"nofollow noreferrer\">mine articles</a> (I tried to condense these in one answer but if you want to understand details <strong>I suggest reading the original articles too</strong>) I do exactly that, I start with a overview of the ECS framework I use, but I do not spent too much time on defining Entities and components, rather I start immediatly implementing pieces of game logic (Systems/Engines). Those works on <strong>EntityViews</strong>.</p></li>\n</ul>\n\n<p>The ECS paradigm emerges as a tool as long as you think your logic in a modular and decoupled way.</p>\n\n<p>I think you should seriously take a tour into <a href=\"https://github.com/sebas77/Svelto.ECS\" rel=\"nofollow noreferrer\">Svelto.ECS</a> (beware, its author renamed \"Systems\" into \"Engines\", I believe to avoid confusion with c#'s namespace \"System\" from .NET), written in C#. </p>\n\n<p>To do that <strong>you have to drive away from most of ECS articles you find on the web</strong>, I'm sad to say that, because I tried to use ECS \"the old way\" and it simply didn't worked well, it forced use of anti-patterns and made me wasting time.</p>\n\n<p>Most ECS frameworks, don't scale. You start easy and when the project becomes big you enter dependency hell, but you don't realize that because the dependency is hidden by components.</p>\n\n<p>With Svelto you just need to start, it seems hard (well it is a change of paradigm afterall), but after you get the first 10 engines done you realize how easy and flexible it is.</p>\n\n<blockquote>\n <p>I would appreciate any advice on decoupling the Systems and Components id's from their base classes. </p>\n</blockquote>\n\n<p>Simply use EntityViews like in Svelto. This concept was introduced with that framework. And I really love it.</p>\n\n<p>Most ECS frameworks have this dull concept that Components are coupled with engines and every engine should loop all components of a certain type. They should not! Both for flexibility and performance issues! (there are even technical articles from AAA industries that use tricks like skipping updating Systems every X frames because they were basically looping too much).</p>\n\n<p><strong>Everything in Svelto is decoupled.</strong></p>\n\n<p><strong>Most ECS frameworks have this concept:</strong></p>\n\n<ul>\n<li>If a entity has X,Y component, then it has to be processed by XY System, X system and Y System</li>\n</ul>\n\n<p><strong>Svelto actually do that:</strong></p>\n\n<ul>\n<li>Entity has X,Y component but to be processed by K Engine it actually need a KEntityView which maps X,Y components</li>\n</ul>\n\n<p>This is deeply different. Basically you can select which engines process which entities without having to resort to specialized components or without resorting to usage of Tags or groups. </p>\n\n<p>Basically when you spawn an entity, you have to select in advance which engines will see that entity. You can change that at any time by updating EntityViews in its descriptor, if there are missing components a nice error message will tell you that (I think you can implement that at compile time with C++, I done something similiar in past).</p>\n\n<p>Basically you may have X entities in your game that have a Position component, but you don't want to process your position the same, so in example static objects should not even have Systems updating them, so they could just have a method that returns the position without allowing to change it (that method does not implement any logic it just returns data).</p>\n\n<pre><code>class IPositionGet\n{\n public:\n virtual const Vector3 & GetPosition() const = 0;\n};\n\nclass IPositionSet\n{\n public:\n virtual void SetPosition( const Vector3 & pos) = 0;\n};\n</code></pre>\n\n<p>This allows you to implement entities in C++ directly (prefer always this, even though direct memory addressing of C++ allows you to do dirty things)</p>\n\n<pre><code>struct Bush: public IPositionGet\n{\n Vector3 BushPosition;\n\n public:\n\n Bush( const Vector3 & InitialBushPostion) { /*blah*/ }\n\n virtual const Vector3& GetPosition() const override\n {\n return BushPosition;\n }\n};\n</code></pre>\n\n<p>When you instantiate a bush you also specify which entity views it will implement, so basically this allows it to be processed by right engines. In example if you want bushes to be avoidable by avoidance algorithm</p>\n\n<pre><code>//no return value. Correct\nfactory->CreateEntity< ObstacleAvoidanceView>( entityId, new Bush( pos));\n</code></pre>\n\n<p>the ObstacleAvoidanceView could be something similiar to (assuming the avoidance is done using a circle or a sphere):</p>\n\n<pre><code>class ObstacleAvoidanceView: Descriptor< IPositionGet, IRadiusGet>\n{\n //...\n}\n</code></pre>\n\n<p>This gives an overview simplified of the design process. You continuosly refine things, because you can't predict everything. I Assumed objects have a position ok, but then after I defined the first piece of logic It was obvious that the bush was missing the radius for collision avoidance. It was not so hard to add it later. This kind of continuos changes are a real pain without an ECS system. And I added a Radius, without warrying if that could interefer with other engines, just because the engines are selected by the entity view, so there is not risk that adding the Radius to bushes automatically makes the bush processed by Radius-realted systems. Bushes are only processed by Systems interested in their EntityViews.</p>\n\n<p>If later I want bushes to be only slowing down player, I could altogheter remove the EntityView from the descriptor, and automatically I change bushes behaviour, without having to change engines, or without having to change the Bush.</p>\n\n<p>Honestly I think the final syntax in C++ will be quite different from C#, but I believe it is actually possible implement the same of Svelto in C++.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-05T08:40:12.993",
"Id": "193725",
"ParentId": "48536",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T02:43:56.617",
"Id": "48536",
"Score": "12",
"Tags": [
"c++",
"design-patterns",
"game",
"c++11",
"entity-component-system"
],
"Title": "An ECS model for game development"
} | 48536 |
<p>Problem:</p>
<blockquote>
<p>\$n!\$ means \$n × (n − 1) × ... × 3 × 2 × 1\$</p>
<p>For example, \$10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800\$, and the sum of the digits in the number \$10!\$ is \$3 + 6 + 2 + 8 + 8 + 0 + 0 = 27\$.</p>
<p>Find the sum of the digits in the number \$100!\$.</p>
</blockquote>
<p>My solution in Clojure:</p>
<pre><code>(reduce + (map (fn[x](Integer. (str x))) (seq (str (apply *' (range 1 101))))))
</code></pre>
<p>Questions:</p>
<ul>
<li>Is there a way to avoid the <code>*'</code> in the factorial bit? <code>(apply *' (range 1 101))</code></li>
<li>I converted the result of the factorial to a string, then to a sequence, and then mapped an Integer cast to a string cast. Surely there must be a way to simplify this? </li>
</ul>
| [] | [
{
"body": "<p>Your first question: you could make range return a list of bigints, and reduce over it</p>\n\n<pre><code>(reduce * (range (bigint 1) 101))\n</code></pre>\n\n<p>your second question: :</p>\n\n<ol>\n<li>you dont have to explicitly use <code>seq</code>, clojure will automatically treat your string as a seq</li>\n<li><p>you dont have to use the full-blown string to number converter, you could for example use <code>int</code> to get the char code: </p>\n\n<pre><code>(map #(- (int %) (int \\0)) \"1234\")`\n</code></pre></li>\n<li>for other ways of getting digits of a number, check out this <a href=\"https://groups.google.com/forum/#!topic/clojure/1dxrxgm8-z4\" rel=\"nofollow\">thread</a></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T06:43:46.537",
"Id": "48546",
"ParentId": "48537",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48546",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T03:46:09.237",
"Id": "48537",
"Score": "1",
"Tags": [
"clojure",
"programming-challenge"
],
"Title": "Project Euler #20 solution in Clojure"
} | 48537 |
<p>I have a class called <code>Piece</code>, and many many subclasses of <code>Piece</code>. I want to add an instance of every single subclass of <code>Piece</code> (under the <code>pieces</code> package) to my <code>JTree</code>. Currently, I have this class with a huge function (well, 57 lines, but still) that increases in size every time I add functionality to my program. </p>
<p>My initial approach to this was "Hey, let's just use reflection or something to find out all of the classes under the package <code>pieces</code> and add them to the tree!" but <a href="https://stackoverflow.com/questions/1087401/is-it-possible-to-get-all-the-subclasses-of-a-class">this</a> SO question shot that down. My second, working approach is to add them all manually by hand. This seems like too much work though and it seems like there would be a better way to do this.</p>
<p>As always, miscellaneous comments on my code are very welcome.</p>
<p><code>initTree()</code> </p>
<pre><code>private void initTree(final UserInterface userInterface) {
tree = new JTree(createTree());
tree.setRootVisible(false);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener(){
@Override
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null){
return;
}
if (node.isLeaf() && node.getUserObject() instanceof Piece) {
Piece pieceCreated = (Piece) ((Piece)node.getUserObject()).getInstance();
userInterface.space.addPiece(pieceCreated);
}
}
});
add( new JScrollPane(tree), BorderLayout.CENTER );
}
</code></pre>
<p><code>createTree()</code></p>
<pre><code>private DefaultMutableTreeNode createTree(){
//create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
//create the child nodes
DefaultMutableTreeNode gatesNode = new DefaultMutableTreeNode("Gates");
DefaultMutableTreeNode arithmeticNode = new DefaultMutableTreeNode("Arithmetic");
arithmeticNode.add(new DefaultMutableTreeNode(new Add(0,0)));
arithmeticNode.add(new DefaultMutableTreeNode(new Subtract(0,0)));
arithmeticNode.add(new DefaultMutableTreeNode(new Multiply(0,0)));
arithmeticNode.add(new DefaultMutableTreeNode(new Divide(0,0)));
arithmeticNode.add(new DefaultMutableTreeNode(new Modulo(0,0)));
arithmeticNode.add(new DefaultMutableTreeNode(new Random(0,0)));
gatesNode.add(arithmeticNode);
DefaultMutableTreeNode bitwiseNode = new DefaultMutableTreeNode("Bitwise");
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseAnd(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseNand(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseNor(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseNot(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseOr(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseXor(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseXnor(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseLeftshift(0,0)));
bitwiseNode.add(new DefaultMutableTreeNode(new BitwiseRightshift(0,0)));
gatesNode.add(bitwiseNode);
//etc with more subclasses of Piece
return root;
}
</code></pre>
<p><strong>Piece.java</strong></p>
<pre><code>public abstract class Piece implements Serializable{
private static final long serialVersionUID = 2022414861350098747L;
private static final Color BACKGROUND_COLOR = new Color(200,200,200);
static final BasicStroke PORT_STROKE = new BasicStroke(1);
protected int x, y, width, height;
protected Input input;
protected Output output;
public Piece(int x, int y, int width, int height, int inputs, int outputs){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.input = new Input(inputs, this);
this.output = new Output(outputs, this);
}
public abstract void draw(Graphics2D g);
public void drawBackground(Graphics2D g){
g.setColor(BACKGROUND_COLOR);
g.fillRoundRect(x, y, width, height,10,10);
input.draw(g);
output.draw(g);
}
public void drawConnections(Graphics2D g){
output.drawConnections(g);
}
public void connect(Piece other, int outputPort, int inputPort){
output.connect(other, outputPort, inputPort);
update();
}
public void disconnect(final int outputPort){
output.disconnect(outputPort);
update();
}
public void update(){
output.update();
}
public abstract Value send(int outputPort);
public abstract void recieve(int inputPort, Value v);
public abstract void doubleClicked();
public abstract Piece getInstance();
public String toString(){
return this.getClass().getSimpleName();
}
public void setPosition(final Point point) {
x = point.x;
y = point.y;
}
public boolean contains(final Point p){
return x < p.getX() &&
y < p.getY() &&
x + width > p.getX() &&
y + height > p.getY();
}
public Integer getOutputPortFromPoint(final Point p){
if(output.contains(p)){
if(output.getConnections().length == 0)
return null;
return output.getOuputFromY(p.y);
}
return null;
}
public Integer getInputPortFromPoint(final Point p){
if(input.contains(p)){
if(input.getConnections().length == 0){
return null;
}
return input.getInputFromY(p.y);
}
return null;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public Point getPointFromOutputPort(int portSelected) {
return output.getPointFromPort(portSelected);
}
}
</code></pre>
<p><strong>Add.java</strong> (Example subclass of <code>Piece</code>)</p>
<pre><code>public class Add extends Piece{
private static final long serialVersionUID = -1786155220275379870L;
//v1 + v2 = v
private ValueInteger param1;
private ValueInteger param2;
private ValueInteger result;
private Title title;
public Add(int x, int y) {
super(x,y,150,75, 2, 1);
title = new Title("Add", this);
param1 = new ValueInteger(0);
result = new ValueInteger(0);
param2 = new ValueInteger(0);
}
@Override
public void draw(Graphics2D g) {
drawBackground(g);
title.draw(g);
g.setColor(Color.BLUE);
if(result != null)
g.drawString(result.toString(), x + 10, y + 20);
}
@Override
public Value send(int outputPort) {
return result;
}
@Override
public void recieve(int inputPort, Value v) {
if(inputPort == 0)
param1 = (ValueInteger) v;
else if (inputPort == 1)
param2 = (ValueInteger) v;
this.result = new ValueInteger(param1.add(param2));
}
@Override
public void doubleClicked() {
// TODO Auto-generated method stub
}
@Override
public Piece getInstance() {
return new Add(10,10);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:20:30.663",
"Id": "85348",
"Score": "0",
"body": "What exactly _is_ a `Piece`? Perhaps you mean `LogicComponent`? The fact that you have so many subclasses is a sign that maybe inheritance is not the best approach. There might be a violation of the Single Responsibility Principle. Or, maybe your application needs to be more data-driven than code-driven."
}
] | [
{
"body": "<p>My solution to keeping track of <code>Piece</code> instances would be a enum <code>PieceRepository</code>.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\n\n\npublic enum PieceRepository {\n\n INSATNCE;\n\n private List<Piece> pieces;\n\n private PieceRepository() {\n pieces = new ArrayList<Piece>();\n }\n\n public void addPiece(Piece piece) {\n pieces.add(piece);\n }\n\n public List<Piece> getPieces() {\n return pieces;\n }\n\n}\n</code></pre>\n\n<p><code>Piece</code> sample code:</p>\n\n<pre><code>public class Piece {\n\n public Piece() {\n PieceRepository.INSTANCE.addPiece(this);\n }\n\n}\n</code></pre>\n\n<p>Some other class that extends <code>Piece</code>:</p>\n\n<pre><code>public class HalfPiece extends Piece {\n\n public HalfPiece() {\n\n }\n\n}\n</code></pre>\n\n<p>And test:</p>\n\n<pre><code>public class TestMain {\n\n public static void main(String[] args) {\n\n new Piece();\n new Piece();\n new Piece();\n new HalfPiece();\n\n System.out.println(PieceRepository.INSTANCE.getPieces().size());\n\n }\n\n}\n</code></pre>\n\n<p>Output is:</p>\n\n<pre><code>4\n</code></pre>\n\n<p>Edit:\nUsed <a href=\"https://stackoverflow.com/questions/3635396/pattern-for-lazy-thread-safe-singleton-instantiation-in-java\">https://stackoverflow.com/questions/3635396/pattern-for-lazy-thread-safe-singleton-instantiation-in-java</a>\nTo make repository thread safe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T12:21:06.093",
"Id": "85293",
"Score": "0",
"body": "The repository is not a thread-safe singleton, and Piece() publishes a reference before it leaves the constructor, which may leave it in an inconsistent state for other threads. This may become an issue since the OP is using Swing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:23:34.140",
"Id": "85295",
"Score": "0",
"body": "Updated my answer regards your first note, though at the moment can't think of fix for second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:57:25.753",
"Id": "85321",
"Score": "0",
"body": "Preventing the self-publishing would need to route creation through a factory method that first constructs and then registers the instance. So instead of `new Piece()` it will be `Piece.create()` or so. It's a slight hassle, but tracking down concurrency bugs is a bit more of a hassle. ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:29:07.113",
"Id": "48551",
"ParentId": "48541",
"Score": "2"
}
},
{
"body": "<p>You will need to maintain a list of what things are in your pieces package manually.</p>\n\n<p>Best way is to do what you do, that is add them one by one to some sort of container.</p>\n\n<p>However selecting them is a separate task from adding them to your tree </p>\n\n<pre><code>static List<Piece> piecesIWant() {\n List<Piece> pieces = new ArrayList<Piece>();\n pieces.add(new Add(0,0));\n pieces.add(new Subtract(0,0));\n return pieces;\n}\n\nvoid createTree(Collection<Piece> wantedPieces) {\n DefaultMutableTreeNode arithmeticNode = new DefaultMutableTreeNode(\"Arithmetic\");\n for (Piece p : wantedPieces) {\n arithmeticNode.add(new DefaultMutableTreeNode(p));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T09:46:39.217",
"Id": "48556",
"ParentId": "48541",
"Score": "2"
}
},
{
"body": "<pre><code>public enum PieceGroups{\n\n BITWISE(BitwiseAnd.class, BitwiseNand.class, BitwiseNor.class, BitwiseNot.class,\n BitwiseOr.class, BitwiseXor.class, BitwiseXnor.class, BitwiseLeftshift.class,\n BitwiseRightshift.class),\n ARITHMETIC(Add.class, Substract.class, Multiply.class, Divide.class, Modulo.class, Random.class);\n\n private Set<Piece> classSet = new HashSet<Piece>();\n\n private PieceGroups(Class... classes) {\n for (Class theClass : classes) {\n try {\n Constructor construtor = theClass.getDeclaredConstructor(int.class, int.class);\n classSet.add((Piece) construtor.newInstance(0, 0));\n } catch (NoSuchMethodException ex) {\n processException();\n } catch (SecurityException ex) {\n processException();\n } catch (InstantiationException ex) {\n processException();\n } catch (IllegalAccessException ex) {\n processException();\n } catch (IllegalArgumentException ex) {\n processException();\n } catch (InvocationTargetException ex) {\n processException();\n }\n }\n }\n\n public Set<Piece> getClasses () {\n return classSet;\n }\n\n private void processException () {\n throw new IllegalArgumentException(\"Something went wrong with the init of the Enum\");\n }\n}\n</code></pre>\n\n<h2>Explication :</h2>\n\n<p>We create an enum, still the best singleton what there is.<br/>\nThen the states of the enum are grouping where the <code>Piece</code> (sub)class can have, like the Bitwise and Arithmetic you showed.</p>\n\n<p>Constructor of the enum is vararg, so you can give up as many classes as you want with one group.</p>\n\n<p>We create an instance of the class in the constructor with reflection.\nAt the moment I saw that all your classes have an constructor with 2 ints, so I rely that is for all the implementations of like that.</p>\n\n<p>An IllegalArgumentException is thrown when your enum can't be created by an fault (class not found, constructor not present,...)<br/>\nYou can also just skip that class at instanciation but then you never know when something went wrong.</p>\n\n<p>At last, just ask <code>PieceGroups.BITWISE.getClasses()</code> and you will have a set of the corresponding group.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:15:27.343",
"Id": "85357",
"Score": "0",
"body": "Thank you, while I still have to hardcode all of the classes in, it's a very clean solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:28:19.927",
"Id": "85358",
"Score": "1",
"body": "In Java 7, you can [handle multiple kinds of exceptions in one `catch` block](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T05:42:49.660",
"Id": "85390",
"Score": "0",
"body": "@200_success you are very correct. When I was creating that class I was thinking of that, but IDE is configured java 6, so for not making faults I go with java 6."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-06T11:30:35.953",
"Id": "86151",
"Score": "0",
"body": "Instead of supplying the class and then using reflection, consider adding an instance directly: `BITWISE(new BitwiseAnd(0,0), new BitwiseNand(0,0), ...)`. The class isn't used but for instantiating through reflection anyway, and that saves us having to guess the constructors."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:36:42.473",
"Id": "48560",
"ParentId": "48541",
"Score": "5"
}
},
{
"body": "<p>I have attempted something similar to this, that (mostly) got rid of the hardcoded registration problem, which was based on using <code>static</code> initialization blocks and class loaders.</p>\n\n<p>In my case, each class was responsible for generating a binary encoding for some data, in varying formats.</p>\n\n<p>First of all, I had a class that would accept the encoder definition</p>\n\n<pre><code>class Encoders {\n public void addEncoding(String identifier, Constructor<Encoder> ctor){\n // ...\n }\n}\n</code></pre>\n\n<p>Each encoder class looked something like this:</p>\n\n<pre><code>class MyEncoder {\n static {\n Encoders.addEncoding(\"MyEncoding\", MyEncoder.class.getDeclaredConstructor());\n }\n\n public MyEncoder(){\n // ...\n }\n}\n</code></pre>\n\n<p>Then to load them all, I iterated through the classes specified in an external config file containing a list of the binary class names for each encoder. One could do something even fancier by processing these configs in different files.</p>\n\n<pre><code>public void loadEncoders(Logger log){\n try(BufferedReader reader = new BufferedReader(new FileReader(\"encoders.txt\"))){\n loadClasses(reader, log);\n } catch (FileNotFoundException e) {\n log.log(Level.WARNING, \"Could not find encoders list!\", e);\n } catch (IOException e){\n log.log(Level.WARNING, \"Could not read encoders list!\", e);\n }\n}\n\npublic boolean loadClasses(BufferedReader reader, Logger log){\n ClassLoader loader = ClassLoader.getSystemClassLoader();\n boolean success = true;\n while(true){\n String name = reader.readLine();\n if(name == null) break;\n\n try {\n loader.loadClass(name);\n } catch (ClassNotFoundException e){\n log.log(Level.WARNING, \"Unable to find \" + name, e);\n success = false;\n }\n return success;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:52:08.373",
"Id": "48582",
"ParentId": "48541",
"Score": "1"
}
},
{
"body": "<p>Depending on your needs, there are ways around this but, sadly, none of them will work <em>automagically</em>, and they may require some effort. Only you can decide what's warranted and what's overkill.</p>\n<p>From what I can see, you're building a GUI for chips or circuits. I imagine you want to provide a component that lists gates for your users, much like the component buttons in WindowBuilder or Matisse. Let's see how these solve the problem.</p>\n<h1>Asking for directions</h1>\n<p>WindowBuilder comes with the standard Swing and AWT components out of the box. Since these will be in pretty much any Java distribution, they can just add the components manually once. It's a bit tedious to do, but you only need to do it once (and maintain forever).</p>\n<p>What about components that aren't standard, like when your users make stuff of their own? Well, there are three main ways that jump out:</p>\n<ol>\n<li><p><strong>Ask your platform for an index.</strong> For WindowBuilder, this is Eclipse, which has information on loaded and available classes. For stand-alone Java applications like GUIs, this will involve scanning your class path.</p>\n<p>Also available for your needs is <code>java.util.ServiceLoader</code>. If you or your users can be bothered to make an index file in provided JARs, ServiceLoader will do some lifting for you.</p>\n</li>\n<li><p><strong>Ask your user for a JAR and scan it.</strong> Open it up, check each class whether it extends <code>Piece</code>, and add/flag it if it does. This covers archives that aren't on the class path.</p>\n</li>\n<li><p><strong>Ask your user for a class name</strong> and let the ClassLoader fetch it. This covers classes that are not in a JAR or on the class path.</p>\n</li>\n</ol>\n<p>Once you have potentially valid types, it's time to figure out how to instantiate and present them.</p>\n<h1>Reflecting on what you found</h1>\n<p>So suppose you have a list of classes that extend <code>Piece</code> and we may or may not be able to accommodate. Unfortunately, <code>Piece.getInstance()</code> won't help us here: to be overridable, it needs to be an instance method; to use an instance method, we need an instance. Egg, meet Chicken.</p>\n<p>Much like we'd do with JavaBeans, we can gleam some information from your classes using reflection and convention:</p>\n<ol>\n<li><p><strong>Find a public static method</strong> matching a specific signature, e.g. a factory method. <code>create()</code>, <code>createInstance()</code>, and so on, are good candidates. Document what you accept, and in what order you search.</p>\n</li>\n<li><p><strong>Find all public constructors</strong>, and try to invoke them with 'default' values. What constitutes default values depends a bit on context. We may need to ask our users to provide values for us. Again, document what is supported, and how you will try instantiating.</p>\n</li>\n</ol>\n<p>After we've done all this, we pretty much have what we need to allow our users to build whatever they want. But GUI builders usually don't forget coordinates to custom components after reloading, so how do we save our users the trouble not to have to input them over and over again?</p>\n<h1>Maintain a registry (optional)</h1>\n<p>We should save two things about found implementations: (1) their class name, so we can find them, and (2) how to instantiate them. How you want to save this is up to preference; I'd lean towards an XML file because that allows enterprising users to tweak, change, or add others if we somehow fail to find them.</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="utf-8"?>\n<pieces version="1">\n <piece>\n <className>com.acme.pieces.Add</className>\n <factory-method name="create">\n </factory-method>\n </piece>\n <piece>\n <className>com.acme.pieces.Explode</className>\n <constructor>\n <arg type="int">10</arg>\n <arg type="int">10</arg>\n </constructor>\n </piece>\n</pieces>\n</code></pre>\n<p>That's really all we need to store. (Do version your data format, even if you plan on only ever supporting one.)</p>\n<h1>Worth it?</h1>\n<p>If we're going to be user-friendly and fail-safe and all these beautiful things, this is a lot of effort, <em>and possibly even overkill</em>. This feels like a basic enough issue that there must be some projects with some support for it (I'm looking sideways at Spring and Apache, here).</p>\n<p>If you're just going for a fixed list of things that you want available, manually maintaining a list in code is pretty much your simplest, if sometimes tedious, solution. It's not shiny or pretty but it's quick and it may meet your needs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:43:35.237",
"Id": "48585",
"ParentId": "48541",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48560",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T04:45:54.050",
"Id": "48541",
"Score": "6",
"Tags": [
"java",
"tree",
"inheritance",
"reflection"
],
"Title": "Initializing JTree"
} | 48541 |
<p>From the <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer">Beautiful Soup documentation</a>:</p>
<blockquote>
<p>Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree.</p>
</blockquote>
<p><a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer">Beautiful Soup 4</a> (commonly known as <code>bs4</code>, after the name of its Python module) is the latest version of Beautiful Soup, and is <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#porting-code-to-bs4" rel="nofollow noreferrer">mostly backwards-compatible</a> with Beautiful Soup 3.</p>
<blockquote>
<p><strong>Notice:</strong> Beautiful Soup 3 works only on Python 2 while Beautiful Soup 4 works on both Python 2 (2.6+) and Python 3</p>
</blockquote>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:55:49.803",
"Id": "48547",
"Score": "0",
"Tags": null,
"Title": null
} | 48547 |
Beautiful Soup is a Python library for pulling data out of HTML and XML files. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T07:55:49.803",
"Id": "48548",
"Score": "0",
"Tags": null,
"Title": null
} | 48548 |
<p>I recently began learning Clojure. In order to get better acquainted with it, I've been tackling Project Euler challenges.</p>
<p>Problem 14 is not really a difficult one. It asks for the number that results in the longest Collatz sequence.</p>
<blockquote>
<p>The following iterative sequence is defined for the set of positive
integers:</p>
<p>n → n/2 (n is even) n → 3n + 1 (n is odd)</p>
<p>Using the rule above and starting with 13, we generate the following
sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1</p>
<p>It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz
Problem), it is thought that all starting numbers finish at 1.</p>
<p>Which starting number, under one million, produces the longest chain?</p>
<p>NOTE: Once the chain starts the terms are allowed to go above one
million.</p>
</blockquote>
<p>Although my solution does solve the problem, I am not sure if it conforms to the Clojure way of doing things, since it seems to be verbose.</p>
<ul>
<li>Does this conform to functional practices?</li>
<li>Are there any mistakes which result in code being longer than needed?</li>
<li>Is there a way of omitting the loop/recur and doing the same with list functions such as <code>map</code> and <code>apply</code></li>
<li>Any other suggestions in general?</li>
</ul>
<pre class="lang-lisp prettyprint-override"><code>(ns problem14)
(use '[clojure.test :only (is)])
(defn count-collatz
"Returns a vector [a b] where b is the
number that initiated the sequence, and
a is the number of steps taken to reach 1."
[input-num]
(loop [num input-num count 1]
(if (= num 1)
(vector count input-num)
(do (if (= (mod num 2) 0)
(recur (/ num 2) (inc count))
(recur (+ (* num 3) 1) (inc count)))))))
;; Test case from the project description.
(is (= (count-collatz 13) [10 13]))
(loop [number 1 peak [0 0]]
(if (>= number 1e6)
(str "Longest chain is " (last peak))
(do (let [result (count-collatz number)]
(do (if (> (first result) (first peak))
(recur (inc number) result)
(recur (inc number) peak)))))))
</code></pre>
| [] | [
{
"body": "<p><strong>CAVEAT I am not a clojure programmer.</strong> (But hopefully you will agree with what I suggest ;))</p>\n\n<p>Put all your code in functions such that all top level forms are <code>def</code>s. Similarly put your tests in <code>deftest</code> forms and run them with <a href=\"http://clojuredocs.org/clojure_core/clojure.test/run-tests\" rel=\"nofollow\"><code>run-tests</code></a>. </p>\n\n<p>In clojure, too, extract meaningful expressions to their own functions and give them names.\nThen promote baked in magic constants in them to parameters so that they are more testable, in REPL and elswhere.</p>\n\n<p>You can use destructuring <code>let</code> to give meaningful names to a function returning a vector.</p>\n\n<p>Applying these general rules</p>\n\n<pre><code>(defn longest-chain [limit]\n (loop [number 1 peak-len 0 peak-val 0]\n (if (>= number limit)\n peak-val\n (do (let [[curr-len curr-val] (count-collatz number)]\n (do (if (> curr-len peak-len)\n (recur (inc number) curr-len curr-val)\n (recur (inc number) peak-len peak-val))))))))))\n\n(defn -main []\n (println \"Longest chain is\" (longest-chain 1e6)))\n</code></pre>\n\n<p>Here is how you can rewrite these functions using core library.</p>\n\n<ul>\n<li><code>(= x 0)</code> is <code>(zero? x)</code></li>\n<li><code>(zero? (mod num 2))</code> is <code>(even? x)</code></li>\n<li>repeatedly applying a function without explicit <code>loop</code>/<code>recur</code> is <code>iterate</code>.</li>\n<li>You can use <a href=\"http://clojuredocs.org/clojure_core/clojure.core/for\" rel=\"nofollow\"><code>for</code> comprehension</a> of a <code>range</code> instead of <code>loop</code>/<code>recur</code> with <code>inc</code>ing a parameter.</li>\n<li>You can also use core library functions that operate on sequences (<code>map</code>, <code>reduce</code> et al) for a more functional style.</li>\n<li>You can use <a href=\"http://clojuredocs.org/clojure_core/clojure.core/-%3E\" rel=\"nofollow\">threading</a> <a href=\"http://clojuredocs.org/clojure_core/clojure.core/-%3E%3E\" rel=\"nofollow\">macros</a> to reduce nesting levels as necessary; and to make your functions read top-down instead of more counter-intuitive inside-out.</li>\n<li>You can use <code>(apply max-key k coll)</code> to get \"the [value] for which (k x), a number, is greatest.\"</li>\n</ul>\n\n<p>Code after above changes:</p>\n\n<pre><code>(defn count-collatz [n]\n (let [f (fn [n] (if (even? n) (/ n 2) (+ (* n 3) 1)))]\n (->> n\n (iterate f)\n (take-while #(> % 1))\n count\n inc)))\n\n(defn longest-chain [limit]\n (->> limit\n (range 1)\n (map #(vector (count-collatz %) %))\n (apply max-key first)\n second)\n</code></pre>\n\n<p>Or using the fact that <code>max-key</code> can get arbitrary function as its first parameter, we get:</p>\n\n<pre><code>(defn longest-chain [limit]\n (apply max-key count-collatz (range 1 limit)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T15:54:23.037",
"Id": "86374",
"Score": "0",
"body": "For a self-professed \"non-Clojure programmer,\" you sure do know your way around writing idiomatic Clojure code! +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:55:36.233",
"Id": "48583",
"ParentId": "48549",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48583",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:05:04.317",
"Id": "48549",
"Score": "4",
"Tags": [
"clojure",
"programming-challenge"
],
"Title": "Project Euler Problem 14 in Clojure"
} | 48549 |
<p>I need to split a list into equal sublists, e. g <code>[1..9]</code> split into groups of 3 will be <code>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]</code>. I have accomplished this task in the following way:</p>
<pre><code>splitInGroupsOf n = takeWhile ((n ==) . length)
. map fst
. drop 1
. iterate (\(res, list) -> splitAt n list)
. (,) []
</code></pre>
<p>where iterate creates list of tuples with first <code>n</code> elements and rest of list. This way I had to use <code>(,) []</code> on argument to ensure correct type, and unwrap result afterwards. My questions are</p>
<ol>
<li>is there a better/more elegant way of performing same task?</li>
<li>is there some standard function I should make use of?</li>
</ol>
<p>P.S.: I'm not sure where to ask simple Haskell-related questions and will appreciate if someone points me a better place for this than SE.</p>
| [] | [
{
"body": "<p>There are <a href=\"http://hackage.haskell.org/package/split-0.2.2/docs/Data-List-Split.html#v%3achunksOf\"><code>Data.List.Split.chunksOf</code></a> and <a href=\"http://hackage.haskell.org/package/list-grouping-0.1.1/docs/Data-List-Grouping.html#v%3asplitEvery\"><code>Data.List.Grouping.splitEvery</code></a> implementations of this routine in specialized packages (and a number included in other application packages: search by <code>Int -> [a] -> [[a]]</code> signature on <a href=\"http://holumbus.fh-wedel.de/hayoo/hayoo.html\">Hayoo</a>). </p>\n\n<p>I think <code>splitEvery</code> implementation is pretty elegant:</p>\n\n<pre><code>splitEvery :: Int -> [a] -> [[a]]\nsplitEvery _ [] = []\nsplitEvery n xs = as : splitEvery n bs \n where (as,bs) = splitAt n xs\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:13:24.640",
"Id": "85332",
"Score": "0",
"body": "strangely enough, Hoogle is unable to find these functions. I've got a second question: when I search Hayoo for `Int -> [a] -> [[a]]` then `chunksOf` is not at top, but when I search `Int -> [e] -> [[e]]`, then `chunksOf` is first. How am I supposed to guess what letter to use as a type variable?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T12:02:45.573",
"Id": "48564",
"ParentId": "48552",
"Score": "11"
}
},
{
"body": "<p>The ready made function <code>chunksOf</code> works very well. When tasked to create 3 elements in sublists with 11 elements in the source list, two elements will be in the last sublist of the result. The following function also includes trailers.</p>\n\n<pre><code>mklsts n = takeWhile (not.null) . map (take n) . iterate (drop n)\n</code></pre>\n\n<p>I use this as <code>pairs</code> with a 2 for <code>n</code> and no <code>n</code> parameter. Pairs rock.</p>\n\n<p><strong>Edit/Add 4/12/2018</strong></p>\n\n<p>The match up of <code>iterate</code> and <code>splitOn</code> is one made in hell. In the questioner above, placing <code>splitOn</code> in a <code>lambda</code> may have compounded the problems. It is possible to make <code>splitOn</code> work with <code>iterate</code> but you have to ditch the <code>fst</code> of the tuple produced. That defeats the entire purpose. It is way cleaner and easier to use <code>drop n</code> with <code>iterate</code>. The results are the same. That's what the preceding function does. Otherwise, it's the same idea.</p>\n\n<p>Here is a novel way of producing the identical results using <code>tails</code> imported from <code>Data.List</code> in a list comprehension. It picks up stragglers, too.</p>\n\n<pre><code>ts n ls = [take n l|l<-init$tails ls,odd (head l)]\n</code></pre>\n\n<p>The parameters are <strong>size-of-sublist</strong> and <strong>list</strong></p>\n\n<p><strong>Edit 4/17/2018</strong></p>\n\n<p>Well, since I had some time at work a list comprehension version that does not use <code>tails</code>, a recursive version and a <code>map</code> version.</p>\n\n<pre><code>ttx s ls=[take s.drop x$ls|x<-[0,s..s*1000]]\n</code></pre>\n\n<p>Recursive</p>\n\n<pre><code>tkn n []=[];tkn n xs=[take n xs]++(tkn n $ drop n xs)\n</code></pre>\n\n<p>Map</p>\n\n<pre><code>tp n ls=takeWhile(not.null)$ map(take n.flip drop ls) [0,n..]\n</code></pre>\n\n<p>The list comprehension is virtually infinite. Change <code>[0,s..s*200]</code> to <code>[0,s..]</code> for true infinity. The recursive is, of course, inherently infinite and the map function uses a big <code>takeWhile (not.null)</code> to end itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-12T07:03:18.130",
"Id": "368315",
"Score": "0",
"body": "\"The ready made function `chunksOf`\"? Which `chunksOf` do you speak of? Where do you address the code of the original poster? Did you intend to comment leventov's answer instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-12T07:59:52.530",
"Id": "368334",
"Score": "0",
"body": "The questions are two. `1 is there a better/more elegant way of performing same task? 2. Is there some standard function I should make use of? It is implied, the code of the original works fine. What I suggest as an alternative is shorter and clear. More elegant? It is relative I thinks so. Am I wrong? i tried so hard to use `splitAt` but this resulted instead out of frustration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-12T08:14:13.897",
"Id": "368338",
"Score": "1",
"body": "Sure, but on *Code Review*, we *review* code. We [do not only provide an alternative solution without an explanation _why_ its better](https://codereview.meta.stackexchange.com/questions/8403/why-are-alternative-solutions-not-welcome?cb=1). I can apply the same critcism on leventov's answer, by the way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-12T16:10:19.727",
"Id": "368425",
"Score": "1",
"body": "Thank you so much for the clarification. Criticisms leveled at me are usually the opposite. I can be tedious. My interest in this function is not incidental nor frivolous. The value is information contained in the sublists exceed that of the source list so they can streamline code and lessen logic. There are few things I value more than criticism. Thank you so very much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-11T22:11:45.143",
"Id": "191827",
"ParentId": "48552",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T08:39:21.077",
"Id": "48552",
"Score": "8",
"Tags": [
"haskell"
],
"Title": "Split list into groups of n in Haskell"
} | 48552 |
<p>"Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.</p>
<p>For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.</p>
<p>What is the total of all the name scores in the file?"</p>
<p>I'm relatively new to clojure, and this is what I came up with:</p>
<pre><code>(def names (sort (map (fn[x] (replace x #"\"" "")) (split (slurp "/users/calvinfroedge/Downloads/names.txt") #","))))
(loop [i 0 total 0]
(if (not= i (count names))
(recur (inc i) (+ total (* (inc i) (reduce + (map (fn[x] (- (int x) 64)) (nth names i))))))
total)
</code></pre>
<p>I read somewhere that doseq is preferred to loop/recur, but it wasn't apparent to me how to comprehensibly AND idiomatically approach this problem without using an explicit loop with an incrementing value.</p>
<p>Am I missing something?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-01T09:21:13.343",
"Id": "91369",
"Score": "0",
"body": "`doseq` is *not* preferable to `loop` ... `recur`. It requires mutated state to do anything, as it returns `nil`. Where both apply, use the latter. Was what you read, perhaps, that lazy sequences and the sequence library were preferable to `loop` ... `recur`?"
}
] | [
{
"body": "<p>Yes. I think you still miss a very useful part of clojure - using its various collection types to model your solution. In your problem, you could use the fact that a string is a seq and a map acts as a function to calculate the cost of a word:</p>\n\n<pre><code>;; this map will act as a function from a name to its ordinal\n(def name->position (zipmap names (map inc (range))))\n\n;; and this map will act as a function from letter to its ordinal\n(def ab-map (zipmap alphabet (map inc (range))))\n</code></pre>\n\n<p>Now that we have these two functions, we could easily calculate a name's value in this way:</p>\n\n<pre><code>(defn score [word]\n (* (reduce + (map ab-map word))\n (name->position word 0)))\n</code></pre>\n\n<p>You can now calculate COLIN:\n<code>(score \"COLIN\")</code></p>\n\n<p>Explicit recursion can many times be avoided by using functions like map and reduce, mainly because often the sequences themselves are defined in <a href=\"http://en.wikipedia.org/wiki/Algebraic_data_type\">terms of recursion</a> </p>\n\n<p>From here, you could solve this question by using <code>map</code> and <code>reduce</code> with the new function <code>score</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:34:27.180",
"Id": "85280",
"Score": "0",
"body": "Thanks for your answer. I updated my question as I had made some improvements already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:35:25.237",
"Id": "85281",
"Score": "1",
"body": "zipmap is really cool!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T23:21:17.157",
"Id": "48554",
"ParentId": "48553",
"Score": "7"
}
},
{
"body": "<p>I would consider using <a href=\"http://clojuredocs.org/clojure_core/clojure.core/map-indexed\" rel=\"nofollow\">map-indexed</a> as a way to use the name's \"position\" (i.e. index) as part of the scoring function. </p>\n\n<p>As @Shlomi mentioned, you can often avoid using recursion/loops by taking a more functional approach and use something like <code>map</code> or <code>reduce</code> to transform your collection of data into your desired result. I would approach a problem like this by defining your data set, writing a series of helper functions, and then bringing it all together at the end:</p>\n\n<pre><code>(require '[clojure.string :as s :only (replace split)])\n\n(def sorted-names\n (-> \n (slurp \"/users/calvinfroedge/Downloads/names.txt\")\n (s/replace #\"\\\"\" \"\")\n (s/split #\",\")\n sort))\n\n(def letter->value\n (zipmap \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" (map inc (range))))\n\n(def scored-names\n (map-indexed (fn [i name] \n (* (inc i) (reduce + (map letter->value name))))\n sorted-names))\n\n(def total-score\n (reduce + scored-names))\n</code></pre>\n\n<p>I really like the idea of using <code>zipmap</code> to easily create a function that gives you the value of a letter, so I've stolen it. :)</p>\n\n<p>This is nitpicky, but I've also simplified your \"name collection\" algorithm by moving the <code>(replace #\"\\\"\" \"\")</code> step before the <code>(split #\",\")</code> step (since you're starting with one big string, you can just get rid of all of the <code>\"</code>s all at once, rather than doing it individually for each name after you split them up), and then putting the whole thing into a threading macro (<code>-></code>) for better readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T15:52:28.430",
"Id": "48994",
"ParentId": "48553",
"Score": "3"
}
},
{
"body": "<p>We can succinctly build the required expression from the bottom. </p>\n\n<pre><code>(let [dec-int-A (->> \\A int dec)\n letter-score #(- (int %) dec-int-A)\n word-score #(->> % (map letter-score) (apply +))\n dict-score #(->> % sort (map word-score) (map * (iterate inc 1)) (apply +))]\n (dict-score (read-string (str \\[ (slurp \"names.txt\") \\]))))\n</code></pre>\n\n<p>There are some novelties: </p>\n\n<ul>\n<li>using <a href=\"http://clojuredocs.org/clojure_core/clojure.core/-%3E%3E\" rel=\"nofollow\"><code>->></code></a> to flatten expressions; </li>\n<li>using <code>(iterate inc 1)</code> to tag the word scores with the correct positions; </li>\n<li>using <a href=\"http://clojuredocs.org/clojure_core/clojure.core/read-string\" rel=\"nofollow\"><code>read-string</code></a> directly on the square-bracketed text (the <a href=\"https://github.com/edn-format/edn\" rel=\"nofollow\">edn\nversion</a> would be safer).</li>\n</ul>\n\n<p>The effect is, I hope, to make the solution clear and easy to read. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-04T18:04:01.317",
"Id": "91928",
"Score": "0",
"body": "Beautifully concise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-03T12:21:48.147",
"Id": "52347",
"ParentId": "48553",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T21:54:57.430",
"Id": "48553",
"Score": "3",
"Tags": [
"clojure",
"programming-challenge"
],
"Title": "More succinct / ideal solution to Project Euler #22"
} | 48553 |
<p>I'm back with a Python solution for <a href="http://projecteuler.net/problem=35" rel="nofollow">Project Euler 35</a>. Any help would be appreciated; I generate the numbers by observing that all circular primes can only have digits 1, 3, 7, and 9. Then I use the Cartesian product built into itertools. I also have a <a href="http://en.wikipedia.org/wiki/Primality_test#Python_implementation" rel="nofollow">local primes test</a> from Wikipedia.</p>
<pre><code>from primes import test as is_prime
from itertools import product # cartesian product
from timeit import default_timer as timer
def find_circular_primes_under(limit):
def is_circular(digits):
digits = list(digits)
for digit in digits:
if not is_prime(int(''.join(map(str, digits)))):
return False
else:
digits.append(digits.pop(0))
return True
if type(limit) != int or limit <= 2:
return "Error: primes are positive integers greater than 1."
elif limit <= 11:
sum = 0
for k in range(limit):
if is_prime(k):
sum += 1
return sum
else:
sum = 4
for k in range(2, len(str(limit))):
for combo in product([1, 3, 7, 9], repeat = k):
if is_circular(combo):
sum += 1
return sum
start = timer()
ans = find_circular_primes_under(10**6)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [] | [
{
"body": "<ul>\n<li>Returning an error message instead of data is not a good approach to handling errors. Try and see what happens if you tweak your code to pass an invalid argument to <code>find_circular_primes_under</code>. Do you see your error message? No, the program raises an exception trying to format the return value as a number. It would be better to raise an appropriate exception instead of returning from the function.</li>\n<li>Modifying a container while iterating over it causes undefined behavior. In <code>is_circular</code> you could use <code>for _ in xrange(len(digits)):</code> instead of <code>for digit in digits:</code> to be safe. The <code>digit</code> variable is not used anyway.</li>\n<li>You could take advantage of <a href=\"https://docs.python.org/2/library/collections.html#deque-objects\" rel=\"nofollow\"><code>collections.deque</code></a> and its <code>rotate</code> method to produce the rotations.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:34:47.420",
"Id": "48584",
"ParentId": "48557",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48584",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T09:58:11.983",
"Id": "48557",
"Score": "2",
"Tags": [
"python",
"optimization",
"programming-challenge"
],
"Title": "Project Euler 35 in Python"
} | 48557 |
<p><a href="http://projecteuler.net/problem=36" rel="nofollow">This one</a> was quick and simple. Any optimizations?</p>
<pre><code>from timeit import default_timer as timer
def sum_double_base_palindromes_under(limit):
def is_palindrome(n):
if str(n) == str(n)[::-1]:
return True
return False
sum = 0
for n in range(limit):
if is_palindrome(n) and is_palindrome(int(bin(n)[2:])):
sum += n
return sum
start = timer()
ans = sum_double_base_palindromes_under(1000000)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:26:35.130",
"Id": "85296",
"Score": "0",
"body": "I don't mean to be an ass, but it is Project Euler's policy that you should not publish solutions to their problems online, see [here](http://projecteuler.net/about). A policy you seem to be making a habit of breaking. If your code works and you got the solution right, then you have access to a protected discussion forum on Project Euler where others have posted their solutions, that's the right place to look for optimizations or ask questions. The first problems are trivial enough so it really doesn't matter, but you are starting to push the limits. Please, don't spoil the fun for others!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T16:19:12.807",
"Id": "85324",
"Score": "2",
"body": "@Jaime All these questions have \"Project Euler\" in the title. One has to take responsibility of ones's own fun and not click on a question that is likely to spoil it. Also, I'm not sure how good a code review you can get on the protected threads on the Euler site. What I've seen is people posting their solution and moving on."
}
] | [
{
"body": "<p>Some quick comments:</p>\n\n<ul>\n<li><p>I don’t know why you’re defining <code>is_palindrome()</code> within your <code>sum_double_base_palindromes_under()</code> function.</p>\n\n<p>Since <code>is_palindrome()</code> is a fairly simple function, and you only call the sum function once, the performance hit is negligible. But if the inner function was very complicated, and you called the outer function multiple times, things might slow down.</p>\n\n<p>It's also worth noting that a function inside a closure can't be used elsewhere. Here's a really trivial example:</p>\n\n\n\n<pre><code>>>> def f(x):\n... def g(x):\n... return 2 * x\n... return x * g(x)\n...\n>>> f(3)\n18\n>>> g(3)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'g' is not defined\n</code></pre>\n\n<p>I'm not overly familiar with Project Euler, but a palindrome-checker seems like it would be useful elsewhere. You should really only define functions inside another function if you're <em>sure</em> that the inner function will never be used by anything inside the outer function. So pull it out.</p></li>\n<li><p>Working on the principle that <a href=\"http://legacy.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">explicit is better than implicity</a>, I would make a separate <code>else</code> branch for the case where you don't find a palindrome.</p>\n\n\n\n<pre><code>def is_palindrome(n):\n if str(n) == str(n)[::-1]:\n return True\n else:\n return False\n</code></pre>\n\n<p>I know that seems like a trivial change, but I think it makes the code easier to read.</p></li>\n<li><p>Since you're using Python 2, for very large ranges you should probably use <code>xrange()</code> over <code>range()</code>. It makes a significant difference as you start to test with larger arguments.</p></li>\n<li><p>Don't use the variable name <code>sum</code>; this is the name of a built-in function. Pick a more specific name that doesn't clash with an existing name; say <code>palindrome_sum</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:35:37.420",
"Id": "85370",
"Score": "1",
"body": "For goodness sake, it's a boolean expression, just do `return str(n) == str(n)[::-1]`. Obscuring the code by adding lots of noise makes it **less** explicit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T04:03:51.890",
"Id": "85386",
"Score": "0",
"body": "The rest of the review is really good though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:52:34.870",
"Id": "48562",
"ParentId": "48558",
"Score": "3"
}
},
{
"body": "<p>In any programming language, I'd consider (assuming <code>c</code> is a condition with a boolean value):</p>\n\n<pre><code>if c:\n return True\nelse:\n return False\n</code></pre>\n\n<p>or it's equivalent :</p>\n\n<pre><code>if c:\n return True\nreturn False\n</code></pre>\n\n<p>to be an anti-pattern that should be written:</p>\n\n<pre><code>return c\n</code></pre>\n\n<hr>\n\n<p>Your <code>for</code> loop can easily be rewritten into a more concise (and more efficient according to my benchmarks) way using <a href=\"https://docs.python.org/release/3.4.0/library/functions.html#sum\"><code>sum</code></a> :</p>\n\n<pre><code>return sum(n for n in range(limit) if is_palindrome(n) and is_palindrome(int(bin(n)[2:])))\n</code></pre>\n\n<hr>\n\n<p>An easy optimisation is not to compute <code>str(n)</code> more than needed :</p>\n\n<pre><code>def is_palindrome(n):\n s = str(n)\n return s == s[::-1]\n</code></pre>\n\n<p>Also, it might even be faster to feed strings to your functions :</p>\n\n<pre><code>def is_palindrome(s):\n return s == s[::-1]\nreturn sum(n for n in range(limit) if is_palindrome(str(n)) and is_palindrome(bin(n)[2:]))\n</code></pre>\n\n<p>On my machine, running your function 10 times, the running time went from 470 ms to 310 ms per iterations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:55:27.903",
"Id": "85351",
"Score": "0",
"body": "On your last note: we don't need to feed _all_ the strings. Just _construct_ the palindromes. Another 500x speedup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:29:43.993",
"Id": "85359",
"Score": "0",
"body": "No time for benchmark right now but this is might be worth an answer on its own."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:30:07.400",
"Id": "48574",
"ParentId": "48558",
"Score": "5"
}
},
{
"body": "<p>Followup to the last Josay comment. There are million numbers in the range, and only 2000 of them are palindromes (<code>abccba</code> covers all even-length palindromes, and <code>abcba</code> covers all odd-length ones). Traversing just them reduces the number of iterations by 500( a perk benefit is that a test on a decimal string disappears). I'd expect a 500x to 1000x speedup.</p>\n\n<p>So, construct decimal palindromes as a string, trim trailing zeroes, and call <code>is_palindrome(bin(int(s)))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:43:05.847",
"Id": "48623",
"ParentId": "48558",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "48623",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T10:14:23.923",
"Id": "48558",
"Score": "1",
"Tags": [
"python",
"optimization",
"programming-challenge",
"palindrome"
],
"Title": "Optimizing Project Euler 36 - double-base palindromes"
} | 48558 |
<p>My project here works upon output that comes out of a Tesseract OCR scan using hOCR format, then I read it with JDOM 2.0 and finally save it one of my own objects, which <em>at a later point</em> needs to be serializable. I have spotted one major codesmell, which is a for-loop of 5 levels deep.</p>
<p>An example hOCR output file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name='ocr-system' content='tesseract 3.02' />
<meta name='ocr-capabilities' content='ocr_page ocr_carea ocr_par ocr_line ocrx_word'/>
</head>
<body>
<div class='ocr_page' id='page_1' title='image "D:\DPC2\converted\60\60.tiff"; bbox 0 0 2479 3508; ppageno 0'>
<div class='ocr_carea' id='block_1_1' title="bbox 1690 267 2165 394">
<p class='ocr_par' dir='ltr' id='par_1' title="bbox 1690 267 2165 394">
<span class='ocr_line' id='line_1' title="bbox 1690 267 2165 394"><span class='ocrx_word' id='word_1' title="bbox 1690 267 2165 394"> </span>
</span>
</p>
</div>
</div>
</body>
</html>
</code></pre>
<p>In reality there can be many pages, areas, paragraphs, lines and words. I have only showed one of each here for simplicity and because I cannot disclose full files, also note that the content of the word shown here is " ", a string of one space.<br>
A minor defect is that there are still some TODO comments which I need to transform to actual loggers.</p>
<p>First the <code>Traversable</code> structure:</p>
<pre><code>/**
*
* @author Frank van Heeswijk
* @param <P> The type of the parent
* @param <C> The type of the children
*/
public interface Traversable<P extends Traversable<?, ?>, C extends Traversable<?, ?>> {
default public boolean hasParent() {
return (getParent() != null);
}
public P getParent();
default public boolean hasChildren() {
return (getChildren().count() > 0);
}
public Stream<C> getChildren();
public void setParent(final P parent);
public void addChild(final C child);
default public void addChildren(final Stream<? extends C> children) {
children.forEach(this::addChild);
}
public String getId();
public BoundingBox getBoundingBox();
abstract public static class Void implements Traversable<Void, Void> {
@Override
public Void getParent() {
return null;
}
@Override
public Stream<Void> getChildren() {
return Stream.empty();
}
@Override
public void setParent(final Void parent) { }
@Override
public void addChild(final Void child) { }
@Override
public String getId() {
return null;
}
@Override
public BoundingBox getBoundingBox() {
return null;
}
}
}
</code></pre>
<hr>
<pre><code>/**
*
* @author Frank van Heeswijk
* @param <P> The type of the parent
* @param <C> The type of the children
*/
abstract public class AbstractTraversable<P extends Traversable<?, ?>, C extends Traversable<?, ?>> implements Traversable<P, C> {
protected final Collection<C> children = new ArrayList<>();
protected P parent;
@Override
public P getParent() {
return parent;
}
@Override
public Stream<C> getChildren() {
return children.stream();
}
@Override
public void setParent(final P parent) {
this.parent = Objects.requireNonNull(parent);
}
@Override
public void addChild(final C child) {
this.children.add(Objects.requireNonNull(child));
}
}
</code></pre>
<hr>
<pre><code>/**
*
* @author Frank van Heeswijk
* @param <P> The type of the parent
* @param <C> The type of the children
*/
abstract public class FileElement<P extends FileElement<?, ?>, C extends FileElement<?, ?>> extends AbstractTraversable<P, C> {
protected final String id;
protected final BoundingBox boundingBox;
public FileElement(final String id, final BoundingBox boundingBox) {
this.id = Objects.requireNonNull(id);
this.boundingBox = Objects.requireNonNull(boundingBox);
}
@Override
public String getId() {
return id;
}
@Override
public BoundingBox getBoundingBox() {
return boundingBox;
}
public static <E extends FileElement<?, ?>> E ofBoundingBoxElement(final Element element, final BiFunction<String, BoundingBox, E> constructor) {
Objects.requireNonNull(element);
Objects.requireNonNull(constructor);
String elementId = element.getAttributeValue("id");
String elementTitle = element.getAttributeValue("title");
Title title = new Title(elementTitle);
return constructor.apply(
elementId,
title.getBoundingBox().orElseThrow(() -> new IllegalStateException("No bounding box present in: " + elementTitle))
);
}
abstract public static class Void extends FileElement<Void, Void> {
public Void(String id, BoundingBox boundingBox) {
super(id, boundingBox);
}
}
}
</code></pre>
<hr>
<pre><code>public class BoundingBox {
private final int x1;
private final int y1;
private final int x2;
private final int y2;
public BoundingBox(final int x1, final int y1, final int x2, final int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public int getX1() {
return x1;
}
public int getY1() {
return y1;
}
public int getX2() {
return x2;
}
public int getY2() {
return y2;
}
@Override
public String toString() {
return BoundingBox.class.getSimpleName() + "(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")";
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.x1;
hash = 89 * hash + this.y1;
hash = 89 * hash + this.x2;
hash = 89 * hash + this.y2;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BoundingBox other = (BoundingBox) obj;
if (this.x1 != other.x1) {
return false;
}
if (this.y1 != other.y1) {
return false;
}
if (this.x2 != other.x2) {
return false;
}
if (this.y2 != other.y2) {
return false;
}
return true;
}
}
</code></pre>
<hr>
<pre><code>public class Title {
private static final Map<String, BiConsumer<Title, Stream<String>>> KEYWORD_CONSUMERS = new HashMap<>();
static {
KEYWORD_CONSUMERS.put("bbox", new BoundingBoxConsumer());
KEYWORD_CONSUMERS.put("image", new ImagePathConsumer());
KEYWORD_CONSUMERS.put("ppageno", new PageNumberConsumer());
}
private Optional<BoundingBox> boudingBox = Optional.empty();
private Optional<Path> imagePath = Optional.empty();
private OptionalInt pageNumber = OptionalInt.empty();
public Title(final String title) {
process(Objects.requireNonNull(title));
}
private void process(final String title) {
for (String part : splitTitle(title)) {
List<String> parts = Arrays.stream(part.split(" "))
.map(String::trim)
.filter(str -> !str.isEmpty())
.collect(Collectors.toList());
if (parts.size() <= 1) {
//TODO logger, ignoring because x
continue;
}
String keyword = parts.get(0);
if (!KEYWORD_CONSUMERS.containsKey(keyword)) {
//TODO logger, zz not found
continue;
}
KEYWORD_CONSUMERS.get(keyword).accept(this, parts.subList(1, parts.size()).stream());
}
}
private List<String> splitTitle(final String input) {
return Arrays.asList(input.split(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)"));
}
private void setBoundingBox(final BoundingBox boundingBox) {
Objects.requireNonNull(boundingBox);
this.boudingBox = Optional.of(boundingBox);
}
private void setImagePath(final Path imagePath) {
Objects.requireNonNull(imagePath);
this.imagePath = Optional.of(imagePath);
}
private void setPageNumber(final int pageNumber) {
this.pageNumber = OptionalInt.of(pageNumber);
}
public Optional<BoundingBox> getBoundingBox() {
return boudingBox;
}
public Optional<Path> getImagePath() {
return imagePath;
}
public OptionalInt getPageNumber() {
return pageNumber;
}
@Override
public String toString() {
return Title.class.getSimpleName() + "(" + boudingBox + ", " + imagePath + ", " + pageNumber + ")";
}
private static class BoundingBoxConsumer implements BiConsumer<Title, Stream<String>> {
@Override
public void accept(final Title title, final Stream<String> stream) {
Objects.requireNonNull(title);
Objects.requireNonNull(stream);
List<Integer> arguments = stream.map(Integer::parseInt).collect(Collectors.toList());
if (arguments.size() != 4) {
//TODO logger, ignoring because y
}
title.setBoundingBox(new BoundingBox(arguments.get(0), arguments.get(1), arguments.get(2), arguments.get(3)));
}
}
private static class ImagePathConsumer implements BiConsumer<Title, Stream<String>> {
@Override
public void accept(final Title title, final Stream<String> stream) {
Objects.requireNonNull(title);
Objects.requireNonNull(stream);
List<Path> arguments = stream.map(str -> str.replace("\"", "")).map(Paths::get).collect(Collectors.toList());
if (arguments.size() != 1) {
//TODO logger, ignoring because yy
}
title.setImagePath(arguments.get(0));
}
}
private static class PageNumberConsumer implements BiConsumer<Title, Stream<String>> {
@Override
public void accept(final Title title, final Stream<String> stream) {
Objects.requireNonNull(title);
Objects.requireNonNull(stream);
List<Integer> arguments = stream.map(Integer::parseInt).collect(Collectors.toList());
if (arguments.size() != 1) {
//TODO logger, ignoring because yyy
}
title.setPageNumber(arguments.get(0));
}
}
}
</code></pre>
<hr>
<pre><code>public class Page extends FileElement<FileElement.Void, Area> {
private final Path imagePath;
private final int pageNumber;
public static Page of(final Element element) {
Objects.requireNonNull(element);
String elementId = element.getAttributeValue("id");
String elementTitle = element.getAttributeValue("title");
Title title = new Title(elementTitle);
return new Page(
elementId,
title.getBoundingBox().orElseThrow(() -> new IllegalStateException("No bounding box present in: " + elementTitle)),
title.getImagePath().orElseThrow(() -> new IllegalStateException("No image path present in: " + elementTitle)),
title.getPageNumber().orElseThrow(() -> new IllegalStateException("No page number present in: " + elementTitle))
);
}
public Page(final String id, final BoundingBox boundingBox, final Path imagePath, final int pageNumber) {
super(id, boundingBox);
this.imagePath = Objects.requireNonNull(imagePath);
this.pageNumber = Objects.requireNonNull(pageNumber);
}
@Override
public FileElement.Void getParent() {
return null;
}
@Override
public void setParent(final FileElement.Void parent) {
throw new IllegalStateException("The Page element has no parent.");
}
public Path getImagePath() {
return imagePath;
}
public int getPageNumber() {
return pageNumber;
}
}
</code></pre>
<hr>
<pre><code>public class Area extends FileElement<Page, Paragraph> {
public Area(final String id, final BoundingBox boundingBox) {
super(id, boundingBox);
}
public static final Area of(final Element element) {
return FileElement.ofBoundingBoxElement(Objects.requireNonNull(element), Area::new);
}
}
</code></pre>
<hr>
<pre><code>public class Paragraph extends FileElement<Area, Line> {
public Paragraph(final String id, final BoundingBox boundingBox) {
super(id, boundingBox);
}
public static final Paragraph of(final Element element) {
return FileElement.ofBoundingBoxElement(Objects.requireNonNull(element), Paragraph::new);
}
}
</code></pre>
<hr>
<pre><code>public class Line extends FileElement<Paragraph, Word> {
public Line(final String id, final BoundingBox boundingBox) {
super(id, boundingBox);
}
public static final Line of(final Element element) {
return FileElement.ofBoundingBoxElement(Objects.requireNonNull(element), Line::new);
}
}
</code></pre>
<hr>
<pre><code>public class Word extends FileElement<Line, FileElement.Void> {
private final String content;
private final boolean strong;
public Word(final String id, final BoundingBox boundingBox, final String content, final boolean strong) {
super(id, boundingBox);
this.content = Objects.requireNonNull(content);
this.strong = strong;
}
public static final Word of(final Element element) {
Objects.requireNonNull(element);
String elementId = element.getAttributeValue("id");
String elementTitle = element.getAttributeValue("title");
Title title = new Title(elementTitle);
Element child = element.getChild("strong");
return new Word(
elementId,
title.getBoundingBox().orElseThrow(() -> new IllegalStateException("No bounding box present in: " + elementTitle)),
child == null ? element.getText() : child.getText(),
child != null
);
}
@Override
public Stream<Void> getChildren() {
return Stream.empty();
}
@Override
public void addChild(final Void child) {
throw new IllegalStateException("The Word element has no children.");
}
public String getContent() {
return content;
}
public boolean isStrong() {
return strong;
}
}
</code></pre>
<p>The usage:</p>
<p>Note that the <code>ScannedFile</code> is <strong>not complete</strong> (but working) yet, I will put convienience methods in there once I need them.</p>
<pre><code>public class ScannedFile implements Serializable {
private static final long serialVersionUID = 859948374926589L;
private final List<Page> pages = new ArrayList<>();
public void addChild(final Page page) {
pages.add(page);
}
public Stream<Page> getPages() {
return pages.stream();
}
}
</code></pre>
<p>The actual XML reading, which has some code smell in it:</p>
<pre><code>public static ScannedFile createScannedFileFromHOCR(final Path directory) {
try {
Objects.requireNonNull(directory);
Path htmlFile = FileUtils.getSingleFileWithExtensionInDirectory(directory, Extension.HTML);
SAXBuilder xmlBuilder = new SAXBuilder();
Document document = xmlBuilder.build(htmlFile.toFile());
ScannedFile scannedFile = new ScannedFile();
XPathFactory factory = XPathFactory.instance();
System.out.println("factory = " + factory);
XPathExpression<Element> xpePages = factory.compile( //arguments are untyped?
"/h:html/h:body/h:div[@class='ocr_page']",
Filters.element(),
null,
Namespace.getNamespace("h", "http://www.w3.org/1999/xhtml")
);
System.out.println("xpePages = " + xpePages);
List<Element> pages = xpePages.evaluate(document);
System.out.println("pages = " + pages);
for (Element pageElement : pages) {
Page page = Page.of(pageElement);
XPathExpression<Element> xpeAreas = factory.compile(
"h:div[@class='ocr_carea']",
Filters.element(),
null,
Namespace.getNamespace("h", "http://www.w3.org/1999/xhtml")
);
List<Element> areas = xpeAreas.evaluate(pageElement);
for (Element areaElement : areas) {
Area area = Area.of(areaElement);
area.setParent(page);
page.addChild(area);
XPathExpression<Element> xpeParagraphs = factory.compile(
"h:p[@class='ocr_par']",
Filters.element(),
null,
Namespace.getNamespace("h", "http://www.w3.org/1999/xhtml")
);
List<Element> paragraphs = xpeParagraphs.evaluate(areaElement);
for (Element paragraphElement : paragraphs) {
Paragraph paragraph = Paragraph.of(paragraphElement);
paragraph.setParent(area);
area.addChild(paragraph);
XPathExpression<Element> xpeLines = factory.compile(
"h:span[@class='ocr_line']",
Filters.element(),
null,
Namespace.getNamespace("h", "http://www.w3.org/1999/xhtml")
);
List<Element> lines = xpeLines.evaluate(paragraphElement);
for (Element lineElement : lines) {
Line line = Line.of(lineElement);
line.setParent(paragraph);
paragraph.addChild(line);
XPathExpression<Element> xpeWords = factory.compile(
"h:span[@class='ocrx_word']",
Filters.element(),
null,
Namespace.getNamespace("h", "http://www.w3.org/1999/xhtml")
);
List<Element> words = xpeWords.evaluate(lineElement);
for (Element wordElement : words) {
Word word = Word.of(wordElement);
word.setParent(line);
line.addChild(word);
}
}
}
}
scannedFile.addChild(page);
}
return scannedFile;
} catch (JDOMException | IOException ex) {
ManualUtils.moveToManual(Base.MANUAL_DIRECTORY, directory);
throw new AutomaticExecutionFailedException(ex);
}
}
</code></pre>
<p>An example usage:</p>
<pre><code>ScannedFile scannedFile = OCRUtils.createScannedFileFromHOCR(path);
System.out.println("Created ScannedFile");
long elementCount = scannedFile.getPages()
.flatMap(Page::getChildren)
.flatMap(Area::getChildren)
.flatMap(Paragraph::getChildren)
.flatMap(Line::getChildren)
.count();
List<String> wordList = scannedFile.getPages()
.flatMap(Page::getChildren)
.flatMap(Area::getChildren)
.flatMap(Paragraph::getChildren)
.flatMap(Line::getChildren)
.map(Word::getContent)
.collect(Collectors.toList());
System.out.println("Word count: " + elementCount);
System.out.println("Word list: " + wordList);
</code></pre>
| [] | [
{
"body": "<p>Looking at just the JDOM portion, there are a couple of tricks you can play.</p>\n\n<p>Unfortunately, XML and streams will always be an uncomfortable mix...</p>\n\n<p>The following factors in JDOM make better performance possible:</p>\n\n<ul>\n<li>DRY\n<ul>\n<li>XPathExpressions are threadsafe. Reuse them</li>\n<li>Namespaces are threadsafe, and immutable. Reuse them</li>\n<li>SAXBuilder has a relatively slow setup time (it needs to query installed XML parsers, etc.). JDOM can reuse a single configuration using a SAXEngine....</li>\n</ul></li>\n</ul>\n\n<p>It is great that you are using relative XPath queries, and using the smaller context for them. This makes a big performance difference.</p>\n\n<p>This is about as neat as I have seen this work done. It is good. I am not sure you will appreciate it if I were to suggest this is really good, and that the alternative tools/libraries (other than JDOM) would be much harder to get right.</p>\n\n<p>Putting these things together, your <code>createScannedFileFromHOCR</code> method can become the following collection of statics (fully thread-safe, and better performing):</p>\n\n<pre><code>private static final XPathFactory factory = XPathFactory.instance();\nprivate static final Namespace XHTML = Namespace.getNamespace(\"h\", \"http://www.w3.org/1999/xhtml\");\n\nprivate static final XPathExpression<Element> OCR_PAGE = factory.compile( //arguments are untyped?\n \"/h:html/h:body/h:div[@class='ocr_page']\",\n Filters.element(),\n null,\n XHTML\n );\n\n\nprivate static final XPathExpression<Element> OCR_CAREA = factory.compile(\n \"h:div[@class='ocr_carea']\",\n Filters.element(),\n null,\n XHTML\n );\nprivate static final XPathExpression<Element> OCR_PAR = factory.compile(\n \"h:p[@class='ocr_par']\",\n Filters.element(),\n null,\n XHTML\n );\nprivate static final XPathExpression<Element> OCR_LINE = factory.compile(\n \"h:span[@class='ocr_line']\",\n Filters.element(),\n null,\n XHTML\n );\nprivate static final XPathExpression<Element> OCRX_WORD = factory.compile(\n \"h:span[@class='ocrx_word']\",\n Filters.element(),\n null,\n XHTML\n );\n\nprivate static final SAXBuilder XMLBUILDER = new SAXBuilder();\n\nprivate static final ThreadLocal<SAXEngine> XMLENGINE = new ThreadLocal<SAXEngine>() {\n @Override\n protected SAXEngine initialValue() {\n try {\n return XMLBUILDER.buildEngine();\n } catch (JDOMException e) {\n throw new IllegalStateException(\"Unable to build Engine\", e);\n }\n }\n};\n\n\npublic static ScannedFile createScannedFileFromHOCR(final Path directory) {\n try {\n Objects.requireNonNull(directory);\n Path htmlFile = FileUtils.getSingleFileWithExtensionInDirectory(directory, Extension.HTML);\n Document document = XMLENGINE.get().build(htmlFile.toFile());\n\n ScannedFile scannedFile = new ScannedFile();\n\n\n System.out.println(\"factory = \" + factory);\n\n System.out.println(\"xpePages = \" + OCR_PAGE);\n List<Element> pages = OCR_PAGE.evaluate(document);\n System.out.println(\"pages = \" + pages);\n for (Element pageElement : pages) {\n Page page = Page.of(pageElement);\n List<Element> areas = OCR_CAREA.evaluate(pageElement);\n for (Element areaElement : areas) {\n Area area = Area.of(areaElement);\n area.setParent(page);\n page.addChild(area);\n List<Element> paragraphs = OCR_PAR.evaluate(areaElement);\n for (Element paragraphElement : paragraphs) {\n Paragraph paragraph = Paragraph.of(paragraphElement);\n paragraph.setParent(area);\n area.addChild(paragraph);\n\n List<Element> lines = OCR_LINE.evaluate(paragraphElement);\n for (Element lineElement : lines) {\n Line line = Line.of(lineElement);\n line.setParent(paragraph);\n paragraph.addChild(line);\n List<Element> words = OCRX_WORD.evaluate(lineElement);\n for (Element wordElement : words) {\n Word word = Word.of(wordElement);\n word.setParent(line);\n line.addChild(word);\n }\n }\n }\n }\n scannedFile.addChild(page);\n }\n return scannedFile;\n\n } catch (JDOMException | IOException ex) {\n ManualUtils.moveToManual(Base.MANUAL_DIRECTORY, directory);\n throw new AutomaticExecutionFailedException(ex);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T12:19:27.153",
"Id": "48566",
"ParentId": "48563",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "48566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T11:52:35.487",
"Id": "48563",
"Score": "10",
"Tags": [
"java",
"xml"
],
"Title": "Saving an XML file created by Tesseract OCR as a traversable object"
} | 48563 |
<p>I was looking at other people code and I realized that mine is not so neat after all.</p>
<p>In this version, I included a base case for the merge part (when there is only 2 elements to merge, just sort it normally). I do not know this is a good idea or not, never seen it in other people' codes.</p>
<p>This is the first time I implemented this algorithm. I hope you can help me out with this code so it could look more readable.</p>
<pre><code>class MergeSort
{
public static void Standard() {
int[] A = new int[] {234, 31, 41, 59, 26, 41, 58, 90, 103, 14, 1235, 2134, 12, 673, 234, 234, 64, 23, 132, 432, 123};
int last_Index = A.Length-1;
SplitMerge(A, 0, last_Index);
foreach (int i in A)
Console.Write(i + " ");
}
//Here is the recursive split merge
private static void SplitMerge(int[] A,int iBegin,int iEnd) {
//Base case. Every recursive has a base case
if (iBegin == iEnd) return;
//Calculate the middle index here. This work for odd number array.
int Middle = (int)Math.Floor((double)(iEnd + iBegin)/2);
//split left
SplitMerge(A, iBegin, Middle);
//split right
SplitMerge(A, Middle+1, iEnd);
//merge left and right
MergeLeftRight(A, iBegin, Middle, iEnd);
}
//This is the merge
private static void MergeLeftRight(int[] A, int iBegin, int iMid, int iEnd) {
//If we are comparing just 2 numbers, just compare them already xD
if (iBegin == iMid) {
int temp_Num = A[iBegin];
if (A[iBegin] >= A[iEnd]) {
A[iBegin] = A[iEnd];
A[iEnd] = temp_Num;
}
return;
}
//Create a temporary list to store numbers
List<int> temp = new List<int> {};
//Declare the last index of left array, we will go to this but will not pass this
int left_End = iMid;
//Same as above. This is for the right array
int right_End = iEnd;
//Left array start from iBegin, but Right array must start fron left_End+1
iMid++;
//Check the number in left and right arrays and sort them while both array still has elements inside
while ((iBegin <= left_End) && (iMid <= right_End)) {
if (A[iBegin] <= A[iMid]) {
temp.Add(A[iBegin]);
iBegin++;
}
else {
temp.Add(A[iMid]);
iMid++;
}
}
//If right array is empty, add all leftover elements from left array to the list
while (iBegin <= left_End) {
temp.Add(A[iBegin]);
iBegin++;
}
//Same as above loop. Add all leftover elements from right array to the list.
while (iMid <= right_End) {
temp.Add(A[iMid]);
iMid++;
}
//Put everything back in the original array, merge everything. Since we are going from right to left
//We need to reverse the List.
temp.Reverse();
foreach (int i in temp) {
A[iEnd] = i;
iEnd--;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Since you're asking for a <a href=\"/questions/tagged/readability\" class=\"post-tag\" title=\"show questions tagged 'readability'\" rel=\"tag\">readability</a> review, here's my input:</p>\n\n<ul>\n<li><strong>Way too many comments</strong>. Comments should say <em>why</em>, not <em>what</em> - the <em>code itself</em> should describe what it's doing.</li>\n<li><p><strong>Use XML comments to describe methods</strong>. <code>// regular comments</code> only work if you're looking at the method's code. When you're <em>using</em> the code, XML comments are picked up by Visual Studio and you get tooltips to help you correctly use the method. For example:</p>\n\n<pre><code>/// <summary>\n/// A recursive split merge method. \n/// </summary>\n/// <param name=\"A\">The array to be sorted.</param>\n/// <param name=\"iBegin\">The lower bound index for the sub-array to be sorted.</param>\n/// <param name=\"iEnd\">The upper bound index for the sub-array to be sorted.</param>\nprivate static void SplitMerge(int[] A, int iBegin, int iEnd)\n</code></pre></li>\n<li><p><strong>Avoid Hungarian Notation</strong>. Prefixing <code>i</code> for <code>int</code> types is useless in .net, and hinders readability. <code>iBegin</code> and <code>iEnd</code> should simply be <code>begin</code> and <code>end</code> to be correct, <code>startIndex</code> and <code>endIndex</code> to be meaningful.</p></li>\n<li><p><strong>Use camelCase for parameters and locals</strong>. Parameter <code>A</code> should be <code>a</code>... but that's an awfully bad name. <code>unsortedArray</code>, or simply <code>unsorted</code>, would be much more descriptive.</p></li>\n<li><p><strong>Avoid snake_case</strong>. C# naming conventions don't encourage the use of an underscore (<code>_</code>) in the middle of an identifier's name. Use <em>camelCase</em> for parameters and locals, and <em>PascalCase</em> for types and public members (actually, <em>exposed</em> is more accurate, since <code>internal</code> and <code>protected</code> members should also be <em>PascalCase</em>).</p></li>\n<li><p><strong>Avoid Java-style curly braces</strong>. Not to start any flamewars, but C# conventions put the opening brace <code>{</code> on the next line.</p></li>\n<li><p><strong>Method names should start with a verb</strong>. <code>Standard()</code> isn't a good method name. Since it's a member of a class named <code>MergeSort</code>, <code>Sort()</code> would probably be best, and should take the array in as a parameter to be any useful...</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:50:24.200",
"Id": "48581",
"ParentId": "48573",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "48581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T13:19:21.207",
"Id": "48573",
"Score": "2",
"Tags": [
"c#",
"sorting",
"mergesort"
],
"Title": "Merge Sort optimization"
} | 48573 |
<p>I created a client side search module. Could anyone please provide review pointers on it?</p>
<pre><code>var search = function(){
"use strict";
var _instanceMap = {};
var maxLimit = 50; //TODO: add a perf test to determine the scale.
/**
* @constructor
* @private
*/
function _IndexCreator(_searchConfig){
this.ref = _searchConfig.ref;
this.id = _searchConfig.id;
this.fieldsConfig = _searchConfig.fieldsConfig;
this.refToDocumentMap = {};
}
/**
* Creates an index with the document and the config
*/
_IndexCreator.prototype.createIndex = function(){
var me = this;
var _idx = lunr(function(){
this.ref(me.ref);
if(!me.fieldsConfig){
return;
}
var idx = this;
for(var key in me.fieldsConfig){
if(key && me.fieldsConfig[key]){
idx.field(key,me.fieldsConfig[key]);
} else {
idx.field(key);
}
}
});
this.idx = _idx;
return _idx;
};
/**
* Searches the index for the document
* @params {object} document - The document to be searched
*/
_IndexCreator.prototype.search = function(docToBeSearched){
var me = this;
var results = this.idx.search(docToBeSearched).map(function(result){
return me.refToDocumentMap[result.ref];
});
return results;
};
return {
/**
* Creates and index and pushes it to the instanceMap
* @params {object} documents - documents to be indexed
* @params {object} searchConfig - config object to create an index.
* @example
* {id:"",
ref:"",
fieldsConfig:{
'tags':{boost:1},
'widgetId'
},
limit:1
} - contains the searchable keys of a document, id of the document,id of the instance and the limit
of the documents which can be indexed
* @params {string} ref - refers to the id of the documents indexed
* @params {string} id - refers to the id of the index created
*/
createInstance: function(documents, searchConfig){
var instance, refToDocumentMap = {},
limit = searchConfig.limit || maxLimit;
if(searchConfig === undefined || searchConfig.id === undefined){
console.log("Invalid configuration passed");
return;
}
if(_instanceMap[searchConfig.id] === undefined){
instance = new _IndexCreator(searchConfig);
var index = instance.createIndex();
var numDocsIndexed = 0;
for (var i = 0; i < documents.length; i++) {
var refId = searchConfig.ref;
var docToBeIndexed = documents[i];
if(refId !== undefined){
var docRefId = docToBeIndexed[refId];
if(numDocsIndexed <= limit && refToDocumentMap[docRefId] === undefined){
index.add(docToBeIndexed);
refToDocumentMap[docRefId] = docToBeIndexed;
numDocsIndexed++;
}
}
}
_instanceMap[searchConfig.id] = instance;
instance.refToDocumentMap = refToDocumentMap;
}
return _instanceMap[searchConfig.id];
},
/**
* Returns the instance of the index based on the id passed
* @paramas {string} ref - id of the index passed.
*/
getInstance: function(id){
return _instanceMap[id];
},
/**
* Updates the index referenced by the id with the document(s)
* @paramas {Array/Object} documents - Documents to be updated, can be either an array of documents
* or a document
* @params {string} id - id of the index to update the document with
*/
update: function(documents, id){
if(_instanceMap[id] === undefined){
console.log("No index found for the id");
return;
}
var idxInstance = _instanceMap[id];
if(Array.isArray(documents)){
for(var i = 0; i < documents.length; i++){
var refId = document[i].refId,
refDocMap = idxInstance.idx.refToDocumentMap;
refDocMap[refId] = documents[i];
idxInstance.idx.update(documents[i]);
}
} else{
idxInstance.idx.update(documents);
var refId = documents.refId,
refDocMap = idxInstance.idx.refToDocumentMap;
refDocMap[refId] = documents;
idxInstance.idx.update(documents[i]);
}
}
}
}
</code></pre>
<p>Here's a few points to consider: </p>
<ul>
<li>The module gets plugged into a separate module management framework.</li>
<li>Need pointers on update being an API while the search being defined as a prototype method. My reasoning was search being a stateless method while update changes the state of the method.</li>
<li><code>getInstance</code> exposes a possibility of Law of Demeter violation by the client. Any thoughts on that? </li>
<li>Any input on developing a debug extension for this and the parameter check would be great.</li>
</ul>
| [] | [
{
"body": "<p>Not a full code review, and my comments might be off base if you based your naming on the API you are using. The naming confuses me. I cannot read this code and know what it does without really focusing, that's not how code should read.</p>\n\n<p>For <code>_IndexCreator</code>:</p>\n\n<ul>\n<li><code>ref</code> <- ref to what ?</li>\n<li><code>fieldsConfig</code> <- since there is no other config, I would call it simpy <code>config</code></li>\n<li><code>refToDocumentMap</code> <-What is a documentMap, and why would you say here what the ref is about but not in <code>ref</code> ?</li>\n</ul>\n\n<p>Also in these comments:</p>\n\n<pre><code> * @params {string} ref - refers to the id of the documents indexed\n * @params {string} id - refers to the id of the index created\n</code></pre>\n\n<p>I would go for </p>\n\n<pre><code> * @params {string} doc(ument)sID - refers to the id of the documents indexed\n * @params {string} indexId - refers to the id of the index created\n</code></pre>\n\n<p>For this: </p>\n\n<pre><code>_IndexCreator.prototype.createIndex = function(){\n var me = this;\n var _idx = lunr(function(){\n this.ref(me.ref);\n if(!me.fieldsConfig){\n return;\n }\n var idx = this;\n for(var key in me.fieldsConfig){\n if(key && me.fieldsConfig[key]){\n idx.field(key,me.fieldsConfig[key]);\n } else {\n idx.field(key);\n }\n }\n });\n this.idx = _idx;\n return _idx;\n};\n</code></pre>\n\n<ul>\n<li>You do not need <code>_idx</code>, you could assign straight to <code>idx</code> instead</li>\n<li>The check for <code>key</code> in your loop is not needed. </li>\n<li>I am not sure, to be tested, but you should be able to always call <code>idx.field(key,me.fieldsConfig[key]);</code> unless you really need that second parameter to be <code>undefined</code>. </li>\n<li>I would create <code>key</code> as a var up front</li>\n<li>You only need to assign <code>this</code> to something for closures, otherwise I would advise to stick to <code>this</code>, it helps the reader</li>\n<li>I would assign <code>me.fieldsConfig[key]</code> to a shortcut variable for easier reading</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>_IndexCreator.prototype.createIndex = function(){\n var me = this;\n this.idx = lunr(function(){\n var key, value;\n if(!me.fieldsConfig){\n return;\n }\n this.ref(me.ref);\n for(key in me.fieldsConfig){\n value = me.fieldsConfig[key];\n if( value ){\n this.field(key, value);\n } else {\n this.field(key);\n }\n }\n });\n return this.idx;\n};\n</code></pre>\n\n<p>For function <code>update</code>, there is a clear case of copy pasting of this : </p>\n\n<pre><code> idxInstance.idx.update(documents);\n var refId = documents.refId,\n refDocMap = idxInstance.idx.refToDocumentMap;\n refDocMap[refId] = documents;\n idxInstance.idx.update(documents[i]); <--- Hmmmm?\n }\n</code></pre>\n\n<p>Except that now you seem to have a bug potentially, since <code>i</code> is either <code>undefined</code> or some random global variable. Create a function with the proper 4 lines and call it either in a loop or not. Actually, my preferred approach for the <em>how to deal with something that could be an array?</em> is turning a not-array into an array and then just deal with arrays:</p>\n\n<pre><code>update: function(documents, id){\n if(_instanceMap[id] === undefined){\n console.log(\"No index found for the id\");\n return;\n }\n var idxInstance = _instanceMap[id];\n //Turn that documents into an array!\n if(!Array.isArray(documents)){\n documents = [documents];\n }\n //Normal processing\n for(var i = 0; i < documents.length; i++){\n var refId = document[i].refId,\n refDocMap = idxInstance.idx.refToDocumentMap;\n refDocMap[refId] = documents[i];\n idxInstance.idx.update(documents[i]);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:54:04.973",
"Id": "48705",
"ParentId": "48575",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:09:19.913",
"Id": "48575",
"Score": "3",
"Tags": [
"javascript",
"api",
"prototypal-class-design"
],
"Title": "Lunr backed client side search module"
} | 48575 |
<p>I use the following code to find the lowest denominator Rational that is within a certain delta from a <code>double</code>.</p>
<p>The rationale is that the I am pulling float numbers from a database and in many cases summing them. All of the numbers are calculated using simple maths such as +, -, * and /. No transcendental numbers are involved, nor is there any trigonometry. In most cases finding the nearest Rational to the float gets what the original figure is supposed to be rather than the results of adding mashed-up numbers together.</p>
<pre><code>// Create a good rational for the value within the delta supplied.
public static Rational valueOf(double dbl, double delta) {
// Primary checks.
if (delta <= 0.0) {
throw new IllegalArgumentException("Delta must be > 0.0");
}
// Remove the sign and integral part.
long integral = (long) Math.floor(dbl);
dbl -= integral;
// The value we are looking for.
final Rational d = new Rational((long) ((dbl) / delta), (long) (1 / delta));
// Min value = d - delta.
final Rational min = new Rational((long) ((dbl - delta) / delta), (long) (1 / delta));
// Max value = d + delta.
final Rational max = new Rational((long) ((dbl + delta) / delta), (long) (1 / delta));
// Start the fairey sequence.
Rational l = ZERO;
Rational h = ONE;
Rational found = null;
// Keep slicing until we arrive within the delta range.
do {
// Either between min and max -> found it.
if (found == null && min.compareTo(l) <= 0 && max.compareTo(l) >= 0) {
found = l;
}
if (found == null && min.compareTo(h) <= 0 && max.compareTo(h) >= 0) {
found = h;
}
if (found == null) {
// Make the mediant.
Rational m = mediant(l, h);
// Replace either l or h with mediant.
if (m.compareTo(d) < 0) {
l = m;
} else {
h = m;
}
}
} while (found == null);
// Bring back the sign and the integral.
if (integral != 0) {
found = found.plus(new Rational(integral, 1));
}
// That's me.
return found;
}
</code></pre>
<p>In a recent test using 0.000001 as my delta this code took 75% of the CPU. Dropping it to 0.0001 reduced that dramatically but it is still a significant bottleneck.</p>
<p>Is there a quicker way of doing this?</p>
<p>My implementation of Rational forces the numerator and denominator to be fully reduced at all times. I accept that that is likely the biggest overhead but as mentioned in <a href="http://en.wikipedia.org/wiki/Mediant_%28mathematics%29" rel="nofollow">Wikipedia</a> the rationals must be fully reduced for the mediant function to work correctly.</p>
<p>Here is the full class - borrowed from the mentioned site and enhanced:</p>
<pre><code>/**
* ***********************************************************************
* Immutable ADT for Rational numbers.
*
* Invariants
* -----------
* - gcd(num, den) = 1, i.e, the rational number is in reduced form
* - den >= 1, the denominator is always a positive integer
* - 0/1 is the unique representation of 0
*
* We employ some tricks to stave of overflow, but if you
* need arbitrary precision rationals, use BigRational.java.
*
* Borrowed from http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html
* because it has a mediant method.
*
************************************************************************
*/
public class Rational extends Number implements Comparable<Rational> {
public static final Rational ZERO = new Rational(0, 1);
public static final Rational ONE = new Rational(1, 1);
private long num; // the numerator
private long den; // the denominator
// create and initialize a new Rational object
public Rational(long numerator, long denominator) {
// deal with x/0
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be 0.");
}
// reduce fraction
long g = gcd(numerator, denominator);
num = numerator / g;
den = denominator / g;
// only needed for negative numbers
if (den < 0) {
den = -den;
num = -num;
}
}
public Rational(Rational from) {
num = from.num;
den = from.den;
}
// return the numerator and denominator of (this)
public long numerator() {
return num;
}
public long denominator() {
return den;
}
// return double precision representation of (this)
public double toDouble() {
return (double) num / den;
}
public BigDecimal toBigDecimal() {
// Do it to just 4 decimal places.
return toBigDecimal(4);
}
public BigDecimal toBigDecimal(int digits) {
// Do it to n decimal places.
return new BigDecimal(num).divide(new BigDecimal(den), digits, RoundingMode.DOWN).stripTrailingZeros();
}
// return string representation of (this)
@Override
public String toString() {
if (den == 1) {
return num + "";
} else {
return num + "/" + den;
}
}
public int compareTo(Rational b) {
// return { -1, 0, +1 } if a < b, a = b, or a > b
Rational a = this;
long lhs = a.num * b.den;
long rhs = a.den * b.num;
if (lhs < rhs) {
return -1;
}
if (lhs > rhs) {
return +1;
}
return 0;
}
@Override
public boolean equals(Object y) {
// is this Rational object equal to y?
if (y == null) {
return false;
}
if (y.getClass() != this.getClass()) {
return false;
}
Rational b = (Rational) y;
return compareTo(b) == 0;
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (int) (this.num ^ (this.num >>> 32));
hash = 97 * hash + (int) (this.den ^ (this.den >>> 32));
return hash;
}
// create and return a new rational (r.num + s.num) / (r.den + s.den)
public static Rational mediant(Rational r, Rational s) {
return new Rational(r.num + s.num, r.den + s.den);
}
// return gcd(|m|, |n|)
private static long gcd(long m, long n) {
if (m < 0) {
m = -m;
}
if (n < 0) {
n = -n;
}
if (0 == n) {
return m;
} else {
return gcd(n, m % n);
}
}
// return lcm(|m|, |n|)
private static long lcm(long m, long n) {
if (m < 0) {
m = -m;
}
if (n < 0) {
n = -n;
}
return m * (n / gcd(m, n)); // parentheses important to avoid overflow
}
// return a * b, staving off overflow as much as possible by cross-cancellation
public Rational times(Rational b) {
Rational a = this;
// reduce p1/q2 and p2/q1, then multiply, where a = p1/q1 and b = p2/q2
Rational c = new Rational(a.num, b.den);
Rational d = new Rational(b.num, a.den);
return new Rational(c.num * d.num, c.den * d.den);
}
// return a + b, staving off overflow
public Rational plus(Rational b) {
Rational a = this;
// special cases
if (a.compareTo(ZERO) == 0) {
return b;
}
if (b.compareTo(ZERO) == 0) {
return a;
}
// Find gcd of numerators and denominators
long f = gcd(a.num, b.num);
long g = gcd(a.den, b.den);
// add cross-product terms for numerator
Rational s = new Rational((a.num / f) * (b.den / g) + (b.num / f) * (a.den / g),
lcm(a.den, b.den));
// multiply back in
s.num *= f;
return s;
}
// return -a
public Rational negate() {
return new Rational(-num, den);
}
// return a - b
public Rational minus(Rational b) {
return plus(b.negate());
}
public Rational reciprocal() {
return new Rational(den, num);
}
// return a / b
public Rational divides(Rational b) {
Rational a = this;
return a.times(b.reciprocal());
}
// Default delta to apply.
public static final double DELTA = 0.0001;
public static Rational valueOf(double dbl) {
return valueOf(dbl, DELTA);
}
public static Rational valueOf(BigDecimal dbl) {
return valueOf(dbl.doubleValue(), DELTA);
}
public static Rational valueOf(double dbl, int digits) {
return valueOf(dbl, Math.pow(10, -digits));
}
public static Rational valueOf(BigDecimal dbl, int digits) {
return valueOf(dbl.doubleValue(), Math.pow(10, -digits));
}
// Create a good rational for the value within the delta supplied.
public static Rational valueOf(double dbl, double delta) {
// Primary checks.
if (delta <= 0.0) {
throw new IllegalArgumentException("Delta must be > 0.0");
}
// Remove the sign and integral part.
long integral = (long) Math.floor(dbl);
dbl -= integral;
// The value we are looking for.
final Rational d = new Rational((long) ((dbl) / delta), (long) (1 / delta));
// Min value = d - delta.
final Rational min = new Rational((long) ((dbl - delta) / delta), (long) (1 / delta));
// Max value = d + delta.
final Rational max = new Rational((long) ((dbl + delta) / delta), (long) (1 / delta));
// Start the fairey sequence.
Rational l = ZERO;
Rational h = ONE;
Rational found = null;
// Keep slicing until we arrive within the delta range.
do {
// Either between min and max -> found it.
if (found == null && min.compareTo(l) <= 0 && max.compareTo(l) >= 0) {
found = l;
}
if (found == null && min.compareTo(h) <= 0 && max.compareTo(h) >= 0) {
found = h;
}
if (found == null) {
// Make the mediant.
Rational m = mediant(l, h);
// Replace either l or h with mediant.
if (m.compareTo(d) < 0) {
l = m;
} else {
h = m;
}
}
} while (found == null);
// Bring back the sign and the integral.
if (integral != 0) {
found = found.plus(new Rational(integral, 1));
}
// That's me.
return found;
}
private static void print(String name, Rational r) {
System.out.println(name + "=" + r + "(" + r.toDouble() + ")");
}
private enum TestNumber {
OneTenth(0.100000001490116119384765625),
Pi(Math.PI),
E(Math.E),
OneThird(0.3333333333333),
MinusOneThird(-0.3333333333333),
ABig1(1.87344227533222758141533568138280569154340745619495504034120344898213260187710089517712780269958755185722145694193999220);
final double v;
TestNumber(double v) {
this.v = v;
}
}
private static void test2() {
for (TestNumber n : TestNumber.values()) {
print(n.name(), Rational.valueOf(n.v));
}
}
private static void test1() {
Rational x, y, z;
// 1/2 + 1/3 = 5/6
x = new Rational(1, 2);
y = new Rational(1, 3);
z = x.plus(y);
System.out.println(z);
// 8/9 + 1/9 = 1
x = new Rational(8, 9);
y = new Rational(1, 9);
z = x.plus(y);
System.out.println(z);
// 1/200000000 + 1/300000000 = 1/120000000
x = new Rational(1, 200000000);
y = new Rational(1, 300000000);
z = x.plus(y);
System.out.println(z);
// 1073741789/20 + 1073741789/30 = 1073741789/12
x = new Rational(1073741789, 20);
y = new Rational(1073741789, 30);
z = x.plus(y);
System.out.println(z);
// 4/17 * 17/4 = 1
x = new Rational(4, 17);
y = new Rational(17, 4);
z = x.times(y);
System.out.println(z);
// 3037141/3247033 * 3037547/3246599 = 841/961
x = new Rational(3037141, 3247033);
y = new Rational(3037547, 3246599);
z = x.times(y);
System.out.println(z);
// 1/6 - -4/-8 = -1/3
x = new Rational(1, 6);
y = new Rational(-4, -8);
z = x.minus(y);
System.out.println(z);
}
// test client
public static void main(String[] args) {
//test1();
test2();
}
// Implement Number.
@Override
public int intValue() {
return (int) doubleValue();
}
@Override
public long longValue() {
return (long) doubleValue();
}
@Override
public float floatValue() {
return (float) doubleValue();
}
@Override
public double doubleValue() {
return toDouble();
}
}
</code></pre>
| [] | [
{
"body": "<h2>Naming</h2>\n\n<p>You definitely need to improve your variable names. Here are some suggested changes with the reasoning</p>\n\n<ul>\n<li><code>dbl</code> -> <code>value</code> (does not change much but repeating the type of a variable as its name does not add value (no pun intended))</li>\n<li><code>delta</code> -> <code>epsilon</code> (the name <code>epsilon</code> is much more common if you want to define a closeness boundary)</li>\n<li><code>ABig1</code> (I have no idea for this but it does not help much. This one is as big as every other double. More importantly, double is not capable of catching all the digits you give there.)</li>\n</ul>\n\n<p>Now to the </p>\n\n<h2>Algorithm</h2>\n\n<p>Doing a binary search is quite efficient in comparison with other methods but it still has an \\$\\mathbb{O}(\\log n)\\$ runtime. Lets think about the representation of doubles in IEEE 754 format.</p>\n\n<p>A double consists of 64 bits of which the first is the sign bit, the next eleven bits store a biased exponent and the remaining 52 bits store the mantissa.</p>\n\n<p>The idea is as follows: We use the mantissa as numerator and the exponent as denominator (if it is negative) or as factor for the numerator when it is positive:</p>\n\n<pre><code>public static long getMantissaBits(double value) {\n // select the 52 lower bits which make up the mantissa\n return Double.doubleToLongBits(value) & 0xFFFFFFFFFFFFFL;\n}\n\npublic static long getMantissa(double value) {\n // add the \"hidden\" 1 of normalized doubles\n return (1L << 52) + getMantissaBits(value);\n}\n\npublic static long getExponent(double value) {\n int exponentOffset = 52;\n long lowest11Bits = 0x7FFL;\n long shiftedBiasedExponent = Double.doubleToLongBits(value) & (lowest11Bits << exponentOffset);\n long biasedExponent = shiftedBiasedExponent >> exponentOffset;\n // remove the bias\n return biasedExponent - 1023;\n}\n\npublic static Rational valueOf(double value) {\n long mantissa = getMantissa(value);\n long exponent = getExponent(value) - 52;\n int numberOfTrailingZeros = Long.numberOfTrailingZeros(mantissa);\n mantissa >>= numberOfTrailingZeros;\n exponent += numberOfTrailingZeros;\n // apply the sign to the numerator\n long numerator = (long) Math.signum(value) * mantissa;\n if(exponent < 0)\n return new Rational(numerator, 1L << -exponent);\n else\n return new Rational(numerator << exponent, 1);\n}\n</code></pre>\n\n<p>As you can see, we don't need the delta anymore as we are as close as possible. Of course there are some caveats. If the double is denormalized <code>getMantissa</code> will give wrong results (but you could detect that and return the correct result). Another problem stems from too big/small exponents where the shift of <code>1L</code> is greater or equal to 64bits (and thus the result is 0). However, if you think about this problem you will find that these exponents only occur when the number is too big/small to fit into your <code>Rational</code> class anyways.</p>\n\n<p>As noticed in the comments this will return the exact result which is not wanted. I tried to come up with a solution to get the rounding correct but I failed so I shamelessly translated <a href=\"http://hg.python.org/cpython/file/4ed1b6c7e2f3/Lib/fractions.py#l218\" rel=\"nofollow\">python's solution</a> to Java:</p>\n\n<pre><code>public Rational limitDenominator(long maximumDenominator) {\n if (maximumDenominator < 1) {\n throw new IllegalArgumentException(\"Denominator cannot be less than 1.\");\n }\n if(this.den <= maximumDenominator)\n // we can't get closer than the current value\n return this;\n long p0 = 0;\n long q0 = 1;\n long p1 = 1;\n long q1 = 0;\n long n = this.num;\n long d = this.den;\n while(true) {\n long a = n / d;\n long q2 = q0 + a * q1;\n if(q2 > maximumDenominator)\n break;\n long oldP0 = p0;\n p0 = p1;\n q0 = q1;\n p1 = oldP0 + a * p1;\n q1 = q2;\n long oldN = n;\n n = d;\n d = oldN - a * d;\n }\n long k = (maximumDenominator - q0) / q1;\n Rational bound1 = new Rational(p0 + k * p1, q0 + k * q1);\n Rational bound2 = new Rational(p1, q1);\n if(bound2.minus(this).abs().compareTo(bound1.minus(this).abs()) <= 0){\n return bound2;\n } else {\n return bound1;\n }\n}\n</code></pre>\n\n<p>I cannot say much about the exact details in play here because I need to first understand them myself but the idea is that you find the closest fraction with a denominator less or equal than the given maximum. To do so you find an upper and lower closest and choose the one that is closer.</p>\n\n<h2>Algorithm explanation (some math?)</h2>\n\n<p>I finally found some time to have a closer look at the algorithm. Let us at first note that the problem we are trying to solve is the <a href=\"http://en.wikipedia.org/wiki/Diophantine_approximation#Best_Diophantine_approximations_of_a_real_number\" rel=\"nofollow\">Diophantine approximation</a>. As noted in the linked article we can use convergents or semiconvergents of the continued fraction representation of the given number to approximate it. </p>\n\n<blockquote>\n <p>Its best approximations for the second definition are</p>\n \n <p>\\$3, \\frac{8}{3}, \\frac{11}{4}, \\frac{19}{7}, \\frac{87}{32}, \\ldots\\,\\$ ,</p>\n \n <p>while, for the first definition, they are</p>\n \n <p>\\$3, \\frac{5}{2}, \\frac{8}{3}, \\frac{11}{4}, \\frac{19}{7}, \\frac{30}{11}, \\frac{49}{18}, \\frac{68}{25}, \\frac{87}{32}, \\frac{106}{39}, \\ldots \\$</p>\n</blockquote>\n\n<p>As you can see the semiconvergents have a much tighter spacing so we should use them (because the target number can lie in a hole between the convergents that is filled by semiconvergents). </p>\n\n<p>If you take a look into the linked python documentation you will find that it also uses semiconvergents.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Continued_fraction#Infinite_continued_fractions\" rel=\"nofollow\">Wikipedia article</a> also tells us that</p>\n\n<blockquote>\n <p>Even-numbered convergents are smaller than the original number, while odd-numbered ones are bigger.</p>\n</blockquote>\n\n<p>So we corner the number from both sides. The same section also tells us that</p>\n\n<blockquote>\n <p>If successive convergents are found, with numerators h1, h2, … and denominators k1, k2, … then the relevant recursive relation is:</p>\n \n <p>\\$h_n = a_nh_{n − 1} + h_{n − 2}\\$,<br>\n \\$k_n = a_nk_{n − 1} + k_{n − 2}\\$.</p>\n \n <p>The successive convergents are given by the formula</p>\n \n <p>\\$\\frac{h_n}{k_n} = \\frac{a_nh_{n − 1} + h_{n − 2}}{a_nk_{n − 1} + k_{n − 2}}\\$ </p>\n</blockquote>\n\n<p>Looking closer in the code you will note that \\$h_{n-1}\\$ corresponds to <code>p1</code> and \\$h_{n-2}\\$ to <code>p0</code> (similarly for the \\$k\\$s and <code>q</code>s), \\$a_n\\$ is <code>a</code> in the code.</p>\n\n<p>So the loop calculates convergents that approximate better and better and always increase in their denominator. This gives a convenient break condition when the next convergent would have a denominator greater than the allowed maximum. So we hit the end of the road and stop there.</p>\n\n<p>Now we found the nearest convergents but there might be a closer semiconvergent.\nWe know that the convergent with the denominator <code>q0 + a * q1</code> is too big and the one with the denominator <code>q1</code> is smaller (or equal) so we only have to look if there are semiconvergents between the two that are closer. Any semiconvergent with bigger denominator will be a better approximation <sup>[<a href=\"http://hg.python.org/cpython/file/4ed1b6c7e2f3/Lib/fractions.py#l237\" rel=\"nofollow\"><strong>Citation Needed</strong></a>]</sup> (say closer). So we need to find the semiconvergent with the biggest denominator that is still smaller than the maximum. The following lines do this exactly:</p>\n\n<pre><code>long k = (maximumDenominator - q0) / q1;\ndenominator = q0 + k * q1;\nnumerator = p0 + k * p1;\n</code></pre>\n\n<p>The python code does compare the closeness of this with \\$\\frac{p1}{q1}\\$ but I am not sure if this is really necessary. This concludes my discussion of the algorithm. The next step would be to explain why the semi-/convergents work that way but I will leave that out just believe Wikipedia/some houndred years of mathematics.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:33:16.443",
"Id": "85420",
"Score": "0",
"body": "Thanks for the feedback. Your naming suggestions - agreed (apart from \"ABig1\" which is just for fun). Your calculation suggestion works well but fails my 1/10 test where it is fed the number 0.100000001490116119384765625. It returns the same number while I was looking for 0.1. I realise all I need to do then is round but I was hoping to avoid that. My version correctly produce 0.1 without rounding. Good suggestion though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T12:11:42.190",
"Id": "85435",
"Score": "0",
"body": "@OldCurmudgeon: I realized some time after posting this, that I misunderstood your task but I am working on another solution, stay tuned :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:45:28.317",
"Id": "85442",
"Score": "0",
"body": "@OldCurmudgeon: I have added another function which solves the rounding problem and is a nice addition to your `Fractional` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T14:13:58.600",
"Id": "85444",
"Score": "0",
"body": "Seems to work well!! Correctly gets 1/10 in my test while still getting 1/3 when requested. A brief look at what the algorithm does [here](http://stackoverflow.com/a/13437804/823393) suggests it is a similar algorithm to mine but should be much faster because it does not involved repeated gcd. I'll do some time tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T08:27:50.000",
"Id": "91482",
"Score": "0",
"body": "@OldCurmudgeon: So, what did your tests find?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T08:40:44.827",
"Id": "91484",
"Score": "0",
"body": "That your algorithm is much quicker than mine. I use it instead of mine an all cases and I have not as yet found a case where it is incorrect while mine is correct. My only worry is that I don't understand how it works but that was not part of the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-02T09:05:42.960",
"Id": "91486",
"Score": "0",
"body": "I hope to find the time to work through this algorithm to understand it myself. If I have done so I might expand this answer by and explanation and give you a pingback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-19T19:33:46.943",
"Id": "102786",
"Score": "0",
"body": "@OldCurmudgeon: I updated my answer with an explanation of the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-19T22:01:35.617",
"Id": "102804",
"Score": "0",
"body": "Thank you for taking the time to dig into the algorithm. I must admit it is still beyond me but I will persevere and perhaps in time It will all fall into place."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:39:17.537",
"Id": "48596",
"ParentId": "48577",
"Score": "7"
}
},
{
"body": "<p>Why not simply have <code>java.util.BigDecimal</code> do the heavy lifting :</p>\n\n<pre><code>public Rational valueOf(double d) {\n BigDecimal bigDecimal = BigDecimal.valueOf(d);\n long numerator = bigDecimal.unscaledValue().longValue();\n long denominator = pow(10L, bigDecimal.scale());\n return new Rational(numerator, denominator);\n}\n\nprivate static long pow(long base, int exponent) {\n long result = 1;\n for (int i = 0; i < exponent; i++) {\n result *= base;\n }\n return result;\n}\n</code></pre>\n\n<p>This simply needs some extra checks for values that are out of range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:40:33.593",
"Id": "85423",
"Score": "0",
"body": "A tidier option than @Nobodys but still has similar issues. Fails with 1/10 producing 0.10000000149011612 instead of 0.1 but correctly handles 1/3 which is good. Thank you for your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T11:42:16.250",
"Id": "85430",
"Score": "0",
"body": "I'd argue my result is more closer to the fed value than what you hope to get. It looks like you really do want rounding rather than a conversion to Rational."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:56:36.040",
"Id": "48604",
"ParentId": "48577",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48596",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:17:42.527",
"Id": "48577",
"Score": "8",
"Tags": [
"java",
"performance",
"mathematics",
"floating-point",
"rational-numbers"
],
"Title": "Finding the nearest Rational to a double - is there a more efficient mechanism?"
} | 48577 |
<p>In mathematics, the mediant of two fractions</p>
<p>$$
\frac {a}{c} \text{ and } \frac {b} {d}
$$
is
$$
\frac {a + b} {c + d}.
$$</p>
<p>that is to say, the numerator and denominator of the mediant are the sums of the numerators and denominators of the given fractions, respectively.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:19:23.690",
"Id": "48578",
"Score": "0",
"Tags": null,
"Title": null
} | 48578 |
the numerator and denominator of the mediant are the sums of the numerators and denominators of the given fractions, respectively. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:19:23.690",
"Id": "48579",
"Score": "0",
"Tags": null,
"Title": null
} | 48579 |
<p>I needed to have a Lisp function that could produce a string of a certain length, created by repeated concatenations of a another string given as argument (so for example by giving 10 and "abc" I could obtain "abcabcabca"). I came up with a perverse idea of using a circular list of characters in combination with the <code>loop</code> macro. I'm not really aiming at great performance, but I'm wondering what are the disadvantages of this approach and what could be improved. I also added a switch indicating at which end to start filling the string.</p>
<pre><code>(defun pad-with-string (n str &key (from-end nil))
"Create a string of length `n` filled with repeating instances of `str`.
If `from-end` is T the string is filled from the end."
(labels ((circular-list (&rest elements)
(let ((cycle (copy-list elements)))
(nconc cycle cycle))))
(loop :repeat n
:for c
:in (apply #'circular-list (coerce (if from-end (nreverse str) str) 'list))
:collect c
:into chars
:finally (return (coerce (if from-end (nreverse chars) chars) 'string)))))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T06:31:44.787",
"Id": "137717",
"Score": "0",
"body": "Alexandria (a very popular library) has a function for creating circular lists: http://common-lisp.net/project/alexandria/draft/alexandria.html#Sequences ."
}
] | [
{
"body": "<p>Not a bad approach. </p>\n\n<p>I can see one arguable bug, and have a few style notes on your code though. Lets start with the bug:</p>\n\n<pre><code>CL-USER> (defparameter a \"test\")\nA\nCL-USER> (pad-with-string 6 a :from-end t)\n\"tsetts\"\nCL-USER> a\n\"tset\"\nCL-USER> \n</code></pre>\n\n<p>Is that what you were expecting? It's happening because you call <code>nreverse</code> on your input argument if <code>from-end</code> is passed. When I've got a situation where I have to mutate parameters, I follow the Scheme convention and name the procedure with a trailing bang (so, like <code>pad-with-string!</code>). Your comments state that you don't care about efficiency though, which leads me to believe you could just use the standard <code>reverse</code> rather than <code>nreverse</code>.</p>\n\n<hr>\n\n<p>You're using <code>apply</code> on circular list, but you're defining it locally and only calling it in one place. In this situation, I'd kill the <code>&rest</code> and just call the function</p>\n\n<pre><code>...\n (labels ((circular-list (elements)\n (let ((cycle (copy-list elements)))\n (nconc cycle cycle))))\n (loop :repeat n \n :for c \n :in (circular-list (coerce (if from-end (nreverse str) str) 'list)) \n...\n</code></pre>\n\n<hr>\n\n<p>You've got the <code>(if from-end (reverse a) a)</code> pattern in a couple of places. I'd pull that out into an additional local definition.</p>\n\n<pre><code>...\n (maybe-reverse (thing) \n (if from-end (reverse thing) thing)))\n (loop :repeat n \n :for c\n :in (circular-list (coerce (maybe-reverse str) 'list)) \n :collect c\n :into chars\n :finally (return (coerce (maybe-reverse chars) 'string)))))\n</code></pre>\n\n<hr>\n\n<p><em>thanks to Rainer for pointing this out</em></p>\n\n<p>The result of the <code>collect</code> call is returned implicitly at the end of the <code>loop</code> unless you give it an explicit name. Which means you can avoid <code>finally (return ...)</code> by wrapping those transformations around the loop itself:</p>\n\n<pre><code>...\n(coerce \n (maybe-reverse\n (loop :repeat n \n :for c\n :in (circular-list (coerce (maybe-reverse str) 'list)) \n :collect c))\n 'string)))\n</code></pre>\n\n<hr>\n\n<p>Not a hard and fast rule, but people typically use symbols rather than keywords for <code>loop</code> words. So, </p>\n\n<pre><code>...\n(coerce \n (maybe-reverse\n (loop repeat n \n for c\n in (circular-list (coerce (maybe-reverse str) 'list)) \n collect c))\n 'string)))\n</code></pre>\n\n<hr>\n\n<p>Again, there's not really a standard for this, but I tend to like putting conditions and their effects/modifiers on the same line.</p>\n\n<pre><code>...\n(coerce \n (maybe-reverse\n (loop repeat n \n for c in (circular-list (coerce (maybe-reverse str) 'list)) \n collect c))\n 'string)))\n</code></pre>\n\n<hr>\n\n<p>So,</p>\n\n<pre><code>(defun pad-with-string (n str &key (from-end nil))\n (labels ((circular-list (elements)\n (let ((cycle (copy-list elements)))\n (nconc cycle cycle)))\n (maybe-reverse (thing) \n (if from-end (reverse thing) thing)))\n (coerce (maybe-reverse\n (loop repeat n\n for c in (circular-list (coerce (maybe-reverse str) 'list))\n collect c))\n 'string)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:34:06.843",
"Id": "85360",
"Score": "0",
"body": "Thanks for the extensive answer, @Inaimathi. I totally missed the possible consequences of using `nreverse`. I used keywords in the `loop` macro, because my SLIME completes those but not symbols."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T08:26:03.660",
"Id": "85402",
"Score": "0",
"body": "As for `circular-list`, it was meant to have syntax analogous to `list` (I took the code from Quickutils), but I agree that with a local definition it would be more natural not to have to use `apply`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T16:33:17.110",
"Id": "85786",
"Score": "1",
"body": "Great answer. Personally I would also get rid of the `FINALLY (RETURN ...)` part and wrap the `(coerce (maybe-reverse ...))` call around the `LOOP`. That would seem to me slightly more Lisp-like."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:02:37.443",
"Id": "48601",
"ParentId": "48580",
"Score": "3"
}
},
{
"body": "<p>Say, if you only wanted to ever pad with the whole given string and not fractions of it, something like this would do the job:</p>\n\n<pre><code>(format nil \"~v@{~A~:*~}\" 3 \"abc\")\n</code></pre>\n\n<p>The above produces: <code>\"abcabcabc\"</code></p>\n\n<p>Which you could then <code>subseq</code> if you wanted to have only a fraction of a string.</p>\n\n<p>Meaning of the directives used in the <code>format</code>:</p>\n\n<ul>\n<li><code>~v</code> allows substitution of a numerical argument for directives that can take a numeric argument.</li>\n<li><code>~@{</code> beginning of iteration, <code>@</code> modifier tells that arguments are taken as if they were inside a list.</li>\n<li><code>~A</code> prints the Lisp object such that it would look \"pretty\", but not necessary readable by the Lisp reader.</li>\n<li><code>~:*</code> instructs the <code>format</code> processor to move to the first argument of the list it was iterating over (in our case there's only one argument).</li>\n<li><code>~}</code> terminates iteration.</li>\n</ul>\n\n<p>Generally speaking. It's best to avoid coercing strings to lists when generating string, unless it's a constant length small string. It's best to use printing and <code>with-output-to-string</code>, as this is usually efficiently handled by the Lisp system.</p>\n\n<p>And a trivial solution for this would look something like this:</p>\n\n<pre><code>(defun padded-string (padding n &optional from-end)\n (with-output-to-string (s)\n (loop :for i :below n\n :with padding := (if from-end (reverse padding) padding)\n :do (princ (char padding (mod i (length padding))) s))))\n</code></pre>\n\n<hr>\n\n<p>The optimized version:</p>\n\n<pre><code>(defun pad-string-optimized (padding n &optional from-end)\n (declare (optimize speed)\n (type string padding))\n (loop :with result := (make-string n :initial-element #\\x)\n :and padding := (if from-end (reverse padding) padding)\n :and len := (length padding)\n :for i fixnum :below n\n :do (setf (aref result i) (aref padding (mod i len)))\n :finally (return result)))\n</code></pre>\n\n<p>Seems to be about 5 times faster than any of the above, and is a lot less demanding in terms of memory usage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T20:50:47.560",
"Id": "137818",
"Score": "0",
"body": "Hm. I'm not seeing it in practice. I just tried to run this function and the one from above using `coerce` through the SLIME profiler and got `measuring PROFILE overhead..done\n seconds | gc | consed | calls | sec/call | name \n----------------------------------------------------------\n 8.454 | 0.064 | 374,104,320 | 40,000 | 0.000211 | PADDED-STRING\n 1.046 | 0.084 | 537,730,656 | 40,000 | 0.000026 | PAD-WITH-STRING\n----------------------------------------------------------\n 9.499 | 0.148 | 911,834,976 | 80,000 | | Total`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T20:52:18.843",
"Id": "137819",
"Score": "0",
"body": "(ctd.) Is that a statistical artifact, does `SBCL` optimize coercions in some way, or something else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T21:32:50.927",
"Id": "137826",
"Score": "0",
"body": "@Inaimathi you are not comparing the right thing... First of all, you need to tell the compiler to optimize your code, if you are interested in the code that runs fast. Next, my code uses an order of magnitude less memory, so depending on what system you will run it it may or may not affect the performance. Anyway, http://pastebin.com/ra4Te3Hq I tried to optimize both functions a bit, but `pad-with-string` is more difficult to optimize too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T21:36:07.340",
"Id": "137828",
"Score": "2",
"body": "On the same note, if you were really after performance, you would simply calculate the length of the string beforehand, and write the pattern into this string as many times as needed. I simply think that my code is less convoluted and just shorter."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-05T07:21:24.063",
"Id": "75690",
"ParentId": "48580",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48601",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T14:27:42.693",
"Id": "48580",
"Score": "4",
"Tags": [
"strings",
"lisp",
"common-lisp"
],
"Title": "Creating a repetitive string in Common Lisp"
} | 48580 |
<p>I've built a simple class <code>RequestHandler</code> that does exactly what I want without any extras I won't be utilizing. When needed I will expand. I'm passing this object to my Router class, to route URls to the correct controller. I will also take any suggestions!</p>
<p><strong>How is the readability?</strong></p>
<p><strong>Good idea to make it a singleton?</strong> There will always be 1 request to process at a time.</p>
<p><strong>What about dependency injection?</strong> I didn't utilize dependency injection with this class. How else would I get the URI without using <code>$_SERVER['REQUEST_URI']</code> or any other similar <code>$_SERVER</code> variable. So I don't see why I would inject it, while there are no other ways.</p>
<pre><code>class RequestHandler
{
private $rawUri;
private $cleanUri;
private $method;
private $controller;
private $action;
private $params = [];
public function __construct()
{
$this->rawUri = $_SERVER['REQUEST_URI'];
$this->cleanUri = preg_replace(['#/+#', '(\.\./)'], '/', trim($this->rawUri, '/'));
$this->method = $_SERVER['REQUEST_METHOD'];
$this->parseUri();
}
private function parseUri()
{
//parse "/controller/action/param1/param2/..." format
$parts = explode('/', $this->cleanUri);
$parts = array_filter($parts);
sort($parts);
if ($parts) {
$this->controller = ucfirst(array_shift($parts)) . 'Controller';
$this->action = array_shift($parts);
$this->params = ($parts) ? $parts : null;
}
}
public function getRawUri()
{
return $this->rawUri;
}
public function getCleanUri()
{
return $this->cleanUri;
}
public function getMethod()
{
return $this->method;
}
public function getController()
{
return $this->controller;
}
public function getAction()
{
return $this->action;
}
public function getParams()
{
return $this->params;
}
}
</code></pre>
| [] | [
{
"body": "<p>Just a quick observation I have made here, and this is by no means a full review, but you have some dead code here:</p>\n\n<pre><code>if ($parts) {\n $this->controller = ucfirst(array_shift($parts)) . 'Controller';\n $this->action = array_shift($parts);\n $this->params = ($parts) ? $parts : null;\n}\n</code></pre>\n\n<p>It will only enter the if-block if <code>$parts</code> is true, and when assigning to <code>$this->params</code> you check it again, but it can never be <code>null</code>.</p>\n\n<p>Therefore you should just assign <code>$this->params = $parts;</code></p>\n\n<p>Overall the readability of the code looks fine to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:55:23.487",
"Id": "48590",
"ParentId": "48586",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:45:05.760",
"Id": "48586",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "RequestHandler: Is my code clean?"
} | 48586 |
<p>I’ve recently coded a way of checking a <a href="http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits" rel="nofollow">10-digit ISBN</a>.</p>
<p>I was wondering if the code works to check the numbers, and if there are any flaws in my code.</p>
<pre><code>def isbn(number):
try:
numberreal = number
#keeps real number with "-"
numberzero = number.replace("-", "")
#this makes sure python doesnt drop the first 0 if it is at the start
number = number.replace("-", "")
number = int(number)
number = str(numberzero)
print("The ISBN Number Entered is", numberreal)
num = int(number[0]) * 10 + int(number[1]) * 9 + int(number[2]) * 8 + int(number[3]) * 7 + int(number[4]) * 6 + int(number[5]) * 5 + int(number[6]) * 4 + int(number[7]) * 3 + int(number[8]) * 2
num = num%11
checknum = 11 - num
print("The Check Digit Should Be", checknum, "and the one in the code provided was", number[9])
if int(checknum) == int(number[9]):
print("The Check Digit Provided Is Correct")
else:
print("The Check Digit Provided Is Incorrect")
except ValueError:
print("Not Valid Number")
error()
except IndexError:
print("Not 10 Digits")
error()
def error():
print("Error")
running = True
while running == True:
isbn(input("What is the isbn 10 digit number? "))
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n" + "-" * 34)
else:
print("closing Down")
running = False
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T16:33:51.653",
"Id": "86560",
"Score": "0",
"body": "I am sure that you wrote this for the learning experience, at least in part – so but if ISBN parsing is a specific thing on your to-do list, the uninventively-named PyISBN module – http://pyisbn.readthedocs.org/ – is something I can personally vouch for, as like a dependably no-nonsense and solid library.Here’s the function in their codebase that’s roughly analogous to what you posted: https://github.com/JNRowe/pyisbn/blob/master/pyisbn/__init__.py#L368-418"
}
] | [
{
"body": "<p>Right now, the code doesn't work. Your code only validates ISBNs that use Arabic numerals, but some ISBNs can end in an "X". Quoting from the <a href=\"http://www.isbn.org/faqs_general_questions#isbn_faq5\" rel=\"nofollow noreferrer\">ISBN FAQs</a>:</p>\n<blockquote>\n<p><strong>Why do some ISBNs end in an "X"?</strong></p>\n<p>In the case of the check digit, the last digit of the ISBN, the upper case X can appear. The method of determining the check digit for the ISBN is the modulus 11 with the weighting factors 10 to 1. The Roman numeral X is used in lieu of 10 where ten would occur as a check digit.</p>\n</blockquote>\n<p>So you should think about how you’d fix that first.</p>\n<h2>Comments on the existing <code>isbn()</code> function</h2>\n<p>This isn't how I'd write it. Your function doesn’t return a True/False value. The code which acts interactively, and prints things to the user, and the code which validates the ISBN, are both intertwined. I would separate the two. This will make debugging issues like the "X" easier, and you can reuse the validating function later.</p>\n<p>For example, if you wanted to enter IBSNs to a database, and verify that the entered numbers were accurate, you could get a True/False value from the function without printing to the console.</p>\n<p>Here are some general comments on the existing <code>isbn()</code> function:</p>\n<ul>\n<li><p>It's not clear what the difference between the <code>numberzero</code>, <code>numberreal</code> and <code>number</code> variables are. This is a side-effect of mixing the validation and printing code.</p>\n</li>\n<li><p>Give it a more specific name, and add a docstring (a way to document functions in Python). Later you may want to validate ISBN-13 codes, and you don't want the namespace cluttered.</p>\n</li>\n<li><p>There are better ways of handling errors than printing the word "Error" to the console. You could raise a custom <code>ValueError</code>, or something else.</p>\n</li>\n<li><p>The line which constructs <code>num</code> is excessively long: you can use <code>sum()</code> and a list comprehension to construct it in a more compact way, and it will make it clearer what formula you're using later down the line.</p>\n</li>\n<li><p>The line <code>num = num%11</code> can be replaced by <code>num %= 11</code>. Just makes things slightly neater.</p>\n</li>\n</ul>\n<p>With those points in mind, here's how I might rewrite your function:</p>\n\n<pre><code>def validate_isbn10(number):\n """A function for validating ISBN-10 codes."""\n formatted_num = number.replace("-", "")\n\n if len(formatted_num) != 10:\n raise ValueError('The number %s is not a 10-digit string.' % number)\n\n check_sum = sum(int(formatted_num[i]) * (10 - i) for i in xrange(8))\n check_sum %= 11\n check_digit = 11 - check_sum\n \n if formatted_num[-1] == "X":\n return check_digit == 10\n else:\n return check_digit == int(formatted_num[-1])\n</code></pre>\n<p>If you wanted to be able to tell the user what the correct check digit should be (in the event of an incorrectly formatted string), then you could factor our a <code>check_digit()</code> function as well.</p>\n<p>I leave it as an exercise to write a separate function which interactively prompts the user for an ISBN-10 code, and tells them whether or nots it correctly formatted.</p>\n<h2>Comments on the rest of the code</h2>\n<p>Here are some things that concern me in the rest of your code:</p>\n<ul>\n<li><p>You should wrap the interactive code in a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == "__main__":</code></a> block. This means that it will only run if the file is executed directly, but you can also <code>import</code> the file to just get the function definitions (say, if you wanted to use this ISBN validator in a larger project).</p>\n</li>\n<li><p>The line <code>while running == True:</code>. If you're going to compare to booleans, then it's much more idiomatic to write <code>while running is True:</code>, or even better, <code>while running:</code>. But that's not a good way to do it.</p>\n<p>Instead, suppose you have a <code>interactive_user_isbn()</code> function which runs the interactive session with the user. Then at the end of that function, if they want to go again, then you can ask them, and if they do, <em>call the function again</em>.</p>\n<p>Make the repeat prompt more explicit about what will be repeated, and give them a hint about what they can type to repeat the function.</p>\n<p>If they type nothing, then I would err on assuming that they don't want to go again, but that's just my opinion.</p>\n<p>Something like:</p>\n\n<pre><code>def interactive_user_isbn():\n # ask the user for an ISBN\n # check if it's correct\n # pay the user a compliment etc\n\n repeat = input("Do you want to check another number? (y/n)")\n if repeat.lower() in ["yes", "y", "ok", "sure"]:\n print("\\n")\n interactive_user_isbn()\n else:\n print("Okay, bye!")\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-17T10:40:36.360",
"Id": "87967",
"Score": "0",
"body": "thnx this is realy helpful and realy helps me learn a lot more about this sort of thing. while running: is a lot better way then I was using so thanks for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-17T05:06:06.850",
"Id": "235009",
"Score": "0",
"body": "Should be `xrange(9)` I think. See this short clip: https://www.youtube.com/watch?v=5qcrDnJg-98"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:29:33.020",
"Id": "48595",
"ParentId": "48588",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:50:12.920",
"Id": "48588",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"validation"
],
"Title": "ISBN Number Check"
} | 48588 |
<p>Is there an effective way, maybe with regex, to change the following text pattern?</p>
<p>I have a string like <code>abc_def_ghi_jkl</code>. I want to replace it to <code>AbcDefGhiJkl</code>. I currently use the following code to change it. Is there a more effective way than this?</p>
<pre><code>implode('',array_map('ucfirst',explode('_',$string)));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-09T08:55:47.323",
"Id": "258262",
"Score": "3",
"body": "What you describe is usually called PascalCase."
}
] | [
{
"body": "<p>You could use <code>preg_replace_callback()</code>, which replaces matches with the result of a function:</p>\n\n<pre><code>$str = \"abc_def_ghi_jkl\";\n$str = preg_replace_callback(\"/(?:^|_)([a-z])/\", function($matches) {\n// Start or underscore ^ ^ lowercase character\n return strtoupper($matches[1]);\n}, $str);\necho $str;\n</code></pre>\n\n<p>Whichever works for you, your solution is fine as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T08:12:45.577",
"Id": "51977",
"ParentId": "48593",
"Score": "2"
}
},
{
"body": "<p>I know, its not the latest question, but here is another solution.</p>\n\n<p>Not really pretty, but works well, is in one line and has a better performance than the solution in the question: <code>str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $str)))</code></p>\n\n<p>BTW. here are some <code>microtime</code> results from my server:</p>\n\n<pre><code>// 9.0599060058594E-6\n// \n$result = implode('',array_map('ucfirst',explode('_',$string)));\n\n// 4.2915344238281E-5\n// \n$result = preg_replace_callback(\"/(?:^|_)([a-z])/\", function($matches) {\n return strtoupper($matches[1]);\n}, $string);\n\n// 5.0067901611328E-6\n// \n$result = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $string)));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-14T09:51:06.720",
"Id": "125664",
"ParentId": "48593",
"Score": "2"
}
},
{
"body": "<p>More effective solution:</p>\n\n<pre><code>str_replace('_', '', ucwords($key, '_'));\n</code></pre>\n\n<p>From <a href=\"https://github.com/Cosmologist/Gears/blob/master/src/Gears/Str/CamelSnakeCase.php\" rel=\"noreferrer\">Gears library</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-31T15:23:25.303",
"Id": "242841",
"Score": "1",
"body": "Hi. Welcome to Code Review! Why is this solution more effective?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-02T12:05:06.977",
"Id": "243164",
"Score": "0",
"body": "Because, array_map is expensive operation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-08T09:58:06.290",
"Id": "275165",
"Score": "1",
"body": "Here's a test that proves the above point: https://repl.it/ERrZ/6 (For the lazy: `array_map`: 575ms, `str_replace`: 365ms). Suggestion: Add more of an explanation next time :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-23T03:28:53.953",
"Id": "295473",
"Score": "1",
"body": "Why not `str_replace('_', '', ucwords($key, '_'))`? It is faster and code shorter by setting delimiter directly in ucwords"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-14T11:13:05.510",
"Id": "321498",
"Score": "0",
"body": "@aokaddaoc, good solution!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-31T13:29:14.453",
"Id": "129765",
"ParentId": "48593",
"Score": "22"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T16:38:38.703",
"Id": "48593",
"Score": "16",
"Tags": [
"php",
"regex"
],
"Title": "Converting snake_case to PascalCase"
} | 48593 |
<p>Following my answer to <a href="https://codereview.stackexchange.com/questions/44936/unique-type-id-in-c/45079#45079">Unique type ID in C++</a>, I have worked towards a "safer" version that I am posting here.</p>
<p>This is a lightweight type that can store a unique (also across compilation units) ID per type for use at runtime, without RTTI.</p>
<p>Instead of using a built-in type for ID representation that is also accessible to the end user, a specific class <code>type_id_t</code> provides the external representation of the ID and encapsulates the actual storage type (a function pointer) that is <em>not</em> accessible.</p>
<p>A helper function template call <code>type_id<T>()</code> returns a <code>type_id_t</code> containing the ID of type <code>T</code>.</p>
<p>Hence, the following operations are only provided:</p>
<ul>
<li>construction <em>only</em> by calling <code>type_id</code> function.</li>
<li>copy/move construction, as implicitly defined</li>
<li>copy/move assignment, as implicitly defined</li>
<li>comparison operators <code>==</code> and <code>!=</code> between two <code>type_id_t</code>'s</li>
</ul>
<p>There is no default constructor for <code>type_id_t</code>.</p>
<p>Here is the implementation:</p>
<pre><code>class type_id_t
{
using sig = type_id_t();
sig* id;
type_id_t(sig* id) : id{id} {}
public:
template<typename T>
friend type_id_t type_id();
bool operator==(type_id_t o) const { return id == o.id; }
bool operator!=(type_id_t o) const { return id != o.id; }
};
template<typename T>
type_id_t type_id() { return &type_id<T>; }
</code></pre>
<p>It is interesting that function <code>type_id</code> returns a (function) pointer to <em>itself</em>, encapsulated into a <code>type_id_t</code>. No nasty type casting is necessary.</p>
<p>This is <em>not</em> a mechanism that provides runtime identification of a (polymorphic) object's type, but can be used as a low-level tool to build such functionality. I actually made this for the needs of my recent <a href="https://codereview.stackexchange.com/q/48344/39083">any</a>, and then improved it.</p>
<p>Just for demonstration, we can store the ID of a number of types e.g. in a vector:</p>
<pre><code>template<typename... T>
std::vector<type_id_t>
make_ids() { return {type_id<T>()...}; }
</code></pre>
<p>Later, we can compare the stored IDs to the ID of a given type:</p>
<pre><code>template<typename T, typename A>
void comp_ids(const A& a)
{
for (auto i : a)
std::cout << (type_id<T>() == i) << " ";
std::cout << std::endl;
}
</code></pre>
<p>and get the following:</p>
<pre><code>auto ids = make_ids<
int, bool, double const&, int&&, char(&)[8],
int, void(int), unsigned char**, std::vector<void(*)()>, double[4][8]
>();
comp_ids<int>(ids); // output: 1 0 0 0 0 1 0 0 0 0
</code></pre>
<p>Here is a <a href="http://coliru.stacked-crooked.com/a/f0bc04694678beaf" rel="noreferrer">live example</a>.</p>
<p>Any comments are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T08:46:04.793",
"Id": "89925",
"Score": "0",
"body": "the type id trick won't work across shared libraries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T09:00:16.880",
"Id": "89927",
"Score": "0",
"body": "@user1095108 Are you sure? I have posted a [specific question](http://stackoverflow.com/q/23437965/2644390) on this. There has been some discussion and it appears that it will work. Bottomline is that templates are defined as weak symbols and are merged into one definition at link time according to iso 3.2/5."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:33:15.220",
"Id": "418653",
"Score": "0",
"body": "Hi, is there any way, how to access type of type_id<T> later in the class? For debug purposes, would be great to be able to access some stringable object id (not pointer address). In VisualStudio, I see that sig has type t1 = {id=0x01bfdc52 {type_id<struct `....stTest>(void)} }. But I'm not able to get this value through typeid() in any way. Thanks."
}
] | [
{
"body": "<p>The first thing I notice when looking at this code is the lack of documentation.</p>\n\n<p>I would provide some more operators. Specifically I would go for <code>operator<</code> so <code>type_id_t</code> is usable as key for <code>std::map</code> and you should think about specializing <code>std::hash</code> so the class can be used with hash maps.</p>\n\n<p>As the code is pretty short I don't find any more to say about it. </p>\n\n<p>Btw.: Well done. I like this solution very much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:07:00.917",
"Id": "85335",
"Score": "1",
"body": "Thanks, very good point about `operator<` and `std::hash`! I thought `==` and `!=` should be enough for *identification*, but being able to use ID as key in an associative container sounds very essential. As for documentation, this is my weakest point--I only *hope* this page could be seen as some form of documentation :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:59:01.323",
"Id": "48600",
"ParentId": "48594",
"Score": "7"
}
},
{
"body": "<p>This is very nice, however, I usually just use:</p>\n\n<pre><code>using typeid_t = void const*;\n\ntemplate <typename T>\ntypeid_t type_id() noexcept\n{\n static char const type_id;\n\n return &type_id;\n}\n</code></pre>\n\n<p>The <code>void const*</code> pointers can be compared and hashed and cannot be dereferenced without casting. Good enough for me. The solution also avoids casts, just like your question.</p>\n\n<p>Alternatively:</p>\n\n<pre><code>using typeid_t = void(*)();\n\ntemplate <typename T>\ntypeid_t type_id() noexcept\n{\n return typeid_t(type_id<T>);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-18T09:04:31.520",
"Id": "288912",
"Score": "0",
"body": "Doesn't work across the shared libraries. The one with the function template instantiation address does work however."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-18T09:28:31.320",
"Id": "288914",
"Score": "0",
"body": "could be you did not export the function. Anyway, I've provided an alternative now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-20T19:25:34.797",
"Id": "409709",
"Score": "0",
"body": "Doesn't work with VS :( it always return same address."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-20T20:48:11.033",
"Id": "409724",
"Score": "0",
"body": "@DawidDrozd if you instantiate it with the same `T`, this is what it should do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-20T23:23:39.620",
"Id": "409732",
"Score": "0",
"body": "@user1095108 nope with different T don't work see yourself... https://rextester.com/QGW35526"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-21T15:50:37.330",
"Id": "409809",
"Score": "1",
"body": "@DawidDrozd put `static` in front of the function definition, there's always a way around vc++ strangeness. I always use this function as a class member not as a free function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-21T16:56:44.917",
"Id": "409812",
"Score": "0",
"body": "@user1095108 seems to work but still I'm not so sure about it. We will see ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-21T18:01:22.457",
"Id": "409817",
"Score": "0",
"body": "`static char` trick works ok, I don't know why you are complicating, there are other approaches too, including a `constexpr` typeid, google for it."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-11-17T19:04:36.780",
"Id": "70112",
"ParentId": "48594",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:24:25.737",
"Id": "48594",
"Score": "20",
"Tags": [
"c++",
"c++11",
"rtti"
],
"Title": "Unique type ID, no RTTI"
} | 48594 |
<p>I always been curious on how to build great application with proper routing to my controllers, but after seeing some sources of applications like Xenforo, Joomla, it seems completely different, and mostly I can't understand them.</p>
<p>From my understanding the user sends a request to the web-server, the controller's job is to get the request, check out how is the request sending (to check if the request was done via XHR, etc) and then checking the sent GET requests and get the correct controller for the sent request, which will do the rest of the work.</p>
<p>This is what I exactly do currently, but I feel like my way is a bit not 'dynamic' as I have to put each controller's object into the switch statement.</p>
<p>This is my router class:</p>
<pre><code>namespace library;
/**
* Controllers
*/
use library\controllers\Controller,
library\controllers\ChatController;
/**
* Class Router
* @package library
*/
class Router {
private $instance;
public function __construct(AsynChat $instance) {
$this->instance = $instance;
}
/**
* Deciding which routing channel to take.
*/
public function processRoutingChannel() {
if ($this->instance->getRequest()->isXHR()) {
$this->routeXHR();
return;
}
$this->route();
}
/**
* Handling a regular, visual web request.
*/
private function route() {
$request = $this->instance->getRequest();
$controller = null;
switch ($request->getGet(Config::$DEFAULT_GET_DIRECTOR)) {
default:
$controller = new ChatController($this->instance);
break;
}
$controller->register();
$controller->initializeTemplate();
}
/**
* Handling response for an AJAX request header.
* returns the needed data.
*/
private function routeXHR() {
$request = $this->instance->getRequest();
$controller = null;
switch ($request->getPost(Config::$DEFAULT_XHR_DIRECTOR)) {
case "chat":
$controller = new ChatController($this->instance);
break;
default:
break;
}
$controller->initializeAjaxResponse();
}
}
</code></pre>
<p>I simply create a new router object and add the main object to it, which contains all the objects like request, database, session and so on.</p>
<p>And then I do <code>$router->processRoutingChannel();</code></p>
<p>I am pretty sure the way I am doing this, is pretty 'Ghetto'.</p>
<p>Is there anything wrong you can tell? What is the best way to do so?</p>
<p>In my controllers, <code>register()</code> method makes the controller start doing it's job, and <code>initializeTemplate()</code> method forces the controller to draw the page, as in include the template.</p>
| [] | [
{
"body": "<p>Kid Diamond has asked for the opinions of other on the subject of routing and whats the best practice to code and he has shown his code.\n<a href=\"https://codereview.stackexchange.com/questions/48396/router-for-mvc-framework-is-it-oo-and-good-to-go\">Here is the link</a></p>\n\n<p>Now I believe that what was said in that thread would be applicable to your thread too considering you wish to know about best way. So i would suggest to take a look at that.</p>\n\n<p>Now secondly: Joomla, Magento, Wordpress and all that - should not be your base to design any routing system. Those aren't frameworks.</p>\n\n<p>Take a look at Symfony 2, Laravel, etc for a better understanding because their routing system are packages and can work as a stand alone system.</p>\n\n<p>As far as the code itself - I will leave those improvements to others to comment on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:11:40.110",
"Id": "48605",
"ParentId": "48597",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48605",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T17:44:33.550",
"Id": "48597",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"mvc",
"url-routing"
],
"Title": "Routing the CMS way"
} | 48597 |
<p>I have written this Perl program to prove a conjecture given a set of clauses. I've actually posted some code from it on here in another question. </p>
<p>This time its all done and I've made it as fast as I need to make it. </p>
<p>Now, I want to calculate the Big O notation of the program. It's something I want to get better at because I learned it in a class last year but I was never very good at it.</p>
<p>I believe the Big O to be \$O(n^4)\$, but like I said, I'm no expert so I'm asking you to help me out. </p>
<p>Also, feel free to criticize my code if you feel it's sub-par. </p>
<pre><code>#!/usr/bin/perl
use v5.14;
#use warnings;
use Getopt::Long; #use with options
$|=1;
# This program uses resolution refutation, using a breadth-first and set of
# support strategy to generate a proof(if possible) and relay the results to
# the user.
# Subsumption can be turned on with the --sub option.
# This is recommended in most cases.
#Algorithm:
#1.) Add the negation of the conjecture to the SOS set.
#2.) For each clause (S) is the SOS.
# 3.)For each clause (C) in the knowledge base
# 4.) Compare clause S to clause C
# 5.) If subsumption is possible, perform subsumption.
# 6.) If resolution is possible, perform the resolution.
# 7.) If the newly generated clause is the null clause: Go to 13.
# 8.) Otherwise, check to see if the newly generated clause is already in
# the knowledge base:
# 9.) If the clause is already in the knowledgebase: Go to 3.
# 10.) Else (if the clause is not already in the knowledge base):
# 11.)Add the clause to the SOS.
# 12.)Add the clause to the knowledge base
#13.) If the null clause was generated, you have proved the conjecture to be
#true. If it was not generated, the conjecture was false.
#14.) Inform the user accordingly
my $conclusion;
my $conclusion2;
my @conclusion;
my @SOS;
my @clauses;
my $found=0;
my $subsumption=0;
GetOptions( 'sub' => \$subsumption);
#batch mode
if($ARGV[0])
{
my $filename = $ARGV[0];
open(IN, "<", $filename);
chomp(@clauses=<IN>);
close(IN);
#additional clean up
for(@clauses)
{
$_ =~ s/[^A-Za-z~,]//g;
}
#negate the negation to get the desired conclusion for later
$conclusion2=$clauses[$#clauses];
@conclusion = split("", $conclusion2);
if($conclusion[0] eq '~')
{
splice(@conclusion, 0, 1);
$found=1;
}
if (!$found)
{
$conclusion = "~$conclusion2";
}
else
{
$conclusion = join("", @conclusion);
}
#now break up each line and make @clauses 2d
$_ = [split /,/ ] for @clauses;
}
#interactive mode
else
{
my $count=0;
say "Welcome to my Theorem Prover!";
say "How many clauses are in your knowledge base?";
say "(this does not include the conclusion)";
print "Amount: ";
my $amt = <>;
say "Enter your clauses: ";
say "Negations can be indicated with a '~'.";
say "Variable names must contain only letters.";
say "Separate each literal with a ',' and be sure not to use the same";
say "variable twice in the same clause\n";
while($count < $amt)
{
print "clause $count:";
$clauses[$count] .= <>;
$clauses[$count] =~ s/[^A-Za-z~,]//g;
$count++;
print "\n";
}
print "\n \n \n Enter the conjecture, the conjecture should be a literal:";
$conclusion = <>;
$conclusion =~ s/[^A-Za-z~]//g;
print "\n";
#negate the conclusion and add it to the set of clauses.
@conclusion = split("", $conclusion);
if($conclusion[0] eq '~')
{
splice(@conclusion, 0, 1);
$found=1;
}
if (!$found)
{
$conclusion2 = "~$conclusion";
}
else
{
$conclusion2 = join("", @conclusion);
}
#add the new conclusion and make @clauses 2d
$_ = [split /,/ ] for @clauses;
$clauses[$count][0] = $conclusion2;
}
#sort all clauses
for my $unsorted (0 .. $#clauses)
{
@{ $clauses[$unsorted] } = sort ( @{ $clauses[$unsorted] });
}
print "Beginning search ....";
##################################################
#Begin search algorithm
$SOS[0][0] = $conclusion2;
my $initial = $#clauses;
my $offset = 1;
my %known_clauses;
for my $i (0 .. $#clauses)
{
my $key = join ( '', sort(@{$clauses[$i]}));
$known_clauses{$key} = $i;
}
my $subs = 0;
say "\nworking......";
my %generated_with; #for use when printing
my $flag = 0; #for use when printing
SOS_ROW:
for (my $sos_row = 0; $sos_row <=$#SOS; $sos_row++)
{
&display_status($sos_row);
my $current_sos_row = $SOS[$sos_row];
CLAUSE_ROW:
for (my $clause_row = 0; $clause_row <= $#clauses ; $clause_row++)
{
if($subsumption)
{
my $matches = 0;
for (@{$SOS[$sos_row]})
{
if ($_ ~~ @{$clauses[$clause_row]})
{
$matches++;
}
}
my $size = @{$clauses[$clause_row]};
if ($matches == $size)
{
splice (@clauses, $clause_row, 1);
$clause_row--;
$subs++;
}
}
my $current_clause_row = $clauses[$clause_row];
my @new_clause = sort (&resolves($current_sos_row,$current_clause_row));
my $new_clause = join ('', @new_clause);
if(!($new_clause eq '0'))
{
#resolution occurred, so check to see if
#the clause already exists before adding it in.
if( exists $known_clauses{$new_clause})
{
next CLAUSE_ROW;
}
#okay its new, so add it to the sets
push(@SOS, \@new_clause);
push(@clauses, \@new_clause);
my $current_clause = $initial + $offset;
$known_clauses{$new_clause} = $current_clause;
#also, remember which clauses generated this one
my $g1 = $known_clauses{join ('', @{$current_clause_row})};
my $g2 = $initial + $sos_row;
$generated_with{$current_clause} = "($g1,$g2)";
#if resolution occurred, but $new_clause is empty
$offset++;
if(!$new_clause)
{
$flag = 1;
}
if($flag == 1)
{
last SOS_ROW;
}
}
}
}
open(RESULTS, ">", 'results.txt');
say RESULTS "\n";
&printClauses;
if($subsumption)
{
say RESULTS "\n\n $subs subsumptions were made.";
}
if($flag)
{
say RESULTS "\n\nGood news! A resolvent was found and the empty set was generated.";
say RESULTS "This means that when the negation of '$conclusion' is added to the knowledge base, a contradiction renders the knowledge base false.";
say RESULTS "Because we know that the clauses in the knowledge base are actually true, we can soundly conclude that '$conclusion' must also be true.";
say RESULTS "The clauses generated by each resolution can be found above.\n\n\n";
}
else
{
say RESULTS "\n\nUnfortunately, we were not able to generate the empty clause.";
say RESULTS "This means that adding the negation of the desired conclusion does not create a contradiction in our knowledge base.";
say RESULTS "Therefore, we can not safely conclude that '$conclusion' is true.";
say RESULTS "Any clauses that we were able to generate through a resolution can be viewed above\n\n\n";
}
print `more results.txt`;
close(RESULTS);
#if a resolution is possible, return the new clause as an array
#if not, return 0.
sub resolves
{
my $removed;
my @sosR = @{$_[0]};
my @clauseR = @{$_[1]};
my %seen;
for(@sosR)
{
$seen{$_}= 1;
}
SOS:
for my $i (0 .. $#sosR)
{
for my $j (0 .. $#clauseR)
{
if("$sosR[$i]" eq "~$clauseR[$j]"
|| "$clauseR[$j]" eq "~$sosR[$i]")
{
splice(@sosR, $i, 1);
splice(@clauseR, $j, 1);
$removed = 1;
last SOS;
}
}
}
if(!$removed)
{
return 0;
}
for(@clauseR)
{
if(!$seen{$_} )
{
push(@sosR, "$_");
}
}
return @sosR;
}
sub display_status
{
my ($round) = @_;
print "\n" if $round % 35 == 0;
print ".";
}
sub printClauses
{
foreach my $name (sort { $known_clauses{$a} <=> $known_clauses{$b} } keys %known_clauses)
{
my $indx = $known_clauses{$name};
my $clause = "clause $indx:\t";
$clause .= "{";
my @name = split ('', $name);
for my $i (0 .. $#name)
{
$clause.= $name[$i];
unless ($i == $#name || $name[$i] eq "~")
{
$clause .= ",";
}
}
$clause .= "}";
#will generate some warnings (because the initial clauses have no parents to print)
printf RESULTS ("%-25s\t%15s\n", $clause, $generated_with{$known_clauses{$name}});
if($indx == $initial)
{
say RESULTS "____________________________________________________________________";
}
}
}
</code></pre>
<p><strong>EDIT:</strong> Some sample input-output to help you understand:</p>
<p>Command line usage: <code>perl ResRef.perl clauses.txt</code></p>
<p>Input file: clauses.txt </p>
<pre><code>a,b,c
~b,c
~c
~a
</code></pre>
<p>(The clauses in the knowledge base are the first 3 lines and the last line is the negated conjecture, so we are trying to prove a is true.)</p>
<p>Output would be something like this:</p>
<pre><code>clause 0: {a,b,c}
clause 1: {~b,c}
clause 2: {~c}
clause 3: {~a}
________________________
clause 4: {b,c} (0,3)
clause 5: {c} (1,4)
clause 6: {b} (2,4)
clause 7: {} (2,5)
</code></pre>
<p>Good news! We found the empty clause.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:21:14.703",
"Id": "85339",
"Score": "1",
"body": "To help us understand what this code does, could you provide some sample inputs and outputs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:05:03.897",
"Id": "85343",
"Score": "0",
"body": "Why is `use warnings;` commented out? You should also add `use strict;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:06:55.603",
"Id": "85344",
"Score": "0",
"body": "Also, Perl has cool things like `$flag = 1 unless $new_clause`. Not sure if you purposely avoided it – I'm actually not sure if this could be considered bad practice (I'm not that proficient in Perl)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:12:08.077",
"Id": "85345",
"Score": "0",
"body": "use 5.14 takes care of use strict and I turned off the warnings after I was done writing the program because It always produces some annoying warnings in the beginning. I know why they appear and it doesn't effect the program."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:02:50.587",
"Id": "48602",
"Score": "2",
"Tags": [
"perl",
"complexity"
],
"Title": "Proving a conjecture given a set of clauses - calculating complexity"
} | 48602 |
<p>I created a DAO class which is base class for all other DAO classes. </p>
<p>I use Spring Framework 4 and Hibernate 4.</p>
<p><strong>Question:</strong> Is there anything that could be done better? </p>
<pre><code>public class GenericDaoImpl<E, I extends Serializable> implements GenericDao<E, I> {
private Class<E> entityClass;
@Autowired
private SessionFactory sessionFactory;
public GenericDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
@Override
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
@Override
@SuppressWarnings("unchecked")
public List<E> findAll() throws DataAccessException {
return getCurrentSession().createCriteria(entityClass).list();
}
@Override
@SuppressWarnings("unchecked")
public E find(I id) {
return (E) getCurrentSession().get(entityClass, id);
}
@Override
public void create(E e) {
getCurrentSession().save(e);
}
@Override
public void update(E e) {
getCurrentSession().update(e);
}
@Override
public void delete(E e) {
getCurrentSession().delete(e);
}
@Override
public void flush() {
getCurrentSession().flush();
}
}
</code></pre>
<p>Sample DAO class which extends base DAO class is for example this one:</p>
<pre><code>@Repository("articleDao")
public class ArticleDaoImpl extends GenericDaoImpl<ArticleEntity, Long> implements ArticleDao {
public ArticleDaoImpl(){
super(ArticleEntity.class);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T18:17:43.130",
"Id": "85804",
"Score": "0",
"body": "I would shorten `getCurrentSession` to `getSession` which is clear enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T18:50:09.053",
"Id": "86412",
"Score": "0",
"body": "@DavidHarkness It is the same as original name from `sessionFactory`. I don't think that it is an improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-01T15:00:50.087",
"Id": "262549",
"Score": "0",
"body": "Where is the Uses for `I`"
}
] | [
{
"body": "<p>To be able to create a parameter-less constructor add the following code into your constructor. It will use reflection to set <code>entityClass</code>. This way you don't even need to worry about passing in a class type, you can extend out your generic DAO and its type will be set by parameterisation.</p>\n\n<pre><code>public GenericDaoImpl() {\n Type e = getClass().getGenericSuperclass();\n ParameterizedType pt = (ParameterizedType) e;\n entityClass = (Class<E>) pt.getActualTypeArguments()[0];\n}\n</code></pre>\n\n<p>This removes the need for having constructors in subclasses of your <code>GenericDAOImpl</code>.</p>\n\n<p>Why don't you combine your create and update methods? It makes for easier service calls.</p>\n\n<pre><code>@Override\npublic void saveOrUpdate(E e){\n getCurrentSession().saveOrUpdate(e);\n}\n</code></pre>\n\n<p>Hibernate will automatically make the determination whether a save or update call is appropriate. If your ID field is set, then perform an update, otherwise perform a save.</p>\n\n<p>Also, I would remove <code>getCurrentSession()</code> from your interface and change the method to private. You shouldn't be accessing the Hibernate session from anywhere outside the DAO so there is no reason to expose out your <code>getCurrentSession()</code> method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-16T04:50:55.080",
"Id": "49906",
"ParentId": "48603",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T18:12:20.633",
"Id": "48603",
"Score": "5",
"Tags": [
"java",
"hibernate",
"spring"
],
"Title": "Create better Base DAO class"
} | 48603 |
<p>Some programming languages provide a built-in (primitive) rational data type to represent rational numbers and to do arithmetic on them (e.g. the ratio type of Common Lisp and analogous types provided by most languages for algebraic computation, such as Mathematica and Maple).</p>
<p>Many languages that do not have a built-in rational type still provide it as a library-defined type.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:13:05.257",
"Id": "48606",
"Score": "0",
"Tags": null,
"Title": null
} | 48606 |
In mathematics, a rational number is any number that can be expressed as the quotient or fraction p/q of two integers, with the denominator q not equal to zero. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:13:05.257",
"Id": "48607",
"Score": "0",
"Tags": null,
"Title": null
} | 48607 |
<p>I am making a Swing application for light local database management and I have the button <code>Run XAMPP</code>.</p>
<p>When that button is pressed this code is executed:</p>
<pre><code>private void jRunXAMPPButtonActionPerformed(java.awt.event.ActionEvent evt)
{
String[] paths = {"C:\\xampp\\xampp-control.exe",
"C:\\Program Files\\xampp\\xampp-control.exe",
"C:\\Program Files (x86)\\xampp\\xampp-control.exe"};
for (String path : paths) {
final File file = new File(path);
if (file.exists()) {
try {
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
} catch (IOException e) {
continue;
}
return;
}
}
Helper.printErrln("xampp-control.exe was not found or is corrupt!"); // Prints error in red
}
</code></pre>
<p>I basically have the three possible paths that xampp could be at and I go through them and check if the file exists and can be executed. If not then it prints the error that the file could not be found or is corrupt.</p>
<p>Do you have any tips for my code? Any better way of doing this and I'm especially concerned that my error handling is not that great.</p>
| [] | [
{
"body": "<ul>\n<li>Give your method a <em>proper</em> name. These auto-generated names are pure terror!</li>\n<li>You can import <code>ActionEvent</code> directly, no need to reference it with the entire package name.</li>\n<li>Your formatting is unusual at best, I'd call it bad. I know this is, for some reason, the preferred way to set braces in the Linux kernel code, but this is Java, not C.</li>\n<li>You are using hard-coded file paths. Absolute no-go. What if the user named his main partition <code>D</code> or installed xampp somewhere else – or is using Mac or Linux?</li>\n<li>Why are you storing the result in <code>Process p</code> if you never use that variable?</li>\n<li>\" // Prints error in red\" is a comment that is both completely useless (why do I need to know this right then and there?) and will rot faster than you can imagine.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T13:17:07.897",
"Id": "86733",
"Score": "0",
"body": "Because I am creating a simple software for mostly personal use (for now) I am not interested in either Linux, Mac or the possibility of the path being something completely different. As for your other points I believe you are right except the braces, I like keeping braces that way since I work with both Java and C++ and it keeps my code generally consistent between the two."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:19:01.687",
"Id": "48611",
"ParentId": "48608",
"Score": "5"
}
},
{
"body": "<p>I agree 100% with <a href=\"https://codereview.stackexchange.com/users/41406/ingo-burk\">@ingo-burk</a>'s answer. Here are a few points on top of that.</p>\n\n<p>You could load the paths from a <code>.properties</code> file quite easily, for example given a properties file on the classpath:</p>\n\n<pre><code># config.properties\npaths = C:/xampp/xampp-control.exe|C:/Program Files/xampp/xampp-control.exe|C:/Program Files (x86)/xampp/xampp-control.exe\n</code></pre>\n\n<p>and this Java code:</p>\n\n<pre><code>private static final String PROPERTIES_FILENAME = \"player.properties\";\nprivate static final String PATHS_PROPERTY = \"paths\";\nprivate static final String ITEM_SEPARATOR = \"|\";\n\nprivate String[] getPaths(String filename, String propName) throws IOException {\n InputStream input = this.getClass().getClassLoader().getResourceAsStream(filename);\n if (input == null) {\n return new String[0];\n }\n Properties prop = new Properties();\n prop.load(input);\n input.close();\n return prop.getProperty(propName, \"\").split(ITEM_SEPARATOR);\n}\n\nprivate String[] getPaths(String filename) throws IOException {\n return getPaths(filename, PATHS_PROPERTY);\n}\n\nString[] getPaths() throws IOException {\n return getPaths(PROPERTIES_FILENAME, PATHS_PROPERTY);\n}\n</code></pre>\n\n<p>Notice that I changed all the path separators from <code>\\\\</code> to <code>/</code>. Java figures out the correct path separator in the operating system, and it's simpler to type this way.</p>\n\n<p>Btw, if the executable is always called <code>xampp-control.exe</code> then perhaps you can put that name in its own property, and remove the duplication from <code>paths</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T13:19:08.673",
"Id": "86734",
"Score": "0",
"body": "Hmmm I already have a method for checking if a property file is corrupted or missing and for getting a specific property from a property file so I guess I can use my code and save some time. All in all I like this approach. Also yes the file will always be called `xampp-control.exe`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T11:45:44.847",
"Id": "49326",
"ParentId": "48608",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "48611",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:14:29.950",
"Id": "48608",
"Score": "4",
"Tags": [
"java",
"swing",
"file",
"error-handling"
],
"Title": "Executing a file through a swing button"
} | 48608 |
<p>Quoted from the manpage:</p>
<blockquote>
<p>tcsh is an enhanced but completely compatible version of the Berkeley
UNIX C shell csh It is a command language interpreter usable both as
an interactive login shell and a shell script command processor. It
includes a command-line editor, programmable word completion, spelling
correction, a history mechanism, job control and a C-like syntax.</p>
</blockquote>
<p><code>tcsh</code> is the default shell on FreeBSD & DragonFly BSD, and was the default shell on earlier versions on Mac OS X.</p>
<p>Official site: <a href="http://www.tcsh.org/" rel="nofollow">http://www.tcsh.org/</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:18:26.223",
"Id": "48609",
"Score": "0",
"Tags": null,
"Title": null
} | 48609 |
tcsh is an enhanced but completely compatible version of the Berkeley UNIX C shell, csh. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:18:26.223",
"Id": "48610",
"Score": "0",
"Tags": null,
"Title": null
} | 48610 |
<p>Once you define the <code><</code> operator, you can have an estimation of how the rest of relational operators behave. I'm trying to implement a way to do that for my classes. </p>
<p>What I want is to <strong>define only the <code><</code> and the rest of the operators to be defaulted implicitly</strong>. What I've got so far is <a href="https://github.com/picanumber/bureaucrat/blob/master/inheritable_behaviors.h">this design</a>, which I'll elaborate on further down:</p>
<pre><code>template<typename T>
struct relational
{
friend bool operator> (T const &lhs, T const &rhs) { return rhs < lhs; }
friend bool operator==(T const &lhs, T const &rhs) { return !(lhs < rhs || lhs > rhs); }
friend bool operator!=(T const &lhs, T const &rhs) { return !(rhs == lhs); }
friend bool operator<=(T const &lhs, T const &rhs) { return !(rhs < lhs); }
friend bool operator>=(T const &lhs, T const &rhs) { return !(lhs < rhs); }
};
</code></pre>
<p>So for a class that implements the <code><</code> operator it would just take inheriting from <code>relational</code> to have the rest of the operators defaulted. </p>
<pre><code>struct foo : relational<foo>
{
// implement < operator here
};
</code></pre>
<ol>
<li>Are there any alternative, better designs? </li>
<li>Is there a time bomb in this code? </li>
<li><p>While trying to use this code with classes that already defined one of { >, ==, !=, <=, >= } I had ambiguity problems. The implementation I opted for (also the one existing in the linked Github repository) is tweaked like so </p>
<pre><code>// inside the relational struct
friend bool operator>(relational const &lhs, relational const &rhs)
{ // functions that involve implicit conversion are less favourable in overload resolution
return (T const&)rhs < (T const&)lhs;
}
</code></pre></li>
</ol>
<p>Are my problems over with this trick?</p>
<p>Here's a <a href="http://ideone.com/Ck7Z6k">demo of the code working</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:11:34.997",
"Id": "85363",
"Score": "2",
"body": "I unfortunately don't have much to say, but if you're wanting to see a well-established, fully fleshed out version of your concept, you could take a look at Boost.Operators: http://www.boost.org/doc/libs/1_55_0b1/libs/utility/operators.htm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:36:16.580",
"Id": "85365",
"Score": "2",
"body": "Another alternative is [`std::rel_ops`](http://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp). These are often criticized as \"greedy and unfriendly\" but I think this is only because they have only one template parameter. With two different parameters for `lhs` and `rhs`, I don't think there would be any ambiguities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T06:14:50.777",
"Id": "85392",
"Score": "0",
"body": "Note: There is already an answer at http://stackoverflow.com/questions/23388739/c-relational-operators-generator"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T06:36:03.777",
"Id": "85395",
"Score": "0",
"body": "@DieterLücking Check the edit log of this question. I was mentioning that I din't got enough input there, that's why I'm asking here. Then Jamal edited that bit out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T07:36:48.880",
"Id": "85398",
"Score": "0",
"body": "@NikosAthanasiou Now, I would down vote the edit of Jamal, if possible - sorry."
}
] | [
{
"body": "<p>The problem I see is that it requires that the class be derived from <code>relational</code>, which is not a very durable design. Instead, why not use the fact that <strike>\"substitution failure is not an error\" (which has the regrettable but commonly used abbreviation SFINAE).</strike> the use of real functions is preferred over the instantiation of templates. That is, if an <code>operator<=</code> actually exists, the templated form will be ignored. That might look like this:</p>\n\n<pre><code>template<typename T>\nbool operator> (T const &lhs, T const &rhs) { return !(lhs <= rhs); }\ntemplate<typename T>\nbool operator< (T const &lhs, T const &rhs) { return !(lhs >= rhs); }\ntemplate<typename T>\nbool operator==(T const &lhs, T const &rhs) { return lhs <= rhs && lhs >= rhs; }\ntemplate<typename T>\nbool operator!=(T const &lhs, T const &rhs) { return !(rhs == lhs); }\ntemplate<typename T>\nbool operator<=(T const &lhs, T const &rhs) { return lhs < rhs || (!(rhs < lhs)); }\ntemplate<typename T>\nbool operator>=(T const &lhs, T const &rhs) { return lhs > rhs || (!(rhs > lhs)); }\n</code></pre>\n\n<p>Note that the differences are that I've made each comparison operator its own template and that I've added one for <code><</code> and defined <code><=</code> and <code>>=</code> in terms of <code><</code> and <code>></code> respectively.</p>\n\n<p>The result is that if any of the comparisons <code><</code>, <code><=</code>, <code>></code> or <code>>=</code> are defined, then all of the other comparisons are also available.</p>\n\n<p><strong>Edit:</strong> I should probably have pointed out why this is different from <code>std::rel_ops</code>. With <code>std::rel_ops</code>, in order to have all six relative operators, you must define <code>operator<</code> and <code>operator==</code>. With this scheme, however, as long as at least one of the ordering operators is defined, all others will also be available. This is due to the way these templates are deliberately circularly defined. That is, <code>></code> is defined in terms of <code><=</code> which is defined using <code><</code> which is defined using <code>>=</code> which is defined using <code>></code>. This arguably adds flexibility, but it also means that it's possible that the performance is not as good because a comparison may go through several templated function instantiations. </p>\n\n<p>Further, if <em>none</em> of those operators is defined, that circular definition will mean infinite recursion at runtime until your stack is exhausted, putting this set of templates into the category of \"perhaps more dangerous than clever\" so <em>Caveat lector.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:23:33.950",
"Id": "85415",
"Score": "1",
"body": "This is exactly the logic of [`std::rel_ops`](http://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp). You should definitely define those inside a *namespace*. Also, if you don't use two different template parameters for `lhs`, `rhs`, ambiguities are on the way and some people may hate you some time. Plus, I don't see any SFINAE here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T12:14:45.900",
"Id": "85436",
"Score": "0",
"body": "It's substantively and deliberately different from the logic of `std::rel_ops` because unlike that, it's carefully designed not to care *which* of the four named relational operators is defined. They are circularly defined as `{ > , <=, <, >= }` where each element is defined in terms of the next element while `std::rel_ops` insists on definitions of operators `<` and `==` only. This flexibility, however, is purchased with a potential performance hit. And you're right - it's not SFINAE, it's \"real functions are preferred over template instantiation.\" I'll update the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:23:56.467",
"Id": "85439",
"Score": "1",
"body": "I meant the fact that they are generic function templates rather than concrete functions for the type you are defining, so that you don't need to derive anything. I didn't mean the exact computations. Performance is an important point indeed. We should be aware of the cost of our laziness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T16:36:57.080",
"Id": "86028",
"Score": "0",
"body": "@iavr I think this design is wrong. And it takes only one argument to prove it. If this code exists in a code base, every class (that 'sees' the header) that defines `<` will have all other operations defined **whether you want it or not**. The concept of explicitly deriving from an empty base as `relational` is not a problem but a solution. `std::rel_ops` kind of bypasses this by requiring its namespace to be explicitly brought into scope, because that scope may have objects that should have nothing implicitly generated for them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T16:43:03.890",
"Id": "86029",
"Score": "0",
"body": "@NikosAthanasiou: I believe that was the point of iavr's first comment that these should be placed inside a namespace (and I would add ... if you use them at all)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T01:48:21.410",
"Id": "48633",
"ParentId": "48622",
"Score": "3"
}
},
{
"body": "<p>First, you should seriously consider if you want keep you design (also in <a href=\"http://www.boost.org/doc/libs/1_55_0b1/libs/utility/operators.htm\" rel=\"nofollow noreferrer\">boost/operators.hpp</a>) where a class inherits its operators from a base, <em>or</em> the design of <a href=\"http://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp\" rel=\"nofollow noreferrer\">std::rel_ops</a> and <a href=\"https://codereview.stackexchange.com/a/48633/39083\">Edwards's answer</a>, where operators are defined as generic function templates. I think there are plus'es and minus'es, so there is no clear winner.</p>\n\n<p>Assuming you want to keep your design, I find two issues:</p>\n\n<ul>\n<li><p>It's better to design operators to match exactly rather than require conversions; otherwise, ambiguities and surprises will come sooner or later. One way to achieve this while being able to override the default behaviour is to <strong>separate interface from implementation</strong>.</p></li>\n<li><p>This class makes things more convenient for the programmer, but officially accepts their laziness, at the cost of runtime performance. It is also possible to reduce code through <strong>implementation that is generic with respect to operators</strong>, at no performance loss.</p></li>\n</ul>\n\n<hr>\n\n<p>Here is my suggestion, dealing with both issues, but staying as close as possible to your design:</p>\n\n<pre><code>template<typename T>\nstruct relational\n{\n // cast to base/derived class\n static const relational&\n base(T const& a) { return static_cast <const relational&>(a); }\n\n const T& der() const { return static_cast<const T&>(*this); }\n\n // interface: relational operators\n friend bool operator< (T const &a, T const &b) { return base(a).compare(op::lt(), b); }\n friend bool operator> (T const &a, T const &b) { return base(a).compare(op::gt(), b); }\n friend bool operator==(T const &a, T const &b) { return base(a).compare(op::eq(), b); }\n friend bool operator!=(T const &a, T const &b) { return base(a).compare(op::ne(), b); }\n friend bool operator<=(T const &a, T const &b) { return base(a).compare(op::le(), b); }\n friend bool operator>=(T const &a, T const &b) { return base(a).compare(op::ge(), b); }\n\n // private dispatcher, to be called by relational operators\n template<typename F>\n bool compare(F f, T const &b) const { return der().comp(f, b); }\n\nprotected:\n // protected implementation, possibly overriden, to be called by compare\n bool comp(op::gt, T const &b) const { return b < der(); }\n bool comp(op::eq, T const &b) const { return !(der() < b || der() > b); }\n bool comp(op::ne, T const &b) const { return !(b == der()); }\n bool comp(op::le, T const &b) const { return !(b < der()); }\n bool comp(op::ge, T const &b) const { return !(der() < b); }\n};\n</code></pre>\n\n<p>Here, operators are defined for <code>T</code> as in your original design and not for the base class as in your eventual workaround. When a derived class needs to define anything else than <code>operator<</code>, it overrides <code>comp</code> rather than defining a relational operator directly. <code>comp</code> is the implementation. <code>operator@</code> is the interface.</p>\n\n<p>Operators are represented by <em>function objects</em> like <code>op::lt</code>, <code>op::gt</code> etc. More on them below. Hence a derived class can override just a single overload of <code>comp</code>, or all of them with a template.</p>\n\n<p><code>base</code> and <code>compare</code> are not very important; they are only needed to make accessible to the operators what is accessible to <code>relational</code>.</p>\n\n<hr>\n\n<p>Let's look at an example:</p>\n\n<pre><code>template<typename... T>\nclass direct : std::tuple<T...>, public relational<direct<T...>>\n{\n friend relational<direct>;\n using U = std::tuple<T...>;\n const U& tup() const { return static_cast<const U&>(*this); }\n\n // override all functions\n template<typename F>\n bool comp(F f, const direct &b) const { return f(tup(), b.tup()); }\n\npublic:\n using U::U;\n};\n</code></pre>\n\n<p><code>direct</code> derives an <code>std::tuple</code> both for data storage and for providing <em>lexicographical</em> comparisons. It defines <em>all comparison operators</em> by overriding <em>all</em> overloads of <code>comp</code> with a single template.</p>\n\n<hr>\n\n<p>A second example is like <code>direct</code> but reverses the relational operators:</p>\n\n<pre><code>template<typename... T>\nclass reverse : std::tuple<T...>, public relational<reverse<T...>>\n{\n friend relational<reverse>;\n using relational<reverse>::comp;\n using U = std::tuple<T...>;\n const U& tup() const { return static_cast<const U&>(*this); }\n\n // override operator< only, rest is automatically generated\n bool comp(op::lt, const reverse &b) const { return tup() > b.tup(); }\n\npublic:\n using U::U;\n};\n</code></pre>\n\n<p>It overrides only one overload of <code>comp</code>, the rest are as defined in the base class <code>relational</code>, but this comes at a runtime cost. I call it the <strong>lazy</strong> version. Why? Because with a little more typing, we could avoid the cost:</p>\n\n<pre><code>template<typename... T>\nclass reverse : std::tuple<T...>, relational<reverse<T...>>\n{\n friend relational<reverse>;\n using U = std::tuple<T...>;\n const U& tup() const { return static_cast<const U&>(*this); }\n\n // override all functions (in fact, only == and !=)\n template<typename F>\n bool comp(F f, const reverse &b) const { return f(tup(), b.tup()); }\n\n // override remaining functions, each separately\n bool comp(op::lt, const reverse &b) const { return tup() > b.tup(); }\n bool comp(op::gt, const reverse &b) const { return tup() < b.tup(); }\n bool comp(op::le, const reverse &b) const { return tup() >= b.tup(); }\n bool comp(op::ge, const reverse &b) const { return tup() <= b.tup(); }\n\npublic:\n using U::U;\n};\n</code></pre>\n\n<p>This overrides all overloads of <code>comp</code>, manually. Code is longer, but there is no runtime cost. It's better to do this if the cost of comparison is low. We might prefer the lazy version if the cost of high (e.g. lexicographical comparison with more the 10 elements), so our \"laziness\" penalty is proportionally small. One exception is <code>operator==</code> (also inherited by <code>!=</code>), which <em>doubles</em> the lexicographical comparison cost, so you'd better manually override <code>==</code> as well (then <code>!=</code> will be fine). The point is: <strong>think about the cost of being lazy</strong>.</p>\n\n<hr>\n\n<p>Here is how we would use the above examples:</p>\n\n<pre><code>direct <int,int> d1{5,2}, d2{6,1}, d3{6,5}, d4{6,5};\nreverse<int,int> r1{5,2}, r2{6,1}, r3{6,5}, r4{6,5};\n\nstd::cout << (d1 > d2) << \" \" << (d2 >= d3) << \" \" << (d3 >= d4) << std::endl; // 0 0 1\nstd::cout << (r1 > r2) << \" \" << (r2 >= r3) << \" \" << (r3 >= r4) << std::endl; // 1 1 1\n</code></pre>\n\n<p>See also <a href=\"http://coliru.stacked-crooked.com/a/e1044873cda62179\" rel=\"nofollow noreferrer\">live example</a>.</p>\n\n<hr>\n\n<p>Now, the <em>function objects</em> are like <code>std::less</code> etc., but slightly different:</p>\n\n<pre><code>namespace op\n{\n struct lt\n {\n template<typename A, typename B>\n auto operator()(A&& a, B&& b) const\n -> decltype(std::forward<A>(a) < std::forward<B>(b))\n { return std::forward<A>(a) < std::forward<B>(b); }\n };\n\n // similarly for gt, eq, ne, le, ge\n}\n</code></pre>\n\n<p>These are as generic as possible, with perfect forwarding and automatically deduced return type (in case someone defines anything other than <code>bool</code>). So they can be used anywhere, not just for this solution. If you are feeling lazy, you could generate them with macros.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T16:19:39.503",
"Id": "48692",
"ParentId": "48622",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "48692",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T21:18:16.993",
"Id": "48622",
"Score": "6",
"Tags": [
"c++"
],
"Title": "Implementing C++ relational operators generator"
} | 48622 |
<p><strong>Question:</strong> Is there anything you could do in order to improve the test? </p>
<p>I am using Spring Framework 4, Hibernate 4, JUnit 4. All DAO unit tests inherit from TestDaoSetup class:</p>
<pre><code>@ContextConfiguration(locations={
"classpath:/config/test/spring.xml",
"classpath:/config/test/hibernate.xml"
})
@TransactionConfiguration
@Transactional
public class TestDaoSetup {
}
</code></pre>
<p>One of unit tests:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
public class CityDaoImplTest extends TestDaoSetup {
@Rule
public ExpectedException exception = ExpectedException.none();
@Autowired
private CityDao cityDao;
@Autowired
private CountryDao countryDao;
@Test
public void create_Created(){
CountryEntity countryEntity = countryDao.find(1L);
CityEntity cityEntity = new CityEntity();
cityEntity.setName("Košice");
cityEntity.setCountryEntity(countryEntity);
cityDao.create(cityEntity);
Assert.assertNotNull("Expected not null value.",cityDao.find(cityEntity.getId()));
}
@Test
public void create_NoCountryAssociation_ExceptionThrown(){
exception.expect(ConstraintViolationException.class);
CityEntity cityEntity = new CityEntity();
cityEntity.setName("Košice");
cityDao.create(cityEntity);
cityDao.flush();
}
@Test
public void create_ExistingNameSameCountry_ExceptionThrown() {
exception.expect(ConstraintViolationException.class);
CountryEntity countryEntity = countryDao.find(1L);
CityEntity cityEntity = new CityEntity();
cityEntity.setName("Bratislava");
cityEntity.setCountryEntity(countryEntity);
cityDao.create(cityEntity);
cityDao.flush();
}
@Test
public void create_ExistingNameDifferentCountry_Created(){
CountryEntity countryEntity = countryDao.find(2L);
CityEntity cityEntity = new CityEntity();
cityEntity.setName("Bratislava");
cityEntity.setCountryEntity(countryEntity);
cityDao.create(cityEntity);
Assert.assertNotNull("Expected not null value.", cityDao.find(cityEntity.getId()));
}
@Test
public void update_ExistingNameSameCountry_ExceptionThrown(){
exception.expect(ConstraintViolationException.class);
CityEntity cityEntity = cityDao.find(2L);
cityEntity.setName("Bratislava");
cityDao.update(cityEntity);
cityDao.flush();
}
@Test
public void update_ExistingNameDifferentCountry_Updated(){
CityEntity cityEntity = cityDao.find(3L);
cityEntity.setName("Bratislava");
cityDao.update(cityEntity);
Assert.assertEquals("Expected different value.", "Bratislava", cityDao.find(3L).getName());
}
@Test
public void delete_NotUsed_Deleted() {
CityEntity cityEntity = cityDao.find(4L);
cityDao.delete(cityEntity);
Assert.assertNull("Expected null value.", cityDao.find(cityEntity.getId()));
}
@Test
public void delete_Used_ExceptionThrown(){
exception.expect(ConstraintViolationException.class);
CityEntity cityEntity = cityDao.find(1L);
cityDao.delete(cityEntity);
cityDao.flush();
}
}
</code></pre>
<p><strong>Question:</strong> Is there anything you could improve in the test? </p>
<p><strong>EDIT:</strong></p>
<p>To make test conditions more clear:</p>
<ul>
<li>There are separated configurations, one is specifically for testing purposes.</li>
<li>There is database script which prepopulates the test database with test data before tests actually start.</li>
<li>Data are the same for each test, because there is a rollback after each test.</li>
<li>Test data are not prepopulated in each test class, but they are prepopulated in separate SQL file, which is executed before tests actually start.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T12:57:56.110",
"Id": "85634",
"Score": "1",
"body": "This is an integration test though, not a unit test. A unit test should depend on the implementation being correct only. Whereas these cases test whether the spring wire-up is correct, the test database creation script includes a unique key for city name on country table, test database enforces such keys etc."
}
] | [
{
"body": "<pre><code>public void create_Created(){\n</code></pre>\n\n<p>This violates Java coding standards. In Java, the convention is camelCase, not snake_case. On top of that, the name <em>create_Created</em> is utterly meaningless. What is that supposed to mean? Give your tests names describing what they test!</p>\n\n<pre><code>@Test\npublic void create_NoCountryAssociation_ExceptionThrown(){\n exception.expect(ConstraintViolationException.class);\n</code></pre>\n\n<p>It's good that you are using the <code>ExpectedException</code> rule, but you are using it wrong. Don't expect the exception until <em>right before</em> the call that you expect to trigger the exception – test setup etc. needs to be done before!</p>\n\n<p>Some of your tests don't seem to set up the data you are using for assertions. For your test cases to be independent, you should create the entry in the database from the test and then assert that the DAO can read this value (or do whatever you're testing). Don't rely on what's in the database – it's a messy road to go down because your tests will start depending on each other, potentially causing what we call <em>blinking tests</em> (sometimes they pass, sometimes they fail).</p>\n\n<p>Common test teardowns also belong in a <code>@After</code> method rather than being done in every test individually.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T01:32:29.157",
"Id": "85374",
"Score": "2",
"body": "Unit tests are a different beast when it comes to method naming, using underscores is definitely a good thing because the way the methodname is built (or should be built) is a lot different than a method in a traditional project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T07:36:38.557",
"Id": "85397",
"Score": "0",
"body": "@JeroenVannevel I disagree, I find camelCase named test methods just as readable as snake_case named tests – and in that case, the consistency argument wins. *However*, it is a matter of convention. In our project, we have a certain type of integration tests, called scenario tests, for which we use snake_case. The only purpose for this, though, is that the framework used for these tests generates reports from the test names that are sent to business, and snake_case allows us to generate normal sentences from the names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T08:04:35.393",
"Id": "85400",
"Score": "0",
"body": "For unit test naming I use these conventions, in my opinion they are clear and logical - http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T08:08:46.997",
"Id": "85401",
"Score": "0",
"body": "Since I did some research, I decided to [post this on programmers.*](http://programmers.stackexchange.com/questions/237561/naming-test-methods-in-java)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T09:01:22.553",
"Id": "85405",
"Score": "2",
"body": "@IngoBürk Regarding this \"it's a messy road to go down because your tests will start depending on each other\" - they won't because each test has exactly the same data. There is a rollback after each test. I explained this in comment to janos's answer as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:24:10.700",
"Id": "85416",
"Score": "0",
"body": "@IngoBürk \"It's good that you are using the ExpectedException rule, but you are using it wrong. ...\" - could you please post some link where this is explained? I am unable to find it in documentation."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:29:36.500",
"Id": "48625",
"ParentId": "48624",
"Score": "3"
}
},
{
"body": "<h3>External data</h3>\n\n<p>Most of your test cases are expected that some records already exist. The details of these records are not visible in the class, which makes them an external dependency. It also makes the test cases harder to understand.</p>\n\n<p>A simple fix is to add the necessary test data in the test cases, or in the <code>@Before</code> method.</p>\n\n<h3>Make assumptions explicit</h3>\n\n<p>Some of the test cases are hard to understand because they make assumptions that are not exactly obvious, for example:</p>\n\n<pre><code>@Test\npublic void create_ExistingNameDifferentCountry_Created(){\n CountryEntity countryEntity = countryDao.find(2L);\n\n CityEntity cityEntity = new CityEntity();\n cityEntity.setName(\"Bratislava\");\n cityEntity.setCountryEntity(countryEntity);\n\n cityDao.create(cityEntity);\n\n Assert.assertNotNull(\"Expected not null value.\", cityDao.find(cityEntity.getId()));\n}\n</code></pre>\n\n<p>Here, I suppose you are testing that you can create a city with the same name in a different country. This test case seems to make some assumptions:</p>\n\n<ul>\n<li>There is no city named Bratislava in the Country with id=2</li>\n<li>There is a city name Bratislava in some other Country</li>\n</ul>\n\n<p>It's better to make these assumptions part of the code, for example:</p>\n\n<pre><code>private CountryEntity createNewCountry() {\n // TODO: create a new unique country (different from all existing)\n}\n\n@Test\npublic void create_ExistingNameDifferentCountry_Created(){\n CountryEntity someCountry = createNewCountry();\n createCity(\"Bratislava\", someCountry);\n\n CountryEntity anotherCountry = createNewCountry();\n\n CityEntity cityEntity = new CityEntity();\n cityEntity.setName(\"Bratislava\");\n cityEntity.setCountryEntity(anotherCountry);\n\n cityDao.create(cityEntity);\n\n Assert.assertNotNull(\"Expected not null value.\", cityDao.find(cityEntity.getId()));\n}\n</code></pre>\n\n<p>There are no more meaningless numbers (such as <code>2L</code>) in this test case, and the assumptions are loud and clear.</p>\n\n<p>Another similar example:</p>\n\n<pre><code>@Test\npublic void update_ExistingNameSameCountry_ExceptionThrown(){\n exception.expect(ConstraintViolationException.class);\n\n CityEntity cityEntity = cityDao.find(2L);\n cityEntity.setName(\"Bratislava\");\n\n cityDao.update(cityEntity);\n cityDao.flush();\n}\n</code></pre>\n\n<p>This test case seems to assume that the city with id=2 is named Bratislava. Consider this instead:</p>\n\n<pre><code>@Test\npublic void update_ExistingNameSameCountry_ExceptionThrown(){\n exception.expect(ConstraintViolationException.class);\n\n CityEntity cityEntity = cityDao.findSomeCity();\n cityEntity.setName(cityEntity.getName());\n\n cityDao.update(cityEntity);\n cityDao.flush();\n}\n</code></pre>\n\n<p>No more hidden assumptions and invisible external data. The city can be any city, if you try to create a new city with the same name as the sample city, the method should throw.</p>\n\n<p>Many of your other methods suffer from the same problem. Review them and ask yourself if there are any assumptions that are not written inside the method itself, and make them explicit.</p>\n\n<h3>Covering all corners</h3>\n\n<p>Some of your test cases could be more strict, for example:</p>\n\n<ul>\n<li>In <code>create_Created</code>, in addition to checking that you can load the new entry that was created, you could check that:\n<ul>\n<li>the number of entries in the database got increased by 1</li>\n<li><code>Assert.assertEquals(cityEntity, cityDao.find(cityEntity.getId()))</code></li>\n</ul></li>\n<li>Similarly in <code>create_ExistingNameDifferentCountry_Created</code></li>\n</ul>\n\n<h3>Expected exceptions</h3>\n\n<p>Have you considered this instead of the <code>@Rule</code> for expected exceptions:</p>\n\n<pre><code>@Test(expected=ConstraintViolationException.class)\npublic void create_NoCountryAssociation_ExceptionThrown(){\n // ...\n}\n</code></pre>\n\n<p>Personally I find this more readable. <code>@Rule</code> is more powerful, because it can match exception messages too, but you're not using that feature anyway. This may be a matter of taste.</p>\n\n<h3>Naming</h3>\n\n<p>I think your test case names could be more intuitive, for example:</p>\n\n<ul>\n<li><code>create_city_with_country_works</code> instead of <code>create_Created</code></li>\n<li><code>create_city_without_country_throws</code> instead of <code>NoCountryAssociation_ExceptionThrown</code></li>\n<li>...</li>\n</ul>\n\n<p>As for camelCase vs underscores vs mixed vs something else, I think it doesn't matter. You can use what you like best. The general naming rules probably don't apply to the test cases the same way as to regular code. Test case names should be specific, identify what is being tested, and as such they tend to be very long.</p>\n\n<p>For example, underscores are very similar to spaces, so <code>create_city_without_country_throws</code> is just a little bit harder to read than a sentence. In <code>createCityWithoutCountryThrows</code> there is no visual separation between the words, which makes it much harder to read than a sentence. At least this is my opinion.</p>\n\n<p>The bottom line is, use whatever naming is agreed in your team, or else whatever naming is more readable to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T09:51:57.993",
"Id": "85408",
"Score": "0",
"body": "@janos Using `expected = …` allows test setup to make the test pass. And yes, in our project we had this happen on several occasions. You just have to use the rule correctly (see my post). I also don't think snake_case is more readable and would argue that this is a hard fact as you make it sound – it's just different for everyone. We actually had internal discussions on this and there was just no consensus."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:26:39.797",
"Id": "85417",
"Score": "0",
"body": "@IngoBürk are you saying that `expected=` can be buggy? I've never seen that, works reliably for me every time. About naming, my last sentence concludes to find a consensus in your team, or use what you like, period. Btw, [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.5.7) doesn't address the case of unit tests. Actually I don't see mention about camelCase either, though I definitely agree that's the convention in production code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T10:28:25.207",
"Id": "85419",
"Score": "0",
"body": "@janos No, `expected=` itself is not buggy, but if you have a test expecting some exception and someone changes the test setup, the setup might now throw this exception. Since your test expects it, it passes – even though it just became useless because it's not testing the production code anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:30:58.810",
"Id": "85495",
"Score": "0",
"body": "@IngoBürk Somehow, I am still not getting it. Is there any documentation or something where it is properly explained?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T17:58:23.397",
"Id": "85506",
"Score": "0",
"body": "@JakubPolák Imagine you want to verify that if a `null` value is read from the database, it causes a NPE in some method. So your test sets up a null value and then calls the method. If someone changes the way you insert the value into the database (which is the setup) so that it causes the exception, your test will still pass, but is pointless, because that's not *where* you expect the exception. Using `ExpectedException` you have the control to only start expecting the assertion *after* your test is set up."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T23:38:38.610",
"Id": "48628",
"ParentId": "48624",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "48628",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:16:51.170",
"Id": "48624",
"Score": "9",
"Tags": [
"java",
"unit-testing",
"junit"
],
"Title": "Create better Unit test"
} | 48624 |
<p>I'm working on a Unix machine where I can't use more than vanilla Perl, and I'm using Perl5.8. This script exits with a 1 if the current directory size is smaller than 1 GB (the character after <code>-d</code> is a literal "tab" character).</p>
<pre><code>my $du = `du --si | tail -1 | cut -d" " -f1`;
chomp $du;
if (substr($du, -1) ne "G") {
exit 1;
}
exit 0;
</code></pre>
<p>This is gross, but I know the data is in <code>du --si</code> so I can write it in 30 seconds. Is there a cleaner, more robust way?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T23:29:48.527",
"Id": "85368",
"Score": "0",
"body": "Why `tail -1`? Doesn't that just choose one of the subdirectories arbitrarily?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:30:59.773",
"Id": "85369",
"Score": "0",
"body": "I believe the last line of that output is the size of everything (it's the directory `.`, which is the current directory). The other lines are sizes of subdirectories."
}
] | [
{
"body": "<p>It is unusual on Code Review, to recommend a different approach, but this process can be simplified a whole bunch..... and avoid perl entirely.....</p>\n\n<pre><code>du -s -B 1 | grep -P -q '^\\d{10,}+\\s.*'\n</code></pre>\n\n<p>It breaks down as follows:</p>\n\n<pre><code>du -s -B 1\n</code></pre>\n\n<p>print a summary (no details for each file), with a byte-per-block size ... i.e. print the number of bytes in the current directory.</p>\n\n<p>Then, using grep (and perl-compatible regex).... use quiet output, which returns 0 on a successful match, and 1 on no-match.</p>\n\n<p>In other words, make sure the line starts with at least 10 digits.... i.e. <code>>= 1,000,000,000</code> bytes.</p>\n\n<p>Putting it together, the grep will be successful if the current directory is at least 1GB.</p>\n\n<p>I tested this with:</p>\n\n<pre><code>du -s -B 1 | grep -P -q '^\\d{10,}+\\s.*' && echo \"Bigger than 1G\" || echo \"less than 1G\"\n</code></pre>\n\n<p>Edit:</p>\n\n<p>This is compatible with your original code, which uses <code>--si</code> on du, which uses 1,000,000,000 bytes to represent GB. If you want to use GiB ( \\$2^{31}\\$ ) then it is actually substantially harder ....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:11:44.873",
"Id": "48630",
"ParentId": "48626",
"Score": "2"
}
},
{
"body": "<p>I agree with @rolfl that this would be much simpler as a one-line shell pipeline. The <code>-s</code> option to <code>du</code> makes it produce a total. <code>awk</code> is a good tool to use for processing multi-column text.</p>\n\n<pre><code>du -s --si | awk '$1 ~ /G/ { exit 1 }'\n</code></pre>\n\n<p>However, the <code>--si</code> option seems to be a non-portable GNU extension. A more portable version would look at the number of 512-byte blocks. The magic number 1953125 is \\$\\dfrac{10^9}{512}\\$.</p>\n\n<pre><code>du -s | awk '$1 < 1953125 { exit 1 }'\n</code></pre>\n\n<p>The second version also works even if the total is in the terabyte or exabyte range.</p>\n\n<hr>\n\n<p>There is an inefficiency, though: you should be able to exit early as soon as you find that the total exceeds 1 GB. For that, you would go back to Perl, but with a proper Perl program instead of a wrapper around <code>du</code>.</p>\n\n<pre><code>use File::Find;\nuse strict;\n\nmy $sum = 0;\nmy %seen_inodes;\nfind(sub {\n my ($inode, $blocks) = (stat)[1, 12] or die \"${File::Find::name}: $!\";\n\n # Do not double-count hard links\n if (!$seen_inodes{$inode}) {\n $seen_inodes{$inode} = 1;\n $sum += 512 * $blocks;\n exit 0 if $sum >= 1_000_000_000;\n }\n}, \".\");\nexit 1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:06:05.873",
"Id": "48636",
"ParentId": "48626",
"Score": "4"
}
},
{
"body": "<p>Calling <code>du</code> to calculate the full size is Ok, as it is not a trivial task. Everything else is better done on the Perl side. Simpler and cleaner.</p>\n\n<pre><code>my $du = `du -bs .`;\nmy $bytes = $du =~ /^(\\d+)/ or die \"du failed\";\nif ($bytes > 1e9) {\n print \"directory is bigger than 1GB\\n\"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-13T11:19:54.867",
"Id": "94355",
"Score": "0",
"body": "Hi, and welcome to code review. `du -s .` does not count the number of bytes used ... but the number of kiloBytes. Consider adding the `-B 1` option to `du`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-13T10:28:55.187",
"Id": "54147",
"ParentId": "48626",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "48636",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T22:48:12.560",
"Id": "48626",
"Score": "4",
"Tags": [
"perl",
"file-system",
"unix"
],
"Title": "Clean way to get size of directory"
} | 48626 |
<p>Currently I'm making a website that has a to-do list that will probably become quite long to write in html. So I decided to make a shorter version for me to write that I find more comfortable to read.</p>
<p>What I am currently doing is using ajax to read the text file from the server. Once the file has been stored into a string, it's sent to a function which formats it correctly for html. After that, it's returned into a variable that is now stored into a <code>container div</code> using jquery div. </p>
<p>This is my javascript code:</p>
<pre><code>var todoListMake = function( reading ){
var wanted =reading.split("\n");
var newString = "";
for( var i = 0; i < wanted.length; i ++ )
{
if( wanted[i] === "\n" )
continue;
/* Place text formatting code below */
wanted[i] = wanted[i].replace("<b>","<strong>");
wanted[i] = wanted[i].replace("</b>","</strong>");
wanted[i] = wanted[i].replace("<c>","<span class=\"cutWord\">");
wanted[i] = wanted[i].replace("</c>","</span>");
if( wanted[i].search("[X]") != -1 )
{
wanted[i] = "<span class=\"workDone\">" + wanted[i].replace("[X]","") + "</span>";
}
if( wanted[i].search("<ul") === -1 && wanted[i].search("</ul") === -1 )
wanted[i] = "<li>" + wanted[i]; // Open the list if no ul tags
if (i === (wanted.length-1) )
{
newString += wanted[i];
break;
}// Break early because the rest cannot be processed correctly
if( wanted[i].search("</ul") != -1 )
wanted[i] += "</li>"; // Close the list at the end of each ul
if ( wanted[i + 1].search("</ul") != -1 )
wanted[i] += "</li>";// Close the list of regular data
//alert(wanted[i]);
newString += wanted[i];
}
return newString;
};
window.onload = function(){
$.get("textData/todoData.txt", function(data) {
var compiledData = todoListMake( data );
$("#todoList").append( compiledData );
});
};
</code></pre>
<p>And then read from the text file like this:</p>
<pre><code><ul id="todoList" class="workList">
<h2>Release 1:</h2> <span class="important"> Completed </span>
<h2>Release 2: <span class="important"> Current Version </span></h2>
<ul>
<b>Core Additions</b>
<ul>
[X] Save Progress
[X] <c>14</c> 9 New Levels
</ul>
<b>Programmers Check List</b>
<ul>
[X] Add functionality to Level Restart
[X] Add checkpoint floater
</ul>
<b>Bug Fixes</b>
<ul>
[X] Hanging on Slopes teleport you
[X] Hanging on Slopes froze the game
[X] Fixed Menu overlay problem
</ul>
</ul>
</ul>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T01:50:55.443",
"Id": "85376",
"Score": "0",
"body": "Why would you do it like this? Use the DOM, check out `innerHTML`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T03:34:10.577",
"Id": "85384",
"Score": "0",
"body": "@elclanrs I used `$.append` to edit the html inside the div because I read somewhere in the past that innerHTML some times destroys other tags and data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T06:38:15.667",
"Id": "85396",
"Score": "0",
"body": "I'd consider an XSLT transformation much better for this. Of course you'd have to build the HTML beforehand using the transformation, but I consider that cleaner than building the content using javascript (causing the content to not show at all if something goes wrong)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T12:50:39.167",
"Id": "85437",
"Score": "0",
"body": "Perhaps consider using a static website generator: no Ajax requests, no JS required, and overall it's a cleaner solution. Your current way of doing things is just… ugh."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:20:59.147",
"Id": "85438",
"Score": "0",
"body": "@ReinisI. I am doing this because reading from a text file is much more readable to myself. This is a web page that I plan on making to become huge and I'm primarily worried with readability of the code... Also, this is going to be a check list. So, not much later from now i'm going to have the LI's clickable and once done, javascript will edit the server to set them as checked off. This way the site isn't so static and cumbersome for me to work with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:29:43.220",
"Id": "85611",
"Score": "1",
"body": "The readability of which code are you worried about? The code you write, or the finished HTML code on the web site? The latter is irrelevant and all you are doing is sacrificing user experience and over all site quality, because you are lazy - and not the good kind of lazy, because you put a lot of unnecessary work in your custom parsing function. There are plenty of great template engines, which do exactly the same you are doing manually with help of macros/mixins/helper functions. Which programming languages are you most comfortable with?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:34:55.887",
"Id": "85612",
"Score": "0",
"body": "Also when you say you want to make the `li`s clickable, you sounds like you want to use JavaScript there. Use checkboxes and wrap them together with the text in `label`s. That way they are clickable without unnecessary JavaScript. What do you mean with \"javascript will edit the server to set them as checked off\"?"
}
] | [
{
"body": "<p>What do you mean with the variable name <code>wanted</code>? I don't understand what it has anything to do with what you are doing, so it's a badly chosen name.</p>\n\n<pre><code>if( wanted[i] === \"\\n\" )\n continue;\n</code></pre>\n\n<p>This won't do anything. Since you split by <code>\"\\n\"</code>, there will be no line breaks leftover. I assume you want <code>wanted[i] === \"\"</code>. Also consider <code>.trim()</code>ing all you lines, otherwise a stray white space will break this.</p>\n\n<pre><code>if (i === (wanted.length-1) )\n {\n // [...]\n break;\n }// Break early because the rest cannot be processed correctly\n</code></pre>\n\n<p>I'm not sure why you are \"breaking early\" here. Your condition triggers for the last line, so it's not really \"early\".</p>\n\n<pre><code>newString += wanted[i];\n</code></pre>\n\n<p>Repeated string concatenation is a slow process and uses a lot of memory. Instead just leave your strings in the array and at the end just <code>return wanted.join();</code></p>\n\n<p>EDIT: One more thing: Both the original <code>div</code> and the other <code>ul</code> you later add inside have the same id. That's invalid.</p>\n\n<p>EDIT: Regarding the ID: In your script you have <code>$(\"#todoList\").append( compiledData );</code> so there's obviouly an element with the id <code>todoList</code>, but your template has the code <code><ul id=\"todoList\" class=\"workList\"></code> in it, so you are creating a second element with the same ID.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:01:05.297",
"Id": "85635",
"Score": "0",
"body": "Alright, I agree with the variable name `wanted` it's not very appropriate. Also, I like the Idea of trimming so I will use that as well. I'm a bit confused on the ID, I don't remember placing any. **I broke early** because right after that the code is set to close a `<LI>` and the last line is the closing `<ul>` so a `</li>` would break the html with closing an unopened `<li>`. And the line after that checks `I+1` out of the array size and will cause an error in the javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T13:24:05.930",
"Id": "85642",
"Score": "0",
"body": "@Lemony-Andrew See 2nd edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T14:02:35.423",
"Id": "85653",
"Score": "0",
"body": "very good catch! I would have never noticed without you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T10:05:58.287",
"Id": "48764",
"ParentId": "48631",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T00:42:02.730",
"Id": "48631",
"Score": "2",
"Tags": [
"javascript",
"html",
"formatting"
],
"Title": "A better way to read text files into html?"
} | 48631 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.