body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<blockquote>
<p><code>NodeData</code> stores all information of the node needed by the <code>AStar</code>
algorithm. This information includes the value of <code>g</code>, <code>h</code>, and <code>f</code>.
However, the value of all 3 variables are dependent on source and
destination, thus obtains at runtime.</p>
<pre><code>@param <T>
</code></pre>
</blockquote>
<p>I'm looking for reviews on optimization, accuracy and best practices.</p>
<pre><code>final class NodeData<T> {
private final T nodeId;
private final Map<T, Double> heuristic;
private double g; // g is distance from the source
private double h; // h is the heuristic of destination.
private double f; // f = g + h
public NodeData (T nodeId, Map<T, Double> heuristic) {
this.nodeId = nodeId;
this.g = Double.MAX_VALUE;
this.heuristic = heuristic;
}
public T getNodeId() {
return nodeId;
}
public double getG() {
return g;
}
public void setG(double g) {
this.g = g;
}
public void calcF(T destination) {
this.h = heuristic.get(destination);
this.f = g + h;
}
public double getH() {
return h;
}
public double getF() {
return f;
}
}
/**
* The graph represents an undirected graph.
*
* @author SERVICE-NOW\ameya.patil
*
* @param <T>
*/
final class GraphAStar<T> implements Iterable<T> {
/*
* A map from the nodeId to outgoing edge.
* An outgoing edge is represented as a tuple of NodeData and the edge length
*/
private final Map<T, Map<NodeData<T>, Double>> graph;
/*
* A map of heuristic from a node to each other node in the graph.
*/
private final Map<T, Map<T, Double>> heuristicMap;
/*
* A map between nodeId and nodedata.
*/
private final Map<T, NodeData<T>> nodeIdNodeData;
public GraphAStar(Map<T, Map<T, Double>> heuristicMap) {
if (heuristicMap == null) throw new NullPointerException("The huerisic map should not be null");
graph = new HashMap<T, Map<NodeData<T>, Double>>();
nodeIdNodeData = new HashMap<T, NodeData<T>>();
this.heuristicMap = heuristicMap;
}
/**
* Adds a new node to the graph.
* Internally it creates the nodeData and populates the heuristic map concerning input node into node data.
*
* @param nodeId the node to be added
*/
public void addNode(T nodeId) {
if (nodeId == null) throw new NullPointerException("The node cannot be null");
if (!heuristicMap.containsKey(nodeId)) throw new NoSuchElementException("This node is not a part of hueristic map");
graph.put(nodeId, new HashMap<NodeData<T>, Double>());
nodeIdNodeData.put(nodeId, new NodeData<T>(nodeId, heuristicMap.get(nodeId)));
}
/**
* Adds an edge from source node to destination node.
* There can only be a single edge from source to node.
* Adding additional edge would overwrite the value
*
* @param nodeIdFirst the first node to be in the edge
* @param nodeIdSecond the second node to be second node in the edge
* @param length the length of the edge.
*/
public void addEdge(T nodeIdFirst, T nodeIdSecond, double length) {
if (nodeIdFirst == null || nodeIdSecond == null) throw new NullPointerException("The first nor second node can be null.");
if (!heuristicMap.containsKey(nodeIdFirst) || !heuristicMap.containsKey(nodeIdSecond)) {
throw new NoSuchElementException("Source and Destination both should be part of the part of hueristic map");
}
if (!graph.containsKey(nodeIdFirst) || !graph.containsKey(nodeIdSecond)) {
throw new NoSuchElementException("Source and Destination both should be part of the part of graph");
}
graph.get(nodeIdFirst).put(nodeIdNodeData.get(nodeIdSecond), length);
graph.get(nodeIdSecond).put(nodeIdNodeData.get(nodeIdFirst), length);
}
/**
* Returns immutable view of the edges
*
* @param nodeId the nodeId whose outgoing edge needs to be returned
* @return An immutable view of edges leaving that node
*/
public Map<NodeData<T>, Double> edgesFrom (T nodeId) {
if (nodeId == null) throw new NullPointerException("The input node should not be null.");
if (!heuristicMap.containsKey(nodeId)) throw new NoSuchElementException("This node is not a part of hueristic map");
if (!graph.containsKey(nodeId)) throw new NoSuchElementException("The node should not be null.");
return Collections.unmodifiableMap(graph.get(nodeId));
}
/**
* The nodedata corresponding to the current nodeId.
*
* @param nodeId the nodeId to be returned
* @return the nodeData from the
*/
public NodeData<T> getNodeData (T nodeId) {
if (nodeId == null) { throw new NullPointerException("The nodeid should not be empty"); }
if (!nodeIdNodeData.containsKey(nodeId)) { throw new NoSuchElementException("The nodeId does not exist"); }
return nodeIdNodeData.get(nodeId);
}
/**
* Returns an iterator that can traverse the nodes of the graph
*
* @return an Iterator.
*/
@Override public Iterator<T> iterator() {
return graph.keySet().iterator();
}
}
public class AStar<T> {
private final GraphAStar<T> graph;
public AStar (GraphAStar<T> graphAStar) {
this.graph = graphAStar;
}
// extend comparator.
public class NodeComparator implements Comparator<NodeData<T>> {
public int compare(NodeData<T> nodeFirst, NodeData<T> nodeSecond) {
if (nodeFirst.getF() > nodeSecond.getF()) return 1;
if (nodeSecond.getF() > nodeFirst.getF()) return -1;
return 0;
}
}
/**
* Implements the A-star algorithm and returns the path from source to destination
*
* @param source the source nodeid
* @param destination the destination nodeid
* @return the path from source to destination
*/
public List<T> astar(T source, T destination) {
/**
* http://stackoverflow.com/questions/20344041/why-does-priority-queue-has-default-initial-capacity-of-11
*/
final Queue<NodeData<T>> openQueue = new PriorityQueue<NodeData<T>>(11, new NodeComparator());
NodeData<T> sourceNodeData = graph.getNodeData(source);
sourceNodeData.setG(0);
sourceNodeData.calcF(destination);
openQueue.add(sourceNodeData);
final Map<T, T> path = new HashMap<T, T>();
final Set<NodeData<T>> closedList = new HashSet<NodeData<T>>();
while (!openQueue.isEmpty()) {
final NodeData<T> nodeData = openQueue.poll();
if (nodeData.getNodeId().equals(destination)) {
return path(path, destination);
}
closedList.add(nodeData);
for (Entry<NodeData<T>, Double> neighborEntry : graph.edgesFrom(nodeData.getNodeId()).entrySet()) {
NodeData<T> neighbor = neighborEntry.getKey();
if (closedList.contains(neighbor)) continue;
double distanceBetweenTwoNodes = neighborEntry.getValue();
double tentativeG = distanceBetweenTwoNodes + nodeData.getG();
if (tentativeG < neighbor.getG()) {
neighbor.setG(tentativeG);
neighbor.calcF(destination);
path.put(neighbor.getNodeId(), nodeData.getNodeId());
if (!openQueue.contains(neighbor)) {
openQueue.add(neighbor);
}
}
}
}
return null;
}
private List<T> path(Map<T, T> path, T destination) {
assert path != null;
assert destination != null;
final List<T> pathList = new ArrayList<T>();
pathList.add(destination);
while (path.containsKey(destination)) {
destination = path.get(destination);
pathList.add(destination);
}
Collections.reverse(pathList);
return pathList;
}
public static void main(String[] args) {
Map<String, Map<String, Double>> hueristic = new HashMap<String, Map<String, Double>>();
// map for A
Map<String, Double> mapA = new HashMap<String, Double>();
mapA.put("A", 0.0);
mapA.put("B", 10.0);
mapA.put("C", 20.0);
mapA.put("E", 100.0);
mapA.put("F", 110.0);
// map for B
Map<String, Double> mapB = new HashMap<String, Double>();
mapB.put("A", 10.0);
mapB.put("B", 0.0);
mapB.put("C", 10.0);
mapB.put("E", 25.0);
mapB.put("F", 40.0);
// map for C
Map<String, Double> mapC = new HashMap<String, Double>();
mapC.put("A", 20.0);
mapC.put("B", 10.0);
mapC.put("C", 0.0);
mapC.put("E", 10.0);
mapC.put("F", 30.0);
// map for X
Map<String, Double> mapX = new HashMap<String, Double>();
mapX.put("A", 100.0);
mapX.put("B", 25.0);
mapX.put("C", 10.0);
mapX.put("E", 0.0);
mapX.put("F", 10.0);
// map for X
Map<String, Double> mapZ = new HashMap<String, Double>();
mapZ.put("A", 110.0);
mapZ.put("B", 40.0);
mapZ.put("C", 30.0);
mapZ.put("E", 10.0);
mapZ.put("F", 0.0);
hueristic.put("A", mapA);
hueristic.put("B", mapB);
hueristic.put("C", mapC);
hueristic.put("E", mapX);
hueristic.put("F", mapZ);
GraphAStar<String> graph = new GraphAStar<String>(hueristic);
graph.addNode("A");
graph.addNode("B");
graph.addNode("C");
graph.addNode("E");
graph.addNode("F");
graph.addEdge("A", "B", 10);
graph.addEdge("A", "E", 100);
graph.addEdge("B", "C", 10);
graph.addEdge("C", "E", 10);
graph.addEdge("C", "F", 30);
graph.addEdge("E", "F", 10);
AStar<String> aStar = new AStar<String>(graph);
for (String path : aStar.astar("A", "F")) {
System.out.println(path);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-07T13:50:57.157",
"Id": "250842",
"Score": "0",
"body": "Why: if (!openQueue.contains(neighbor)) { openQueue.add(neighbor); }\nis only if `tentativeG < neighbor.getG()`?"
}
] |
[
{
"body": "<p>This is quite good and professional-looking code. There are many small aspects which I <em>really</em> like:</p>\n\n<ul>\n<li>Using <code>Collections.unmodifiableMap</code> instead of a shallow copy is brilliant.</li>\n<li>The use of a generic <code>nodeId</code> is clever and makes for elegant code.</li>\n<li>There are input checks in <em>all</em> public methods (well, there are some exceptions: only the <code>AStar</code> and <code>NodeData</code> constructors, <code>NodeComparator#compare</code>, and <code>AStar#astar</code> are not checked).</li>\n<li>You make perfect use of empty lines to separate unrelated blocks.</li>\n</ul>\n\n<p>But there were some aspects that made your code sometimes a bit harder to follow:</p>\n\n<ul>\n<li><p>Lack of encapsulation of some parts like <code>heuristic</code>: What is this <code>Map<T, Map<T, Double>></code>? Can't I have nice self-documenting accessors for a <code>Heuristic<T></code> instance?</p></li>\n<li><p>Sequential coupling in <code>NodeData</code>: whenever I <code>setG</code> I also have to call <code>calcF</code>. You could have made this easier by slapping a <code>return this</code> in there instead of <code>void</code> methods, but the real solution is to get rid of <code>public calcF</code> and make it <code>private</code> instead. The <code>NodeData</code> class is responsible on its own to maintain its invariants, so any call to <code>setG</code> should update dependent fields.</p></li>\n<li><p>Bad naming. The letters <code>g</code>, <code>f</code> and <code>h</code> have a specific meaning in the context of A* and are OK here. Of course it would have been better to include a link to this algorithm's Wikipedia page so that a future maintainer can understand why you used <code>g</code> instead of <code>distance</code>.</p>\n\n<p>But nodes don't have a <em>distance</em>, nodes or edges have <em>weights</em>. In the context of optimization problems it is also common to talk about a <em>cost</em> – a term which does not occur once in your code.</p>\n\n<p>It's called <code>heuristic</code>, not <code>hueristic</code>. Typos are easy to correct, and should be corrected while they're still young (The <a href=\"https://en.wikipedia.org/wiki/HTTP_referer\">origin of the <code>referer</code> field in a HTTP request</a> should be edutaining here).</p></li>\n<li><p>There are some formatting “errors” that can be easily rectified by an automatic formatter. E.g. don't use braces when a conditional is on a single line like <code>if (cond) { single_statement; }</code> – removing the braces reduces line noise. Otherwise, you could also put the statement on its own line.</p>\n\n<p>Some of your lines are excessively long and should be broken up (see also the next tip).</p></li>\n<li><p>As laudable as your input checks are, they do add visual clutter. Consider hiding them behind helper methods, e.g. <code>heuristic.assertContains(nodeId)</code> or preferably <code>Assert.nonNull(nodeId, \"node\")</code> (which assumes a whole class dedicated to input checking). Arguments against this are less useful stack traces and reduced performance (method call overhead, compiler optimizations are more difficult), but pro-arguments include more self-documenting, concise code.</p></li>\n</ul>\n\n<p>Other notes:</p>\n\n<ul>\n<li><p>Your documentation does not state what happens when there is no path from the start to the destination (e.g. if the nodes are in unconnected subgraphs). The implementation is rather clear here: A <code>null</code> is returned instead of a list.</p></li>\n<li><p>The <a href=\"https://en.wikipedia.org/wiki/A%2A#Pseudocode\">Pseudocode given on the A* Wikipedia page</a> uses a slightly different condition for updating the <code>path</code> and possibly adding neighbours to the <code>openQueue</code>:</p>\n\n<pre><code>if (!openQueue.contains(neighbor) || tentativeG < neighbor.getG())`\n</code></pre>\n\n<p>whereas you use <code>if (tentativeG < neighbor.getG())</code>. It might be worth checking an authoritative source what the correct condition is.</p></li>\n<li><p>You could translate between <code>T</code> instances and a continuous range of <code>int</code>s at your component's boundaries (in other words: internally, every <code>nodeId</code> would be an integer). Using integers allows for more efficient data structures like arrays. This would remove most <code>Map</code> lookups, but also the <code>NodeData</code> class. The disadvantage is that your code would look like C afterwards… I would just try out the transformation and see (a) whether there is a noticeable increase in performance and (b) whether the increased ugliness is really worth it.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T04:12:37.120",
"Id": "65301",
"Score": "0",
"body": "The Pseudocode given on the A* Wikipedia page uses a slightly different condition for updating the path and possibly adding neighbours to the openQueue. Its a great catch but i think my `this.g = Double.MAX_VALUE;` is taking care of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T04:14:31.223",
"Id": "65302",
"Score": "0",
"body": "Lack of encapsulation of some parts like heuristic: What is this Map<T, Map<T, Double>>? Can't I have nice self-documenting accessors for a Heuristic<T> instance? - `very good point.`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T09:42:37.817",
"Id": "38380",
"ParentId": "38376",
"Score": "21"
}
},
{
"body": "<p>The code seems ok, but in my humble opinion, I think there are some things that can improve your code:</p>\n\n<ol>\n<li>Why does each node have a heuristic table? It may be better to use just the node to encapsulate the cost and the score, but let the algorithm compute the <code>f</code> cost for you. </li>\n<li><p>Similarly, the <code>f</code> computation is embedded in the node but is also in the <code>AStar</code> algorithm. Why not use a different component to compute <code>f</code>? Let the node act just as a \"container\" of the data. I think is much better to compute the <code>f</code> in the <code>AStar</code> only, instead of having a similar computation in the <code>Node</code> and in the <code>AStar</code>: </p>\n\n<pre><code> // You are calculating g here, why f is computed in the node?\n // Responsabilities of each component are not clear\n double distanceBetweenTwoNodes = neighborEntry.getValue();\n double tentativeG = distanceBetweenTwoNodes + nodeData.getG();\n\n if (tentativeG < neighbor.getG()) {\n neighbor.setG(tentativeG);\n neighbor.calcF(destination); // confusing\n</code></pre></li>\n<li><p><code>AStar</code> can be used only with <code>AStarGraph</code>. This code is a little bit tied. You can define instead a function that computes the successors for a state, so instead of using <code>graph.edgesFrom</code> you can use <code>transitions.from(state)</code>. This function can be computed using your graph structure or any other thing.</p></li>\n</ol>\n\n<p>Check <a href=\"http://goo.gl/yfRz2p\" rel=\"nofollow\">this implementation</a> to see some of these ideas; it may give you some hints on implementing an even better version of the A*.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T11:36:23.277",
"Id": "51748",
"ParentId": "38376",
"Score": "7"
}
},
{
"body": "<p>I like you code but I think there is a bug: in <code>neighbor.setG(tentativeG)</code> you update the priority of a node that may already have been inserted in the openQueue. The latter is a java <code>PriorityQueue</code>, which does not support priority updates. In changing the priority of an object in the queue without adjusting it's position (sifting up in your case) you could be breaking its structure. In orderer to do the update safely in a java <code>PriorityQueue</code> you should remove the node (O(N)), update it and insert it back in.\nIn term of performance, you are already paying a O(N) (here N is the typical size of the open set) in <code>openQueue.contains(neighbor)</code>, so the removal is going to be comparable to that. I think you can improve that by, for example, avoiding checking on the priority queue but book-keeping on separate hash instead. This though would not solve the O(N) that you should pay when removing a node before updating it. A possible way out could be to just avoid removing the obsolete node and simply add a new one with the updated priority. If you do that, make sure you hash the close set by some id rather than with the object itself, so that when you poll an obsolete node (which will have the same id of the newer one already visited as the latter had higher priority) it will be classified as already visited.\nThe cost of this approach is that you will have in general a longer queue, but operations will all be O(log(N)) at most.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-01T18:08:41.163",
"Id": "68611",
"ParentId": "38376",
"Score": "5"
}
},
{
"body": "<p>Why:</p>\n\n<pre><code>if (!openQueue.contains(neighbor)) {\n openQueue.add(neighbor);\n}\n</code></pre>\n\n<p>is only if <code>tentativeG < neighbor.getG()</code>?</p>\n\n<p>In a generic A* pseudocode the update is done in any case.</p>\n\n<p>See, e.g. on <a href=\"https://en.wikipedia.org/wiki/A*_search_algorithm\" rel=\"nofollow\">Wikipedia</a></p>\n\n<p>I tried running the code, it finds the optimal solution only \"thanks\" to the other bug mentioned by mzivi.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-07T14:59:48.590",
"Id": "134180",
"ParentId": "38376",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38380",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T23:32:16.700",
"Id": "38376",
"Score": "31",
"Tags": [
"java",
"algorithm",
"search",
"graph",
"pathfinding"
],
"Title": "A* search algorithm"
}
|
38376
|
<p>Is there a way I could improve my code's readability, or have I finally won the war against sloppy coding?</p>
<p>Here's a game launcher I made for <em>The Sims 3</em> to fix the awful performance caused by big cache files.</p>
<pre><code>using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Sims_3___Anti_Cache
{
public partial class Form1 : Form
{
Game Sims3;
public Form1()
{
InitializeComponent();
Sims3 = new Game();
Sims3.cache = new List<string>() { "CASPartCache.package", "compositorCache.package", "scriptCache.package",
"simCompositorCache.package", "socialCache.package" };
Sims3.cache_path = "C:/Users/DarkShadow/Documents/Electronic Arts/The Sims 3/";
Sims3.clear_cache();
Sims3.path = "C:/Program Files (x86)/Electronic Arts/The Sims 3/Game/Bin/TS3.exe";
isCleared.Enabled = true;
}
private void isCleared_Tick(object sender, System.EventArgs e)
{
if (Sims3.cache_cleared)
{
Process.Start(Sims3.path);
Application.Exit();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T16:29:57.883",
"Id": "63955",
"Score": "1",
"body": "This is quite simple code, there isn't much to review here. Why didn't you include the Game class too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T16:48:04.240",
"Id": "63956",
"Score": "0",
"body": "Because there's nothing special about it. All it does is store values, check if the file in cache exist and delete it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T17:03:52.260",
"Id": "63957",
"Score": "1",
"body": "Was the title misleading? We generally like to have titles that reflect the code's purpose. This helps increase visibility on the site and on search engines."
}
] |
[
{
"body": "<p>You would benefit from removing the hard-coded strings out of the code. Best to put them in an app.config file or a resource file. The config file has the additional advantage that the strings could be changed by the user without recompiling.</p>\n\n<p>The naming of the methods and properties is not standard for C#. Use Pascal case for public methods and properties with no underbar, e.g.</p>\n\n<pre><code>Sims3.CachePath = configCachePath;\nSims3.ClearCache();\n</code></pre>\n\n<p>The naming of local variables and private methods uses camel case, e.g.</p>\n\n<pre><code>isClearedTick();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:28:19.937",
"Id": "38387",
"ParentId": "38383",
"Score": "4"
}
},
{
"body": "<p>What is the <code>Game</code> class? What does it do?</p>\n\n<p>Some issues though:</p>\n\n<ul>\n<li>hard-coding the locations and names of the files is a problem. At a minimum you should make the code more portable by making those values configurable (command-line, using variables like <a href=\"http://technet.microsoft.com/en-us/library/dd560744%28v=ws.10%29.aspx\" rel=\"nofollow\"><code>PROGRAMFILES(X86)</code> and <code>CSIDL_MYDOCUMENTS</code></a>).</li>\n<li>you do not do any validation to ensure that the data actually exists.</li>\n</ul>\n\n<p>From the code you show, this launcher does not do very much, it clears a cache (In the background?) and (on a call-back) starts a child process.</p>\n\n<p>Is there any reason you need to create a full program for this? A Batch file seems like the right tool (maybe you need a program to clear the actual cache files?):</p>\n\n<pre><code>@echo off\nrem clear cache files\nClearCaches \"%CSIDL_MYDOCUMENTS%\\Electronic Arts\\The Sims 3\\*Cache.package\"\nrem start game\n\"%PROGRAMFILES(X86)%\\Electronic Arts\\The Sims 3\\Game\\Bin\\TS3.exe\"\n</code></pre>\n\n<h3>P.S. After Googling <a href=\"http://www.carls-sims-3-guide.com/technicalhelp/slowgame.php\" rel=\"nofollow\">I found this advice</a>:</h3>\n\n<blockquote>\n <p>When you click the batch file it will run and delete the four cache files then run the Sims.</p>\n</blockquote>\n\n<pre><code>@echo off\ndel \"C:\\Documents and Settings\\My Computer\\My Documents\\Electronic Arts\\The Sims 3\\CASPartCache.package\"\ndel \"C:\\Documents and Settings\\My Computer\\My Documents\\Electronic Arts\\The Sims 3\\scriptCache.package\"\ndel \"C:\\Documents and Settings\\My Computer\\My Documents\\Electronic Arts\\The Sims 3\\compositorCache.package\"\ndel \"C:\\Documents and Settings\\My Computer\\My Documents\\Electronic Arts\\The Sims 3\\simCompositorCache.package\"\nstart /d \"C:\\Program Files\\Electronic Arts\\The Sims 3 Ambitions\\Game\\Bin\" Sims3Launcher.exe\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:47:45.390",
"Id": "63954",
"Score": "0",
"body": "While I agree with the intent of `%CSIDL_MYDOCUMENTS%`, it doesn't appear to be defined for me. Instead the closest I can suggest for a batch file appears to be `%USERPROFILE%\\Documents\\...` or via [registry queries](http://serverfault.com/questions/10938/finding-users-documents-folder-in-bat-script)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:36:54.880",
"Id": "38388",
"ParentId": "38383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38387",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:00:38.963",
"Id": "38383",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "Game launcher for The Sims 3"
}
|
38383
|
<p>I want to get the number if items with state <code>4</code> and <code>1</code> from my database for each day between a certain date. Is there a smarter and more performative way than this one?</p>
<p>I am aware that I should use MySQLi and that MySQL is deprecated.</p>
<p>Code explanation:</p>
<ul>
<li>the <code>for</code> loop is to go through everyday between 2 dates</li>
<li><code>$sql_condition</code> is in case the query has a specific item, otherwise empty variable</li>
</ul>
<p>My code:</p>
<pre><code>for( $thisDay = $start; $thisDay <= $end; $thisDay = $thisDay + 86400){
$formatedDate = date('Y-m-d', $thisDay);
// booked houses
$sql="SELECT id FROM ".T_BOOKINGS." WHERE id_state=1 ".$sql_condition." AND the_date='".$formatedDate."'";
$res=mysql_query($sql) or die("Error getting states<br>".mysql_Error());
//reserved houses
$sql2="SELECT id FROM ".T_BOOKINGS." WHERE id_state=4 ".$sql_condition." AND the_date='".$formatedDate."'";
$res2=mysql_query($sql2) or die("Error getting states<br>".mysql_Error());
$bookings['booked'][] = mysql_num_rows($res);
$bookings['reserved'][] = mysql_num_rows($res2);
$dates[] = $formatedDate;
}
</code></pre>
|
[] |
[
{
"body": "<p>Three major points:</p>\n\n<ul>\n<li>Executing SQL queries in a loop will nearly always cause a performance problem. You want to formulate a query that gives you all the data you want.</li>\n<li><code>mysql_query()</code> and similar functions are deprecated; use <code>mysqli</code> or <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a> instead.</li>\n<li>Composing your query by concatenation and interpolation, without escaping, could easily lead to an SQL injection vulnerability. Better yet, use a database interface that supports placeholders for parameters so that you don't have to worry about escaping.</li>\n</ul>\n\n<p>A better solution would go something like this:</p>\n\n<pre><code>function bookings_between($booking_state, $start, $end) {\n $formattedStart = date('Y-m-d', $start);\n $formattedEnd = date('Y-m-d', $end);\n\n $query = mysql_query(\"\n SELECT the_date, COUNT(id)\n FROM \".T_BOOKINGS.\"\n WHERE id_state=$booking_state\n $sql_condition AND\n the_date BETWEEN '$formattedStart' AND '$formattedEnd'\n GROUP BY the_date;\")\n or die (\"Error getting states<br>\".mysql_error());\n\n $results = array();\n while ($row = mysql_fetch_array($query, MYSQL_NUM)) {\n $results[$row[0]] = $row[1];\n }\n return $results;\n}\n\n$booked = bookings_between(1, $start, $end);\n$reserved = bookings_between(4, $start, $end);\n</code></pre>\n\n<p>The results are not in the same format as your original. This returns the bookings in associative arrays, keyed by the date (as formatted by MySQL). Days that have no bookings will not have an entry. If you need to, you can post-process <code>$booked</code> and <code>$reserved</code> back into a data structure compatible with the original code. The big win, though, is that you execute just two queries instead of two queries per day of the period in question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:44:33.580",
"Id": "63948",
"Score": "0",
"body": "This was very interesting! +1 - so you mean that event if I have a loop after this code you suggested, to get back into a array the dates were select did not return `the_date`, it would anyway be better and faster than my code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:45:20.923",
"Id": "63949",
"Score": "1",
"body": "yes it would, you got it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:47:28.347",
"Id": "63950",
"Score": "0",
"body": "Then I say: thak you @rolfl and 200_success, and have a nice 2014 :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T14:01:12.583",
"Id": "63951",
"Score": "0",
"body": "Just implementd your code, had a performance gain of 1,5 second per year between dates! impressive, nice! Wish I could __+1 you again__ :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T18:21:29.213",
"Id": "63959",
"Score": "0",
"body": "you know what would make this answer super perfect? updating it to use MySQLi instead of the deprecated `mysql_*` syntax..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:27:46.033",
"Id": "63962",
"Score": "1",
"body": "@Rikard You're welcome. Unfortunately, it's too late to be eligible for [Best of Code Review 2013](http://meta.codereview.stackexchange.com/q/1320/9357)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:39:37.597",
"Id": "38385",
"ParentId": "38384",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:09:07.293",
"Id": "38384",
"Score": "4",
"Tags": [
"php",
"optimization",
"mysql",
"datetime"
],
"Title": "Optimize MySQL double select inside for-loop"
}
|
38384
|
<p>I am trying to concatenate the echo statements but I am failing. Also any other tips are appreciated in your review.</p>
<pre><code><?php
// load all 'category' terms for the post
$terms = get_the_terms($post->ID, 'category');
// we will use the first term to load ACF data from
if( !empty($terms) )
{
$term = array_pop($terms);
$custom_field = get_field('category_image', 'category_' . $term->term_id );
// do something with $custom_field
echo "<a href=" get_field('category_link', $custom_field) ">";
echo "<img src="<?php echo $image; ?>" alt="<?php echo get_cat_name($cat->term_id); ?>" class="item-image">";
echo "</a>";
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>The places where I have worked, as well as a number of articles I have read, have taught me that <code>echo</code>ing HTML is bad practice, and really if you think about it from a maintenance perspective you want that clear separation of PHP and HTML. An example of your code with that separation:</p>\n\n<pre><code><?php\n $terms = get_the_terms($post->ID, 'category');\n\n if(!empty($terms)){\n $term = array_pop($terms);\n $custom_field = get_field('category_image', 'category_' . $term->term_id );\n?>\n <a href=\"<?php echo get_field('category_link', $custom_field); ?>\">\n <img src=\"<?php echo $image; ?>\" alt=\"<?php echo get_cat_name($cat->term_id); ?>\" class=\"item-image\" />\n </a>\n<?php } ?>\n</code></pre>\n\n<p>Or if you wanted to simplify it a bit for future readers:</p>\n\n<pre><code><?php\n $terms = get_the_terms($post->ID, 'category');\n\n if(!empty($terms)){\n $term = array_pop($terms);\n $custom_field = get_field('category_image', 'category_' . $term->term_id );\n $href = get_field('category_link', $custom_field);\n $cat_name = get_cat_name($cat->term_id);\n?>\n <a href=\"<?php echo $href; ?>\">\n <img src=\"<?php echo $image; ?>\" alt=\"<?php echo $cat_name; ?>\" class=\"item-image\" />\n </a>\n<?php } ?>\n</code></pre>\n\n<p>Or you could build an array out of the values if you wanted to \"encapsulate\" the link or something instead. Either way, a setup like this is much clearer and more maintainable than if you were to concatenate everything into one giant string and <code>echo</code> it.</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:40:16.880",
"Id": "38389",
"ParentId": "38386",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38389",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:08:47.460",
"Id": "38386",
"Score": "0",
"Tags": [
"php"
],
"Title": "Need review on concatenation"
}
|
38386
|
<p>I wanted to write a simple Log class for PHP, I use ajax calls with AngularJS and often return the log in an array</p>
<p>Example:</p>
<pre class="lang-php prettyprint-override"><code>$return['data'] = $returnedDataArray;
$return['log'] = $logDataArray;
$return['status'] = 'success';
echo json_encode($return);
</code></pre>
<p>I was hoping to implement a logging system in my other classes, like my DB wrapper, etc.</p>
<p>Example:</p>
<pre class="lang-php prettyprint-override"><code>Log::put('sql', $sql, 'DB');
Log::put('fields', $fieldsArray, 'DB');
</code></pre>
<p>And than pass the log.</p>
<p>Example:</p>
<pre class="lang-php prettyprint-override"><code>$return['log'] = Log::getLog();
</code></pre>
<p>Here is my Log class:</p>
<pre class="lang-php prettyprint-override"><code>class Log {
private static $_loggingOn = true, $_log = array();
public static function put ($key, $value, $className = null, $functionName = null) {
if ($className) {
if ($functionName) {
self::$_log[$className][$functionName][$key] = $value;
} else {
self::$_log[$className][$key] = $value;
}
} else {
self::$_log[$key] = $value;
}
}
public static function getLog () {
if (self::loggingOn()) {
return self::$_log;
}
return array('Logging is turned off.');
}
public static function loggingOn () {
return self::$_loggingOn;
}
}
</code></pre>
<p>I am wondering if using the static class would be a recommended approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T18:41:22.477",
"Id": "64364",
"Score": "0",
"body": "What exactly _are_ you logging in this class? It's not writing anything to anywhere... besides: you've not included the possibility of having to log in a namespaced environment, and you're using `static`, which isn't very useful in a PHP context"
}
] |
[
{
"body": "<p>No, using static methods is not a recommand approach. With static methods, your class always knows which class it calls. That means you can never switch to another logger class (e.g. one that writes the logs in a file).</p>\n\n<p>A class should be independent of other classes as much as possible. In this case, you should just create a <code>LoggerInterface</code> (or use the one from PSR-3) and base on that interface. Inject it in the classes that needs a logger and then use that object. This way, you can always change from loggers (as long as they implement the correct interface) and your class doesn't know which classes it uses.</p>\n\n<p>Example:</p>\n\n<pre><code>interface LoggerInterface\n{\n public function put($key, $value, $class = null, $function = null);\n public function getMessages();\n}\n\nclass Logger\n{\n protected $messages;\n\n public function put($key, $value, $class = null, $function = null)\n {\n // ...\n }\n\n public function getMessages()\n {\n // ...\n }\n}\n\nclass DataBase\n{\n protected $logger;\n\n public function __construct(LoggerInterface $logger)\n {\n $this->logger = $logger;\n }\n\n public function someDbFunction(...)\n {\n // ... do something\n\n $this->logger->put(...); // log something\n }\n}\n</code></pre>\n\n<p>This approach is called Dependency Injection. To make live easier for you, you can sue a Dependency Injection Container (also called a Service Container) to manage which classes depends on which other classes and creating those objects. A simple example is <a href=\"http://pimple.sensiolabs.org/\" rel=\"nofollow\">Pimple</a></p>\n\n<hr>\n\n<p>There are also more disadvantages of using static methods. You can for instance never have 2 different instances of the logger, as there are no instances. That means that all messages are put in the same instance. You may want to internally use a logger in the Database section of your lib and another logger in the Form section of your lib and then one logger for your complete lib.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-14T11:05:42.293",
"Id": "101655",
"Score": "0",
"body": "`With static methods, your class always knows which class it calls. That means you can never switch to another logger class` That's not entirely true. If you called the class as `static::put()` instead of `self::put()` then you can override it with [late static binding](http://php.net/lsb)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:15:17.950",
"Id": "38395",
"ParentId": "38393",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38395",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T17:51:15.423",
"Id": "38393",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"static"
],
"Title": "Writing a static Log class for PHP"
}
|
38393
|
<p>I'm a complete neophyte to Haskell with only a smidge of FP experience – I did some Racket programming academically and have written some semi-FP JavaScript professionally, but now I'm trying to learn Haskell (and FP better). So I read <a href="https://www.fpcomplete.com/school/starting-with-haskell/haskell-fast-hard" rel="nofollow">Haskell Fast & Hard</a> with no problems up until the last chapter.</p>
<p>Monads.</p>
<blockquote>
<p>Make a program that sums all of its arguments. Hint: use the function <code>getArgs</code>.</p>
</blockquote>
<p>I eventually wrote a program that nominally achieves this requirement, but it felt very hacky. For reference, here is a "correct" program by the author that I think I was supposed to model after. It sums the numbers in a comma-delimited string.</p>
<pre><code>import Data.Maybe
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x,"")] -> Just x
_ -> Nothing
getListFromString :: String -> Maybe [Integer]
getListFromString str = maybeRead $ "[" ++ str ++ "]"
askUser :: IO [Integer]
askUser = do
putStrLn "Enter a list of numbers (separated by comma):"
input <- getLine
let maybeList = getListFromString input in
case maybeList of
Just l -> return l
Nothing -> askUser
-- show
main :: IO ()
main = do
list <- askUser
print $ sum list
</code></pre>
<p>Based on the above approach, I wrote a function to convert the list of argument-strings back into a comma-delimited string so that most of the other functions could work unchanged.</p>
<pre><code>import Data.Maybe
import System.Environment (getArgs)
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x,"")] -> Just x
_ -> Nothing
getListFromString :: String -> Maybe [Integer]
getListFromString str = maybeRead $ "[" ++ str ++ "]"
getArgsAsString :: [String] -> String
getArgsAsString [] = "0"
getArgsAsString (x:xs) = x ++ "," ++ getArgsAsString xs
askUser :: [String] -> [Integer]
askUser input = case (getListFromString (getArgsAsString input)) of
Just l -> l
Nothing -> error "failsauce"
main :: IO ()
main = do
input <- getArgs
print $ sum (askUser input)
</code></pre>
<p>I am trying to stick to the spirit of the exercise and not go too far into library functions that solve the problem for me without teaching me anything (in particular, the author says not to try too hard to understand the syntax of <code>maybeRead</code>), but it feels very wrong to convert a list of strings to a comma-separated string only to split it out again into a maybe-list of integers.</p>
<p>All advice is appreciated! (But educational guidance is appreciated more than "just use xyz lib function".)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T12:22:38.537",
"Id": "63992",
"Score": "0",
"body": "If all you want to do on an invalid input is to raise an error with an inane message, then you can be done with `print $ sum $ map read input`"
}
] |
[
{
"body": "<p>The reference solution is already a bit flawed: It depends on the fact that the standard library happens to use commas to separate elements when pretty-printing lists. That's the only reason it can just throw brackets on the string and then run it through <code>reads</code> (these functions reconstruct the data structure from its pretty-printed form, e.g. <code>read \"[1,2]\" -> [1,2]</code>). If the question was about a semicolon-separated list, this approach would need significant modification.</p>\n\n<p>Building on top of this is a complete waste, I would suggest you approach the problem with a fresh mind instead. Your problem isn't complicated - you get a list of <code>String</code>s from <code>getArgs</code>, and want a list of <code>Integer</code>s to pass to <code>sum</code>. Do you know how to read an <code>Integer</code> from a <code>String</code>? Do you know how to apply an operation to all elements of a list? That's really all you need here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:36:06.233",
"Id": "64156",
"Score": "1",
"body": "It's how it's defined in the Haskell Report, so I'd say that using `read` to parse a comma-separated list is fair game, although not very efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:11:20.220",
"Id": "64448",
"Score": "1",
"body": "Sure - my point was that it's inflexible. Hard-coding the comma separation like this is simply bad style."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T23:54:30.570",
"Id": "38405",
"ParentId": "38394",
"Score": "5"
}
},
{
"body": "<p>There's very little I would salvage from the model code.</p>\n\n<ol>\n<li>Converting the arguments list into comma-separated string is a little hackish and not very efficient (nevertheless it works, and I'd be totally OK with it for a quick throw away script). Therefore I would not use <code>getListFromString</code>.</li>\n<li><code>askUser</code> is not needed since we're not interacting with the user.</li>\n<li>There's already an alternative to <code>maybeRead</code>, in <code>Text.Read</code> called <code>readMaybe</code>.</li>\n</ol>\n\n<p>This is how I would implement it:</p>\n\n<pre class=\"lang-haskell prettyprint-override\"><code>import System.Environment (getArgs)\nimport Text.Read (readMaybe)\n\nmain :: IO ()\nmain = do\n values <- fmap (map readMaybe) getArgs\n putStrLn $ maybe \"Arguments invalid\" (show . sum) $ sequence values\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-26T22:32:34.443",
"Id": "206587",
"Score": "0",
"body": "SuggestIon: instead of using `fmap` and `sequence` like that, just use `do { values <- getArgs ; putStrLn $ … $ mapM readMaybe values }`. This is immediately clearer, in my opinion; you only work in one monad at a time. If you prefer pointfree-golf, this can also be written as the one-liner `getArgs >>= putStrLn . maybe \"Arguments invalid\" (show . sum) . mapM readMaybe`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:29:58.050",
"Id": "38501",
"ParentId": "38394",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38501",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T18:10:20.590",
"Id": "38394",
"Score": "3",
"Tags": [
"beginner",
"haskell",
"functional-programming",
"type-safety"
],
"Title": "\"Hell Difficulty\" Haskell Fast & Hard"
}
|
38394
|
<pre><code>#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
{
for (int i = 0; i <= 3; i++) //give the user 4 guesses at the word.
{
std::string guess;
cout <<"Guess the word" <<endl;
cin >>guess;
if (guess == "Dog")
{
cout <<"You guessed correctly. " <<endl;
break;
}
else
{
cout <<"You guessed incorrectly. " <<endl;
}
}
char f;
cin >>f;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>#include \"stdafx.h\"</code> is superfluous.</p>\n\n<p>The standard idiom in C++ for doing something 4 times is:</p>\n\n<pre><code>for (int i = 0; i < 4; i++) {\n ...\n}\n</code></pre>\n\n<p>Don't deviate from that pattern unless there is a good reason.</p>\n\n<p>Requiring an extra character input to exit the program is a weird user experience, especially since there is no prompt. I would just get rid of <code>char f; cin >> f;</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:57:28.603",
"Id": "63964",
"Score": "0",
"body": "With such a \"pause\" in place, it's fair to assume the OP is using an IDE (probably with no built-in pause). It is also much better than `system(\"PAUSE\")`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:00:17.187",
"Id": "63965",
"Score": "0",
"body": "@Jamal That makes sense. (I usually don't use an IDE.) In that case, a comment would be useful: `// Pause so that output can be examined when running in an IDE`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:03:19.287",
"Id": "63966",
"Score": "0",
"body": "Fair enough. You may add that to your answer, especially for others not too familiar with such IDEs."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:49:34.500",
"Id": "38397",
"ParentId": "38396",
"Score": "5"
}
},
{
"body": "<p>Looks good to me. Don't know what the last <code>cin >> f</code> is for but the function runs well. Just a tip, you don't need to include the <code>std::</code> scope in front of <code>string guess</code>, as you've already declared that you're <code>using namespace std.</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T21:05:04.363",
"Id": "63969",
"Score": "3",
"body": "Note he should not be using `using namespace std;` so prefer to add `std::` to all the places it has been left off. The `cin >> f` forces the application to pause until the user hits return. If running in a hosted environment this prevents the window from closing too quickly to see the answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:50:07.970",
"Id": "38398",
"ParentId": "38396",
"Score": "0"
}
},
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p>Be sure to include <code><string></code> since you're using <code>std::string</code>.</p></li>\n<li><p>Prefer <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a> over <code>operator>></code> for all user input into an <code>std::string</code>:</p>\n\n<pre><code>std::getline(std::cin, guess);\n</code></pre></li>\n<li><p>If you want to avoid case-sensitivity issues, I'd recommend having both <code>guess</code> and the word in the same case (lowercase or uppercase).</p>\n\n<p>You can use <a href=\"http://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\"><code>std::transform()</code></a> on <code>guess</code> to make it lowercase or uppercase, and have the word provided in the same case:</p>\n\n<pre><code>// get the input\n\n// transform the guess string to all lowercase\nstd::transform(guess.begin(), guess.end(), guess.begin(), ::tolower);\n\nif (guess == \"dog\")\n{\n // ...\n}\n</code></pre></li>\n<li><p>The \"pause\" at the end is okay, but here's another one:</p>\n\n<pre><code>std::cin.get();\n</code></pre>\n\n<p>This one doesn't involve an extra variable, although it doesn't really matter. The program still \"waits\" for user input before exiting.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:50:22.010",
"Id": "38399",
"ParentId": "38396",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:19:08.187",
"Id": "38396",
"Score": "4",
"Tags": [
"c++",
"strings"
],
"Title": "Char string review"
}
|
38396
|
<p><code>Progress</code> class was written using TDD.</p>
<p>Interface of this class (pseudo-code):</p>
<pre><code>class Progress
constructor(title, progressLength)
getTitle() : String
getLength() : int
getCompletedSteps() : List<Integer>
getCompleted() : int
getUncompleted() : int
</code></pre>
<p>Please criticize from the following perspectives:</p>
<ul>
<li>OO design</li>
<li>naming</li>
<li>cleanliness</li>
<li>testing</li>
</ul>
<p><strong>Unit tests (JUnit 3):</strong></p>
<pre><code>public class TestProgress extends TestCase {
private int progressLength;
private Integer[] completedSteps;
private Progress progress;
private Progress progressWithoutCompletedSteps;
private String title;
@Override
protected void setUp() throws Exception {
super.setUp();
title = "Tested Instance";
progressLength = 200;
progress = new Progress(title, progressLength);
completedSteps = new Integer[] { 1, 2, 10, 3 };
for (Integer step : completedSteps) {
progress.complete(step);
}
progressWithoutCompletedSteps = new Progress("Title", 100);
}
public void testConstructorSetsFieldsCorrectly() {
assertEquals(title, progress.getTitle());
assertEquals(progressLength, progress.getLength());
}
public void testConstructorThrowsExceptionIfTitleIsNull() {
checkThrowsIllegalArgumentException(new Runnable() {
@Override
public void run() {
String failTitle = null;
new Progress(failTitle, 100);
}
});
}
private void checkThrowsIllegalArgumentException(Runnable runnable) {
try {
runnable.run();
fail("Missing exception");
} catch (IllegalArgumentException e) {
// all right
} catch (Exception e) {
fail("Type of exception should be IllegalArgumentException");
}
}
public void testConstructorThrowsExceptionIfProgressLengthLessThanOne() {
checkThrowsIllegalArgumentException(new Runnable() {
@Override
public void run() {
int failProgressLength = 0;
new Progress("Title", failProgressLength);
}
});
}
public void testGetCompletedSteps() {
List<Integer> expectedCompletedSteps = Arrays.asList(completedSteps);
assertEquals(expectedCompletedSteps, progress.getCompletedSteps());
}
public void testGetCompletedStepsOfProgressWithoutCompletedSteps() {
List<Integer> noCompletedSteps = new ArrayList<Integer>();
assertEquals(noCompletedSteps, progressWithoutCompletedSteps.getCompletedSteps());
}
public void testGetCompleted() {
int expectedCompleted = sumOf(completedSteps);
assertEquals(expectedCompleted, progress.getCompleted());
}
private int sumOf(Integer[] numbers) {
int sum = 0;
for (Integer each : numbers) {
sum += each;
}
return sum;
}
public void testGetCompletedOfProgressWithoutCompletedSteps() {
int expectedCompleted = 0;
assertEquals(expectedCompleted, progressWithoutCompletedSteps.getCompleted());
}
public void testGetUncompleted() {
int expectedUncompleted = progressLength - sumOf(completedSteps);
assertEquals(expectedUncompleted, progress.getUncompleted());
}
public void testGetUncompletedOfProgressWithoutCompletedSteps() {
int expectedUncompleted = progressWithoutCompletedSteps.getLength();
assertEquals(expectedUncompleted, progressWithoutCompletedSteps.getUncompleted());
}
}
</code></pre>
<p><strong>Progress class:</strong></p>
<pre><code>public class Progress {
private final String title;
private final int length;
private int completed;
private List<Integer> completedSteps;
public Progress(String title, int progressLength) {
checkArguments(title, progressLength);
this.title = title;
this.length = progressLength;
this.completedSteps = new ArrayList<Integer>();
this.completed = 0;
}
private void checkArguments(String title, int progressLength) {
if (title == null) {
throw new IllegalArgumentException("Illegal title: <" + title + ">");
}
if (progressLength < 1) {
throw new IllegalArgumentException("Illegal progress length: <" + progressLength + ">");
}
}
public String getTitle() {
return title;
}
public int getLength() {
return length;
}
public void complete(int lengthToComplete) {
completedSteps.add(lengthToComplete);
completed += lengthToComplete;
}
public List<Integer> getCompletedSteps() {
return completedSteps;
}
public int getCompleted() {
return completed;
}
public int getUncompleted() {
return length - completed;
}
}
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>In addition to what is written.</p>
<p>In your opinion, is the following version of the constructor better than the one already shown?</p>
<pre><code> public Progress(String title, int progressLength) {
this.title = title;
this.length = progressLength;
this.completedSteps = new ArrayList<Integer>();
this.completed = 0;
checkInitState();
}
private void checkInitState() {
if (title == null) {
throw new IllegalArgumentException("Illegal title: <" + title + ">");
}
if (progressLength < 1) {
throw new IllegalArgumentException("Illegal progress length: <" + progressLength + ">");
}
}
</code></pre>
<p>Or I should not check the correctness of the arguments in the constructor? Maybe it would be better if the obligation to ensure the correctness of the arguments entrust to the client?</p>
|
[] |
[
{
"body": "<p>It's not clear to me, what is the purpose of this class? Is it a progress tracker for a process with discrete steps (such as for a multi-page survey) or for a progress bar (such as for a filesystem consistency scanner)? In <code>.complete(int lengthToComplete)</code>, the first line (<code>completedSteps.add(lengthToComplete)</code>) suggests the former, whereas the second line (<code>completed += lengthToComplete</code>) suggests the latter.</p>\n\n<p>Is the <code>progressLength</code> constructor argument supposed to indicate the maximum number of elements expected for the <code>ArrayList</code>? If so, use it as a size hint when constructing the <code>ArrayList</code>. Also consider just using an <code>int[]</code> array if you know an upper bound for the array length.</p>\n\n<p>I'm not comfortable with the idea of returning an a <code>List<Integer></code> from <code>.getCompletedSteps()</code>. Since the returned list is mutable, you're giving away the ability for other code to muck with the internal state of this object. It would be better to expose a more minimal interface, such as <code>public boolean isCompleted(int step)</code>. The <code>.isCompleted(int)</code> method would mirror <code>.complete(int)</code> nicely, which is an indicator of a better design. It also does not commit you to using a <code>List<Integer></code> in your implementation; you would be free to change the internal representation to use any suitable data structure in the future.</p>\n\n<p>To avoid ambiguity, I would rename <code>getCompleted()</code> to <code>getCompletedCount()</code>, and <code>getUncompleted()</code> to <code>getIncompleteCount()</code>.</p>\n\n<p>If you are going to check that the preconditions are satisfied, do so as early as possible, before you even get a chance to use the possibly illegal parameter values.</p>\n\n<p>If this class is to be used with a GUI, it might be useful to add some event-handling functionality to it: <code>.addProgressListener(…)</code>, <code>.removeProgressListener(…)</code>. Then, whenever someone calls <code>.complete()</code>, you call <code>.fireProgressEvent()</code> to notify all listeners.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T21:15:41.957",
"Id": "38403",
"ParentId": "38401",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38403",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:38:59.213",
"Id": "38401",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"unit-testing",
"tdd"
],
"Title": "Simple class to represent progress"
}
|
38401
|
<p>Needed a quick stream to get JSON objects.</p>
<pre><code>#ifndef THORSANVIL_SIMPLE_STREAM_THOR_STREAM_H
#define THORSANVIL_SIMPLE_STREAM_THOR_STREAM_H
#include <istream>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <curl/curl.h>
#include <string.h>
namespace ThorsAnvil
{
namespace Stream
{
extern "C" size_t writeFunc(char* ptr, size_t size, size_t nmemb, void* userdata);
extern "C" size_t headFunc(char* ptr, size_t size, size_t nmemb, void* userdata);
class IThorStream;
class IThorSimpleStream: public std::istream
{
friend class IThorStream;
struct SimpleSocketStreamBuffer: public std::streambuf
{
typedef std::streambuf::traits_type traits;
typedef traits::int_type int_type;
SimpleSocketStreamBuffer(std::string const& url, bool useEasyCurl, bool preDownload, std::function<void()> markStreamBad)
: empty(true)
, open(true)
, sizeMarked(false)
, droppedData(false)
, preDownload(preDownload)
, sizeLeft(0)
, markStreamBad(markStreamBad)
{
curl = curl_easy_init();
if(!curl)
{ markStreamBad();
}
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunc);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headFunc);
curl_easy_setopt(curl, CURLOPT_WRITEHEADER, this);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl, CURLOPT_PRIVATE, this);
if (useEasyCurl)
{
/* Perform the request, res will get the return code */
CURLcode result = curl_easy_perform(curl);
if ((result != CURLE_OK) && (result != CURLE_WRITE_ERROR))
{ markStreamBad();
}
}
}
~SimpleSocketStreamBuffer()
{
curl_easy_cleanup(curl);
}
virtual int_type underflow()
{
if (droppedData)
{ markStreamBad();
}
return EOF;
}
protected:
friend size_t writeFunc(char* ptr, size_t size, size_t nmemb, void* userdata)
{
std::size_t bytes = size*nmemb;
SimpleSocketStreamBuffer* owner = reinterpret_cast<SimpleSocketStreamBuffer*>(userdata);
std::unique_lock<std::mutex> lock(owner->mutex);
if ((!owner->empty) && (!owner->preDownload))
{
// Its not bad yet.
// It only becomes bad if the user tries
// to read any of this data. Then we mark
// it bad. So the actual marking bad is done
// in underflow().
owner->droppedData=true;
return 0;//CURL_WRITEFUNC_PAUSE;
}
owner->empty = false;
std::size_t oldSize = owner->buffer.size();
owner->buffer.resize(oldSize + bytes);
std::copy(ptr, ptr + bytes, &owner->buffer[oldSize]);
owner->setg(&owner->buffer[0], &owner->buffer[0], &owner->buffer[oldSize + bytes]);
owner->cond.notify_one();
if (owner->sizeMarked)
{
owner->sizeLeft -= bytes;
owner->open = (owner->sizeLeft != 0);
}
return bytes;
}
friend size_t headFunc(char* ptr, size_t size, size_t nmemb, void* userdata)
{
if (strncmp(ptr, "HTTP/", 5) == 0)
{
int respCode = 0;
char* space = strchr(ptr+5, ' ');
if ((space != NULL) && (sscanf(space," %d OK", & respCode) == 1) && (respCode == 200))
{ /* GOOD */ }
else
{
SimpleSocketStreamBuffer* owner = reinterpret_cast<SimpleSocketStreamBuffer*>(userdata);
std::unique_lock<std::mutex> lock(owner->mutex);
owner->markStreamBad();
}
}
if (strncmp(ptr, "Content-Length:", 15) == 0)
{
SimpleSocketStreamBuffer* owner = reinterpret_cast<SimpleSocketStreamBuffer*>(userdata);
std::unique_lock<std::mutex> lock(owner->mutex);
owner->sizeLeft = atoi(ptr+15);
owner->sizeMarked = true;
if (owner->preDownload)
{
owner->buffer.reserve(owner->sizeLeft);
}
}
return size*nmemb;
}
bool empty;
bool open;
bool sizeMarked;
bool droppedData;
bool preDownload;
std::size_t sizeLeft;
std::mutex mutex;
std::condition_variable cond;
std::vector<char> buffer;
CURL* curl;
std::function<void()> markStreamBad;
};
SimpleSocketStreamBuffer buffer;
public:
IThorSimpleStream(std::string const& url, bool preDownload = false)
: std::istream(NULL)
, buffer(url, true, preDownload, [this](){this->setstate(std::ios::badbit);})
{
std::istream::rdbuf(&buffer);
}
};
}
}
#endif
</code></pre>
<p>It was inspired by this gist:<br>
<a href="https://gist.github.com/Loki-Astari/8201956" rel="nofollow noreferrer">https://gist.github.com/Loki-Astari/8201956</a></p>
<p>Which uses an early version of this code and my JSON library to easily make REST calls to an HTTP enpoint and retrieve the JSON response object directly into an object with no manual parsing. The JSON parsing code has already been reviewed here:</p>
<p><a href="https://codereview.stackexchange.com/questions/11138/json-serializer">JSON Serializer</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T08:19:31.603",
"Id": "63978",
"Score": "0",
"body": "The only thing which strikes me as odd is: Why does all the implementation have to reside in a header file? I usually try to keep my header files lean and mean. Unfortunately with template programming that is not always possible but unless I'm blind this doesn't apply here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:28:31.180",
"Id": "64069",
"Score": "4",
"body": "@ChrisWue: Its called a header only library. It means that to use it you just need to `#include` the header file no further requirements on libraries required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:30:10.860",
"Id": "64070",
"Score": "0",
"body": "@ChrisWue: I am working on an async version that requires linking against a library (as there are certain limitations in the above implementation). The alternatives will be available for code review shortly. But you can see me tinkering in the git hub project: https://github.com/Loki-Astari/ThorsStream"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:43:27.523",
"Id": "64086",
"Score": "0",
"body": "@ChrisWue: http://codereview.stackexchange.com/questions/38455/http-stream-part-2-a-stream-that-opens-an-http-get-and-then-acts-like-a-normal-c"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T17:53:32.480",
"Id": "74593",
"Score": "0",
"body": "@mats-mug Available here: https://github.com/Loki-Astari/ThorsStream along with https://github.com/Loki-Astari/ThorsSerializer Cool gist of it in action https://gist.github.com/Loki-Astari/8201956#file-gistfile2-cpp"
}
] |
[
{
"body": "<p>I have a few comments that are unrelated to the synchronous/asynchronous and/or header-only nature of the code.</p>\n<h2>parameters</h2>\n<h3>bools</h3>\n<p>I don't like passing <code>bool</code>s as parameters. I really dislike a function like your <code>SimpleSocketStreamBuffer</code> constructor that take <em>multiple</em> <code>bool</code>s. You need to do a fair amount of looking to be sure how:</p>\n<pre><code>foo x("www.google.com", false, true, bar);\n</code></pre>\n<p>differs from:</p>\n<pre><code> foo x("www.google.com", true, false, bar);\n</code></pre>\n<p>(...and the same for the other variations as well). I'd strongly prefer to create an enumeration and have the parameters of that type.</p>\n<h3>std::function</h3>\n<p>I don't like passing a <code>std::function</code> as a parameter either. I'd prefer to see a template parameter to specify the function type, and then use an <code>std::function</code> only internally for storage. With those, the constructor looks something like this:</p>\n<pre><code>enum class curl_type { easy, hard };\nenum class dl_strategy { lazy, greedy };\n\ntemplate <class func>\nSimpleSocketStreamBuffer(std::string const& url, \n curl_type ct, \n dl_strategy download, \n func markStreamBad)\n</code></pre>\n<p>Then we modify the remainder to suit:</p>\n<pre><code>, preDownload(download == dl_strategy::greedy)\n</code></pre>\n<p>and:</p>\n<pre><code>if (ct == curl_type::easy)\n // ...\n</code></pre>\n<p>Of course, if you're going to do this, you want to do it throughout (e.g., to the stream definition, not just the stream buffer definition).</p>\n<p>Using these, defining an object looks more like this:</p>\n<pre><code>foo x("www.google.com", curl_type::easy, dl_strategy::greedy, bar);\n</code></pre>\n<p>...which strikes me as quite a bit more self-explanatory.</p>\n<h2>userdata pointer</h2>\n<p>In <code>writeFunc</code> and <code>headerFunc</code>, it would probably be best to verify that <code>userdata</code> isn't a null pointer before using it. Once you've verified that it's non-null, I think I'd prefer to define <code>owner</code> as a reference instead of a pointer:</p>\n<pre><code>SimpleSocketStreamBuffer & owner = *reinterpret_cast<SimpleSocketStreamBuffer*>(userdata);\n</code></pre>\n<p>This prevents accidentally re-assigning <code>owner</code> to point anywhere else, and (arguably) simplifies the rest of the code a bit by letting you use <code>.</code> instead of <code>-></code> when you're dealing with the <code>owner</code> object.</p>\n<h2>buffer manipulation</h2>\n<p>I also don't particularly like the code you used to add data to the end of the buffer:</p>\n<pre><code>owner->buffer.resize(oldSize + bytes);\nstd::copy(ptr, ptr + bytes, &owner->buffer[oldSize]);\n</code></pre>\n<p>I think I'd prefer to just insert the data in a single step:</p>\n<pre><code>owner->buffer.insert(owner->buffer.end(), ptr, ptr + bytes);\n</code></pre>\n<h2>lambda syntax</h2>\n<p>There's one other change I'd consider, but I'm a bit less certain about whether I'd actually make it. A lambda that takes no parameters doesn't need to include empty parens. Using this (and taking the preceding changes into account) the ctor for <code>IThorSimpleStream</code> can end up looking like this:</p>\n<pre><code>IThorSimpleStream(std::string const& url, dl_strategy s = dl_strategy::lazy)\n : std::istream(NULL)\n , buffer(url, curl_type::easy, s, [this]{this->setstate(std::ios::badbit); })\n {\n std::istream::rdbuf(&buffer);\n }\n</code></pre>\n<p>Particularly given the degree to which people are undoubtedly accustomed to using empty parens when defining functions, this <em>could</em> lead to some confusion. I suspect when people are more accustomed to lambda syntax, we'll probably view the empty parens are kind of foolish looking, but for now it <em>may</em> be better to leave them there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T08:05:02.940",
"Id": "74550",
"Score": "0",
"body": "Thanks, I like all those. I did not know about dropping the empty param (not sure I like it (might get used to) but some experimenting is in order)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:01:56.163",
"Id": "43205",
"ParentId": "38402",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "43205",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:45:53.190",
"Id": "38402",
"Score": "14",
"Tags": [
"c++",
"socket",
"stream",
"curl",
"http"
],
"Title": "Stream that opens an HTTP GET and then acts like a normal C++ istream"
}
|
38402
|
<p><a href="http://projecteuler.net/problem=82" rel="nofollow noreferrer">Project Euler problem 82</a> asks:</p>
<p><img src="https://i.stack.imgur.com/LXxVG.png" alt="enter image description here"></p>
<p>Here's my solution:</p>
<pre><code>def main():
matrix = [
[131, 673, 234, 103, 18],
[201, 96, 342, 965, 150],
[630, 803, 746, 422, 111],
[537, 699, 497, 121, 956],
[805, 732, 524, 37, 331]
]
size = len(matrix)
best = [matrix[row][0] for row in range(size)]
for col in range(1, size):
column = [matrix[row][col] for row in range(size)]
tmp = column[:]
for i in range(size):
column[i] += best[i] # right
for j in range(0, i): # up
if sum([best[j]]+tmp[j:i+1]) < column[i]:
column[i] = sum([best[j]]+tmp[j:i+1])
for k in range(i, size): # bottom
if sum([best[k]] +tmp[i:k+1]) < column[i]:
column[i] = sum([best[k]] +tmp[i:k+1])
best = column
#print(best)
return min(best)
if __name__ == "__main__":
print(main())
</code></pre>
<p>Please advise how it can be improved.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T23:30:18.207",
"Id": "63970",
"Score": "0",
"body": "[Here's a interesting read on #82](http://csjobinterview.wordpress.com/2012/08/03/project-euler-problem-82/) if you haven't seen it yet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T09:26:31.117",
"Id": "63982",
"Score": "0",
"body": "@megawac This solution uses the same strategy described in the article, except that it's already more eloquent."
}
] |
[
{
"body": "<p>To solve the Project Euler challenge, you'll have to handle a large matrix from a file. Therefore, your function should accept the matrix as a parameter.</p>\n\n<p>You used <code>size</code> to represent both the number of rows and the number of columns. I would use two variables to avoid hard-coding the assumption that the input is a square matrix.</p>\n\n<p>Your dynamic programming algorithm is sound. I would use the <code>min()</code> function to avoid finding the minimum by iteration. Also, setting <code>best</code> all at once instead of mutating the elements of <code>column</code> avoids having to copy <code>column</code> into a temporary variable.</p>\n\n<pre><code>def euler82(matrix):\n nrows, ncols = len(matrix), len(matrix[0])\n best = [matrix[row][0] for row in range(nrows)]\n\n for col in range(1, ncols):\n column = [matrix[row][col] for row in range(nrows)]\n\n best = [\n # The cost of each cell, plus...\n column[row] +\n\n # the cost of the cheapest approach to it\n min([\n best[prev_row] + sum(column[prev_row:row:(1 if prev_row <= row else -1)])\n for prev_row in range(nrows)\n ])\n for row in range(nrows)\n ]\n\n #print(best)\n\n return min(best)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T09:07:18.863",
"Id": "38412",
"ParentId": "38404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38412",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T22:58:46.347",
"Id": "38404",
"Score": "2",
"Tags": [
"python",
"project-euler",
"matrix",
"dynamic-programming"
],
"Title": "Project Euler #82 - path sum: three ways"
}
|
38404
|
<p>I consider myself a beginner at writing in Java. I have never had a programming class, nor had my code reviewed. I have come to Code Review for some pointers. (Tips that is, not data references.). I have written a simple server/client set, where the server behaves as a textual message relay, receiving and forwarding text between clients. This is not my first attempt at writing socket programs, and I want to know if I am on the right track when it comes to handling data and structuring my code in general. I must warn you, it’s a reasonably big sample.</p>
<p>Before I dump my code on the page, I would like to write some concerns of my own. In some cases, I don’t know or fully understand a better solution. In others I really couldn’t be bothered fixing it.
Concerns and questions:</p>
<p>I really can’t be bothered fixing things and doing it ‘the right way’ for this single purpose. It seems, from reading other Code Review posts, code structure is taken very seriously. I try to get the job done in any consistent and logical manner.</p>
<p>I don’t know if I have murdered OO Programming by enclosing SIX classes. Maybe the Entry classes can be condensed into the standard Client and Server objects. (I won’t reuse this code.) Have I fractured these two programs too much?</p>
<p>Is my user input command parsing (in the crudest sense of the word parsing) adequate? Commands don’t accept parameters directly, and must ask for them after processing.</p>
<p>Is there a better method for storing/handling client connections than my custom ClientCollection class? Is the current client disconnection handling any good? I would think a more event-based version would be nicer, but I simply don’t know how.</p>
<p>It has been said that ignoring exceptions is the mark of a naïve programmer. Are (any of) my <code>// ignore</code> filled catch clauses correct?</p>
<p>I feel like a crotchety man faced with the monkey bars when it comes to using Locks and Conditions. Are there holes in my concurrent coordination?</p>
<p>I run NetBeans IDE (Best thing). Is that red line on the right of the source code editor the threshold of too-deep structures? If so, my code is ‘shallow’ enough. The worst parts, I fear, are the client listener of the server, and client message listener of the client. This is due to the control structures concerned with locks. Maybe I could restructure these sections and separate them into individual methods…</p>
<p>My comments are sort of self-moderated and seem insufficient.</p>
<p>I have left streams to be passed by argument, for if I ever want to plug in some sort of ‘custom console’. That’ll never happen. Not with project.</p>
<p>I have posted some samples and a link to the full files on Dropbox. Happy reading. Happy Deciphering. </p>
<p>Command ‘Parsing’:</p>
<pre><code>private void parseCommand(String command){
//switch statement
switch(command){
case "/help":
writeOutput("\n commands:"
+ "\n /help"
+ "\n /connect"
+ "\n /disconnect"
+ "\n /broadcast"
+ "\n /exit");
break;
case "/connect":
try{
String host = readLine("\nhostname: (IP)\n");
int port = readInteger("port to connect to: ");
serverHandler.openServer(host, port);
} catch(IOException | NumberFormatException e){
writeOutput("unable to connect");
}
break;
case "/disconnect":
writeOutput("\ndisconnecting...");
serverHandler.closeServer();
break;
// … …
}
</code></pre>
<p>Some awkward code:</p>
<pre><code>public void closeHandler() throws IOException, InterruptedException{
if(alive){
alive = false; // kill
open = false; // interrupt client search
if(serverSocket != null){
serverSocket.close();
}
clientListenerLock.lock();
try{
clientArrayNotFull.signal(); // end this loop
open = true; // escape the listenerOpens check (thread is dead and
clientListenerOpens.signal(); // nothing else will happen after this)
} finally{ // alive == false will end thread
clientListenerLock.unlock();
}
join();
}
}
</code></pre>
<p>My ClientCollection class:</p>
<pre><code>class ClientCollection{
Client[] clientArray;
Lock clientArrayLock;
PrintWriter outputStream;
ClientCollection(int clientLimit, PrintStream outputStream){
clientArray = new Client[clientLimit];
clientArrayLock = new ReentrantLock();
this.outputStream = new PrintWriter(outputStream, true);
}
public void addClient(Socket newClientSocket) throws IOException{
clientArrayLock.lock();
try{
Client newClient = new Client(newClientSocket, this);
if(!full()){
int nextSlot = nextAvailableClientSlot();
clientArray[nextSlot] = newClient;
newClient.assignIndex(nextSlot);
newClient.start();
writeOutput("client " + nextSlot + " added");
} else{
newClient.disconnect(); // reject
}
} finally{
clientArrayLock.unlock();
}
}
public void removeClient(int clientIndex){
clientArrayLock.lock();
try{
Client oldClient = clientArray[clientIndex];
clientArray[clientIndex] = null; // off register
oldClient.message(">> closed by server");
oldClient.disconnect();
writeOutput("client " + clientIndex + " kicked");
} finally{
clientArrayLock.unlock();
}
}
public void reportDisconnect(int clientIndex){ // notice no .disconnect()
if(clientArray[clientIndex] != null){ // ie not already kicked
clientArrayLock.lock();
try{
clientArray[clientIndex] = null;
writeOutput("client " + clientIndex + " disconnected");
} finally{
clientArrayLock.unlock();
}
}
}
// … …
}
</code></pre>
<p>My projects (including plain source code) can be found at <a href="https://www.dropbox.com/s/lu4l402gz2a3yyi/messageBroadcast.zip" rel="nofollow">https://www.dropbox.com/s/lu4l402gz2a3yyi/messageBroadcast.zip</a>. I would be grateful if someone could give me some feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:17:51.817",
"Id": "63988",
"Score": "1",
"body": "\"I really can’t be bothered fixing things and doing it ‘the right way’ for this single purpose.\" That's a bad attitude to request a code review with. Or did I misunderstand you there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:28:41.550",
"Id": "64085",
"Score": "0",
"body": "What I mean here is that for a project that no one else is going to see or use, I usually keep a working part working. Is the term 'Refactoring'? I am a little scared of this process, so I either RESTART or leave it alone. What I am trying to achieve here, is doing the right way the first time around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:18:59.550",
"Id": "64119",
"Score": "0",
"body": "If you're afraid to change something because it could break something, you shouldn't be coding in my opinion. No no no, let me explain: Part of the biggest problems in IT are people which are stuck in the \"meh, why change it, it works\" mentality. It's not \"preserving state\" or \"keeping it working\", it's pushing technical debt and work down the road. Fix things that need to be fixed, refactor everything that needs to be refactored, change names left and right if that makes your code better, fix bugs and problems you introduced...don't be afraid of change, ever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:22:37.063",
"Id": "64120",
"Score": "0",
"body": "As an analogy, imagine you build a table in your spare time for your dining room. It's not a pretty table and it wobbles slightly when touched, but it is a table you can eat on...should you build or buy a better one? Why should you, you can eat on it, sure from time to time you spill some milk because somebody kicked it and it wobbled so heavily that the glasses fell off, but it works, right? Okay, the leg came off the other day, but a nail fixed it, it works, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:28:06.100",
"Id": "64121",
"Score": "0",
"body": "If you're afraid that changes might break something, you should have a look into test driven development. Also I *completely* understand what you mean by \"why should I invest time into something that only I am using?\", but the answer is clearly in that case \"for yourself\"...if you can spare the time, obviously. Rewriting code, refactoring structures, even only thinking about doing it will make you a better coder at the end of the day. Will the code after refactoring be easier to read? Easier to use? Faster? Better? Higher? Don't you want to know if *you* can do better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:08:34.220",
"Id": "64306",
"Score": "0",
"body": "I suppose I will get better at rewriting my code if I practice. would you suggest backing up source files if major changes are to occur?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T17:20:01.713",
"Id": "64359",
"Score": "0",
"body": "Wait, you're not using a version control system?! Okay, that's step 0 when starting to code. SVN, Git, Mercurial, Bazaar and CVS are pretty much the widest used ones, you should know at least two of them and how to handle them. Never code without a version control system, it will ease your life a thousand times over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T05:25:04.603",
"Id": "64409",
"Score": "0",
"body": "Well, I code for something to do, you know, just for fun. I enjoy solving problems and to play God with the computer (thus my custom client buffer). I do not consider this project or any other one I have ever done as 'my life' or of the kind. If the code was deleted, I suppose I would rewrite it. I wouldn't be too depressed. Maybe the new code would be better. If I was going to work on any big project, though, a version handler would be a good idea."
}
] |
[
{
"body": "<p>You have a lot of things in here to review, so I am just going to cherry-pick the things that stand out to me:</p>\n\n<ul>\n<li>It is unconventional to use the new-line handling you have... It is normal to assume that the 'cursor' is at the start of a line when you print, instead of assuming it is at the end of the previous line. For example, this is 'normal' <code>writeOutput(\"Hello there\\n\");</code> instead of <code>writeOutput(\"\\nHelloThere\");</code>. While what you have is not 'wrong', it can lead to odd behavioud on terminals that use the last line of the screen for the prompt, and it may over-write your last message.</li>\n<li>your exception handling <strong>is</strong> poor. Take for example the line <code>writeOutput(\"unable to connect\");</code> when you cannot connect to a host. The user (you) will want to know if that is because they mis-typed <code>www.goog1e.com</code> or the port number <code>8O</code> (intentionally got errors in those). You should at least help the user fix their mistakes.</li>\n<li>in the 'awkward' code you have <code>serverSocket.close()</code>. <code>java.net.ServerSocket</code> is an actual class that is commonly used in Java Server applications. You should avoid using names that make your regular socket appear to be a <code>ServerSocket</code> (which is an entirely different, though related, thing).</li>\n<li><code>ClientCollection</code> should just be something from <code>java.util.concurrent.*</code> (a <code>ConcurrentHashMap</code> probably). You are reinventing the wheel there, and your implementation is not as robust as others. There is no point in reviewing that code.</li>\n</ul>\n\n<p>In general, your locks follow the pattern (lock-try-finally-unlock) which is good, but, apart from that there is not enough context to determine whether it is right or not. There are <strong>some</strong> problems, like:</p>\n\n<ul>\n<li><code>clientArrayNotFull.signal(); // end this loop</code> What loop?, and why are you signalling that there is space in the Collection when you have done nothing to create space?</li>\n<li>why do you set <code>open</code> to false, and then back to true? There is nothing to suggest that anything will actually <strong>see</strong> it being false (you do not show us the declaration of <code>open</code>. In other words, this makes no sense: <code>open = false; // interrupt client search</code> ... setting a boolean to false is not going to interrupt anything.... and, if those other things are waiting to get a signal with a 'false' value, well, they will be disappointed because <code>open</code> will be back to true when they get the signal.</li>\n</ul>\n\n<p>In general, you have not given enough context to evaluate the concurrency handling. What you have shown hints at there being other problems too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:19:34.613",
"Id": "64308",
"Score": "0",
"body": "My awkward code does a number of bizarre things: it has to deal with each set of locks in order. first, to exit the client search, open is set to false and is signaled. That is not the end of the story: now the code waits for the client search to begin again (before `alive==false` while-loop is checked). to escape this, open is set to true, a signal is sent, and the whole `while(alive){}` loop is exited. this is obviously unnatural code that solves a problem that the code itself creates. I have never used a has map, and I was wondering about the usual ways to write to the output. thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T05:29:30.543",
"Id": "64410",
"Score": "0",
"body": "I have since edited some things. I am still at a loss as to what should be done when closing a socket _fails_: \"Sorry sir, I can't delete your important data. You must retain it - there is no other way around it.\" My new edit throws a Runtime Exception. I guess I am relying on the GC to clean up after me here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T06:02:25.070",
"Id": "38481",
"ParentId": "38410",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T07:05:37.943",
"Id": "38410",
"Score": "3",
"Tags": [
"java",
"server"
],
"Title": "Helping my coding style with a java text server"
}
|
38410
|
<p>I wonder if my script is all right. Please review my code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Menu</title>
<style>
ul {list-style-type:none; margin:0; padding:0;}
li {display:inline;}
a.active {background:red;}
</style>
</head>
<body>
<ul>
<li><a href="http://www.example.com/home">Home</a></li>
<li><a href="http://www.example.com/news">News</a></li>
<li><a href="http://www.example.com/contact">Contact</a></li>
<li><a href="http://www.example.com/about">About</a></li>
</ul>
<script>
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].href == document.URL) {
document.links[i].className = 'active';
}
}
</script>
</body>
</html>
</code></pre>
<p>It should highlight the current page link in the navigation bar.</p>
|
[] |
[
{
"body": "<p>you can use these for <code><a></code> tag</p>\n\n<pre><code>a:link {color:#FF0000;} /* unvisited link */\na:visited {color:#00FF00;} /* visited link */\na:hover {color:#FF00FF;} /* mouse over link */\na:active {color:#0000FF;} /* selected link */\n</code></pre>\n\n<p>See this <a href=\"http://jsbin.com/OCUYALI/2/\" rel=\"nofollow\">DEMO</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:49:30.440",
"Id": "63991",
"Score": "1",
"body": "Thanks for the answer, but my question is mainly focused on the `script` tag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T12:51:07.517",
"Id": "63993",
"Score": "0",
"body": "what do you want with script"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-30T14:29:16.230",
"Id": "376325",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:46:19.400",
"Id": "38414",
"ParentId": "38413",
"Score": "-3"
}
},
{
"body": "<h1><code>querySelectorAll</code></h1>\n\n<p>Here's another approach, if you don't mind older browsers. You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll\" rel=\"noreferrer\"><code>querySelectorAll</code></a> instead of <code>document.links</code>. That way, <a href=\"http://jsfiddle.net/Hmb54/\" rel=\"noreferrer\">you end up with a smaller result set</a> rather than all links, and save you CPU cycles for running the loop.</p>\n\n<p>In this case, we get only those links that have the same <code>href</code> value as the current document url:</p>\n\n<pre><code>var links = document.querySelectorAll('a[href=\"'+document.URL+'\"]');\n</code></pre>\n\n<p>However, note the <a href=\"http://caniuse.com/queryselector\" rel=\"noreferrer\">browser compatibility</a> and there are quirks across implementations.</p>\n\n<h2>Not all links need <code>active</code></h2>\n\n<p>Now if you think about it, not all links with the <code>document.URL</code> need to have <code>active</code>. Say you have <code>active</code> set the font to <code>2em</code>. If you get all links that point to the same page, they'd be <code>2em</code> in size, regardless of where they are in the page!</p>\n\n<p>Most likely, you only need it for the primary navigation. Consider adding a class to further refine the result set.</p>\n\n<pre><code><ul class=\"navigation\">\n <li><a href=\"http://www.example.com/home\">Home</a></li>\n <li><a href=\"http://www.example.com/news\">News</a></li>\n <li><a href=\"http://www.example.com/contact\">Contact</a></li>\n <li><a href=\"http://www.example.com/about\">About</a></li>\n</ul>\n\n// Getting only the links that are in .navigation\nvar links = document.querySelectorAll('.navigation a[href=\"'+document.URL+'\"]');\n\n// More specific CSS\n.navigation a.active {background:red;}\n</code></pre>\n\n<h1><code>className</code></h1>\n\n<p>Now you have to note that setting <code>className</code> <em>replaces it</em> with the value, <a href=\"http://jsfiddle.net/u7VE2/2/\" rel=\"noreferrer\">like this example</a>. If the links you have happen to have existing classes (and styles that come with them), your script will unintentionally remove their styles due to the replaced <code>className</code>.</p>\n\n<p>What you can do is get the existing <code>className</code> value, split them by spaces (multiple class names are separated by spaces), append your class name, join them back <em>and then</em> change the value, <a href=\"http://jsfiddle.net/u7VE2/1/\" rel=\"noreferrer\">like I did here</a>:</p>\n\n<pre><code>var element = document.getElementById('change');\nvar classNames = element.className.split(' ');\nclassNames.push('huge');\nelement.className = classNames.join(' ');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T12:57:47.873",
"Id": "38417",
"ParentId": "38413",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "38417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:41:54.843",
"Id": "38413",
"Score": "4",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Highlight the active link in a navigation menu"
}
|
38413
|
<p>I am still fairly green when it comes to SQL joins. The below code works but I want to check that I am doing it the best way before I copy and paste errors into other work in the future.</p>
<p>The idea of the below code is to get the <code>PropertyID</code> and <code>Name</code> of a property from the first Table and using the <code>PropertyID</code> join them. In this case I am actually using every field in Table B (thus the *).</p>
<pre class="lang-html prettyprint-override"><code><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQL %>"
SelectCommand="
select TblA.PropertyID as PId, TblA.Propertyname as PNa, TblB.*
from TbPropertyDetails as TblA
inner join TbPropertyDetailsSafeguarding as TblB on TblA.PropertyID = TblB.PropertyID
where TblA.RegionID <> '0' and TblA.PropertyID LIKE '%' + @PropertyID + '%'
order by TblA.PropertyID asc;"
>
<SelectParameters>
<asp:SessionParameter DefaultValue="" Name="PropertyID" SessionField="PropertyID"
Type="string" />
</SelectParameters>
</asp:SqlDataSource>
</code></pre>
<p>I am programming in VB.net but this is really standalone SQL.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:11:04.493",
"Id": "63998",
"Score": "0",
"body": "Do you mean Microsoft SQL? If so that is the one I am using, do you need more detail"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:37:42.340",
"Id": "64003",
"Score": "0",
"body": "Do you want to show all properties or just those which are in the TblB too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:42:20.787",
"Id": "64007",
"Score": "0",
"body": "Have you tested this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:47:18.317",
"Id": "64009",
"Score": "1",
"body": "Yes, it works and filters correctly. The SessionParameter relates to @PropertyID"
}
] |
[
{
"body": "<p>In this small of a query I wouldn't alias anything. It doesn't make it any more readable and you don't use those column aliases anywhere else in the <strong>query</strong>.</p>\n\n<p>Don't do the reporting stuff on the SQL Server. you can set the title of the column in the datagrid. Don't do it here, it creates clutter if you try to do it in the SQL.</p>\n\n<p>Whatever you are using to display this data is what you should use to give it a <strong><em>display title</em></strong>. </p>\n\n<p>Always separate <strong>retrieving data</strong> from <strong>displaying data</strong> it makes it easier to code.</p>\n\n<hr>\n\n<p>I assume that you have all of your RegionID's Positive so you could change the query from</p>\n\n<pre><code>WHERE RegionID <> '0'\n</code></pre>\n\n<p>to </p>\n\n<pre><code>WHERE RegionID > 0\n</code></pre>\n\n<p>I hope that <code>RegionID</code> is an <strong>Integer</strong> in which case the <code>'</code> are not needed because they make it a string.</p>\n\n<hr>\n\n<p>Something else that I just noticed, must have been an addition when you edited your post. </p>\n\n<pre><code>WHERE TblA.PropertyID LIKE '%' + @PropertyID + '%'\n</code></pre>\n\n<p>I always think of an ID field being an integer, and if that is the case then you shouldn't (and <strong>CANNOT</strong>) use Wildcards or the <code>LIKE</code> operator on that column. <em>I really don't know how it is running like that.</em> </p>\n\n<p>the <code>LIKE</code> Operator uses a lot of performance as well, <em>so let's say it works</em>, why would you want to do this in the first place, if you put in\n<code>1</code> for <code>@PropertyID</code> it will bring back records with a <code>PropertyID</code> of </p>\n\n<pre><code>1,11,111,1111,12,13,14,15,16,17,18,19,21,31,41,51,61,71,81,91,(100 <= x < 200)... \n</code></pre>\n\n<p>if you put in <code>13</code> you will get </p>\n\n<pre><code>13,113, 133,1413,1313,1334,1113,2132,1132, ...\n</code></pre>\n\n<p>I don't see this as being what you want to functionally happen in this query</p>\n\n<hr>\n\n<p>You don't need this in the Query</p>\n\n<pre><code>ORDER BY TblA.PropertyID ASC\n</code></pre>\n\n<p>This should be done in the VB code as well.</p>\n\n<hr>\n\n<p>This is more of a common coding practice type of thing (<strong>nitpick</strong>) all of your reserved words should be in all Caps</p>\n\n<pre><code>WHERE, JOIN, INNER, SELECT, LIKE, FROM, ORDER BY, AND, AS, ON\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:09:42.253",
"Id": "63997",
"Score": "0",
"body": "Typo correct re:alias. The alias will be used in the datagrid (not show here). The idea is to show a small example and if that is correct then I can use it as a baseline going forward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:24:26.430",
"Id": "64001",
"Score": "0",
"body": "don't do the reporting stuff on the SQL Server. you can set the title of the column in the datagrid. don't do it here, it's clutter. and those aren't very good Aliases anyway"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:26:59.607",
"Id": "64002",
"Score": "0",
"body": "The alias is for the datafield on the datagrid. How would you do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:39:13.547",
"Id": "64005",
"Score": "0",
"body": "regionID is an Integer. Nice idea, marginal gains :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:20:50.093",
"Id": "64126",
"Score": "0",
"body": "Nitpik away :-) That's the whole idea. The wild card is the client specific request (I agree it's not ideal but when off site they sometimes can not remember the full site ID, what I might do it put a Site Name and wild card that and have Property ID with no wildcard)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:21:43.160",
"Id": "64127",
"Score": "0",
"body": "In terms of doing the sort in the VB code this code sites on the .aspx page so is in the VB code (?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:37:03.797",
"Id": "64157",
"Score": "0",
"body": "SQL is never run by asp.net or VB, the VB holds the Query statement in text format and when it is executed it is still executed on the SQL Server not on the ASP.NET Server. the VB should pull the information you need, then sort, then display. or display then allow the user to decide the sort (ASC or DESC) doing that on the SQL side is not necessary"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T13:23:32.793",
"Id": "38419",
"ParentId": "38415",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38419",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:50:37.450",
"Id": "38415",
"Score": "5",
"Tags": [
"sql",
"asp.net",
"sql-server"
],
"Title": "SQL Join with PropertyID and Name"
}
|
38415
|
<p>I've created this code which can call functions/ajax requests or pieces of code sequentially, using jQuery. The code not only can call functions/ajax requests or pieces of code sequentially but it also tracks when those calls fail or succeed and when the code fails it stops and doesn't exectue the rest of the queue.<br/><br/>
(Bold italic are the names of the queues)<br/>
In my example i've 5 timeouts who get queued, the 2 first share a queue named <strong><em>first</em></strong> (1 and 1b) get executed at the same time and when those 2 finish and succeed(fire resolve) the next on the queue gets executed (next in queue is <strong><em>two</em></strong> which contains only 1 timeout). <br/>After <strong><em>two</em></strong> gets executed and succeed the <strong><em>third</em></strong> gets executed. I've coded in a way that the <strong><em>third</em></strong> fires a reject which changes the state of promise to reject(fails the request) and thanks to that the last timeout doesn't get called(to simulate a failed ajax request).</p>
<p>I know the code is pretty messy (it's my first version). I would like some ideas on how I could structure this better or reduce the code considerably.</p>
<p>A problem I have with my code is that when I add a <code>setTimeout</code>, I have to include the <code>deferred.resolve()</code> in it. I don't see a way around this. Does anyone have an idea how to resolve this problem?</p>
<p>Code: <a href="http://jsfiddle.net/g55PC/" rel="nofollow">http://jsfiddle.net/g55PC/</a></p>
<pre><code>function myqueue(){
var myself=this;
var ord=[];// contains names used in promiseArr
var funcArr=[];// contains setTimeout functions
var me = $(document);
this.add = function (func, name) {
if (typeof funcArr[name] !== "object") funcArr[name] = [];
funcArr[name].push(func);
if($.inArray(name, ord)==-1){
ord.unshift(name);
}
}
this.call= function (name) {
me.queue("deferQueue", function () {
var promiseArr=[];
for(func in funcArr[name]){
promiseArr[func]=(function(){
var dfd = new jQuery.Deferred();
funcArr[name][func](dfd);
return dfd.promise();
})();
}
$.when.apply($,promiseArr).then(function () {
console.log("Success "+name);
me.dequeue("deferQueue");
}, function () {
console.log("Fail "+name);
});
});
}
this.start = function () {
while(ord.length>0) {
this.call(ord.pop());
}
me.dequeue("deferQueue");
}
};
myPlugin = new myqueue();
myPlugin.add(function (dfd) {
setTimeout(function () {
$("#result").append("<div>1</div>");
//console.log("1");
dfd.resolve();
}, 2000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
setTimeout(function () {
$("#result").append("<div>1b</div>");
//console.log("1b");
dfd.resolve();
}, 1000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
setTimeout(function () {
$("#result").append("<div>2</div>");
//console.log("2");
dfd.resolve();
}, 1000);
}, "second");//second = queue Name
myPlugin.add(function (dfd) {
setTimeout(function () {
$("#result").append("<div>3</div>");
//console.log("3");
dfd.reject();
}, 500);
}, "third");//third = queue Name
//forth will not be fired since third failed
myPlugin.add(function (dfd) {
setTimeout(function () {
$("#result").append("<div>4</div>");
//console.log("4");
dfd.resolve();
}, 3000);
}, "forth");//forth = queue Name
myPlugin.start();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:47:51.797",
"Id": "64010",
"Score": "0",
"body": "If you could be kind enough to summarize what the queue does, and how it works. Because improving the code is one thing. Providing you a better solution is another."
}
] |
[
{
"body": "<p>I like the idea of your code but you defenitely have some bugs and convention issues that should be dealt with:</p>\n\n<ol>\n<li>Major bug: call does not remove <code>funcArr[name]</code> after iterating them so if you add something to the \"first\" queue and call the first queue, adding something to the first queue will still have the functions from before you called the queue earlier. I created a (<a href=\"http://jsfiddle.net/Y3njW/\" rel=\"nofollow noreferrer\">demo of the issue</a>); as you see the alert will be shown twice as <code>funcArr[name]</code> is never emptied </li>\n<li>You're storing keys (function names) in the array <code>funcArr</code>. <code>funcArr</code> should be a hash object rather than an array.</li>\n<li><p>You're using <code>for..in</code> on an array (<a href=\"https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea#answer-500531\">why this is bad</a>) and moreover, the variable <code>func</code> will be global. Use a regular for loop instead here. I'd recommend using <code>$.each</code> here. With <code>$.each</code> you'd write the loop</p>\n\n<pre><code>$.each(funcArr, function(i, fn) {\n var dfd = $.Deferred();\n fn(dfd);\n promiseArr.push(dfd.promise()); \n});\n</code></pre></li>\n<li><p>You're module pattern seems off... 1) its common convention that a class name should be capitalized, ie <code>MyQueue</code>, 2) theres no real reason to use the <code>this</code> keyword if you're not planning to add these functions on prototype, 3) In <code>this.start</code> your line <code>this.call(ord.pop());</code> is a bit confusing.<br>\nAs you were not making use of prototype in your function I adapted your code to use the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript\" rel=\"nofollow noreferrer\">\"module pattern\"</a>. This allows your module to be created without the <code>new</code> keyword whereas before it would of caused major issues.</p></li>\n</ol>\n\n<p>Here's how I would write your queue. I added comments on most of my cahnges</p>\n\n<pre><code>function myqueue(){\n var ord=[];\n var funcHash = {}; // Use a hash as you're using keys rather than indicies\n var me = $(document);//(minor)convention would be to name this $doc\n\n var plugin = {\n add: function (func, name) {\n if(!funcHash.hasOwnProperty(name)) {//name does not exist yet\n funcHash[name] = [];\n ord.unshift(name);\n }\n funcHash[name].push(func);//now just queue the function \n },\n\n call: function (name) {\n me.queue(\"deferQueue\", function () { \n var promiseArr=[];\n var funcArr = funcHash[name];\n\n //funcArr is a hash of arrays don't use for in\n //also func was a global variable!]\n\n $.each(funcArr, function(i, fn) {\n var dfd = new jQuery.Deferred();\n fn(dfd);\n promiseArr.push(dfd.promise()); \n });\n\n //I assume you want to remove the functions after you call them so requeing the same name doesn't add to the old queue\n delete funcHash[name];\n\n $.when.apply($,promiseArr).then(function () {\n console.log(\"Success \"+name);\n me.dequeue(\"deferQueue\");\n }, function () {\n console.log(\"Fail \"+name);\n });\n });\n },\n\n start: function () {\n while(ord.length>0) {\n plugin.call(ord.pop());\n }\n me.dequeue(\"deferQueue\");\n }\n };\n\n return plugin;\n};\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/g55PC/2/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/g55PC/2/</a></p>\n\n<p>As for the second question of having to do the <code>.resolve()</code> in the timeout, you may want to consider adding a helper to your <code>myqueue</code> module along the lines of</p>\n\n<pre><code>//helper function for automatically managing a delay using timeout\naddDelayed: function(fn, name, delay) {\n this.add(function(dfd) {\n setTimeout(function () {\n fn(dfd);\n dfd.resolve();\n }, delay || 250);\n }, name);\n}\n</code></pre>\n\n<p>So your old pattern code be reduced to just:</p>\n\n<pre><code>myPlugin.addDelayed(function (dfd) {\n $(\"#result\").append(\"<div>1</div>\");\n}, \"first\", 1000);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:06:23.807",
"Id": "64048",
"Score": "0",
"body": "Welcome to CR, excellent review! I would have chosen a different name for `ord`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T09:20:50.390",
"Id": "64124",
"Score": "0",
"body": "Thx for your help. Some names came from past codes so at that point some variables names don't make much sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T15:46:45.607",
"Id": "38426",
"ParentId": "38420",
"Score": "3"
}
},
{
"body": "<h1>Naming</h1>\n\n<p>First off, I'd name my variables in the purpose they serve. Rather than <code>ord</code>, <code>funcHash</code> or even <code>me</code>.</p>\n\n<h1>Queue adding and removing</h1>\n\n<p>You should remove the items that have executed from the queue. That's what a queue is all about, and that's what your code lacks at the moment.</p>\n\n<p>Also, <code>unshift</code> and <code>shift</code> are more costly operations than 'pop' and 'push' because they need to move the array contents to new indices. You're correct in your implementation, that <code>enqueue</code> should use the <code>unshift</code> while execution uses <code>pop</code>.</p>\n\n<h1>Collection of callbacks</h1>\n\n<p>You don't need 2 arrays to store the order of named queues. You can have one array, but each item is named. One advantage of this is that you only have one array to push to, and you keep the absolute order, regardless of name. And no more nested loops.</p>\n\n<pre><code>function enqueue(fn,name){\n queue.push({\n name : name,\n fn : fn\n })\n}\n</code></pre>\n\n<p>You can then use <code>Array.prototype.filter</code> to filter out the queue, if you want to only unload certain queued items with a certain name. Here's how you can do it:</p>\n\n<pre><code>function dequeue(name){\n var fns = queue.filter(function(current){\n return (current.name === name);\n });\n\n // pop-off and run\n}\n</code></pre>\n\n<p>This code defaults to all items when <code>name</code> is not supplied</p>\n\n<pre><code>function dequeueAll(name){\n var fns = (!name) ? queue : queue.filter(function(current){\n return (current.name === name);\n });\n\n // pop-off and run all\n}\n</code></pre>\n\n<h1>Async control</h1>\n\n<p>Now, you don't have total control over the process that takes place in the queued function. The user could pop-in an async operation, and your library won't even know it, and will run wild. That's where your deferreds come in to play.</p>\n\n<p>However, you don't really need deferreds. You can pass in a function to the queued function that calls the next function. This is similar to ExpressJS's middlewares, where there's a magical <code>next</code> function supplied to each middleware. Here's how it's implemented</p>\n\n<pre><code>// Lets assume you have a queue like the one above, filtered optionally\n\n(function recursive(index){\n // get the item at the index\n var currentItem = queue[index];\n\n // This is to check if there's no more functions in the queue\n if(!currentItem) return;\n\n //Otherwise, run providing the instance of your object, and the magic \"next\"\n currentItem.fn.call(instance,function(){\n //This function gets called when the current queued item is done executing\n\n // Splice off this item from the queue. We use splice since the\n // item we might be operating on is from a filtered set, not in the same\n // index as the original queue\n queue.splice(queue.indexOf(currentItem),1);\n\n // Run the next item\n recursive(++index);\n\n });\n\n// start with 0\n}(0));\n</code></pre>\n\n<p>Here's how to use it:</p>\n\n<pre><code>// So you can have something synchronous\nenqueue(function(next){\n //do something\n next();\n});\n\n// Or something asynchronous\nenqueue(function(next){\n somethingAsync(function(){\n // done?\n next();\n });\n});\n</code></pre>\n\n<h1>Fluent API</h1>\n\n<p>Consider fluent, aka \"jQuery-like\" APIs. It's pretty simple, just have the methods return the current instance, and that's it:</p>\n\n<pre><code>enqueue : function(){\n ...\n return this;\n}\n</code></pre>\n\n<p>Then you can do something like jQuery and other libraries:</p>\n\n<pre><code>myQueue.enqueue(function(){...}).enqueue(function(){...}).enqueue(function(){...})\n</code></pre>\n\n<h1>Demonstration</h1>\n\n<p><a href=\"http://jsbin.com/aNOFUjUs/3/edit?js,console\" rel=\"nofollow\">Here's a small demo I have made here</a>. It has some bugs in some corner cases and needs a few fixing. But given your code example, it works quite similarly. Not to mention, it is a bit shorter, and uses no libraries.</p>\n\n<pre><code>function Queue() {\n this.queue = []\n}\nQueue.prototype = {\n constructor: Queue,\n enqueue: function (fn, queueName) {\n this.queue.push({\n name: queueName || 'global',\n fn: fn || function (next) {\n next()\n }\n });\n return this\n },\n dequeue: function (queueName) {\n var allFns = (!queueName) ? this.queue : this.queue.filter(function (current) {\n return (current.name === queueName)\n });\n var poppedFn = allFns.pop();\n if (poppedFn) poppedFn.fn.call(this);\n return this\n },\n dequeueAll: function (queueName) {\n var instance = this;\n var queue = this.queue;\n var allFns = (!queueName) ? this.queue : this.queue.filter(function (current) {\n return (current.name === queueName)\n });\n (function recursive(index) {\n var currentItem = allFns[index];\n if (!currentItem) return;\n currentItem.fn.call(instance, function () {\n queue.splice(queue.indexOf(currentItem), 1);\n recursive(index)\n })\n }(0));\n return this\n }\n};\n\nvar myQueue = new Queue();\nmyQueue.enqueue(function (next) {\n console.log('D1: first test1');\n next()\n}, 'first').enqueue(function (next) {\n setTimeout(function () {\n console.log('D1: first test2');\n next()\n }, 2000)\n}, 'first').enqueue(function (next) {\n console.log('D1: second test1');\n next()\n}, 'second').enqueue(function (next) {\n console.log('D1: second test2');\n next()\n}, 'second').dequeueAll();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:00:35.047",
"Id": "64125",
"Score": "0",
"body": "I like your code but the thing about your demonstration is that i'ts a completely different thing than mine. My code is able to queue functions/ajax requests or pieces of codes and execute them sequentially. And the thing about it is that some pieces of code can fail or succeed. If one piece/function fails the code ends. I like your code and i will try to take some of your ideas and improve my code thx to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T12:20:46.150",
"Id": "64141",
"Score": "0",
"body": "@Marcio Actually, if the queued code fails to call `next()`, then the next queued code doesn't run."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:56:25.373",
"Id": "38443",
"ParentId": "38420",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T13:39:32.640",
"Id": "38420",
"Score": "6",
"Tags": [
"javascript",
"jquery"
],
"Title": "Sequential function call in JavaScript"
}
|
38420
|
<p>Today, I will require your help to improve an iterator adapter. The goal of the adapter (I called it <code>get_iterator</code>) is to adapt <code>std::map</code> iterators for example: map iterators return <code>std::pair</code> instances, a <code>get_iterator<0, std::map<...>::iterator></code> will provide an iterator which iterates through the keys while a <code>get_iterator<1, std::map<...>::iterator></code> will provide an iterator which iterates through the values. Here is my implementation:</p>
<p>Here is the header file:</p>
<pre><code>template<std::size_t N, typename Iterator>
class get_iterator:
public std::iterator<
typename std::iterator_traits<Iterator>::iterator_category,
typename std::remove_reference<decltype(std::get<N>(*Iterator{}))>::type,
typename std::iterator_traits<Iterator>::difference_type>
{
private:
Iterator _current;
public:
using iterator_type = Iterator;
using value_type = typename std::remove_reference<decltype(std::get<N>(*_current))>::type;
using pointer = value_type*;
using reference = value_type&;
get_iterator();
explicit get_iterator(Iterator it);
template<typename U>
get_iterator(const get_iterator<N, U>& other);
template<typename U>
auto operator=(const get_iterator<N, U>& other)
-> get_iterator&;
auto base() const
-> Iterator;
auto operator*() const
-> reference;
auto operator->() const
-> pointer;
auto operator++()
-> get_iterator&;
auto operator++(int)
-> get_iterator&;
auto operator--()
-> get_iterator&;
auto operator--(int)
-> get_iterator&;
};
</code></pre>
<p>And here is the implementation file:</p>
<pre><code>template<std::size_t N, typename Iterator>
get_iterator<N, Iterator>::get_iterator()
= default;
template<std::size_t N, typename Iterator>
get_iterator<N, Iterator>::get_iterator(Iterator it):
_current(it)
{}
template<std::size_t N, typename Iterator>
template<typename U>
get_iterator<N, Iterator>::get_iterator(const get_iterator<N, U>& other):
_current(other.base())
{}
template<std::size_t N, typename Iterator>
template<typename U>
auto get_iterator<N, Iterator>::operator=(const get_iterator<N, U>& other)
-> get_iterator&
{
if (&other != this)
{
_current = other.base();
}
return *this;
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::base() const
-> Iterator
{
return _current;
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator*() const
-> reference
{
return std::get<N>(*_current);
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator->() const
-> pointer
{
return &(operator*());
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator++()
-> get_iterator&
{
++_current;
return *this;
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator++(int)
-> get_iterator&
{
auto tmp = *this;
++_current;
return tmp;
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator--()
-> get_iterator&
{
--_current;
return *this;
}
template<std::size_t N, typename Iterator>
auto get_iterator<N, Iterator>::operator--(int)
-> get_iterator&
{
auto tmp = *this;
--_current;
return tmp;
}
</code></pre>
<p>I don't provide <code>operator==</code>, <code>operator<</code> and their friends in this question since their implementation is trivial and mimicks this of <a href="http://en.cppreference.com/w/cpp/iterator/reverse_iterator" rel="nofollow"><code>std::reverse_iterator</code></a>. Are there functions lacking in the interface or things to be improved in the implementation? Also, do you have any idea of a more suitable name for such an iterator adaptor?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:34:05.700",
"Id": "64072",
"Score": "0",
"body": "Still getting used to the new syntax for the return type. Not sure why you are using it here. The normal syntax should work and is much clearer (in my opinion)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:57:39.973",
"Id": "64162",
"Score": "0",
"body": "@LokiAstari I personally find it clearer: it allows to split the return type and the rest of the function in one glance. Moreover, it resembles the functions notation in type theory. Well, it also allows me to always use one and only one return type syntax everywhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:07:19.857",
"Id": "64243",
"Score": "0",
"body": "Remember you are not writing code for you to understand. You wrote it, thus you should quickly pick it up again. You really need to write code for the next person that is not you. As they have to maintain it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:25:43.253",
"Id": "64247",
"Score": "0",
"body": "@LokiAstari Well, at least I try to be consistent when writing it. I don't see what's the big deal with this syntax; I do not see how the old syntax is clearer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T23:54:17.693",
"Id": "65148",
"Score": "1",
"body": "If you're actually planning on using this in a project, I feel like I need to point out boost has a [transform_iterator](http://www.boost.org/doc/libs/1_55_0/libs/iterator/doc/transform_iterator.html) that's quite a bit more flexible."
}
] |
[
{
"body": "<h1>Define <code>get_iterator</code> in terms of <code>transform_iterator</code></h1>\n\n<p>As pointed by @Yuushi, Boost has a <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/iterator/doc/transform_iterator.html\" rel=\"noreferrer\"><code>transform_iterator</code></a> class which will apply a function to the return value of <code>operator*</code>. Therefore, <code>get_iterator</code> could be define as an alias template:</p>\n\n<pre><code>struct getter\n{\n template<typename T>\n auto operator()(T&& value)\n -> decltype(auto)\n {\n return std::get<N>(std::forward<T>(arg));\n }\n};\n\ntemplate<std::size_t N, typename Iterator>\nusing = boost::iterators::transform_iterator<getter<N>, Iterator>;\n</code></pre>\n\n<p>The function object would have had another advantage had Boost allowed its <code>transform_iterator</code> to take advantage of the <a href=\"http://en.cppreference.com/w/cpp/language/ebo\" rel=\"noreferrer\">empty base optimization</a>. Unfortunately, this is not the case right now, but using a function object may trigger a free improvement when Boost finally implements EBO in <code>transform_iterator</code>.</p>\n\n<p>I would have loved to use <a href=\"http://en.wikipedia.org/wiki/Argument-dependent_name_lookup\" rel=\"noreferrer\">ADL</a> to find the most suitable <code>get</code> to use, but <code>get</code> always need an integer template parameter. And ADL is not triggered when a template parameter is provided by hand instead of being deduced.</p>\n\n<h1>Add a construction function</h1>\n\n<p>Let's assume that we still want to write a <code>get_iterator</code> by hand. While the integer template parameter is always provided by hand, the ability to deduce the <code>Iterator</code> template parameter is still something we want to have. Therefore, we will add a construction function:</p>\n\n<pre><code>template<std::size_t N, typename Iterator>\nauto make_get_iterator(Iterator it)\n -> get_iterator<N, Iterator>\n{\n return get_iterator<N, Iterator>(it);\n}\n</code></pre>\n\n<p>Moreover, adding such a construction function is consistent with the standard library. After all, <a href=\"http://en.cppreference.com/w/cpp/iterator/make_reverse_iterator\" rel=\"noreferrer\"><code>std::make_reverse_iterator</code></a> was added to C++14 for consistency.</p>\n\n<h1>Miscellaneous tidbits</h1>\n\n<p>There are more things that could be improved, but they are more subtle and less interesting:</p>\n\n<ul>\n<li><p>The check <code>&other != this</code> in <code>operator=</code> seems pretty useless. It is almost always a pessimization and I cannot think of a scenario where assigning <code>base()</code> to itself would go wrong.</p></li>\n<li><p><code>operator++(int)</code> and <code>operator--(int)</code> shoud return <code>get_iterator</code> instead of <code>get_iterator&</code>. Currently they return references to temporary variables, which is plain wrong. That proves that I didn't write proper tests.</p></li>\n<li><p>More iterator-related functions could have been overloaded to support the requirements of a [<code>RandomAccessIterator</code>][5] when needed since nothing prevents it and supporting more iterators is better than support fewer. The functions that could have been added are <code>operator+</code>, <code>operator-</code>, <code>operator+=</code>, <code>opperator-=</code> and <code>opeator[]</code>.</p></li>\n<li><p>It would be better to put <code>= default</code> on its first declaration instead of separating the declaration and the definition of the default constructor. The rationale is that <code>Iterator it{}</code> can zero-initialize the iterator instead of dedault-initializing it if <code>= default</code> appears on the first declaration. I have no idea whether this can change something for any iterator, but initializing memory with zero cannot be worse than initializing it with garbage.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T21:29:02.257",
"Id": "73981",
"ParentId": "38421",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "73981",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:38:00.923",
"Id": "38421",
"Score": "11",
"Tags": [
"c++",
"c++11",
"iterator"
],
"Title": "Iterator adaptor for iterators returning tuple-like values"
}
|
38421
|
<p>I wrote the following piece of Python as a part of a larger system. Profiling reveals that a large amount of time is spent in <code>DocumentFeature.from_string</code>. So far I've tried compiling the unmodified code with Cython and got a 33% improvement in running time. Any suggestions as to how this code can be improved further are greatly appreciated.</p>
<p>Here's the code and the unit tests I've been using.</p>
<pre><code>import logging
from operator import itemgetter
from functools import total_ordering
from unittest import TestCase
import nose
class DocumentFeature(object):
def __init__(self, type, tokens):
self.type = type
self.tokens = tokens
@classmethod
def from_string(cls, string):
"""
Takes a string representing a DocumentFeature and creates and object out of it. String format is
"word/POS" or "word1/PoS1 word2/PoS2",... The type of the feature will be inferred from the length and
PoS tags of the input string.
:type string: str
"""
try:
token_count = string.count('_') + 1
pos_count = string.count('/')
if token_count != pos_count:
return DocumentFeature('EMPTY', tuple())
tokens = string.strip().split('_')
if len(tokens) > 3:
raise ValueError('Document feature %s is too long' % string)
bits = [x.split('/') for x in tokens]
if not all(map(itemgetter(0), bits)):
# ignore tokens with no text
return DocumentFeature('EMPTY', tuple())
tokens = tuple(Token(word, pos) for (word, pos) in bits)
if len(tokens) == 1:
t = '1-GRAM'
elif ''.join([t.pos for t in tokens]) == 'NVN':
t = 'SVO'
elif ''.join([t.pos for t in tokens]) == 'JN':
t = 'AN'
elif ''.join([t.pos for t in tokens]) == 'VN':
t = 'VO'
elif ''.join([t.pos for t in tokens]) == 'NN':
t = 'NN'
elif len(tokens) == 2:
t = '2-GRAM'
elif len(tokens) == 3:
t = '3-GRAM'
else:
t = 'EMPTY'
except:
logging.error('Cannot create token out of string %s', string)
raise
return DocumentFeature(t, tokens)
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
# other irrelevant methods removed
@total_ordering
class Token(object):
def __init__(self, text, pos, index=0):
self.text = text
self.pos = pos
self.index = index
def __str__(self):
return '{}/{}'.format(self.text, self.pos) if self.pos else self.text
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return (not self < other) and (not other < self)
def __lt__(self, other):
return (self.text, self.pos) < (other.text, other.pos)
def __hash__(self):
return hash((self.text, self.pos))
class Test_tokenizer(TestCase):
def test_document_feature_from_string(self):
x = DocumentFeature.from_string('big/J_cat/N')
y = DocumentFeature('AN', (Token('big', 'J'), Token('cat', 'N')))
self.assertEqual(y, x)
self.assertEqual(
DocumentFeature('1-GRAM', (Token('cat', 'N'), )),
DocumentFeature.from_string(' cat/N ')
)
self.assertEqual(
DocumentFeature('VO', (Token('chase', 'V'), Token('cat', 'N'))),
DocumentFeature.from_string('chase/V_cat/N')
)
self.assertEqual(
DocumentFeature('NN', (Token('dog', 'N'), Token('cat', 'N'))),
DocumentFeature.from_string('dog/N_cat/N')
)
self.assertEqual(
DocumentFeature('3-GRAM', (Token('dog', 'V'), Token('chase', 'V'), Token('cat', 'V'))),
DocumentFeature.from_string('dog/V_chase/V_cat/V')
)
self.assertEqual(
DocumentFeature('2-GRAM', (Token('chase', 'V'), Token('cat', 'V'))),
DocumentFeature.from_string('chase/V_cat/V')
)
self.assertEqual(
DocumentFeature('SVO', (Token('dog', 'N'), Token('chase', 'V'), Token('cat', 'N'))),
DocumentFeature.from_string('dog/N_chase/V_cat/N')
)
for invalid_string in ['a\/s/N', 'l\/h/N_clinton\/south/N', 'l\/h//N_clinton\/south/N',
'l//fasdlj/fasd/dfs/sdf', 'l//fasdlj/fasd/dfs\_/sdf', 'dfs\_/sdf',
'dfs\_/fadslk_/sdf', '/_dfs\_/sdf', '_/_/', '_///f_/', 'drop_bomb',
'drop/V_bomb', '/V_/N', 'cat']:
self.assertEqual(
DocumentFeature('EMPTY', tuple()),
DocumentFeature.from_string(invalid_string)
)
if __name__ == '__main__':
nose.core.runmodule()
</code></pre>
|
[] |
[
{
"body": "<p>I find your error handling is a bit counterintuitive: if the input string is invalid, you return an \"empty\" <code>DocumentFeature</code>, but if there are too many tokens, it raises an exception. I would raise exceptions in both cases, and let the caller decide what to do.</p>\n\n<p>I think that you're being too pessimistic in validating your inputs: the validation repeats some of the real work that would be done anyway. Furthermore, counting slashes and underscores is insufficient validation — for example, <code>\"word1_word2//\"</code> passes the initial validation, only to fail at <code>tuple(Token(word, pos) for (word, pos) in bits)</code>. Instead, I would suggest validating as you perform the transformations.</p>\n\n<pre><code>_TYPES = dict([\n ('NVN', 'SVO'), ('JN', 'AN'), ('VN', 'VO'), ('NN', 'NN')\n])\n\n@classmethod\ndef from_string(cls, string):\n \"\"\"\n Takes a string representing a DocumentFeature and creates and object out of it. String format is\n \"word/PoS\" or \"word1/PoS1_word2/PoS2\",... The type of the feature will be inferred from the length and\n PoS tags of the input string. \n\n :type string: str\n \"\"\"\n try:\n tokens = string.strip().split('_')\n if len(tokens) > 3:\n raise ValueError('Document feature %s is too long' % string)\n\n tokens = [token.split('/') for token in tokens]\n\n # Check for too many slashes, too few slashes, or empty words\n if not all(map(lambda token: len(token) == 2 and token[0], tokens)):\n raise ValueError('Invalid document feature %s' % string)\n\n tokens = tuple(Token(word, pos) for (word, pos) in tokens)\n\n type = cls._TYPES.get(''.join([t.pos for t in tokens]),\n ('EMPTY', '1-GRAM', '2-GRAM', '3-GRAM')[len(tokens)])\n except:\n logging.error('Cannot create token out of string %s', string)\n raise\n\n return DocumentFeature(type, tokens)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T12:01:06.480",
"Id": "64139",
"Score": "0",
"body": "Thanks for your feedback, especially for spotting the problem with counting underscores and slashes. You corrected implementation is also ~5% faster on my machine.\n\nRegarding your first point, invalid input strings are due to data formatting. Since I'm dealing with natural language, there will inevitably be a small number of such tokens. There's nothing that can be done about that and I don't consider this to be exceptional. However, having more than 3 tokens violates a hard constraint and indicates a problem with my own code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:44:10.013",
"Id": "38446",
"ParentId": "38422",
"Score": "4"
}
},
{
"body": "<p>By parsing the string using a regular expression, I get a 20% performance increase over your original code.</p>\n\n<pre><code>from itertools import izip_longest\nimport re\n\nclass DocumentFeature(object):\n def __init__(self, type, tokens):\n self.type = type\n self.tokens = tokens\n\n _TYPES = dict([\n ('NVN', 'SVO'), ('JN', 'AN'), ('VN', 'VO'), ('NN', 'NN')\n ])\n _TOKEN_RE = re.compile(r'([^/_]+)/([NVJ])(?:_|$)')\n\n @classmethod\n def from_string(cls, string):\n try:\n match = cls._TOKEN_RE.split(string, 3)\n type = ''.join(match[2::3])\n match = iter(match)\n tokens = []\n for (junk, word, pos) in izip_longest(match, match, match):\n if junk: # Either too many tokens, or invalid token\n raise ValueError(junk)\n if not word:\n break\n tokens.append(Token(word, pos))\n type = cls._TYPES.get(type,\n ('EMPTY', '1-GRAM', '2-GRAM', '3-GRAM')[len(tokens)])\n return DocumentFeature(type, tuple(tokens))\n except:\n raise\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T16:17:18.840",
"Id": "64719",
"Score": "0",
"body": "This is indeed faster, thank you. One minor point though: the regex is assuming the thing following the forward slash can only have three values [NVJ], whereas my original code doesn't. You couldn't have known that as I didn't make it explicit and the unit tests I provided do not cover any other cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T17:15:27.487",
"Id": "64742",
"Score": "0",
"body": "Your observation is correct. `([^/_]+)/([^/_]+)(?:_|$)` would be closer in spirit to the original, but I chose something more strict since the original was excessively permissive. Feel free to tweak the regex to suit your needs."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:44:43.347",
"Id": "38726",
"ParentId": "38422",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38726",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:45:06.643",
"Id": "38422",
"Score": "4",
"Tags": [
"python",
"performance",
"parsing",
"cython"
],
"Title": "Speeding up a Cython program"
}
|
38422
|
<p>The following code is to enlarge pictures using bilinear interpolation. What can be modified in the function of <code>slow_rescale</code> to make it more efficient? I expect to modify it from the view of Principles of Computer Organization.</p>
<pre><code>unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)
{
double step_x,step_y; // Step increase as per instructions above
unsigned char R1,R2,R3,R4; // Colours at the four neighbours
unsigned char G1,G2,G3,G4;
unsigned char B1,B2,B3,B4;
double RT1, GT1, BT1; // Interpolated colours at T1 and T2
double RT2, GT2, BT2;
unsigned char R,G,B; // Final colour at a destination pixel
unsigned char *dst; // Destination image - must be allocated here!
int x,y; // Coordinates on destination image
double fx,fy; // Corresponding coordinates on source image
double dx,dy; // Fractional component of source image coordinates
dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char)); // Allocate and clear destination image
if (!dst) return(NULL); // Unable to allocate image
step_x=(double)(src_x-1)/(double)(dest_x-1);
step_y=(double)(src_y-1)/(double)(dest_y-1);
for (x=0;x<dest_x;x++) // Loop over destination image
for (y=0;y<dest_y;y++)
{
fx=x*step_x;
fy=y*step_y;
dx=fx-(int)fx;
dy=fy-(int)fy;
getPixel(src,floor(fx),floor(fy),src_x,&R1,&G1,&B1); // get N1 colours
getPixel(src,ceil(fx),floor(fy),src_x,&R2,&G2,&B2); // get N2 colours
getPixel(src,floor(fx),ceil(fy),src_x,&R3,&G3,&B3); // get N3 colours
getPixel(src,ceil(fx),ceil(fy),src_x,&R4,&G4,&B4); // get N4 colours
// Interpolate to get T1 and T2 colours
RT1=(dx*R2)+(1-dx)*R1;
GT1=(dx*G2)+(1-dx)*G1;
BT1=(dx*B2)+(1-dx)*B1;
RT2=(dx*R4)+(1-dx)*R3;
GT2=(dx*G4)+(1-dx)*G3;
BT2=(dx*B4)+(1-dx)*B3;
// Obtain final colour by interpolating between T1 and T2
R=(unsigned char)((dy*RT2)+((1-dy)*RT1));
G=(unsigned char)((dy*GT2)+((1-dy)*GT1));
B=(unsigned char)((dy*BT2)+((1-dy)*BT1));
// Store the final colour
setPixel(dst,x,y,dest_x,R,G,B);
}
return(dst);
}
void getPixel(unsigned char *image, int x, int y, int sx, unsigned char *R, unsigned char *G, unsigned char *B)
{
// Get the colour at pixel x,y in the image and return it using the provided RGB pointers
// Requires the image size along the x direction!
*(R)=*(image+((x+(y*sx))*3)+0);
*(G)=*(image+((x+(y*sx))*3)+1);
*(B)=*(image+((x+(y*sx))*3)+2);
}
void setPixel(unsigned char *image, int x, int y, int sx, unsigned char R, unsigned char G, unsigned char B)
{
// Set the colour of the pixel at x,y in the image to the specified R,G,B
// Requires the image size along the x direction!
*(image+((x+(y*sx))*3)+0)=R;
*(image+((x+(y*sx))*3)+1)=G;
*(image+((x+(y*sx))*3)+2)=B;
}
</code></pre>
|
[] |
[
{
"body": "<p>Please make everyone (including yourself) a favor :</p>\n\n<ul>\n<li>Declare your variable in the smallest possible scope. Also define them as your declare them if you can (and you usually can).</li>\n<li>Indent your code properly.</li>\n</ul>\n\n<p>Then you'd get something like :</p>\n\n<pre><code>unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)\n{\n unsigned char* dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char)); // Allocate and clear destination image\n if (!dst) return(NULL); // Unable to allocate image\n\n double step_x=(double)(src_x-1)/(double)(dest_x-1);\n double step_y=(double)(src_y-1)/(double)(dest_y-1);\n\n for (int x=0;x<dest_x;x++) // Loop over destination image\n {\n for (int y=0;y<dest_y;y++)\n {\n double fx=x*step_x;\n double fy=y*step_y;\n double dx=fx-(int)fx;\n double dy=fy-(int)fy;\n\n unsigned char R1,R2,R3,R4; // Colours at the four neighbours\n unsigned char G1,G2,G3,G4;\n unsigned char B1,B2,B3,B4;\n\n getPixel(src,floor(fx),floor(fy),src_x,&R1,&G1,&B1); // get N1 colours\n getPixel(src,ceil(fx),floor(fy),src_x,&R2,&G2,&B2); // get N2 colours\n getPixel(src,floor(fx),ceil(fy),src_x,&R3,&G3,&B3); // get N3 colours\n getPixel(src,ceil(fx),ceil(fy),src_x,&R4,&G4,&B4); // get N4 colours\n // Interpolate to get T1 and T2 colours\n double RT1=(dx*R2)+(1-dx)*R1;\n double GT1=(dx*G2)+(1-dx)*G1;\n double BT1=(dx*B2)+(1-dx)*B1;\n double RT2=(dx*R4)+(1-dx)*R3;\n double GT2=(dx*G4)+(1-dx)*G3;\n double BT2=(dx*B4)+(1-dx)*B3;\n // Obtain final colour by interpolating between T1 and T2\n unsigned char R=(unsigned char)((dy*RT2)+((1-dy)*RT1));\n unsigned char G=(unsigned char)((dy*GT2)+((1-dy)*GT1));\n unsigned char B=(unsigned char)((dy*BT2)+((1-dy)*BT1));\n // Store the final colour\n setPixel(dst,x,y,dest_x,R,G,B);\n }\n }\n return(dst);\n}\nvoid getPixel(unsigned char *image, int x, int y, int sx, unsigned char *R, unsigned char *G, unsigned char *B)\n{\n // Get the colour at pixel x,y in the image and return it using the provided RGB pointers\n // Requires the image size along the x direction!\n *(R)=*(image+((x+(y*sx))*3)+0);\n *(G)=*(image+((x+(y*sx))*3)+1);\n *(B)=*(image+((x+(y*sx))*3)+2);\n}\n\nvoid setPixel(unsigned char *image, int x, int y, int sx, unsigned char R, unsigned char G, unsigned char B)\n{\n // Set the colour of the pixel at x,y in the image to the specified R,G,B\n // Requires the image size along the x direction!\n *(image+((x+(y*sx))*3)+0)=R;\n *(image+((x+(y*sx))*3)+1)=G;\n *(image+((x+(y*sx))*3)+2)=B;\n}\n</code></pre>\n\n<p>Then, try to compute things once and only once when possible and you'll get something like :</p>\n\n<pre><code>unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)\n{\n unsigned char* dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char)); // Allocate and clear destination image\n if (!dst) return(NULL); // Unable to allocate image\n\n double step_x=(double)(src_x-1)/(double)(dest_x-1);\n double step_y=(double)(src_y-1)/(double)(dest_y-1);\n\n for (int x=0;x<dest_x;x++) // Loop over destination image\n {\n double fx=x*step_x;\n double dx=fx-(int)fx;\n int ffx = floor(fx);\n int cfx = ceil(fx);\n for (int y=0;y<dest_y;y++)\n {\n double fy=y*step_y;\n double dy=fy-(int)fy;\n int ffy = floor(fy);\n int cfy = ceil(fy);\n\n unsigned char R1,R2,R3,R4,G1,G2,G3,G4,B1,B2,B3,B4;\n\n getPixel(src, (ffx + ffy*src_x)*3, &R1,&G1,&B1); // get N1 colours\n getPixel(src, (cfx + ffy*src_x)*3, &R2,&G2,&B2); // get N2 colours\n getPixel(src, (ffx + cfy*src_x)*3, &R3,&G3,&B3); // get N3 colours\n getPixel(src, (cfx + cfy*src_x)*3, &R4,&G4,&B4); // get N4 colours\n // Interpolate to get T1 and T2 colours\n double RT1 = dx*R2 + (1-dx)*R1;\n double GT1 = dx*G2 + (1-dx)*G1;\n double BT1 = dx*B2 + (1-dx)*B1;\n double RT2 = dx*R4 + (1-dx)*R3;\n double GT2 = dx*G4 + (1-dx)*G3;\n double BT2 = dx*B4 + (1-dx)*B3;\n // Obtain final colour by interpolating between T1 and T2\n unsigned char R = dy*RT2 + (1-dy)*RT1;\n unsigned char G = dy*GT2 + (1-dy)*GT1;\n unsigned char B = dy*BT2 + (1-dy)*BT1;\n // Store the final colour\n setPixel(dst, (x + y*dest_x)*3,R,G,B);\n }\n }\n return(dst);\n}\n\ninline void getPixel(unsigned char *image, int offset, unsigned char *R, unsigned char *G, unsigned char *B)\n{\n *R=image[offset+0];\n *G=image[offset+1];\n *B=image[offset+2];\n}\n\ninline void setPixel(unsigned char *image, int offset, unsigned char R, unsigned char G, unsigned char B)\n{\n image[offset+0]=R;\n image[offset+1]=G;\n image[offset+2]=B;\n}\n</code></pre>\n\n<p>I'd expect this to be much much faster than your original code and to do roughtly the same thing (I have have introduced errors though).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T16:35:34.293",
"Id": "38433",
"ParentId": "38423",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T14:51:31.143",
"Id": "38423",
"Score": "5",
"Tags": [
"optimization",
"c",
"image"
],
"Title": "Bilinear interpolation"
}
|
38423
|
<p>I'm developing a site, which has an image upload section, and members and like the image, but a member can like it only once.</p>
<p>I have a table, named <code>uploads</code> which has columns <code>id, ...{more columns}..., like</code>.</p>
<p>I identify members by a token(a 16 digit number)</p>
<p>Now, when a user likes an image, the code executed is:</p>
<pre><code>public function imgLike($post) {
$pgid = filter_var(trim($post['id']), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
if((isset($_SESSION['public'])) && (!empty($_SESSION['public']))) {
$this->dbconnect();
$name = filter_var(trim($_SESSION['public']), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
try {
$query = $this->db->prepare("SELECT `like` FROM `uploads` WHERE id=?");
$query->execute(array($pgid));
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$likes = json_decode($row['like']);
}
array_push($likes, $name);
$final = json_encode($likes);
} catch (Exception $e) {
die("There were some issues while processing your request, please refresh. Error code #55");
}
$queryUp = $this->db->prepare("UPDATE `uploads` SET `like`=? WHERE `id`=?");
try {
$queryUp->execute(array($final,$pgid));
} catch (Exception $e) {
die("There were some issues while processing your request, please refresh. Error code #55");
}
return $final;
} else {
return "not logged in";
}
}
</code></pre>
<p>For few members it's ok, but if there are 1000 members then the length of the <code>like</code> column in the row goes up to 16,000.</p>
<p>Now if I need to check whether the member has liked the image or not, then I have to read a string as long as 16,000 characters.</p>
<p>So my main question is, how can this be done in a better way?</p>
|
[] |
[
{
"body": "<p>Yes this can be done better. Storing data in a serialized format in a database (be it JSON or XML) is a bad idea more often than not. The main issue is that you will have a hard time querying for specific items in the serialized blob (e.g. trying to find which member has liked which images).</p>\n\n<p>The basic thing you can do is to normalize your data by introducing a <code>UploadLike</code> table:</p>\n\n<pre><code>| Name | UploadId |\n</code></pre>\n\n<p>where each row states which <code>name</code> likes which <code>upload</code>. </p>\n\n<p>If you already have a members table then it might feasible to actually link the table to the member rather than a name:</p>\n\n<pre><code>| MemberId | UploadId |\n</code></pre>\n\n<p>So whenever a member likes an image you insert a row for that member and the associated upload id into that table.</p>\n\n<p>Also when you get the likes for an upload you do this:</p>\n\n<blockquote>\n<pre><code> while($row = $query->fetch(PDO::FETCH_ASSOC)){ \n $likes = json_decode($row['like']);\n }\n</code></pre>\n</blockquote>\n\n<p>Which seems weird. There should only be one upload with the given id anyway and I'd consider it an error to have multiple rows with the same upload id. So why do you loop here?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:01:04.343",
"Id": "64046",
"Score": "0",
"body": "I have to agree on storing serialized data in a db (unless using a db which allows searches within json, etc - (iirc the latest postgres allows this and a bunch of NoSQL stores too))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T19:29:04.617",
"Id": "64063",
"Score": "0",
"body": "Looping was a bad idea..I have changed it, and thanks for the tip, I do have a members table again thanks :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:58:30.087",
"Id": "38438",
"ParentId": "38425",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T15:23:38.137",
"Id": "38425",
"Score": "2",
"Tags": [
"php",
"pdo",
"image"
],
"Title": "Image rate system"
}
|
38425
|
<p>I've just started writing my own little templating library in JavaScript, because as I went through others, there is always this voice in head, which says: "Oh, this is a lot of code and functionality. Is that really necessary or would it slow down the performance?"</p>
<p><em>If you are able to follow conventions, you would probably run into less issues.</em></p>
<p>So I ended up with this little script with the upper quote in my head. The convention, here is that <em>data</em> needs an object and its keys must be the same like in template, mentioned between those delimiter-brackets "{{key}}"</p>
<pre><code>function Template(url, data) {
this.url = url;
this.data = data;
this.delimiter = ['{{','}}'];
this.load = function() {
var string = new String();
var http = null;
if ( window.XMLHttpRequest ) {
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.open('GET', url, false);
http.onreadystatechange = function() {
if ( http.readyState === 4 ) {
string = http.response;
}
};
http.send(null);
this.template = string;
return this;
};
this.exchange = function() {
for ( var key in this.data ) {
var bracketedKey = this.delimiter[0] + key + this.delimiter[1];
var indexOfKey = this.template.indexOf(bracketedKey);
var lengthOfKey = bracketedKey.length;
var exchange = this.template.substring(indexOfKey, indexOfKey+lengthOfKey);
this.template = this.template.replace(exchange, this.data[key]);
}
return this;
};
this.build = function(selector) {
this.load();
this.exchange();
var div = document.createElement('div');
div.innerHTML = this.template;
div = div.firstChild;
if ( typeof selector === 'string' ) {
document.querySelector(selector).appendChild(div);
} else {
return div;
}
};
}
</code></pre>
<p>But now I've started thinking about the fact, that other libraries include more code than mine and there must be a reason for it, mustn't it?</p>
<p>There also a few more things that are coming to my head, like:</p>
<ol>
<li><p>Less code = better performance?</p></li>
<li><p>Why do so many people relate their projects with this templating library?
(Matter of performance => that would refute my first point)</p></li>
</ol>
<p>It'd be cool if someone could explain me a few things about this topic.</p>
<ol>
<li>Am I right with my mindset?</li>
<li>When I am right, is there something that I could improve, or even when I am wrong?</li>
<li>If you would recommend a library to me, what is your reason?</li>
</ol>
|
[] |
[
{
"body": "<p><a href=\"http://garann.github.io/template-chooser/\" rel=\"nofollow\"><strong>Different templating libraries</strong></a> offer different functions: including helper functions/logic (eg foreach of an object/array and if statements), precompilation, and DOM binding.</p>\n\n<p>In terms of raw performance, libraries that precompile the templates will often be fastest, as you're serving a special javascript file with contents along the lines of <code>function(context) { return \"name: \" + context.name}</code> from template <code>\"name: {{name}}\"</code> and it won't need to be compiled on the clientside.</p>\n\n<p>Anyway your template engine seems more of a simple formatter and doesn't have much functionality baked in. Your <code>exchange</code> function also has a rather obvious bug in that it will miss multiple keys in keys. For example try running it on <code>\"{{name}} {{name}}\"</code> - it will only replace the first occurance of <code>{{name}}</code>.</p>\n\n<p><strong>Update</strong> here's a common way of doing a regex format (I stole most of this <a href=\"https://github.com/mootools/mootools-core/blob/master/Source/Types/String.js#L78\" rel=\"nofollow\">regexp from mootools</a>)</p>\n\n<pre><code>this.exchange = function() {\n var data = this.data;\n this.template = this.template.replace(/\\\\?\\{\\{([^{}]+)\\}\\}/g, function(match, name){//reasonably complicated regex replace matches a string surrounded by {{key}}\n return data[name] || match;//if the object has property in {{key}} replace it otherwise don't change\n });\n\n return this;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:09:44.560",
"Id": "64049",
"Score": "0",
"body": "okay, this is helpful, and the multiple occurance of an string like you mentioned, is a nice feature, which I haven't thought of, but probably because I'm in no need of that functionality.\n\nso your advise to me would probably be, that I should send the data to file (for example a php script) directly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:30:58.500",
"Id": "64053",
"Score": "0",
"body": "Your approach is absolutely fine for formatting a string however you may want to consider a regexp replace for your exchange function. I'll update my answer a bit later today with an example of how to achieve that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T06:41:43.957",
"Id": "64113",
"Score": "0",
"body": "Besides `{{name}} {{name}}` not working, you can also place substitution markers inside the arguments to the template, which is usually undesirable. Your solution solves this too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:57:28.900",
"Id": "38437",
"ParentId": "38435",
"Score": "7"
}
},
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><code>delimiter</code> should be <code>delimiters</code></li>\n<li><code>var string = new String();</code> could be <code>var string = '';</code>, it raises less questions</li>\n<li>On a general note, I think it is bad design to AJAX each template..</li>\n<li>Worse, you do not cache AJAX results, using a template n times will trigger n AJAX calls</li>\n<li>The <code>exchange</code> function could be more elegant by using the split join trick:</li>\n</ul>\n\n<blockquote>\n<pre><code>this.exchange = function() {\n for ( var key in this.data ) {\n var token = this.delimiter[0] + key + this.delimiter[1];\n this.template = this.template.split( token ).join( this.data[key] );\n }\n};\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Note that the way <code>template</code> gets changed stops re-use of the template, which really goes against what a template is meant for.</li>\n<li>You keep returning <code>this</code>, but you do not chain your function calls</li>\n<li>I am not sure how your code works? Update : now I know how it works, a synchronous call per template function call is a bad idea.</li>\n</ul>\n\n<p>On a side note, I use the following for my personal templating needs:</p>\n\n<pre><code>function RNG( array )\n{ //Return a random entry from the provided array, all hail the RNG\n return array[Math.floor( Math.random() * array.length )];\n} \n\nfunction fillTemplate( s )\n{ //Replace ~ with further provided arguments, those might be arrays\n for( var i = 1 ; i < arguments.length ; i++ )\n s = s.replace( \"~\" , arguments[i].pop?RNG( arguments[i] ):arguments[i] );\n return s;\n} \n\nvar template = \"~ hits you in the ~ for ~ damage points\";\nvar bodyParts = ['head','chest','groins'];\nvar output = fillTemplate( template , 'The coding troll' , bodyParts , 3.14 );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:47:51.370",
"Id": "64058",
"Score": "0",
"body": "Thanks for your review, you've mentioned many useful things :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:57:29.273",
"Id": "64059",
"Score": "0",
"body": "So when you say, it's bad \"to ajax each template\", there must be a better way to deal with it, mustn't it?\n\nBut if I use AJAX, I should call the exchange function, when the ready state change, so within the in the http.onreadystatechange function, whichs allows me to make the ajax call asynchronous again or am I totally wrong now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T19:11:53.483",
"Id": "64061",
"Score": "1",
"body": "I meant that this will slow down performance, I would personally get the template with the initial JS script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:08:35.363",
"Id": "64065",
"Score": "0",
"body": "okay, I'm just a beginner, so any opinion is welcome to me :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:27:19.603",
"Id": "64076",
"Score": "0",
"body": "*this.template = string; seems pointless, since string will not be set yet* -- Jon's using **synchronous** XMLHTTPRequest. So it kinda works. (Not a good idea though.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:59:05.507",
"Id": "64088",
"Score": "0",
"body": "Ah! I will adjust my review accordingly."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:41:53.807",
"Id": "38440",
"ParentId": "38435",
"Score": "8"
}
},
{
"body": "<blockquote>\n<p>... as I went through others, there is always this voice in head, which says: "Oh, this is a lot of code and functionality. Is that really necessary or would it slow down the performance?"</p>\n</blockquote>\n<p>This is a reasonable consideration, but <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"noreferrer\">premature optimisation is evil for a reason</a>. It might be a good idea to try to roll out your own solution, but it would be beneficial to learn more about the problem and other existing solutions before implementing it yourself.</p>\n<p>As for minimalistic templating library, take a look at Underscore <a href=\"http://underscorejs.org/docs/underscore.html#section-134\" rel=\"noreferrer\"><code>_.template</code></a>.<br />\nIt's literally 45 lines (add one or two helper functions) and does its job well.</p>\n<p>As for your solution, I have a few points:</p>\n<h3>Don't use AJAX to load templates</h3>\n<p>If you're worried about performance, loading templates via AJAX is a bad idea. <em>This</em> will be a terrible bottleneck, not some hundred more lines of code in a different templating library.</p>\n<p>Moreover, your code assumes you need to make an HTTP request <em>each</em> time you render something. If you have a list view with 20 items, that would be 20 requests.</p>\n<p>This is <strong>absolutely unsuitable for production code</strong>.</p>\n<h3>Don't use synchronous AJAX calls, like, ever</h3>\n<p>The very <em>point</em> of AJAX is processing things asynchronously, without blocking other scripts from executing. There is rarely a reason to do things synchronously.</p>\n<p>Again, please don't do this in production code.</p>\n<h3>Instead, put templates in HTML or (better) compile them to JS</h3>\n<p>Most, if not all, templating libraries assume <strong>the template is already available in the client code</strong>, and this is the correct way to go. Now, there are two ways how you can accomplish this:</p>\n<p><strong>1. You can embed templates in DOM with <a href=\"https://stackoverflow.com/q/4912586/458193\">tricks like <code><script text="text/template"></code></a></strong></p>\n<p>The upside is that it is simple (no additional build steps), but the downside is that all your templates will have to be repeatedly passed in HTML with every page.</p>\n<p><strong>2. But really, you should <a href=\"https://github.com/gruntjs/grunt-contrib-jst\" rel=\"noreferrer\">precompile templates to a JS file</a></strong></p>\n<p>In this case, your build workflow will include an additional step when a certain command-line script goes over your <code>templates/*.html</code> files and compiles each HTML template into a JavaScript function that “takes” data arguments and returns the “rendered” HTML string.</p>\n<p>For example, a template like</p>\n<pre><code><div class="editor-Gallery-media">\n <div class="editor-Gallery-mediaItem"\n style="background-image: url({{ thumbnail_url }});"\n data-orientation="{{ orientation }}">\n\n <div class="editor-Gallery-deleteMediaItem"><i class="icon-cross"></i></div>\n\n <div class="editor-GrabboxMedia-orientation"></div>\n\n <div class="editor-Gallery-mediaItemCaption">{{ caption }}</div>\n </div>\n</div>\n</code></pre>\n<p>would be compiled in a function like</p>\n<pre><code>this["st"]["Template"]["templates/editor/items/gallery_media.html"] = function(obj) {\nobj || (obj = {});\nvar __t, __p = '', __e = _.escape;\nwith (obj) {\n__p += '<div class="editor-Gallery-media">\\n <div class="editor-Gallery-mediaItem"\\n style="background-image: url(' +\n((__t = ( thumbnail_url )) == null ? '' : __t) +\n');"\\n data-orientation="' +\n((__t = ( orientation )) == null ? '' : __t) +\n'">\\n\\n <div class="editor-Gallery-deleteMediaItem"><i class="icon-cross"></i></div>\\n\\n <div class="editor-GrabboxMedia-orientation"></div>\\n\\n <div class="editor-Gallery-mediaItemCaption">' +\n((__t = ( caption )) == null ? '' : __t) +\n'</div>\\n </div>\\n</div>';\n\n}\nreturn __p\n};\n</code></pre>\n<p>which would be placed in a generated <code>templates.js</code> file. This would be <em>blazing</em> fast.</p>\n<p>Note that there is no overhead of parsing in this case, because <strong>parsing happens on your machine, during the build</strong>. The client uses pregenerated functions.</p>\n<p>Such functions can be generated by most templating engines.</p>\n<h3>Don't parse the same template twice</h3>\n<p>Even if we bundle templates with the HTML (<code>script type="text/template"</code> approach), your code still suffers from the fact it parses the same template every time it is being rendered. That means, for 20 identical items, the same template is parsed 20 times. Of course, parsing is nothing compared to fetching HTML, but it's something that is relatively straightforward to optimize away.</p>\n<p>Instead, you should <strong>parse the template once</strong>, somehow cache the “parsed” version and figure out how to “apply” it to different models. As I advocated before, the natural way to it is to <strong>make <code>template</code> build a function that corresponds to your template.</strong></p>\n<p>This is exactly what <a href=\"http://underscorejs.org/#template\" rel=\"noreferrer\">Underscore's <code>_.template</code></a> does, so you want to look at its implementation (see also an <a href=\"http://underscorejs.org/docs/underscore.html#section-134\" rel=\"noreferrer\">annotated version</a>):</p>\n<pre><code>_.template = function(text, data, settings) {\n var render;\n settings = _.defaults({}, settings, _.templateSettings);\n\n var matcher = new RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n var index = 0;\n var source = "__p+='";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset)\n .replace(escaper, function(match) { return '\\\\' + escapes[match]; });\n\n if (escape) {\n source += "'+\\n((__t=(" + escape + "))==null?'':_.escape(__t))+\\n'";\n }\n if (interpolate) {\n source += "'+\\n((__t=(" + interpolate + "))==null?'':__t)+\\n'";\n }\n if (evaluate) {\n source += "';\\n" + evaluate + "\\n__p+='";\n }\n index = offset + match.length;\n return match;\n });\n source += "';\\n";\n\n\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = "var __t,__p='',__j=Array.prototype.join," +\n "print=function(){__p+=__j.call(arguments,'');};\\n" +\n source + "return __p;\\n";\n\n try {\n render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n if (data) return render(data, _);\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n template.source = 'function(' + (settings.variable || 'obj') + '){\\n' + source + '}';\n\n return template;\n};\n</code></pre>\n<p>It parses your template, “converting” it to a JavaScript function, and returns this function. When you call this function with different models, no parsing occurs: it was only done once, during initialization.</p>\n<h3>Minor considerations</h3>\n<ul>\n<li><p>Your templating library should probably be agnostic of jQuery. After all, what you want to do is to transform a <code>string + data</code> into another <code>string</code>. That you insert this string into DOM is another matter, and doesn't seem to belong here.</p>\n</li>\n<li><p>On a minor note,</p>\n<pre><code> var string = new String();\n</code></pre>\n<p>is not idiomatic JavaScript; you never need to call <code>String</code>, <code>Array</code> or <code>Object</code> constructors explicitly. If you want to set <code>string</code> to an empty string, write <code>var string = '';</code>. Still, this is unnecessary because you don't plan to use the empty value, so why bother assigning? Write <code>var string;</code> and leave it <code>undefined</code> until you assign it later. But <code>string</code> is a really bad name for a variable. It is a template, right? So you should probably write</p>\n<pre><code> var template;\n</code></pre>\n<p>Having an <code>undefined</code> represent a value that is not yet initialized/ready is okay.</p>\n</li>\n<li><p>If you're there for performance, <a href=\"http://olado.github.io/doT/index.html\" rel=\"noreferrer\">doT</a> claims to be fastest (although I'm not convinced their weird interpolation syntax justifies shaving off a few milliseconds).</p>\n</li>\n</ul>\n<p>To conclude, I advise you learn from <a href=\"http://underscorejs.org/#template\" rel=\"noreferrer\">Underscore</a>, <a href=\"http://olado.github.io/doT/index.html\" rel=\"noreferrer\">doT</a>, <a href=\"https://github.com/janl/mustache.js\" rel=\"noreferrer\">mustache.js</a>. It's fun and good for learning to reinvent something, but it's unwise to consider your implementation more performant before taking the time to test it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T03:10:16.623",
"Id": "64106",
"Score": "0",
"body": "wow, I'd never expected this huge amount of helpful information! thank you, I appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:18:57.260",
"Id": "38449",
"ParentId": "38435",
"Score": "21"
}
},
{
"body": "<p>In a good implementation you pay for a lot of functionality only if you are actually using that functionality - so a lot of functionality doesn't necessarily mean slow. In fact, more often than not, implementations with small amount of functionality are very sloppy and not fast. Consider underscore using a <code>with</code>-statement. This slows down performance unspeakably but is done because it takes no effort from the implementer. Implementing variable referencing properly without using <code>with</code> would take a lot more code.</p>\n\n<p>Overall an optimized library will always have a lot of more code than an unoptimized one. It's a simple physical law.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T02:20:28.230",
"Id": "38470",
"ParentId": "38435",
"Score": "3"
}
},
{
"body": "<p>I wanted to have templates in JavaScript too, and managed to create something even simpler than your approach:</p>\n\n<pre><code>String.prototype.replaceAll = function(find, replace) {\n return this.split(find).join(replace);\n};\n\nString.prototype.insertVariables = function (nameValuePairs) {\n var string = this.valueOf();\n\n for (var key in nameValuePairs) {\n if (nameValuePairs.hasOwnProperty(key)) {\n string = string.replaceAll('{{' + key + '}}', nameValuePairs[key]);\n }\n }\n\n return string;\n};\n</code></pre>\n\n<p>And you use it like this:</p>\n\n<pre><code>'some {{i}} variable'.insertVariables({i: 'inserted'}); // some inserted variable\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-02T20:41:00.340",
"Id": "61810",
"ParentId": "38435",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:41:03.307",
"Id": "38435",
"Score": "25",
"Tags": [
"javascript",
"template",
"library"
],
"Title": "Templating libraries' intelligibility and their performance (compared to mine)"
}
|
38435
|
<p>Here is a python function I wrote to implement the Newton method for optimization for the case where you are trying to optimize a function that takes a vector input and gives a scalar output. I use numdifftools to approximate the hessian and the gradient of the given function then perform the newton method iteration.</p>
<pre><code>import numpy as np
import numdifftools as nd
class multivariate_newton(object):
def __init__(self,func,start_point,step_size=0.8,num_iter=100,tol=0.000001):
'''
func: function to be optimized. Takes a vector argument as input and returns
a scalar output
step_size: step size in newton method update step
num_iter: number of iterations for newton method to run
tol: tolerance to determine convergence
'''
self.func=func
self.start_point=np.array(start_point)
self.num_iter=num_iter
self.step_size=step_size
self.tol=tol
def newton_method(self):
'''
perform multivariate newton method for function with vector input
and scalar output
'''
x_t=self.start_point
#Get an approximation to hessian of function
H=nd.Hessian(self.func)
#Get an approximation of Gradient of function
g=nd.Gradient(self.func)
for i in range(self.num_iter):
x_tplus1=x_t-self.step_size*np.dot(np.linalg.inv(H(x_t)),g(x_t))
#check for convergence
if abs(max(x_tplus1-x_t))<self.tol:
break
x_t=x_tplus1
self.crit_point=x_tplus1
self.max_min=self.func(x_t)
return self
def critical_point(self):
'''
print critical point found in newton_method function. newton_method function
must be called first.
'''
print self.crit_point
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:43:57.847",
"Id": "64042",
"Score": "0",
"body": "Can you explain what was wrong with the functions in [`scipy.optimize`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:50:20.683",
"Id": "64043",
"Score": "0",
"body": "I could not find one for the case of a function with vector input and scalar output. I tried fsolve but it would only work with vector input/output functions. Now that I look again, 'root' may work. I will give it a try."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:56:16.520",
"Id": "64044",
"Score": "0",
"body": "nevermind, 'root' required the input and output dimensions to be the same which is not what I want"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T19:26:00.993",
"Id": "64062",
"Score": "5",
"body": "This would better be a function instead of a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-21T00:48:14.560",
"Id": "374904",
"Score": "0",
"body": "I'm not sure what is commonly done here but I think you can avoid computing the inverse of the Hessian directly, which may be more costly and less numerically accurate (see [here](https://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/))."
}
] |
[
{
"body": "<p><a href=\"http://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis\" rel=\"nofollow\">Pathological cases</a> exist where Newton's method will not converge on a solution. Yet, there is no obvious way for the caller to tell whether convergence was achieved. You should distinguish between whether the loop terminated via the <code>break</code> (success) or by exhaustion of the loop condition (failure).</p>\n\n<pre><code>for _ in range(self.num_iter):\n x_tplus1 = x_t - self.step_size * np.dot(np.linalg.inv(H(x_t)), g(x_t))\n #check for convergence\n if abs(max(x_tplus1-x_t))<self.tol:\n break\n x_t = x_tplus1\nelse:\n raise SolutionNotFound, \"No convergence after %d iterations\" % (self.num_iter)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T11:16:05.427",
"Id": "39649",
"ParentId": "38436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39649",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:42:05.837",
"Id": "38436",
"Score": "8",
"Tags": [
"python",
"optimization",
"mathematics",
"numerical-methods"
],
"Title": "Python class that implements the Newton method"
}
|
38436
|
<p>In a current javascript project, I'm working with the browsers localStorage, and it will pretty consistently be full. To overcome this, I wrote a wrapper to surround the localStorage object that would keep track of when an object was added.</p>
<p>The hard(er) part, was coming up with the algorithm to make room for any new data. I was wondering if anyone could critique my method, and let me know if a better method exists.</p>
<pre><code>DataStore.prototype.makeRoom = function() {
var tmpData = {};
for (var key in localStorage) {
var expTime = JSON.parse(localStorage.getItem(key)).expirationTime;
if (Object.size(tmpData) < 3) {
tmpData[key] = expTime;
continue;
}
for (var tmpKey in tmpData) {
var tmpExp = JSON.parse(localStorage.getItem(tmpKey)).expirationTime;
if (tmpExp > expTime) {
delete tmpData[tmpKey];
tmpData[key] = expTime;
break;
}
}
}
for (var deleteKey in tmpData) {
this.destroyItem(deleteKey);
}
return true;
};
</code></pre>
<p>And for reference, DataStore.destroyItem(), and DataStore.store() where the data is written:</p>
<pre><code>DataStore.prototype.store = function(dataKey, data, minutesUntilExpiration, overWrite) {
if (!overWrite && this.hasItem(dataKey))
return false;
var dataToSave = {
data: data,
expirationTime: (new Date().getTime() + (minutesUntilExpiration * 60 * 1000))
};
try {
localStorage.setItem(dataKey, JSON.stringify(dataToSave));
} catch (e) {
this.makeRoom();
this.store(dataKey,data,minutesUntilExpiration,overWrite);
}
return true;
};
DataStore.prototype.destroyItem = function(dataKey) {
if (this.hasItem(dataKey)) {
localStorage.removeItem(dataKey);
return true;
}
return false;
};
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:18:28.337",
"Id": "64067",
"Score": "0",
"body": "How many items do you expect to manage in localStorage ( maximum ) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:54:44.260",
"Id": "64073",
"Score": "0",
"body": "Wouldn't you rather delete items that are past their expiration time before you start ejecting items arbitrarily?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:31:43.170",
"Id": "64078",
"Score": "0",
"body": "tom, between 50-150 have been my observations before it has to start deleting"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:32:32.003",
"Id": "64079",
"Score": "0",
"body": "200_success, Ideally, but under consistent use for say 5-10 minutes, the cache will have already filled. The data is essentially good forever so the only logical way in my mind was to start deleting the oldest. I'm primarily using it so when the user clicks the back button, it only needs to make 1 ajax call, rather than 20 that have to be spaced a second apart."
}
] |
[
{
"body": "<h1>Object.size</h1>\n\n<p>First off, if it's ok with you to use ES5 APIs (you use <code>localStorage</code>, it should be okay), then here's a quicker way to get the number of keys in an object using <code>Object.keys</code>.</p>\n\n<pre><code>return Object.keys(obj).length\n</code></pre>\n\n<h1>Delete by <code>N</code></h1>\n\n<p>Also, from what I understand in your code, you're deleting keys by 3's. If so, then you should not hardcode the 3. Instead, have it configurable in your object.</p>\n\n<h1>Verbose Variable Naming</h1>\n\n<p>Here's one I get often. Name variables according to use. <code>tmpExp</code> will not help anyone understand its purpose. Name them verbosely. I should understand code like I read the back of a milk box or something.</p>\n\n<h1>Compress the algorithm</h1>\n\n<p>I suggest you compress the algorithm, make it simple. </p>\n\n<p>Nested loops are just bad for performance. Also, <code>getItem</code> is a synchronous operation, which means that if it freezes, it freezes the UI as well. Nesting that along with a <code>JSON.parse</code> makes it even more slow.</p>\n\n<p>If you can, do operations with the least loop runs and function calls as much as possible. If you can cram several loops into one big loop (like batched operations), then do so.</p>\n\n<p>Here's a proposed fix for <code>makeRoom</code>. Keeping it simple, it just removes the oldest among the stored data.</p>\n\n<pre><code>// Just grab the expiry and store the expiry-key into an object\nvar expiries = Object.keys(localStorage).reduce(function(collection,key){\n var currentExpirationTime = JSON.parse(localStorage.getItem(key)).expirationTime;\n collection[currentExpirationTime] = key;\n return collection;\n},{});\n\n// Get the expiry dates into an array\nvar expiryDates = Object.keys(expiries);\n\n// For N times, find the oldest (smallest timestamp) and destroy\nfor(var i = 0; i < N; i++){\n var oldestDate = Math.min.apply(null,expiryDates);\n this.destroyItem(expiries[oldestDate]);\n}\n</code></pre>\n\n<h1><code>getTime</code> <code>now()</code>!</h1>\n\n<p>Instead of <code>new Date().getTime()</code>, there's the new <code>Date.now()</code>. Same effect, but saves you memory from creating a new <code>Date</code> instance just to get the current timestamp.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:49:44.340",
"Id": "64080",
"Score": "0",
"body": "Thank you for the feedback! That algorithm looks like it should perform much better, I feel a little dumb for not coming up with a more elegant solution. 'Verbose Variable Naming' - absolutely, as sad as it is, this is a major improvement for me, I used to be the king of 1 letter variables. I have seen the light though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:09:51.317",
"Id": "38445",
"ParentId": "38441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38445",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:51:36.473",
"Id": "38441",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"html5",
"cache"
],
"Title": "Function to delete oldest items out of HTML5 localStorage. Can I make it more efficient?"
}
|
38441
|
<p>I have some code that I wrote almost a year ago exactly (<em>1/9/2013</em>) and I would like to know if I wrote it well or if it can be improved. I don't have any fun input or output, as these are not set results coming out of this column in the table.</p>
<pre><code>-- =============================================
-- Author: Malachi (Name Changed to Protect the possibly Guilty)
-- Create date: 1/9/2013
-- Description: Will give a list of the Bond Conditions
-- =============================================
CREATE FUNCTION [dbo].[fnBondConditionList]
(
@BondID int
)
RETURNS Varchar(MAX)
AS
BEGIN
DECLARE @Result Varchar(MAX)
SELECT @Result = (Select Justice.dbo.uCode.Description as BondConditions
FROM Justice.dbo.uCode INNER JOIN
Justice.dbo.xBondCondition ON Justice.dbo.uCode.CodeID = Justice.dbo.xBondCondition.ConditionID
WHERE Justice.dbo.xBondCondition.BondID = @BondID
FOR XML PATH (''))
SET @Result = replace(@Result, '<BondConditions>','')
SET @Result = replace(@Result, '</BondConditions>','<br />')
Set @Result = LEFT(@Result, LEN(@Result) - 1)
RETURN @Result
END
</code></pre>
<p>I cannot change the tables. Here are the table layouts:</p>
<p><strong>uCode:</strong></p>
<pre><code>CREATE TABLE [dbo].[uCode](
[CodeID] [dbo].[CodeID] NOT NULL,
[CacheTableID] [dbo].[CacheTableID] NOT NULL,
[RevisionID] [dbo].[RevisionID] NOT NULL,
[Code] [dbo].[Word] NOT NULL,
[RootNodeID] [dbo].[NodeID] NOT NULL,
[EffectiveDate] [datetime] NULL,
[ObsoleteDate] [dbo].[ObsoleteDate] NULL,
[UserIDCreate] [dbo].[UserIDCreate] NOT NULL,
[TimestampCreate] [dbo].[TimestampCreate] NOT NULL,
[UserIDChange] [dbo].[UserIDChange] NULL,
[TimestampChange] [dbo].[TimestampChange] NULL,
[FilterState] [dbo].[StateCode] NULL,
[FilterSiteID] [dbo].[GUID] NULL,
[Description] [dbo].[DescriptionLong] NULL,
CONSTRAINT [PK_uCode] PRIMARY KEY NONCLUSTERED
(
[CodeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IXuCode1] UNIQUE CLUSTERED
(
[CacheTableID] ASC,
[CodeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code></pre>
<p><strong>xBondCondition:</strong></p>
<pre><code>CREATE TABLE [dbo].[xBondCondition](
[BondID] [dbo].[BondID] NOT NULL,
[ConditionID] [dbo].[CodeID] NOT NULL,
CONSTRAINT [PK_xBonduCode] PRIMARY KEY CLUSTERED
(
[BondID] ASC,
[ConditionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code></pre>
<p>This code was created to stuff everything from one column into a single column of a single record, which is then fed to a stored procedure that fills a datagrid.</p>
<p>Should I be looping this somehow (<em>I get a bad taste in my mouth just typing that</em>)?</p>
<p>I update this because I find myself using the same <code>FOR XML PATH ('')</code> Template for something very similar.</p>
<p>I cannot use <code>CONCAT</code> because I am using SQL SERVER 2008 (<em>wouldn't that be nice</em>).</p>
<p>With all that going into the Stored Procedure, the SPROC Renders something similar to this:<img src="https://i.stack.imgur.com/epUVC.jpg" alt="Image of Resulting Gridview"></p>
<p>Where the rightmost column is the column of the SPROC that was produced by a function almost exactly the same as above.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-17T23:46:51.990",
"Id": "151718",
"Score": "0",
"body": "I think you might need to have an argument with somebody about separating the presentation from the data. The code smells because the requirements smell."
}
] |
[
{
"body": "<p>If you do not want the XML Tags, then do not add them!</p>\n\n<p>This code frustrates me because:</p>\n\n<ul>\n<li>you have not given any indication as to what this code should be doing.</li>\n<li>you are embedding presentation-layer logic in the database layer</li>\n<li>you convert all the data to an XML document, and then strip all the XML tags from the result because this appears to be a <em>'cheap'</em> way to get all the data as a single result instead of multiple rows.</li>\n<li>you do not document this</li>\n<li>you use less-common features of the database (XML manipulation) without good reason, which locks you in to a single provider for the database ;-)</li>\n<li>there is no documented reason for why you strip the last character from the <code>@result</code>... this will strip the closing <code>></code> from the last <code><br /></code>, and will thus leave some invalid X?HTML? I presume? A bug?</li>\n</ul>\n\n<p>As for some nit-picks:</p>\n\n<ul>\n<li>You should not be using <code>SELECT @Result = (...)</code>, but should, instead be using <code>SET @Result = (...)</code> <a href=\"http://technet.microsoft.com/en-us/library/ms187330.aspx\">See the documentation for SELECT</a>.</li>\n<li>you capitalize some of your query key-words, but not all. I recommend using whatever case you do <strong>not</strong> use for your columns. In your case, your db.schema.table.columns are all lower/CamelCase, so your keywords should all be full CAPITALS. Thus, you should have <code>SELECT</code> everywhere. You have one <code>SELECT</code>, and one <code>Select</code>. You have one <code>LEFT</code>, and two <code>replace</code>. Your consistency of convention should be improved.</li>\n<li>you do not use table-aliases for your query objects. Not only do table-aliases make the SQL more readable, but, if you need to change a table name for some reason (e.g. to get data from a view, or different schema), then you have to change multiple places, and could lead to bugs....</li>\n</ul>\n\n<p>As far as I am concerned, this function should be removed entirely, and a simple presentation-layer system should be added that simply appends a <code><br /></code> after each bond description from the query:</p>\n\n<pre><code>SELECT uC.Description\nFROM Justice.dbo.uCode uC\nINNER JOIN Justice.dbo.xBondCondition xBC\n ON uC.CodeID = xBC.ConditionID\nWHERE xBC.BondID = ?\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T04:06:55.543",
"Id": "64528",
"Score": "0",
"body": "good answer, I am taking Data that is Created by an application and displaying it on an additional information page of a website. I agree with the `SET` and as far as the removing the last character, I think that there was something being returned at the end of the string other than the trailing `<br />`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:36:15.390",
"Id": "71816",
"Score": "0",
"body": "I think that I did some `Dirty Things` to create what I wanted, in other words I agree with you completely. when I get back around to this project again, I will think of about this and see if I can change it. it might tell me why I did this in the first place as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T03:30:56.847",
"Id": "38668",
"ParentId": "38444",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "38668",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T19:39:04.443",
"Id": "38444",
"Score": "8",
"Tags": [
"sql",
"sql-server"
],
"Title": "Small query - removing XML tags"
}
|
38444
|
<p>The aim of the code below is to see if selected fields are empty so data can be saved in that field. Since I'm making a library system, I wanted to record the basic info on one record (all the books they have taken out so the ID's of them as well as author and title) but this proves to be quite tricky and quite long to code.</p>
<p>I was wondering whether there's an easier way to code this instead of the very long <code>if</code> loop. It would also help if I could use the same solution (obviously tweaked) when displaying their loans on the form as well. </p>
<pre><code>procedure Save;
{ procedure to locate which field groups are empty so product and loan informati
- on can be saved }
begin
if LoanRecords.ProductID1 ='' then
begin
LoanRecords.ProductID1 := ProductRecords.UniqueId;
LoanRecords.ProductTitle1 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor1 := ProductRecords.ProductAuthor;
end
else if LoanRecords.ProductID2 = '' then
begin
LoanRecords.ProductID2 := ProductRecords.UniqueId;
LoanRecords.ProductTitle2 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor2 := ProductRecords.ProductAuthor;
end
else if LoanRecords.ProductID3 = '' then
begin
LoanRecords.ProductID3 := ProductRecords.UniqueId;
LoanRecords.ProductTitle3 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor3 := ProductRecords.ProductAuthor;
end
else if LoanRecords.ProductID4 ='' then
begin
LoanRecords.ProductID4 := ProductRecords.UniqueId;
LoanRecords.ProductTitle4 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor4 := ProductRecords.ProductAuthor;
end
else if LoanRecords.ProductID5 ='' then
begin
LoanRecords.ProductID5 := ProductRecords.UniqueId;
LoanRecords.ProductTitle5 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor5 := ProductRecords.ProductAuthor;
end
else if LoanRecords.ProductID6='' then
begin
LoanRecords.ProductID6 := ProductRecords.UniqueId;
LoanRecords.ProductTitle6 := ProductRecords.ProductTitle;
LoanRecords.ProductAuthor6 := ProductRecords.ProductAuthor;
end
end;
</code></pre>
<p>This is the record structure-</p>
<pre><code> TLoan = record
LoanUniqueId: integer; { of loan record }
DateDue: TDateTime; { date when products are due to be returned }
MemberUniqueID: integer; { from MemberDetails File }
MemberName: string[50]; { from MemberDetails File }
MemberSecondName: string[50]; { from MemberDetails File }
AmountBorrowed: integer; { amount of items currently on loan }
{ Product 1 }
ProductID1: integer; { product ID }
ProductTitle1: string[80]; { product title }
ProductAuthor1: string[80]; { product author }
Return1: boolean;
{ has book been returned- true/false- set to false until book is returned }
{ Product 2 }
ProductID2: integer;
ProductTitle2: string[80];
ProductAuthor2: string[80];
Return2: boolean;
{ Product 3 }
ProductID3: integer;
ProductTitle3: string[80];
ProductAuthor3: string[80];
Return3: boolean;
{ Product 4 }
ProductID4: integer;
ProductTitle4: string[80];
ProductAuthor4: string[80];
Return4: boolean;
{ Product 5 }
ProductID5: integer;
ProductTitle5: string[80];
ProductAuthor5: string[80];
Return5: boolean;
{ Product 6 }
ProductID6: integer;
ProductTitle6: string[80];
ProductAuthor6: string[80];
Return6: boolean;
end; { of TLoan- loan details }
</code></pre>
|
[] |
[
{
"body": "<p>Technically, there is no such thing as if-loops. Your code is just a bunch of if-else <em>statements</em> (sorry, this was the language police speaking)</p>\n\n<p>What your code actually needs, is actually a real loop. Use an array or a list of a record, <code>TLoanProduct</code> and loop through it. Your current approach allows a maximum of six products in one loan, it involves a lot of code duplication which in itself is a code smell, and it could be a bit weird if the values for Product 3 were set but not Product 1.</p>\n\n<p>My Delphi skills are a bit rusty, but consider changing <code>TLoan</code> into an <code>object</code> or a <code>class</code> instead of a pure <code>record</code>. That way you could have the <code>Save</code> method as part of the <code>TLoan</code> object/class.</p>\n\n<p>This is some code for how I think it should look. It's been a long while since I worked with Delphi so this might not be 100% correct code, but it should get you started in the right direction.</p>\n\n<pre><code>TLoanProduct = record\n ProductID: integer;\n ProductTitle: string[80];\n ProductAuthor: string[80];\n Returned: boolean;\nend;\nTLoan = record\n LoanUniqueId: integer; { of loan record }\n DateDue: TDateTime; { date when products are due to be returned }\n MemberUniqueID: integer; { from MemberDetails File }\n MemberName: string[50]; { from MemberDetails File }\n MemberSecondName: string[50]; { from MemberDetails File }\n AmountBorrowed: integer; { amount of items currently on loan }\n LoanProducts: array [0..5] of TLoanProduct;\nend;\n\n...\n\nprocedure Save;\n{ procedure to locate which field groups are empty so product and loan informati\n - on can be saved }\nvar i: integer;\nbegin\n for i := 0 to High(LoanRecords.LoanProducts) do\n if LoanRecords.LoanProducts[i].ProductID = '' then\n begin\n LoanRecords.LoanProducts[i].ProductID := ProductRecords.UniqueId;\n LoanRecords.LoanProducts[i].ProductTitle := ProductRecords.ProductTitle;\n LoanRecords.LoanProducts[i].ProductAuthor := ProductRecords.ProductAuthor;\n Exit; // Exit the method so that this is only applied for one element\n end;\nend;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:26:16.660",
"Id": "64282",
"Score": "0",
"body": "wouldn't that write the data (Unique ID, Product Title etc) to each loan product if no items were loaned? so I'd end up having 5 sets of the same data? @SimonAndréForsberg"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:51:19.810",
"Id": "64284",
"Score": "0",
"body": "@Hawwa You're right. Missed that important part. I've added an `Exit;` statement to end the execution of the method to fix that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:13:06.307",
"Id": "64653",
"Score": "0",
"body": "I tried the above method but for some reason the ProductID, ProductTitle and Author come up with the following error- [dcc32 Error]: E2018 Record, object or class type required"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:24:27.673",
"Id": "64658",
"Score": "0",
"body": "...............@SimonAndréForsberg"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:36:26.683",
"Id": "64660",
"Score": "0",
"body": "@Hawwa I made a few updates to my code here. If this still doesn't work for you, update your question and add a section containing what you are attempting. I also noticed that ProductID is an integer and not a string, so how you would manage to compare it against an empty string goes beyond my comprehension."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:43:15.317",
"Id": "64662",
"Score": "0",
"body": "i just did the IntToStr/StrToInt conversion and use length to check that. Thanks for the update the errors have gone :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:55:31.173",
"Id": "38551",
"ParentId": "38448",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T20:50:10.227",
"Id": "38448",
"Score": "4",
"Tags": [
"delphi"
],
"Title": "Locating empty field groups for saving data"
}
|
38448
|
<p>I would especially like to find out how this project should be constructed to be "fully MVVM". I did some reading about MVVM and I started to implement some ideas, but I don't fully understand it yet.</p>
<p>The game works, but I would like to get some advice regarding what could be done better/differently. Does it make sense to make such project MVVM in the first place?</p>
<h3>MainWindow.xaml.cs:</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace PongGame
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = _ball;
RightPad.DataContext = _rightPad;
LeftPad.DataContext = _leftPad;
Ball.DataContext = _ball;
label4.DataContext = _rightPad;
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Start();
timer.Tick += _timer_Tick;
}
private double _angle = 155;
private double _speed = 5;
private int _padSpeed = 7;
void _timer_Tick(object sender, EventArgs e)
{
if (_ball.Y <= 0) _angle = _angle + (180 - 2*_angle);
if (_ball.Y >= MainCanvas.ActualHeight - 20)_angle = _angle + (180 - 2*_angle);
if (CheckCollision() == true)
{
ChangeAngle();
ChangeDirection();
}
double radians = (Math.PI / 180) * _angle;
Vector vector = new Vector { X = Math.Sin(radians), Y = -Math.Cos(radians) };
_ball.X += vector.X * _speed;
_ball.Y += vector.Y * _speed;
if (_ball.X >= 790)
{
_ball.LeftResult += 1;
GameReset();
}
if (_ball.X <= 5)
{
_ball.RightResult += 1;
GameReset();
}
}
private void GameReset()
{
_ball.Y = 210;
_ball.X = 380;
}
private void ChangeAngle()
{
if (_ball.MovingRight == true) _angle = 270 - ((_ball.Y + 10) - (_rightPad.YPosition + 40));
else if (_ball.MovingRight == false) _angle = 90 + ((_ball.Y + 10) - (_leftPad.YPosition + 40));
}
private void ChangeDirection()
{
if (_ball.MovingRight == true) _ball.MovingRight = false;
else if (_ball.MovingRight == false) _ball.MovingRight = true;
}
private bool CheckCollision()
{
bool collisionResult = false;
if (_ball.MovingRight == true)
collisionResult = _ball.X >= 760 && (_ball.Y > _rightPad.YPosition - 20 && _ball.Y < _rightPad.YPosition + 80);
if (_ball.MovingRight == false)
collisionResult = _ball.X <= 20 && (_ball.Y > _leftPad.YPosition - 20 && _ball.Y < _leftPad.YPosition + 80);
return collisionResult;
}
readonly Ball _ball = new Ball { X = 380, Y = 210 , MovingRight = true};
readonly Pad _leftPad = new Pad { YPosition = 90 };
readonly Pad _rightPad = new Pad { YPosition = 70 };
private void MainWindow_OnKeyDown(object sender, KeyboardEventArgs e)
{
if (Keyboard.IsKeyDown(Key.W)) _leftPad.YPosition -= _padSpeed;
if (Keyboard.IsKeyDown(Key.S)) _leftPad.YPosition += _padSpeed;
if (Keyboard.IsKeyDown(Key.Up)) _rightPad.YPosition -= _padSpeed;
if (Keyboard.IsKeyDown(Key.Down)) _rightPad.YPosition += _padSpeed;
}
}
}
</code></pre>
<h3>Ball.cs:</h3>
<pre class="lang-cs prettyprint-override"><code>using System.ComponentModel;
using PongGame.Annotations;
namespace PongGame
{
class Ball : INotifyPropertyChanged
{
private double _x;
private double _y;
private bool _movingRight;
private int _leftResult;
private int _rightResult;
public double X
{
get { return _x; }
set
{
_x = value;
OnPropertyChanged("X");
}
}
public double Y
{
get { return _y; }
set
{
_y = value;
OnPropertyChanged("Y");
}
}
public bool MovingRight
{
get { return _movingRight; }
set
{
_movingRight = value;
OnPropertyChanged("MovingRight");
}
}
public int LeftResult
{
get { return _leftResult; }
set
{
_leftResult = value;
OnPropertyChanged("LeftResult");
}
}
public int RightResult
{
get { return _rightResult; }
set
{
_rightResult = value;
OnPropertyChanged("RightResult");
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
</code></pre>
<h3>Pad.cs:</h3>
<pre class="lang-cs prettyprint-override"><code>using System.ComponentModel;
using System.Linq;
using System.Text;
using PongGame.Annotations;
namespace PongGame
{
class Pad : INotifyPropertyChanged
{
private int _yPosition;
public int YPosition
{
get { return _yPosition; }
set { _yPosition = value;
OnPropertyChanged("YPosition");}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
</code></pre>
<h3>MinWindow.xaml:</h3>
<pre class="lang-xml prettyprint-override"><code> <Window x:Class="PongGame.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System;assembly=System"
KeyDown="MainWindow_OnKeyDown"
Title="MainWindow" Height="503" Width="824" ResizeMode="NoResize">
<Canvas Width="800" Height="475" Name="MainCanvas" Background="#FFD1D1D1">
<Rectangle Height="80" Width="20" Fill="Blue"
Canvas.Top="{Binding YPosition}"
Name="LeftPad"></Rectangle>
<Rectangle Height="80" Width="20" Fill="Brown"
Canvas.Top="{Binding YPosition}"
Canvas.Left="780"
Name="RightPad"></Rectangle>
<Line X1="400" X2="400" Y2="500" Y1="0" StrokeThickness="2" Stroke="#FFDBB062"></Line>
<Ellipse Width="20" Height="20" Canvas.Left="{Binding X}"
Canvas.Top="{Binding Y}" Name="Ball" DataContext="{Binding Path=ball}" StrokeThickness="0.1" Fill="#FFF84949">
</Ellipse>
<Label Canvas.Left="630" Canvas.Top="34" Content="{Binding Y}" Height="28" Name="label1" />
<Label Canvas.Left="565" Canvas.Top="34" Content="Y of ball" Height="28" Name="label2" />
<Label Canvas.Left="535" Canvas.Top="68" Content="Y of right pad" Height="28" Name="label3" />
<Label Canvas.Left="630" Canvas.Top="68" Content="{Binding YPosition}" Height="28" Name="label4" />
<Label Canvas.Left="638" Canvas.Top="128" Content="{Binding MovingRight}" Height="28" Name="label5" />
<Label Canvas.Left="184" Canvas.Top="34" Content="{Binding X}" Height="28" Name="label6" />
<Label Canvas.Left="119" Canvas.Top="34" Content="X of ball" Height="28" Name="label7" />
<Label Canvas.Left="89" Canvas.Top="68" Content="X of right pad" Height="28" Name="label8" />
<Label Canvas.Left="184" Canvas.Top="68" Content="{Binding YPosition}" Height="28" Name="label9" />
<Label Canvas.Left="349" Canvas.Top="35" Content="{Binding LeftResult}" Height="auto" Name="label10"
FontSize="40" Foreground="Blue"/>
<Label Canvas.Left="421" Canvas.Top="35" Content="{Binding RightResult}" Height="auto" Name="label11"
FontSize="40" Foreground="Brown"/>
</Canvas>
</Window>
</code></pre>
|
[] |
[
{
"body": "<p>quick look; What the heck is this for ?</p>\n\n<blockquote>\n<pre><code>public event PropertyChangedEventHandler PropertyChanged;\n\n[NotifyPropertyChangedInvocator]\nprotected virtual void OnPropertyChanged(string propertyName)\n{\n PropertyChangedEventHandler handler = PropertyChanged;\n if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));\n</code></pre>\n</blockquote>\n\n<p>I've never needed or used [NotifyPropertyChangedInvocator] (re-sharper thing, not part of c#)</p>\n\n<p>Why re-assign the external variable? Just do </p>\n\n<blockquote>\n<pre><code>if (PropertyChanged!= null) PropertyChanged(this, new\nPropertyChangedEventArgs(propertyName)); ....\n</code></pre>\n</blockquote>\n\n<p>It is also fairly common these days to let the compiler do the work;</p>\n\n<blockquote>\n<pre><code>void OnPropertyChanged([CallerMemberName] String T = \"\")\n{\n if (PropertyChanged != null)\n PropertyChanged(this, new PropertyChangedEventArgs(T));\n}\n</code></pre>\n</blockquote>\n\n<p>So your update code is cleaner e.g.;</p>\n\n<blockquote>\n<pre><code> float _FeedRate = 5f;\n [Category(\"Machine\")]\n public float FeedRate { get { return _FeedRate; } set { _FeedRate = value; OnPropertyChanged(); } }\n</code></pre>\n</blockquote>\n\n<p>Consider <code>INotifyPropertyChanged</code> vs Dependency properties. They do the same thing. I tend to keep visual info in depencies, data model stuff in propertyChanged.</p>\n\n<p>You really have no data model <em>per se</em>. The paddle locations are indeed visual, but to me, the ball location, and collision logic should be the data Model part of mvvm.</p>\n\n<p>As you probably know by now, canvas has some nasty re-sizing problems, but that does not reflect on your mvvm strategy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:05:03.323",
"Id": "64234",
"Score": "3",
"body": "`if (PropertyChanged != null) PropertyChanged(…)` This has a race condition, because the handler could be removed after the `null` check, but before the invocation. That's why the pattern of storing the value in a local first is commonly used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:18:31.533",
"Id": "64235",
"Score": "0",
"body": "Oh yeah, heard/read about that. Personally do not subscribe to the 'add code for the one in a billion possibility' Especially when it introduces 2 more additional possibilities of the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:23:51.300",
"Id": "64236",
"Score": "3",
"body": "This doesn't introduce any additional possibilities for race conditions. And I certainly don't think it makes sense to change correct code to one that's subtly incorrect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:33:44.583",
"Id": "64239",
"Score": "0",
"body": "No it doesn't add a race condition, but it does still allow a de-activated function to be called unintentionally, which may be just as bad or worse. Its wasted effort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:36:45.187",
"Id": "64240",
"Score": "3",
"body": "Yeah, but the difference is that your code will throw `NullReferenceException` when that race condition happens, while the original code never does that. You're right that calling deregistered handler is possible in both cases, and that's not the reason for this. Sorry I wasn't clear about that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T19:06:09.133",
"Id": "38532",
"ParentId": "38451",
"Score": "2"
}
},
{
"body": "<pre><code>DataContext = _ball;\nRightPad.DataContext = _rightPad;\nLeftPad.DataContext = _leftPad;\nBall.DataContext = _ball;\nlabel4.DataContext = _rightPad;\n</code></pre>\n\n<p>I don't think you should be setting <code>DataContext</code> for each control like this. Instead, you should have a <em>view model</em> object that you set as the <code>DataContext</code> of the whole window. That view model would contain all the context objects that you need and you would use binding in your XAML to get to them.</p>\n\n<p>Also, <code>label4</code> is a very bad name, you should use descriptive names for everything.</p>\n\n<p>And if you do it this way, shouldn't <code>label9</code> be here too? (If the first label was called something like <code>LeftPadYPosition</code>, then it would be much easier to see that the label for right pad is missing here.)</p>\n\n<hr>\n\n<pre><code>var timer = new DispatcherTimer();\n</code></pre>\n\n<p>I believe this timer will be collected as soon as the garbage collector runs, which means it will stop ticking then. You should keep the timer in a field.</p>\n\n<hr>\n\n<pre><code>if (_ball.Y <= 0) _angle = _angle + (180 - 2*_angle);\n</code></pre>\n\n<p>One line conditions are quite unreadable, the statement should be on its own line.</p>\n\n<hr>\n\n<pre><code>if (CheckCollision() == true)\n</code></pre>\n\n<p>This could be simplified to just <code>if (CheckCollision())</code>.</p>\n\n<p>The same applies to similar conditions throughout your code. And <code>== false</code> should be replaced with <code>!</code>.</p>\n\n<hr>\n\n<pre><code>double radians = (Math.PI / 180) * _angle;\nVector vector = new Vector { X = Math.Sin(radians), Y = -Math.Cos(radians) };\n</code></pre>\n\n<p>Converting angle to coordinates on the unit circle sounds like something that should be in its own method. And so does converting degrees to radians.</p>\n\n<hr>\n\n<pre><code>if (_ball.X >= 790) \n</code></pre>\n\n<p>Why exactly 790? Constants like these should be named. This makes the code clearer and easier to modify.</p>\n\n<hr>\n\n<pre><code>bool collisionResult = false;\nif (_ball.MovingRight == true)\n collisionResult = _ball.X >= 760 && (_ball.Y > _rightPad.YPosition - 20 && _ball.Y < _rightPad.YPosition + 80);\n\nif (_ball.MovingRight == false)\n collisionResult = _ball.X <= 20 && (_ball.Y > _leftPad.YPosition - 20 && _ball.Y < _leftPad.YPosition + 80);\n\nreturn collisionResult;\n</code></pre>\n\n<p>You could simplify this to:</p>\n\n<pre><code>if (_ball.MovingRight)\n return _ball.X >= 760 && (_ball.Y > _rightPad.YPosition - 20 && _ball.Y < _rightPad.YPosition + 80);\nelse\n return _ball.X <= 20 && (_ball.Y > _leftPad.YPosition - 20 && _ball.Y < _leftPad.YPosition + 80);\n</code></pre>\n\n<p>(That <code>else</code> isn't actually necessary, but I like the symmetry.)</p>\n\n<p>The previous comment about named constants also applies here.</p>\n\n<p>And it would also help if you extracted the second part of the condition into a separate method, taking <code>Pad</code> as a parameter. This way, you avoid duplicated code.</p>\n\n<hr>\n\n\n\n<pre class=\"lang-xml prettyprint-override\"><code><Rectangle Height=\"80\" Width=\"20\" Fill=\"Blue\"\n Canvas.Top=\"{Binding YPosition}\"\n Name=\"LeftPad\"></Rectangle>\n</code></pre>\n\n<p>Consider using empty element tags, they are shorter and imply that you don't intend to add anything inside the element later:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><Rectangle Height=\"80\" Width=\"20\" Fill=\"Blue\"\n Canvas.Top=\"{Binding YPosition}\"\n Name=\"LeftPad\" />\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-xml prettyprint-override\"><code><Label Canvas.Left=\"630\" Canvas.Top=\"34\" Content=\"{Binding Y}\" Height=\"28\" Name=\"label1\" />\n</code></pre>\n\n<p>In cases like this, using WPF panels to place the controls is much better: you don't have to specify the exact position, the layout is easier to change and it also works better with resizing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:28:56.817",
"Id": "38636",
"ParentId": "38451",
"Score": "6"
}
},
{
"body": "<p>This bit of code is much longer than it needs to be:</p>\n\n<pre><code>private void ChangeDirection()\n{\n if (_ball.MovingRight == true) _ball.MovingRight = false;\n else if (_ball.MovingRight == false) _ball.MovingRight = true;\n}\n</code></pre>\n\n<p>It can simplified to:</p>\n\n<pre><code>private void ChangeDirection()\n{\n _ball.MovingRight = !_ball.MovingRight;\n}\n</code></pre>\n\n<p>With <code>bool</code> conditionals, you never need to use <code>(variable == true)</code> or <code>(variable == false)</code>. Rather just use <code>(variable)</code> or <code>(!variable)</code> respectively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-24T14:30:45.987",
"Id": "101801",
"ParentId": "38451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:24:41.870",
"Id": "38451",
"Score": "10",
"Tags": [
"c#",
"game",
"wpf",
"mvvm"
],
"Title": "Pong game in WPF"
}
|
38451
|
<p>This is only my third Python script. Be brutal with me. Any tips, tricks, best practices, or better usages would be great!</p>
<pre><code>import socket
from concurrent.futures import ThreadPoolExecutor
THREADS = 512
CONNECTION_TIMEOUT = 1
def ping(host, port, results = None):
try:
socket.socket().connect((host, port))
if results is not None:
results.append(port)
print(str(port) + " Open")
return True
except:
return False
def scan_ports(host):
available_ports = []
socket.setdefaulttimeout(CONNECTION_TIMEOUT)
with ThreadPoolExecutor(max_workers = THREADS) as executor:
print("\nScanning ports on " + host + " ...")
for port in range(1, 65535):
executor.submit(ping, host, port, available_ports)
print("\nDone.")
available_ports.sort()
print(str(len(available_ports)) + " ports available.")
print(available_ports)
def main():
scan_ports("127.0.0.1")
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:17:37.553",
"Id": "64097",
"Score": "0",
"body": "What is the purpose of this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:22:42.123",
"Id": "64098",
"Score": "0",
"body": "@GarethRees Just learning from a book. If I were being malicious, I certainly wouldn't post the question under my real name. Haha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-11T18:51:22.403",
"Id": "190993",
"Score": "0",
"body": "[Follow up question here](http://codereview.stackexchange.com/questions/46842/python-port-scanner-2-0)"
}
] |
[
{
"body": "<p>It's not Pythonic to pass in a mutable object and use that to store results (like it is in C).</p>\n\n<p><code>range(start, stop)</code> is not inclusive of stop, so you have an off by one error as well.</p>\n\n<p>Using a catch-all <code>except</code> line is also poor practice. It's important to catch expected exceptions and reraise the rest.</p>\n\n<p>Also Python lists are thread safe only because of the <a href=\"https://wiki.python.org/moin/GlobalInterpreterLock\">GIL</a> in CPython. This code would not be thread safe in other implementations such as Jython. Notice how your version always reports open ports in ascending order.</p>\n\n<p>Threads are fine for IO bounded actions, but since pinging localhost is so fast GIL contention slows down performance in this case. Your implementation ran in 27 seconds on my laptop.</p>\n\n<p>By comparison, my implementation ran in 2.76 seconds. Replacing <code>map()</code> with <code>pool.map()</code> led to a runtime of 1.38 seconds:</p>\n\n<pre><code>#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom errno import ECONNREFUSED\nfrom functools import partial\nfrom multiprocessing import Pool\nimport socket\n\nNUM_CORES = 4\n\n\ndef ping(host, port):\n try:\n socket.socket().connect((host, port))\n print(str(port) + \" Open\")\n return port\n except socket.error as err:\n if err.errno == ECONNREFUSED:\n return False\n raise\n\n\ndef scan_ports(host):\n p = Pool(NUM_CORES)\n ping_host = partial(ping, host)\n return filter(bool, p.map(ping_host, range(1, 65536)))\n\n\ndef main(host=None):\n if host is None:\n host = \"127.0.0.1\"\n\n print(\"\\nScanning ports on \" + host + \" ...\")\n ports = list(scan_ports(host))\n print(\"\\nDone.\")\n\n print(str(len(ports)) + \" ports available.\")\n print(ports)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:15:48.707",
"Id": "64152",
"Score": "0",
"body": "Wow. Amazing performance difference! Thanks for all your comments. I've got some Googling to do to completely figure out how your code works, but this will definitely help me learn the language better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:45:15.883",
"Id": "64159",
"Score": "0",
"body": "Can you explain your usage of the `filter()` function? I don't get why your first argument is `bool`. It seems like the function is supposed to take another function as the first argument, or `None` to just purge `False` (which seems like what you're trying to do). Would passing in `None` have worked just as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:01:30.150",
"Id": "64164",
"Score": "0",
"body": "Interestingly, your version actually runs a lot slower on my PC. The performance benefits may only be on *nix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:21:07.817",
"Id": "64216",
"Score": "0",
"body": "Forking is cheap on *nix, expensive on Windows. Vice versa for threads. Also make sure `NUM_CORES` accurately reflects how many physical cores on the machine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:26:14.270",
"Id": "64217",
"Score": "0",
"body": "From `map(ping_host(range(1, 65536)))` we get an example list `[False, 2, False, 4, ...]`. `filter(bool, list)` will apply `bool()` to each element in the list and only keep those that evaluate to `True`. `None`, `False`, `0`, `[]`, `''` evaluates to `False`, everything else evaluates to `True`. Thus `filter(bool, [None, 2, False, 4])` results in the list `[2, 4]`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T04:49:04.903",
"Id": "38476",
"ParentId": "38452",
"Score": "11"
}
},
{
"body": "<p>Apart from wting's answer I'd add that you call <code>main()</code> and then <code>scan_ports()</code> when you could've called <code>scan_ports</code> directly in the <code>if __name__ == '__main__':</code> block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:32:03.353",
"Id": "64218",
"Score": "1",
"body": "It's preferable that Jeff calls `main()` and implements logic within that function. This allows for better use at the interpreter (`from scan import main`) and unit testing. Guido goes into this a bit more: https://www.artima.com/weblogs/viewpost.jsp?thread=4829"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:01:39.500",
"Id": "38485",
"ParentId": "38452",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38476",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:45:47.150",
"Id": "38452",
"Score": "9",
"Tags": [
"python",
"multithreading",
"python-3.x",
"socket"
],
"Title": "Python Port Scanner"
}
|
38452
|
<p>I'm not familiar with Java at all, so I'd like to get some feedback on this piece of code. </p>
<p>I made it by looking at a few Hello World-esque Java server examples, so it may have drawbacks I'm not aware of.</p>
<p>My task was <strong>turning an existing Java console app into a single-threaded server</strong> listening on some port. Each connection should “launch” what previously was the console app, where actual “arguments” are passed by the client. Anything that was written by console app to stdout, should go into process' stdout; but <strong>what was previously written to stderrm needs to be redirected to the client</strong>. Finally, when the processing has finished, if there was no error, the client should receive <code>"OK"</code> and get disconnected. (And the next client should be processed.)</p>
<p>Here's the original and my version side by side:</p>
<pre><code>// Change: we want to run this as a server instead
// public static void main(String [] args) {
// (new Main(args)).execute();
// System.exit(0);
// }
public static void main(String args[]) throws Exception {
int port = Integer.parseInt(args[0]);
ServerSocket welcomeSocket = new ServerSocket(port);
System.out.format("Listening on %d\n", port);
PrintStream defaultStderr = System.err;
while (true) {
// Establish a connection
Socket connectionSocket = welcomeSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
// Hook System.err
System.setErr(new PrintStream(output));
try {
// Run Batik as if we ran console app, but without the launch overhead
(new Main(input.readLine().split(" "))).execute();
} catch (Throwable t) {
// Normally, we shouldn't get here (as Batik should not crash).
// If we *do* get here, print to stderr, which we redirect to output stream anyway.
t.printStackTrace();
}
// Let the client know how it went
if (output.size() == 0) {
output.writeBytes("OK");
}
output.close();
// Restore stderr
System.setErr(defaultStderr);
}
}
</code></pre>
<p>What can I make better? I want to clarify I do <em>not</em> want to change any other method in the app to keep it easy to merge upstream changes.</p>
|
[] |
[
{
"body": "<h2>General:</h2>\n\n<p>Commandline handling in any application is a PITA.... My recommendation is that you change both the client side, and server side, to put each argument on a different line so that you don't have to 'split' it on the Server. This would be relatively simple to do.</p>\n\n<h2>OOP:</h2>\n\n<p>This is a 'for future improvement' thing. It is a common pattern in Java for servers to handle different 'clients' in different threads. It is really easy if you have the basic infrastructure in place. Simply creating a class called \"ClientManager\" or something is a start, and having the following:</p>\n\n<pre><code>class ClientManager {\n private final Socket socket;\n ClientManager(Socket socket) {\n this.socket = socket;\n }\n\n public void processSocket() {\n\n // do all your things for the socket in here.\n\n }\n}\n</code></pre>\n\n<p>With this simple class, your Java server becomes:</p>\n\n<pre><code>while (true) {\n // Establish a connection\n ClientManager client = new ClientManager(welcomeSocket.accept());\n client.processSocket();\n}\n</code></pre>\n\n<p>This has some advantages. The first is that it becomes easier to separate Server problems from client problems, and the second is that the <code>client.processSocket()</code> can be easily moved off to any thread we want to use.</p>\n\n<p>Right now, using a single thread is probably fine, but, the Error handling would be much better with this distinction. Consider the following:</p>\n\n<pre><code>try {\n while (true) {\n // Establish a connection\n ClientManager client = new ClientManager(welcomeSocket.accept());\n try {\n client.processSocket();\n } catch (Exception e) {\n // this is unusual to catch `Exception` but it is done intentionally!\n // Any exception in the client code is specific to **that** client.\n // Clients should be better behaved and manage their own exceptions\n // but no client is perfect.\n // Log the issue, and wait for the next customer.\n e.printStackTrace();\n }\n }\n} catch (IOException serverexception) {\n // this is an exception in the **server** code, and thus the server dies:\n serverexception.printStackTrace();\n}\n</code></pre>\n\n<p>OK, so we have a Server that is well isolated from the client code it runs.</p>\n\n<h2>The client handler</h2>\n\n<p>The client code is handled by a ClientManager class. What happens in there.... this is a copy/paste of the relevant code:</p>\n\n<pre><code> BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));\n DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());\n\n // Hook System.err\n System.setErr(new PrintStream(output));\n\n try {\n // Run Batik as if we ran console app, but without the launch overhead\n (new Main(input.readLine().split(\" \"))).execute();\n } catch (Throwable t) {\n // Normally, we shouldn't get here (as Batik should not crash).\n // If we *do* get here, print to stderr, which we redirect to output stream anyway.\n t.printStackTrace();\n }\n\n // Let the client know how it went\n if (output.size() == 0) {\n output.writeBytes(\"OK\");\n }\n\n output.close();\n\n // Restore stderr\n System.setErr(defaultStderr);\n</code></pre>\n\n<p>Now, this client/server setup is simple. It is a call-response type only, with a 'success' indicated by 'OK'. Anything else is a problem.</p>\n\n<p>The protocol can be set up that the client pushes the arguments, and then closes that stream.... and then waits for results. Closing the stream has the advantage that we can read the arguments nicely (wait for end-of-stream):</p>\n\n<pre><code>List<String> arguments = new ArrayList<>();\nString line = null;\nwhile ((line = input.readLine()) != null) {\n arguments.add(line);\n}\n</code></pre>\n\n<p>Let's introduce the Java7 try-with-resources system. This has a number of advantages, but, in this case it makes sure that, if there's a problem, the client side of the process knows immediately instead of hanging around waiting for a socket to die (get garbage collected).</p>\n\n<p>Note, never catch <code>Throwable</code>.... it will catch all sorts of things you don't want to, like ThreadKillError, etc.</p>\n\n<p>First up, we manage the input/output streams:</p>\n\n<pre><code>PrintStream defaultStderr = System.err;\ntry ( BufferedReader input = new BufferedReader(\n new InputStreamReader(socket.getInputStream()));\n DataOutputStream output = new DataOutputStream(socket.getOutputStream());\n PrintStream stderr = new PrintStream(output);\n) {\n // at this point, the input/output is guaranteed to close\n List<String> arguments = new ArrayList<>();\n String line = null;\n while ((line = input.readLine()) != null) {\n arguments.add(line);\n } \n\n // Hook System.err\n System.setErr(stderr);\n\n try {\n // Run Batik as if we ran console app, but without the launch overhead\n Main batik - new Main(arguments.toArray(new String[arguments.size]));\n batik.execute();\n } catch (Exception t) {\n // Normally, we shouldn't get here (as Batik should not crash).\n // If we *do* get here, print to stderr, which we redirect to output stream anyway.\n t.printStackTrace();\n }\n\n // Let the client know how it went\n if (output.size() == 0) {\n output.writeBytes(\"OK\");\n }\n output.flush();\n} finally {\n // note, we close the socket explicitly when we are done.\n // even if the input and output are closed, you should still close the socket.\n this.socket.close();\n\n // Restore stderr\n System.setErr(defaultStderr);\n} \n</code></pre>\n\n<p>note that this handling of System.err is a problem.... you will never be able to multi-thread until you fix this.</p>\n\n<p>All the best, I hope this makes sense to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:48:45.177",
"Id": "64094",
"Score": "0",
"body": "Hi, thanks for the comments! So catching Throwable doesn't buy me anything at all? How about weird scenarios like allocation errors? (The console app may eat a lot of memory and potentially can exhaust system resources in rare scenarios. It would be nice to keep the server running, and only fail “for one client” instead of shutting it down.) Currently I do it in a single thread by design but you're right I might want to make it at least two threads later—sadly, `System.err` ruins it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T17:50:16.860",
"Id": "64361",
"Score": "1",
"body": "I would recommend against it anyway. If (when) you go multi-thread, for e.g. OutOfMemoryErrors you have no certainty that the thread-that-fails is the one with the actual problem. Catching Error is always a bad idea, for almost all values of 'always'."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:36:52.710",
"Id": "38461",
"ParentId": "38453",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:58:31.363",
"Id": "38453",
"Score": "4",
"Tags": [
"java",
"console",
"socket",
"stream",
"server"
],
"Title": "Turning a Java console app into a server"
}
|
38453
|
<p>This is the domain class called <code>WordType</code> which has Id as its unique DB generated value and Name and Description as other values.</p>
<p>I was going through the <em>Effective Java</em> <a href="http://web.archive.org/web/20110622072109/http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf" rel="nofollow noreferrer">resource</a> by Joshua Bloch and having a tough time assimilating the entire contents the first time. So I am looking at the implementation in my code by some other programmers so I learn by example and also validate the existing implementation. And the author states that for the usual classes the existing equals and hashcode works fine.</p>
<blockquote>
<p>The easiest way to avoid problems is not to override the equals
method, in which case each instance is equal only to itself.</p>
</blockquote>
<p>I am really skeptical if the below equals and hashcode implementation will work or if we should live with the default equals and hashcode without overriding them. </p>
<p>Each word would be unique as in dictionary for instance, and hence the ID would also be unique. If so, should I combine ID and Word to generate an equals and hashcode method?</p>
<pre><code>public class WordType implements Serializable {
private static final long serialVersionUID = 1L;
//... other properties, getters and setters
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof WordType)) {
return false;
}
WordType other = (WordType) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:29:22.393",
"Id": "64092",
"Score": "1",
"body": "There is a [good checklist](http://stackoverflow.com/a/27609/458193) to check against. Looks like your implementation is fine (assuming `id` can't mutate over time). It is weird that `id` is nullable though."
}
] |
[
{
"body": "<p>What exactly <em>is</em> the <code>id</code> variable? <code>int</code>? <code>long</code>? <code>Integer</code>? Your <code>hashCode</code> and <code>equals</code> implementations really just \"pass the buck\" to the <code>id</code>.</p>\n\n<p>That being said, the code you posted will work fine; two <code>WordType</code> objects are equal if they both have the same <code>id</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:49:21.470",
"Id": "64087",
"Score": "0",
"body": "Thank you, ID is just an auto-generated field in the database."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:41:08.273",
"Id": "64093",
"Score": "2",
"body": "@oneworld If it is an autogenerated field, make sure you put the instance in a dictionary **after** it has been assigned an ID, or `contains` would break."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:44:41.930",
"Id": "38457",
"ParentId": "38454",
"Score": "3"
}
},
{
"body": "<p>The hashCode method can be simplified down to (just simply restructuring your logic and removing redundancy):</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return id == null ? 0 : id.hashCode();\n}\n</code></pre>\n\n<p>The equals method is a bit more complicated. Your code does appear to keep the hashCode/equals contract, so that is good, but, sometimes there are better ways than others to test for things. For example, often when you override hashCode and equals it is because these instances are used in a Set or Map. A shortcut is to often check for identity before checking for equality.... i.e. <code>if (other == this) return true;</code> This can (often/sometimes) save a lot of internal processing to resolve equality.</p>\n\n<p>I have a template I tend to use for <code>equals(...)</code> and it goes like this:</p>\n\n<pre><code>@Override\npublic boolean equals(final Object other) {\n if (this == other) {\n // nothing declared for simplest case.\n return true;\n }\n if (!(other instanceof MyClass)) {\n // other is null or not one of us.....\n return false;\n }\n // Code appropriate for **your** class goes here\n final Myclass their = (MyClass)other;\n if (this.id == their.id) {\n // identity goes first.\n // this works for both values null too.\n return true;\n }\n if (this.id == null) {\n // we are null, they are not.\n return false;\n }\n return id.equals(their.id);\n}\n</code></pre>\n\n<p>This method is longer than yours, but it makes the logic clear.</p>\n\n<p>When you have to conform to 'bigger' contracts like the hashCode/equals contract (or the Comparable contract), it is often better to make the logic progression very obvious....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:51:30.693",
"Id": "38458",
"ParentId": "38454",
"Score": "5"
}
},
{
"body": "<p>I'm nitpicking but instead of </p>\n\n<pre><code>if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {\n return false;\n}\nreturn true;\n</code></pre>\n\n<p>you could write</p>\n\n<pre><code>return (this.id == other.id)\n || (this.id != null && this.id.equals(other.id));\n</code></pre>\n\n<p>This reads easier because the intent is obvious (“same or equal”).</p>\n\n<p>I prefer <a href=\"https://codereview.stackexchange.com/a/38458/2634\">rolfl's verbose option</a> though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:37:41.520",
"Id": "38462",
"ParentId": "38454",
"Score": "3"
}
},
{
"body": "<p>NEVER implement a hashcode on the base of attributes that may change. So following implementation is invalid by definition as the \"id\" is either expected to change or you have nonsensical objects:</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return id == null ? 0 : id.hashCode(); // do not do this!!!\n}\n</code></pre>\n\n<p>A valid implementation would be:</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return id.hashCode();\n}\n</code></pre>\n\n<p>The minimal implementation would be:</p>\n\n<pre><code>@Override\npublic int hashCode() {\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-01T22:23:30.360",
"Id": "154215",
"ParentId": "38454",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38458",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:23:32.933",
"Id": "38454",
"Score": "5",
"Tags": [
"java",
"hashcode"
],
"Title": "Equals and hashCode implementation"
}
|
38454
|
<p>The review I asked for yesterday was for a header only library.<br />
<a href="https://codereview.stackexchange.com/questions/38402/http-stream-a-stream-that-opens-an-http-get-and-then-acts-like-a-normal-c-istr">Stream that opens an HTTP GET and then acts like a normal C++ istream</a></p>
<p>This has some limitations as it downloads all the data as part of the constructor. This can lead to delays during start up if the file is large (usually during REST communications the size is small so the header only version is sufficient).</p>
<p>But if you want larger files and don't want a delay here is a version that downloads the data in the background asynchronously. If the stream buffer underflows the next block (which has been accumulated in the background) is quickly swapped into the buffer and the main thread can continue processing.</p>
<p>The disadvantage is that this is no longer a header only library and you will need to link against the library.</p>
<p><a href="https://github.com/Loki-Astari/ThorsStream" rel="noreferrer">https://github.com/Loki-Astari/ThorsStream</a></p>
<h3>ThorsStream.h</h3>
<pre><code>#ifndef THORSANVIL_STREAM_THOR_STREAM_H
#define THORSANVIL_STREAM_THOR_STREAM_H
// Note "ThorsSimpleStream.h" is up fro review in a seprate question
// https://codereview.stackexchange.com/questions/38402/http-stream-a-stream-that-opens-an-http-get-and-then-acts-like-a-normal-c-istr
#include "ThorsSimpleStream.h"
#include <thread>
#include <iostream>
namespace ThorsAnvil
{
namespace Stream
{
class IThorStream: public std::istream
{
// Class to handle the down-loading of all http connections in the background.
class ThorStreamManager
{
public:
// Everybody will use the same instance
static ThorStreamManager& defaultManager()
{
static ThorStreamManager defaultManager;
return defaultManager;
}
ThorStreamManager()
: finished(false)
, multi(curl_multi_init())
, streamThread(&ThorStreamManager::eventLoop, this, multi != NULL)
{
if (multi == NULL)
{ throw std::runtime_error("Failed to startup");
}
}
~ThorStreamManager()
{
// When destroying the object.
// Make sure we first take care of any threads.
{
std::unique_lock<std::mutex> lock(mutex);
finished = true;
}
cond.notify_one();
streamThread.join();
// Now we can clean up any resources.
curl_multi_cleanup(multi);
}
// Interface to add/remove http requests.
void addHTTPRequest(CURL* easy)
{
std::unique_lock<std::mutex> lock(mutex);
curl_multi_add_handle(multi, easy);
}
void delHTTPRequest(CURL* easy)
{
std::unique_lock<std::mutex> lock(mutex);
curl_multi_remove_handle(multi, easy);
}
private:
// Event loop is run by the thread.
// It handles all interactions with sockets.
void eventLoop(bool ok);
bool finished;
CURLM* multi;
std::mutex mutex;
std::condition_variable cond;
std::thread streamThread;
};
// The stream buffer.
class SocketStreamBuffer: public IThorSimpleStream::SimpleSocketStreamBuffer
{
public:
typedef IThorSimpleStream::SimpleSocketStreamBuffer::traits_type traits;
typedef traits::int_type int_type;
SocketStreamBuffer(std::string const& url, std::function<void()> markStreamBad)
: SimpleSocketStreamBuffer(url, false, false, markStreamBad)
{
/* Perform the request, res will get the return code */
ThorStreamManager::defaultManager().addHTTPRequest(curl);
}
~SocketStreamBuffer()
{
ThorStreamManager::defaultManager().delHTTPRequest(curl);
}
virtual int_type underflow()
{
{
std::unique_lock<std::mutex> lock(mutex);
empty = true;
}
curl_easy_pause(curl, CURLPAUSE_CONT);
{
std::unique_lock<std::mutex> lock(mutex);
cond.wait(lock, [&empty, &open](){return !(empty && open);});
}
return empty ? EOF : buffer[0];
}
// Used by ThorStreamManager to mark that the stream has
// finished downloading data.
virtual void markAsDone()
{
std::unique_lock<std::mutex> lock(mutex);
open = false;
cond.notify_one();
}
};
SocketStreamBuffer buffer;
public:
IThorStream(std::string const& url)
: std::istream(NULL)
, buffer(url, [this](){this->setstate(std::ios::badbit);})
{
std::istream::rdbuf(&buffer);
}
};
}
}
#endif
</code></pre>
<h3>ThorsStream.cpp</h3>
<pre><code>#include "ThorsStream.h"
using namespace ThorsAnvil::Stream;
// Of OK is not true then the object
// will have thrown an exception so its
// its not safe to do anything but return
// immediately
void IThorStream::ThorStreamManager::eventLoop(bool ok)
{
// If multi failed to initialize in the constructor
// There is no point in continuing the thread.
if (!ok)
{ return;
}
// Can not let an exception escape a thread.
// If it did it would cause the application
// to terminate.
try
{
std::unique_lock<std::mutex> lock(mutex);
while(!finished)
{
// 1: Get the File descriptors that curl has ready.
int max_fd = 0;
fd_set read;
fd_set writ;
fd_set exec;
FD_ZERO(&read);
FD_ZERO(&writ);
FD_ZERO(&exec);
CURLMcode result = curl_multi_fdset(multi, &read, &writ, &exec, &max_fd);
if (result != CURLM_OK) {throw std::runtime_error("curl_multi_fdset: Failed");}
if (max_fd == 0)
{
// No file descriptors.
// There is no point doing anything.
// So wait until a new curl easy object is added.
// Then re-start the loop.
cond.wait(lock);
continue;
}
// 2: Calculate the timeout we can use in select/poll
timespec timeoutSpec = {0,0};
if (max_fd == -1)
{
// curl special case.
// We need to call curl_multi_perform() soon
// so use a 100 millisecond timeout
timeoutSpec.tv_sec = 0;
timeoutSpec.tv_nsec = 100 * 1000000; // convert milli to nano
}
else
{
long timeout;
result = curl_multi_timeout(multi, &timeout);
if (result != CURLM_OK) {throw std::runtime_error("curl_multi_timeout: Failed");}
if (timeout == -1)
{ timeout = 300;
}
timeoutSpec.tv_sec = timeout/1000;
timeoutSpec.tv_nsec = timeout%1000 * 1000000; // convert milli to nano
}
// 3: Wait for activity on any of the file descriptors.
int count;
do
{
lock.unlock();
count = pselect(max_fd+1, &read, &writ, &exec, &timeoutSpec, NULL);
lock.lock();
}
while ((count == -1) && (errno == EINTR));
if (count == -1) {throw std::runtime_error("pselect: Failed");}
// 4: Handle all the CURL calllback routines.
int running_handles;
do
{
result = curl_multi_perform(multi, &running_handles);
}
while(result == CURLM_CALL_MULTI_PERFORM);
if (result != CURLM_OK) {throw std::runtime_error("curl_multi_perform: Failed");}
// 5: Handle all the messages generated by curl.
// Currently this is simply the fact that a stream has closed.
CURLMsg* message;
int msgs_in_queue;
while((message = curl_multi_info_read(multi, &msgs_in_queue)) != NULL)
{
if (message->msg == CURLMSG_DONE)
{
CURL* easy = message->easy_handle;
char* priv;
if (curl_easy_getinfo(easy, CURLINFO_PRIVATE, &priv) == CURLE_OK && priv != NULL)
{
IThorStream::SocketStreamBuffer* owner = reinterpret_cast<IThorStream::SocketStreamBuffer*>(priv);
owner->markAsDone();
}
}
}
}
}
catch(std::exception const& e)
{
// Log error:
std::cerr << "Exception in Thread:\n\t" << e.what() << "\n";
}
catch(...)
{
// Log error:
std::cerr << "Exception in Thread:\n\tUNKNOW (...)\n";
}
// Ignore error
}
</code></pre>
<p>Unfortunately I used the <code>select()</code> version of the CURL interface. I have plans to re-write this to use the <code>poll()</code> version of the interface. But that's another day.</p>
<p>A simple example using the above stream and my previous JSON parser library to connect to a REST interface and download data directly into a C++ class object without parsing the JSON directly.</p>
<p><a href="https://gist.github.com/Loki-Astari/8201956" rel="noreferrer">https://gist.github.com/Loki-Astari/8201956</a></p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>#include \"ThorsSimpleStream.h\"\n</code></pre>\n</blockquote>\n\n<p>There's no <code>ThorsSimpleStream</code> identifier used in the header: instead, \"ThorsSimpleStream.h\" declares <code>class IThorSimpleStream</code>.</p>\n\n<p>I prefer it if the filename of the header matches the name of identifier which it declares.</p>\n\n<hr>\n\n<p>IThorSimpleStream declares <code>friend class IThorStream</code>.</p>\n\n<p>I prefer it if <code>friend</code> classes are defined in the same header file (this suggestion comes from <a href=\"http://rads.stackoverflow.com/amzn/click/0201633620\" rel=\"nofollow\">Lakos</a>, summarized as \"no long-distance friendship\").</p>\n\n<p><code>SimpleSocketStreamBuffer</code> seems to be a private member of <code>IThorStream</code> and <code>IThorSimpleStream</code>. Instead of declaring friendship between <code>IThorStream</code> and <code>IThorSimpleStream</code>, perhaps you could simply define <code>SimpleSocketStreamBuffer</code> in its own header file.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>class IThorStream\n</code></pre>\n</blockquote>\n\n<p>I'm used to <code>I</code> being used for designate 'interfaces': or pure abstract classes in C++. I don't see why you're prefixing your class names with <code>I</code>.</p>\n\n<hr>\n\n<p>You could move more out of the header and into the CPP file: the definition/implementation of <code>SocketStreamBuffer</code> methods, and the whole <code>ThorStreamManager</code> class declaration.</p>\n\n<p>Users of your header file would then have less to read, and fewer headers such as <code><thread></code> included into their code.</p>\n\n<p>You could hide the whole <code>SocketStreamBuffer</code> declaration too, using the 'cheshire cat' aka 'pimpl' idiom (i.e. by making it an opaque pointer).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> lock.unlock();\n count = pselect(max_fd+1, &read, &writ, &exec, &timeoutSpec, NULL);\n lock.lock();\n</code></pre>\n</blockquote>\n\n<p>Might you want to do <code>if (finished) break;</code> after re-acquiring the lock, in case the system is shutting down / waiting to shutdown?</p>\n\n<hr>\n\n<blockquote>\n <p>catch(std::exception const& e)</p>\n</blockquote>\n\n<p>This is outside the while loop so the thread will die so the <code>ThorStreamManager</code> is dead. You might like to move that into the while loop, or re-create the <code>ThorStreamManager</code> in case there's a next request.</p>\n\n<hr>\n\n<p>(I haven't learned the CURL API so can't review your eventLoop in any detail.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T00:50:13.517",
"Id": "78671",
"Score": "0",
"body": "`IThorStream` is following the conventions of the standard library. `istream`, `ifstream` and `ostream`, `ofstream`. I don't use the `I` is for interface convention as I feel it is redundant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T01:00:41.977",
"Id": "78673",
"Score": "0",
"body": "I used the name `ThorsSimpleStream.h` as one day I may add the class `OThorSimpleStream`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T22:14:11.770",
"Id": "45159",
"ParentId": "38455",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "45159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:31:35.857",
"Id": "38455",
"Score": "10",
"Tags": [
"c++",
"socket",
"stream",
"curl",
"http"
],
"Title": "HTTP Stream Part 2 A stream that opens an HTTP GET and then acts like a normal C++ istream"
}
|
38455
|
<p>I've built a framework that primarily provides automated Ajax and a way to emulate classes. I've pasted the framework below and I hope it is well-commented.</p>
<p><code>klass()</code> and <code>machine()</code> are the interesting methods.</p>
<p>I've also posted some application code so you have some idea of how it used.</p>
<p>I'm looking for general feedback on logic and organization.</p>
<p>I'm not looking to add any other features or increase the scope for now. If anything, I need to make it smaller.</p>
<p><strong>Library</strong></p>
<pre><code>/*******************************************************************************
** FRAME
** manageGlobal - manages the single global variable that FRAME uses
** time - basic timer
** getDomElements - pull elements from the DOM
** getLibElements - creates library elements ( change name )
** initByProperty - execute class methods by property
** klass - emulates a class system
** machine - runs ajax on the classes among other things
** definePipe - defines the model data for the entire application
** makePipe - makes the model data for a single Ajax call
*******************************************************************************/
(function () {
"use strict";
var $A,
$P = {},
$R = {};
$P.last = {};
$R.Classes = {};
$R.packet_hold = {};
// requires utility and comms module
(function manageGlobal() {
if (window.$A && window.$A.pack && window.$A.pack.utility &&
window.$A.pack.comms) {
$A = window.$A;
$A.pack.frame = true;
} else {
throw "frame requires utility and comms module";
}
}());
// used to time performance by machine()
$R.time = (function () {
var measurements = [];
return function (control) {
var index,
intervals = [],
time_current = new Date().getTime();
if (control === 'start') {
measurements = [];
measurements.push(time_current);
return;
}
if (control !== 'finish') {
measurements.push(time_current);
return;
}
if (control === 'finish') {
measurements.push(time_current);
index = measurements.length;
while (index) {
index -= 1;
intervals[index - 1] = (measurements[index] -
measurements[index - 1]) + 'ms';
}
return intervals;
}
};
}());
// get dom elements for each module
$P.getDomElements = function (el_hold) {
var list;
// iterate through each module
$A.someKey($R.Classes, function (val) {
list = val[el_hold];
if (list) {
// iterate through each module's el_hold properties
$A.someKey(list, function (val, key) {
// replace the id w/ an element reference
list[key] = $A.el(val);
});
}
});
};
// get library elements for each module
$P.getLibElements = function (lib_hold, lib_global) {
var list;
// iterate through each module
$A.someKey($R.Classes, function (val) {
list = val[lib_hold];
if (list) {
// iterate through the module's l_hold properties
$A.someKey(list, function (val, key) {
list[key] = lib_global(val);
});
}
});
};
// initialize each module by property
$P.initByProperty = function (prop) {
// iterate through each module
$A.someKey($R.Classes, function (val) {
// if the property exists execute it
if (val[prop]) {
val[prop]();
}
});
};
$P.klass = function (obj, config_module) {
// log the class
$R.Classes[obj.Name] = obj;
// all properties are private and static ( there is no access )
if (!config_module) {
return undefined;
}
// all properties are public and static ( there is access, no instance )
if (config_module === true) {
return obj;
}
// constructor based, all properties are public and static/instance
if (config_module === 'constructor') {
var object_public;
// retrieve the constructor
if (obj.constructor) {
object_public = obj.constructor;
delete obj.constructor;
}
// add methods and properties to the prototye chain
$A.someKey(obj, function (val, key) {
object_public.prototype[key] = val;
});
// return the constructor
return object_public;
}
};
// automates ajax using pre() and post()
// built out as needed for arcmarks.com
$P.machine = function (obj) {
// make a pipe and pull the animation element
var pipe = $A.makePipe(obj),
data_send,
ajax_type,
wait_animation = document.getElementById('wait_animation'),
// use let when ES6 and move to appropriate block
form_data,
message;
if ($R.Classes[pipe.model] && $R.Classes[pipe.model].hasOwnProperty("pre")) {
// start the timer
$R.time('start');
// run pre() and get pipe
pipe = $R.Classes[pipe.model].pre(pipe);
// time it took pre() to run
$R.time('middle');
$A.Reg.set('pipe_pre', pipe);
} else {
// pre() is required to run ajax
return;
}
// final block, pre() must return true to continue
if (pipe.state === true) {
// special form data ajax request
// do you need to use ecode URI?
if (pipe.form_data) {
form_data = pipe.form_data;
ajax_type = 'multi';
delete pipe.form_data;
form_data.append("pipe", JSON.stringify(pipe));
data_send = form_data;
// turn the object literal into a string an encode it
} else {
ajax_type = 'post';
data_send = 'pipe=' + encodeURIComponent(JSON.stringify(pipe));
}
// start the animation so the user knows ajax is going
if (wait_animation) {
wait_animation.style.opacity = 1;
}
// run ajax
$A.ajax({
type: ajax_type,
url: $A.Reg.get('path') + $A.Reg.get('path_ajax'),
data: data_send,
callback: function (pipe_string_receive) {
var pass_prefix = pipe_string_receive.slice(0, 3),
times;
// turn off ajax animation
if (wait_animation) {
wait_animation.style.opacity = 0;
}
// if the server want to talk it will prefix its message with |D|, and continue
// normal comms with an |A|
if (pass_prefix === '|D|') {
message = pipe_string_receive.match(/^(\|D\|)([\s\S]*)(\|A\|)/);
$A.log('|D|FROM SERVER|');
$A.log(message[2]);
// remove the debug message
pipe_string_receive = pipe_string_receive.slice((message[1] + message[2]).length);
// this should always be an |A|, update
pass_prefix = pipe_string_receive.slice(0, 3);
}
if (pass_prefix === '|A|') {
$R.time('middle');
pipe = JSON.parse(pipe_string_receive.slice(3));
// if post exists run it
if ($R.Classes[pipe.model].hasOwnProperty("post")) {
pipe = $R.Classes[pipe.model].post(pipe);
// record timing information for pre(), transit, and post()
times = $R.time('finish');
pipe.time.pre = times[0];
pipe.time.transit = times[1];
pipe.time.post = times[2];
$A.Reg.set('pipe_post', pipe);
} else {
return;
}
} else {
throw "<No '|A|' or '|D|'>" + pipe_string_receive;
}
}
});
}
};
// holds the pipe definition
$P.definePipe = function (obj) {
$R.packet_hold = obj;
};
// clones the pipe and extends any additional properties
$P.makePipe = function (obj) {
return $A.extend($A.clone($R.packet_hold), obj);
};
// module complete, add it to the global scope
$A = $A.extendSafe($A, $P);
}());
</code></pre>
<p><strong>Application Code</strong></p>
<pre><code>/***************************************************************************************************
**MArc uses MUserAny on the server side.
*/
$A.klass({
Name: 'MArc',
S: {
Arcmarks: new Arcmarks()
},
E: {
fm: '#fm'
},
J: {
fm: '#fm'
},
init: function () {
$A.machine({model: this.Name});
},
initJ: function () {
var self = this;
$A.Event.add('malleable', function () {
self.J.fm.draggable();
self.J.fm.draggable('enable');
});
$A.Event.add('malleable_not', function () {
self.J.fm.draggable('disable');
self.J.fm.draggable('destroy');
});
},
pre: function (pipe) {
pipe.server.smalls.h_token = '1FOO';
pipe.state = true;
return pipe;
},
post: function (pipe) {
this.S.Arcmarks.render(pipe.server.arcmarks, this.E.fm);
return pipe;
}
});
</code></pre>
|
[] |
[
{
"body": "<p>I'm polarized by this code.</p>\n<p>I see many good practices in use here:</p>\n<ul>\n<li>you <strong><code>use strict</code></strong>, consistently indent your code and apparently lint it too;</li>\n<li>you <strong>correctly use scoping</strong> to provide encapsulation, split code in modules and don't use globals;</li>\n<li><strong>methods are small and clean</strong>, the code is easy to read.</li>\n</ul>\n<p>However, if you ask me to look at it at a more conceptual level, I would argue against using such code in production. There are several reasons for this.</p>\n<p>Firstly, in my opinion this code violates <strong>the principle of <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility</a></strong>. It doesn't <strong><a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"noreferrer\">separate concerns</a></strong> quite well, mixing AJAX, some kind of a state machine, DOM interaction and a pseudo-OOP framework in one module.</p>\n<p>It may just be me being silly, but I don't understand what this code does, after reading it fully for several times. <strong>The individual components seem deceptively simple but I don't understand how they work together.</strong></p>\n<p>The usage example you provided strikes me as rather cryptic too. It looks like a state machine (<code>machine</code> helps), but what are <code>S</code>, <code>E</code>, <code>J</code>, <code>fm</code>? Is there some asynchronous request being made (<code>pre</code> and <code>post</code>)? Is <code>pipe</code> some kind of shared state? When do machine's states change?</p>\n<p>Finally, <strong>I find naming to be hard to understand and confusing</strong>. The comments don't help because they seem to assume the reader already knows the system. This may not be the case for your team members, any new hires, or maybe even for yourself a few months down the road.</p>\n<p>A few example that could benefit from better naming:</p>\n<ul>\n<li><code>$R</code>, <code>$P</code>, <code>$A</code>: private, public and... global? I've never seen “R” for “private” anywhere else.</li>\n<li><code>someKey</code>: I'd assume it returns true if some objects in an array have a specified key. Doesn't seem to be the case. Is this actually a <code>forEach</code>?</li>\n<li><code>packet_hold</code>: is it a packet that needs to be held for some time? What is a packet? Why does calling <code>makePipe</code> set this variable?</li>\n<li><code>getDomElements</code>: this sounds very broad (I thought it's something like <code>querySelector</code>) but in fact it does something very specific. It <em>looks</em> like it somehow binds “classes” defined through pseudo-OOP framework to DOM elements. So these classes are akin to MVC views? Shouldn't this code belong to a base view class?</li>\n<li><code>getLibElements</code>: Totally no idea what this does. The name is very vague. Even stranger, despite being called <code>get</code>, it doesn't return anything.</li>\n<li><code>initByProperty</code>: Runs a method on each module? Is this something like <a href=\"http://underscorejs.org/#invoke\" rel=\"noreferrer\"><code>invoke</code></a>?</li>\n<li><code>pipe_string_receive</code>: Is this a boolean? A string?</li>\n<li><code>makePipe</code>: When I first saw the “pipes” thing, I thought you're referring to Unix-like or NodeJS-like pipes. Pipe is a quite specific concept in programming, so I'm curious why you're using the same word while apparently meaning something entirely different.</li>\n</ul>\n<p>To sum it up, in my opinion this code is a bit over-engineered and suffers from <a href=\"http://c2.com/cgi/wiki?PrematureAbstraction\" rel=\"noreferrer\">premature abstraction</a>. I don't think this abstraction will scale well as the website gets more complex.</p>\n<p>For inspiration, I advise you to check out <strong><a href=\"http://backbonejs.org\" rel=\"noreferrer\">Backbone</a></strong> for nice ideas about <strong>models, views, and how they interact with each other</strong> while being separate.</p>\n<p>Don't miss <strong><a href=\"http://backbonejs.org/#Model-extend\" rel=\"noreferrer\">Backbone.Model.extend</a></strong> and how it <strong>properly sets up prototype chain</strong>, so <code>instanceof</code> works, etc.</p>\n<p><strong>Stateful views</strong> are a really good idea—check out <strong><a href=\"http://facebook.github.io/react/\" rel=\"noreferrer\">Facebook React</a></strong> if you're interesting in taking this idea further.</p>\n<p>What you're trying to achieve with a custom framework is usually done with a combination of Backbone and jQuery, AngularJS and jQuery, React, or other frameworks. I'd argue the abstractions they provide are more generic and modular, and you might want to take a look at them and maybe adapt some ideas for your code.</p>\n<p>Cheers!</p>\n<blockquote>\n<p>An older version of this answer <a href=\"https://codereview.meta.stackexchange.com/q/1385/2634\">was overly harsh</a>.</p>\n<p>While I stay by my opinion that I wouldn't use this code in production, I tried to give more perspective for why it is so instead of <a href=\"https://codereview.meta.stackexchange.com/a/1388/2634\">just being mean</a>.</p>\n<p>I'm grateful to CR community for pointing out <a href=\"https://codereview.meta.stackexchange.com/questions/1385/question-removed-after-a-harsh-review#comment4150_1388\">I was wrong</a>.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T19:12:42.063",
"Id": "38714",
"ParentId": "38460",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "38714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:33:31.000",
"Id": "38460",
"Score": "8",
"Tags": [
"javascript",
"ajax"
],
"Title": "A package for classes and Ajax"
}
|
38460
|
<p>I have never really had to use Json.net until now, so I'm very rusty at it. For that reason, I would appreciate it if someone could have a look over my code and let me know if the way I have done it is correct. It works as I want it; I just need a more professional eye.</p>
<p>For the class <code>TravelAdvice</code>, I've used <a href="http://json2csharp.com/" rel="nofollow">http://json2csharp.com/</a>.</p>
<pre><code> public class TravelAdvice
{
public string Id { get; set; }
public string WebUrl { get; set; }
public string Title { get; set; }
public string Format { get; set; }
public string UpdatedAt { get; set; }
public List<Tag> Tags { get; set; }
public List<Related> Related { get; set; }
public Details3 Details { get; set; }
public List<object> RelatedExternalLinks { get; set; }
public ResponseInfo ResponseInfo { get; set; }
}
public class FcoTravelAdvice : IFcoTravelAdvice
{
public IEnumerable<TravelAdvice> GetFcoTravelAdvice(string country)
{
var url = "https://www.gov.uk/api/foreign-travel-advice/british-virgin-islands.json";
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
// JObject obj = JObject.Parse(content);
// JArray arr = (JArray)obj["fields"];
var fCoData = JsonConvert.DeserializeObject<TravelAdvice>(content);
return new[] {fCoData};
//return test.Details.summary;
//return fCoData.ToString();
//DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(RootObject));
//using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
//{
//var data = (RootObject)s.ReadObject(ms);
//}
// return content;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:11:00.560",
"Id": "64171",
"Score": "0",
"body": "There's not much code to look at here. What concerns you? I'd certainly remove the dead code (in comments), but I don't think that's what you mean by reviewing it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:42:22.893",
"Id": "64193",
"Score": "0",
"body": "Hi Dan Abramov thanks for the reply, that's what I'm wondering about, all examples I have seen used lots of code, inside the FcoTravelAdvice class I have used about 5 lines, so I was wondering if I have done it correctly."
}
] |
[
{
"body": "<blockquote>\n<p>all examples I have seen used lots of code, inside the FcoTravelAdvice class I have used about 5 lines, so I was wondering if I have done it correctly.</p>\n</blockquote>\n<p>If it works, you definitely have!</p>\n<p>Still, I have a couple suggestions.</p>\n<h3>Don't make synchronous requests</h3>\n<p>It's 2014, and we don't write synchronous applications anymore. If your method if called from GUI app, the app will freeze until the request has completed. Imagine if user has a network problem—the app will just be unresponsive, and you don't seem to have provided any means to cancel the request.</p>\n<p>Instead, you should use <a href=\"http://msdn.microsoft.com/en-us/library/hh138332(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>DownloadStringTaskAsync</code></a> to provide asynchronous method:</p>\n<pre><code>public class FcoTravelAdvice : IFcoTravelAdvice\n{\n public async Task<TravelAdvice> GetFcoTravelAdvice(string country)\n {\n var url = "https://www.gov.uk/api/foreign-travel-advice/british-virgin-islands.json";\n var client = new WebClient();\n var content = await client.DownloadStringTaskAsync(url);\n\n return JsonConvert.DeserializeObject<TravelAdvice>(content);\n }\n}\n</code></pre>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/hh191443.aspx\" rel=\"nofollow noreferrer\">Read about <code>async</code></a> if you haven't used it yet. It's life-changing.</p>\n<h3>Minor considerations</h3>\n<ul>\n<li>Why <code>fCoData</code> and not <code>fcoData</code>? The capitalization looks weird. Moreover, "<code>whateverData</code>" is often a bad kind of name. Why not call it <code>advice</code>? After all, that's what you're deserialising.</li>\n<li>I would dump <code>FCO</code> prefix from code altogether (<code>TravelAdvice</code>, <code>GetTravelAdvice</code>, <code>advice</code>). It doesn't make code more meaningful. Do you really plan to support travel advice <em>not</em> from FCO?</li>\n<li>Finally, why is your API always return single item, but the interface returns <code>IEnumerable</code>? It's a mystery to me.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:58:37.627",
"Id": "64254",
"Score": "0",
"body": "Hi Dan thanks for the reply, \"Finally, why is your API always return single item, but the interface returns IEnumerable? It's a mystery to me.\" I'm stuck on that bit, could not get code to work unless I did it the way I did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:04:14.170",
"Id": "64255",
"Score": "0",
"body": "@George: Just return `JsonConvert.DeserializeObject<TravelAdvice>(content)` and change return type to `TravelAdvice`, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:24:24.813",
"Id": "64262",
"Score": "0",
"body": "Hi Dan, that's what I have done, thanks for the help :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:07:30.730",
"Id": "38535",
"ParentId": "38464",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38535",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:56:39.123",
"Id": "38464",
"Score": "3",
"Tags": [
"c#",
"beginner",
"json.net"
],
"Title": "TravelAdvice class"
}
|
38464
|
<p>I have designed a PySide interface for the 3D rendering software package Maya whose purpose is to take a file with animation on a single stream and break it up and export each range of animation. I'm pretty new to PySide and would like just a general overview (or harsh critique) of what I could do to improve the quality of this code. It's not entirely finished so some features of the UI don't actually hook up to anything yet such as the tpose box.</p>
<pre><code>from PySide import QtGui, QtCore
from maya import OpenMayaUI as omui
from shiboken import wrapInstance
import pymel.core as pm
import os
def mayaMainWindow():
mainWinPtr = omui.MQtUtil.mainWindow()
return wrapInstance(long(mainWinPtr), QtGui.QWidget)
class ExportBar(QtGui.QFrame):
def __init__(self, parent=None):
super(ExportBar, self).__init__(parent)
self.parent = parent
print parent.width(), parent.height()
self.resize(parent.width() - 30, 75)
self.widgets = [
QtGui.QLineEdit(),
QtGui.QSpinBox(),
QtGui.QLabel("-"),
QtGui.QSpinBox(),
QtGui.QPushButton(" Export "),
QtGui.QPushButton("Del")
]
self.widgets[1].setMaximum(pm.playbackOptions(max=1, q=1))
self.widgets[3].setMaximum(pm.playbackOptions(max=1, q=1))
self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)
self.setLineWidth(2)
self.initUI()
def initUI(self):
mainLO = QtGui.QHBoxLayout()
self.setLayout(mainLO)
self.widgets[0].setPlaceholderText("File Name")
self.widgets[-2].clicked.connect(lambda: exportAnimation(self))
self.widgets[-1].clicked.connect(self.deleteWidget)
for w in self.widgets:
mainLO.addWidget(w)
def deleteWidget(self):
self.parent.exportBars.remove(self)
self.close()
self.parent.holder.resize(self.parent.holder.width(), self.parent.holder.height() - self.height())
if self.parent.exportBars == []:
self.parent.cycleRow.newExportBar()
class FileBrowser(QtGui.QWidget):
def __init__(self, parent=None):
super(FileBrowser, self).__init__(parent)
self.parent = parent
self.resize(parent.width(), 20)
mainLO = QtGui.QHBoxLayout()
self.setLayout(mainLO)
mainLO.setSpacing(10)
self.pathBar = QtGui.QLineEdit(parent.workScenePath)
self.pathBar.textChanged.connect(self.changeWorkPath)
fileButton = QtGui.QPushButton("Browse Files")
fileButton.clicked.connect(self.changePath)
mainLO.addWidget(self.pathBar)
mainLO.addWidget(fileButton)
def changePath(self):
newPath = pm.fileDialog2(fileMode=3, okc="Select")
try:
self.pathBar.setText(newPath[0])
except Exception:
pass
def changeWorkPath(self):
self.parent.workScenePath = self.pathBar.text()
class CycleRow(QtGui.QWidget):
def __init__(self, parent=None):
super(CycleRow, self).__init__(parent)
self.resize(parent.width(), 20)
self.parent = parent
mainLO = QtGui.QHBoxLayout()
mainLO.setContentsMargins(0, 0, 0, 0)
mainLO.setSpacing(25)
mainLO.addSpacing(2)
self.setLayout(mainLO)
self.newExpBarButton = QtGui.QPushButton(" New Cycle List ")
self.newExpBarButton.clicked.connect(self.newExportBar)
self.tPoseFrameBox = QtGui.QSpinBox()
self.tPoseFrameBox.setContentsMargins(0, 0, 70, 0)
self.tPoseFrameBox.valueChanged.connect(self.changeTPoseFrame)
expAllButton = QtGui.QPushButton(" Export All ")
expAllButton.setContentsMargins(0, 0, 0, 0)
expAllButton.clicked.connect(lambda: exportAllAnimations(parent))
label = QtGui.QLabel("T Pose Frame")
label.setContentsMargins(0, 0, 0, 0)
mainLO.addWidget(label)
mainLO.addWidget(self.tPoseFrameBox)
mainLO.addWidget(self.newExpBarButton)
mainLO.addWidget(expAllButton)
def newExportBar(self):
exportBar = ExportBar(self.parent)
self.parent.holderLO.addWidget(exportBar)
self.parent.exportBars.append(exportBar)
self.parent.holder.resize(self.parent.holder.width(), self.parent.holder.height() + exportBar.height())
def changeTPoseFrame(self):
self.parent.tPoseFrame = self.tPoseFrameBox.text()
class AnimationCycleSplitter(QtGui.QWidget):
def __init__(self, parent=mayaMainWindow()):
super(AnimationCycleSplitter, self).__init__(parent)
self.workScenePath = os.path.join(pm.workspace.path, "scenes\\")
self.setWindowFlags(QtCore.Qt.Window)
self.setGeometry(300, 300, 600, 350)
self.setWindowTitle("Animation Cycle Splitter")
self.exportBars = []
self.initUI()
def initUI(self):
mainLO = QtGui.QVBoxLayout()
mainLO.setSpacing(10)
self.setLayout(mainLO)
browser = FileBrowser(self)
self.holder = QtGui.QWidget()
self.holder.resize(self.width() - 30, 0)
self.holderLO = QtGui.QVBoxLayout()
self.holderLO.setContentsMargins(0, 0, 0, 0)
self.holder.setLayout(self.holderLO)
scrollArea = QtGui.QScrollArea()
scrollArea.setWidget(self.holder)
self.cycleRow = CycleRow(self)
self.tPoseFrame = self.cycleRow.tPoseFrameBox.value()
self.cycleRow.newExportBar()
mainLO.addWidget(browser)
mainLO.addWidget(scrollArea)
mainLO.addWidget(self.cycleRow)
self.show()
class Keyframe(object):
def __init__(self, objs):
self._frame = pm.currentTime()
self._values = {attr:attr.get() for obj in objs for attr in obj.listAnimatable()}
self._objs = objs
def paste(self, frame):
pm.currentTime(frame)
for attr in self._values.keys():
try:
attr.set(self._values[attr])
except RuntimeError:
pass
pm.setKeyframe(self._objs)
def exportAllAnimations(gui, fileType=".ma"):
for ebar in gui.exportBars:
exportAnimation(ebar, fileType=fileType)
def getKeysForFramerange(beg, end, joints):
keys = []
for num, frame in enumerate(range(beg, end)):
pm.currentTime(frame)
keys.append(Keyframe(joints))
return keys
def pasteKeysForFramerange(keys):
for frame, key in enumerate(keys):
key.paste(frame)
def exportAnimation(gui, fileType=".ma"):
pm.currentTime(gui.tPoseFrame)
joints = pm.ls(type="joint")
tPose = [Keyframe(joint) for joint in joints]
pm.select(joints)
fullPathToFile = os.path.join(gui.parent.workScenePath, gui.widgets[0].text() + fileType)
beg, end = gui.widgets[1].value(), gui.widgets[3].value()
keys = getKeysForFramerange(beg, end, joints)
pm.copyKey()
pm.cutKey()
pasteKeysForFramerange(keys)
pm.currentTime(0)
pm.exportAll(fullPathToFile, force=1)
pm.pasteKey()
</code></pre>
<p><img src="https://i.stack.imgur.com/jAGNE.png" alt="This is what it creates after I hit the new cycle list button a few times."></p>
|
[] |
[
{
"body": "<p>My PySide is a bit rusty but I can't see anything immediately wrong with your structure. I have noticed a few places you could modify to make the code more readable/easier to manage though.</p>\n\n<ol>\n<li><p>You've manually padded some strings to center them in widgets, don't push buttons center text automatically? If not you should be able to do something like </p>\n\n<pre><code>button.setStyleSheet(\"Text-align:center\")\n</code></pre>\n\n<p>If that doesn't work, python strings can be padded using <code>format()</code>. To pad \"New Cycle List\" with spaces to 42 characters use: </p>\n\n<pre><code>'{: ^42}'.format('New Cycle List')\n</code></pre>\n\n<p><a href=\"http://docs.python.org/2/library/string.html#formatstrings\" rel=\"nofollow noreferrer\">See here in the documentation.</a></p></li>\n<li><p>In <code>ExportBar.__init__</code>, perhaps group your widgets in a dictionary rather than a list. At the moment, you have to refer back to <code>__init__</code> to see which widget the following code refers to:</p>\n\n<pre><code>self.widgets[-1].clicked.connect(self.deleteWidget)\n</code></pre>\n\n<p>Whereas if <code>self.widgets</code> was a dictionary, it would be clearer:</p>\n\n<pre><code>self.widgets['deleteButton'].clicked.connect(self.deleteWidget)\n</code></pre>\n\n<p>Of course one drawback is you'll need to iterate through the widgets with </p>\n\n<pre><code>for widget in self.widgets.values():\n</code></pre></li>\n<li><p>Are you using an IDE which supports tab completion? If you are, make life easier for yourself by initialising widgets to stored variables before grouping them: </p>\n\n<pre><code>self.deleteButton = QtGui.QPushButton(\"Del\")\nself.exportButton = QtGui.QPushButton({: ^30}.format(\"Export\"))\n...\nself.widgets = {\n 'deleteButton': self.deleteButton,\n 'exportButton': self.exportButton,\n ...\n}\n</code></pre>\n\n<p>In IDEs I've used, tab completion usually fails when accessing an element in a structure. (ie. <code>['one', 'two'][0].upp</code> + TAB usually doesn't find <code>upper()</code>). Having direct access to widgets in addition to grouping for iteration is handy in this regard.</p></li>\n<li><p>It's generally bad form to initialise/call a potentially mutable object in definitions as you have done in the following:</p>\n\n<pre><code>class AnimationCycleSplitter(QtGui.QWidget):\n def __init__(self, parent=mayaMainWindow()):\n</code></pre>\n\n<p>Instead do:</p>\n\n<pre><code>def __init__(self, parent=None):\n if parent is None:\n parent = mayaMainWindow()\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument\">See here if you're unsure why.</a></p></li>\n<li><p>Don't be afraid to group everything! Continuing from points 2. and 3., it doesn't hurt to group widgets several times. If you get to the stage when you have a dozen buttons, a few more lineEdits etc, make groups for each of these widget types.</p>\n\n<pre><code>self.widgets = {'deleteButton': self.deleteButton ...}\nself.buttons = {'delete': self.deleteButton, 'save': self.saveButton ...}\nself.lineEdits = {'password': self.passwordLineEdit ...}\n</code></pre></li>\n</ol>\n\n<p><strong>Summary</strong></p>\n\n<p>In my experience, when using PySide it helps to write everything as verbosely and clearly as possible. Use dictionaries with meaningful keys to group widgets and make sure your code allows tab completion to work!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T12:10:45.073",
"Id": "38492",
"ParentId": "38467",
"Score": "2"
}
},
{
"body": "<p>I don't know much about Maya (I've only programmed 3ds Max) so this is a \"generic\" review.</p>\n\n<ol>\n<li><p>There are no docstrings. What do all these classes and methods do? How are they supposed to be used? Imagine someone having to maintain this code when you're no longer working on it. What questions would they want to ask you?</p></li>\n<li><p>Be careful with <code>import X as Y</code>: unless <code>Y</code> is a very well known abbreviation for <code>X</code> (such as <code>np</code> for <code>numpy</code>) then this makes your code harder for people to read and understand. In this case:</p>\n\n<pre><code>from maya import OpenMayaUI as omui\n</code></pre>\n\n<p>you only use <code>omui</code> once, so I think that you don't really gain anything by this abbreviation.</p></li>\n<li><p>Where do the numbers (30, 75, 20, etc.) come from? If these are related to things like the heights of the default fonts, it would be better to calculate these by calling <code>QFontInfo.pixelSize()</code> or whatever. This would make it clear what the numbers mean.</p></li>\n<li><p>It seems to me that there ought to a better way to get a wider button than by padding the label with spaces.</p></li>\n<li><p>There seems to be some confusion about the choice of directory separator. The screenshot shows that <code>pm.workspace.path</code> uses forward slashes but you've used <code>os.path.join</code> which uses native (backwards) slashes.</p></li>\n<li><p>You maintain an <code>exportBars</code> list containing the <code>ExportBar</code> instances in <code>holderLO</code>. So every time you change the latter you have to keep the former in sync. Why not use <code>holderLO.children()</code> and avoid the need to maintain two copies of this data?</p></li>\n<li><p>You copy a key and then cut it:</p>\n\n<pre><code>pm.copyKey()\npm.cutKey()\n</code></pre>\n\n<p>but <a href=\"http://download.autodesk.com/global/docs/maya2013/en_us/CommandsPython/cutKey.html\" rel=\"nofollow\">if I understand the documentation rightly</a>, <code>cutKey</code> also copies to the clipboard, so is the <code>copyKey</code> call really necessary?</p></li>\n<li><p>Why do you put some initialization code in <code>__init__</code> and some in <code>initUI</code>? There doesn't seem to be a principled separation here.</p></li>\n<li><p>The <code>exportAnimation</code> function needs to know all about the internals of the <code>ExportBar</code> class, so surely it ought to be a method on that class. You could then write:</p>\n\n<pre><code>self.widgets[-2].clicked.connect(self.exportAnimation)\n</code></pre></li>\n<li><p>Writing <code>self.widgets[X]</code> is quite unclear (which button is number 3, again?). It would be clearer to write the initialization code like this:</p>\n\n<pre><code>export_button = QtGui.QPushButton(\" Export \")\nexport_button.clicked.connect(self.exportAnimation)\ndelete_button = QtGui.QPushButton(\"Del\")\ndelete_button.clicked.connect(self.deleteWidget)\n\nself.widgets = [..., export_button, delete_button]\n</code></pre></li>\n<li><p>The <code>exportAllAnimations</code> function needs to know about the implementation of the <code>AnimationCycleSplitter</code> class, so surely it ought to be a method on that class.</p></li>\n<li><p>The <code>FileBrowser</code> class manages a path that is stored in <code>parent.workScenePath</code>. This seems wrong to me: what if you wanted to attach multiple <code>FileBrowser</code> objects to the same parent? It would be better for the <code>FileBrowser</code> class to store the path in one of its own attributes, and then the <code>AnimationCycleSplitter</code> class can provide a method that fetches the path from the <code>FileBrowser</code> instance.</p></li>\n<li><p>It seems pointless to have keyword arguments like <code>fileType=\".ma\"</code> on functions like <code>exportAnimation</code> which are attached to buttons in the GUI. There is no way for the user to pass values for these keyword arguments, so what is their purpose? A global variable would be clearer. (Also, <code>fileType</code> ought to be named <code>fileExtension</code> or something similar.)</p></li>\n<li><p>There are a few places where I would appreciate a comment. (i) what is the purpose of the <code>cutKey</code> and <code>pasteKey</code> operations? Is this to preserve the current selection? But won't it clobber the clipboard? (ii) Why might you get a <code>RuntimeError</code> in <code>Keyframe.paste</code>?</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:50:15.740",
"Id": "64220",
"Score": "0",
"body": "@ejrb Thank you both for the reviews they have been very beneficial, sadly I can only accept one however I learned a lot from both of you. I will make the changes you all suggested and post that for another review later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T12:16:49.910",
"Id": "38493",
"ParentId": "38467",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38493",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T01:24:22.930",
"Id": "38467",
"Score": "4",
"Tags": [
"python",
"maya",
"pyside"
],
"Title": "PySide interface for Autodesk Maya"
}
|
38467
|
<p>In the Java world while writing the data access layer (for CRUD) and the model layer, I have done something like this:</p>
<pre><code>public abstract class AbstractDao<N extends AbstractModel>{
protected Class<N> persistentClass;
public N findById(String id){
return (N)mongoOperation.findById(id, persistentClass,persistentClass.getSimpleName());
}
}
class FlightDao extends AbstractDao<Flight>
class AirlineDaoImpl extends AbstractMongoDao<Airline>
</code></pre>
<p>Where <code>Flight extends AbstractModel</code> and ,<code>Airline extended AbstractModel</code></p>
<p>Now calling the findById was as trivial as </p>
<pre><code>Flight flight = flightDao.findById("FlightId1");
</code></pre>
<p>I feel this was a decent way of doing things because it kept my code DRY. And most of the model objects needed the same CRUD methods. </p>
<p>Now coming to Scala, Play framework 2, anorm, I would like to know what is the right way of doing something such as this.</p>
<p>I read that model classes should be case classes but then that prevents us from inheritance. And moreover the data access definitions were given in the companion objects. This is what I have at the moment.</p>
<pre><code>case class Airline(id:Pk[Long]=NotAssigned,name:String)
case class Flight(id:Pk[Long]=NotAssigned,code:String,airlineId:Long,date:DateTime)
object Flight{
def getById(id:Long):Option[Flight] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from flight
where flight.id = {id}
"""
).on(
'id -> id
).as(Flight.simple.singleOpt)
}
}
}
object Airline{
def getById(id:Long):Option[Airline] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from airline
where airline.id = {id}
"""
).on(
'id -> id
).as(Airline.simple.singleOpt)
}
}
}
</code></pre>
<p>I'm <strong>certain</strong> there must be a better way to do this. I would love to know how I could write neat / clean Scala code for this. Any pointers, design patterns and feedback is much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:54:53.970",
"Id": "64356",
"Score": "1",
"body": "Nothing prevent your case classes from using inheritance at all. What you can't do is extend case classes. Example https://gist.github.com/fedesilva/d9e636695484d8eaddea"
}
] |
[
{
"body": "<p>I believe that in addition to the stated Java -> Scala OO question, that you may also be wondering about a good way to \"organize\" Models/DAOs/Controllers in Play 2. So I will incorporate that in my answer.</p>\n\n<p>I would have asked in a comment, but I don't seem to have the rep yet...</p>\n\n<p>A few notes before we get into an answer:</p>\n\n<ul>\n<li>fedesilvia is correct, that case classes can extend traits and/or classes.</li>\n<li>Model classes generally should be case classes. They're a nice, easy-to-use construct that provides your \"equals\" method, \"toString\" method, and \"hashcode\" method. Also, many libraries have provided great mechanisms for working with case classes for a variety of purposes. Not to mention matching, immutable by default, etc...</li>\n</ul>\n\n<p>Let's take a look at how to organize this from top to bottom.</p>\n\n<h2>Controllers</h2>\n\n<p>As you know, Play's Router sends requests in from the HTTP client to your Controller. It is my opinion that the Controllers then have 3 <em>core</em> responsibilities:</p>\n\n<ol>\n<li>Deserialize the request.</li>\n<li>Serialize the response.</li>\n<li>Handle any errors appropriately.</li>\n</ol>\n\n<p>Missing between responsibilities 1 and 2, is the actual \"handling\" of the request. For a CRUD app, this could be where your DAOs come in.</p>\n\n<h2>DAOs</h2>\n\n<p>In my application, DAOs are <em>Objects</em> that extend a <strong>MongoDAO</strong> trait. The trait \"knows\" how to interact the the database drivers (get a connection), and supplies basic utilities. For instance:</p>\n\n<pre><code>/** Basic DAO Behavior for MongoDB documents. */\ntrait MongoDao {\n /** Name of the MongoDB Collection. */\n protected def colName: String\n\n /** Returns the default database. */\n protected def db = ReactiveMongoPlugin.db\n\n /** The actual collection used by the DAO. */\n protected def col: JSONCollection =\n db.collection[JSONCollection](colName)\n\n /** Returns the first result, if any, for the given query. */\n def findOne[DOC](q: JsObject)(implicit reads: Reads[DOC]) =\n col.find(q).cursor[DOC].headOption\n\n ...\n</code></pre>\n\n<p>I also have an <em>abstract class</em> that extends <strong>MongoDAO</strong> called, \"AssetDAO\". <strong>AssetDao</strong> provides 90% to 100% of the DAO implementation for 13 of the Models in my App. Here is it's type:</p>\n\n<pre><code>/** Common DAO behavior for all Assets. */\nabstract class AssetDao[A <: AssetModel]\n (override val colName: String)(implicit format: Format[A])\nextends MongoDao with ModulePermissions {\n</code></pre>\n\n<p>The DAO implementations can look like this:</p>\n\n<pre><code>object ArchetypeDao extends AssetDao[Archetype](\"archetypes\")\n</code></pre>\n\n<p>But most of them also have a couple methods that are all their own. Usually when I need to make use of Model specific properties in a query.</p>\n\n<h2>Model Companion Objects</h2>\n\n<p>Given the libraries that I'm using (notably <em>play.api.lib.json</em>), I find it best to put (de-)serialization code in the Companion Objects. For instance:</p>\n\n<pre><code>object Archetype {\n /** Converts Archetype to/from its MongoDB representation */\n implicit val fmt = Json.format[Archetype]\n\n /** Reads that are used for both Create and Update. */\n val coreReads = (\n (__ \\ \"name\" ).json.pickBranch(smlReqStr) and\n (__ \\ \"summary\").json.pickBranch(medReqStr) and\n\n ((__ \\ \"description\").json.pickBranch(fullText) or emptyObj)\n ) reduce\n}\n</code></pre>\n\n<p>As you can see, the <em>Companion Object</em> contains all of the information it needs to (de-)serialize the <em>case class</em> to/from its MongoDB representation; and to/from its \"client\" representation. So the <em>DAO</em> ends up using the <strong>Json.format</strong> and the <em>Controller</em> uses the JSON Transformers.</p>\n\n<h2>Models</h2>\n\n<p>In this setup, all <em>Models</em> are simple <em>case classes</em> that represent <em>persisted</em> data. For instance:</p>\n\n<pre><code>case class Archetype (\n _id: BSONObjectID,\n module_id: BSONObjectID,\n doc_meta: DocMeta,\n name: String,\n summary: String,\n description: Option[String]\n) extends AssetModel\n</code></pre>\n\n<p>And here is the <strong>AssetModel</strong> trait that <strong>Archetype</strong> implements:</p>\n\n<pre><code>/** Describes some common behavior of asset types */\ntrait AssetModel {\n def _id: BSONObjectID\n def module_id: BSONObjectID\n def doc_meta: DocMeta\n}\n</code></pre>\n\n<p>You may have noticed earlier that <strong>Archetype.coreReads</strong> doesn't reference all the fields the model has. That's because the \"AssetControllers\" are taking care of the rest of the fields for every <strong>AssetModel</strong>. Implementing <strong>AssetModel</strong> here is what makes that work.</p>\n\n<p>To do it again, I might have the <strong>AssetModel</strong> <em>Companion Objects</em> extend a trait that provides the common field (de)serialization.</p>\n\n<h1>Conclusion</h1>\n\n<p>Hopefully, this answer has provided you with:</p>\n\n<ol>\n<li>A better understanding of using OO in Scala.</li>\n<li>Some ideas for organizing your Play App to write DRY code.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:23:06.837",
"Id": "68228",
"Score": "3",
"body": "Now THAT's an answer! Awesome, keep it up! Don't feel pressured to post very long answers that cover everything though, posting a partial review is perfectly fine ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-12T04:14:57.017",
"Id": "275905",
"Score": "0",
"body": "Github or Gist with examples?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T04:55:45.850",
"Id": "39716",
"ParentId": "38471",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "39716",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T02:27:46.027",
"Id": "38471",
"Score": "7",
"Tags": [
"scala",
"inheritance"
],
"Title": "Case class design in Scala"
}
|
38471
|
<h2>Introduction</h2>
<p>I am designing a website as a hobby. As you can probably tell from the code below, I am an absolute beginner. The first thing I'd like to do is to create a nice webpage template that I can use for every page. This is what I have so far (I've added <code>background-color</code>s to the <code>div</code>s just for visability):</p>
<h2>HTML</h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Fiddling Bits</title>
<meta charset="utf-8">
<meta name="description" content="All Things C and Embedded C">
<meta name="author" content="Paul Dunn">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="layout">
<div class="layout header">
</div>
<div class="layout main_nav">
</div>
<div class="layout sub_nav">
</div>
<div class="layout content">
</div>
<div class="layout footer">
</div>
</div>
</body>
</html>
</code></pre>
<h2>CSS</h2>
<pre><code>.layout
{
position: relative;
width: 1000px;
margin: 0 auto;
}
.layout .header
{
float: left;
display: inline;
height: 100px;
background-color: red;
}
.layout .main_nav
{
float: left;
display: inline;
height: 50px;
background-color: orange;
}
.layout .sub_nav
{
float: left;
display: inline;
height: 300px;
width: 20%;
background-color: yellow;
}
.layout .content
{
float: left;
display: inline;
float: right;
height: 300px;
width: 80%;
background-color: blue;
}
.layout .footer
{
float: left;
display: inline;
height: 50px;
background-color: green;
}
</code></pre>
<h2>Output</h2>
<p><img src="https://i.stack.imgur.com/WjSAb.png" alt="Webpage"></p>
<h2>Sections</h2>
<ol>
<li>Header (Red)</li>
<li>Main Navigation (Orange)</li>
<li>Sub-Navigation (Yellow)</li>
<li>Content (Blue)</li>
<li>Footer (Green)</li>
</ol>
<h2>Conclusion</h2>
<p>Any advice that you can render on how I can improve, no matter how minor, would be greatly appreciated.</p>
|
[] |
[
{
"body": "<p><a href=\"http://jsbin.com/OnATOsOj/1/edit\" rel=\"nofollow noreferrer\">Here's a quick demo of what I did</a></p>\n<h1>Heights</h1>\n<p>First off, I'd avoid height. Let the content define the container's height. Otherwise, you'll run into problems, like when the content is taller than the container. You can set a <code>min-height</code> for times when the content is small (like 1-line of text).</p>\n<h1>Target styles</h1>\n<p>I notice that <code>.layout</code> is targetted to both the container and the sections. Unless you're setting common styles, I'd avoid doing so. I see that you are setting <code>1000px</code> width on <code>.layout</code>, which you assign to elements that don't need <code>1000px</code>.</p>\n<h2><code><div></code> is a block element</h2>\n<p>Just so you know, a <code><div></code> is a block element. It takes up 100% width automatically and forces itself below the previous element, and forces the one after it below it.</p>\n<p>So as long as your container is <code>1000px</code>, any <code><div></code> in it automatically is <code>1000px</code>.</p>\n<h1>Sidebars</h1>\n<p>We all came across the problem of fitting the sidebar to the side, another just across the page, and have a central content that fills the remaining center.</p>\n<h2>Floats</h2>\n<p>Commonly done in floats, but the issue every developer I come across is that they set the <code>width</code> for just about everything. You know, <a href=\"http://jsfiddle.net/gPrJ3/\" rel=\"nofollow noreferrer\">there's a way to set the sidebar width to a fixed size, and have the content fill up the rest of the space without setting a width for it</a>:</p>\n<p>HTML:</p>\n<pre><code><div class="container">\n <div class="sidebar">Sidebar</div>\n <div class="content">Content</div>\n</div>\n</code></pre>\n<p>CSS:</p>\n<pre><code>.container{\n overflow:hidden;\n}\n\n.sidebar{\n background: red;\n float:left;\n width: 100px;\n height: 200px;\n}\n\n.content{\n background: blue;\n height: 200px;\n overflow:hidden;\n}\n</code></pre>\n<h2>CSS Tables</h2>\n<p>No, I'm not talking about HTML tables. I'm talking about the display properties that allow elements to display similar to tables. It has the same HTML structure as your tables, but aren't tables. <a href=\"http://jsfiddle.net/gPrJ3/1/\" rel=\"nofollow noreferrer\">I like this approach better</a>, and Bootstrap seems to use it too.</p>\n<p>HTML:</p>\n<pre><code><div class="table">\n <div>\n <div class="sidebar">Sidebar</div>\n <div class="content">Content</div>\n </div>\n</div>\n</code></pre>\n<p>CSS:</p>\n<pre><code>.table{\n display:table;\n width: 100%;\n height: 200px;\n}\n\n.table > *{\n display:table-row;\n}\n\n.table > * > *{\n display:table-cell;\n}\n\n.sidebar{\n background: red;\n width: 100px;\n}\n\n.content{\n background: blue;\n}\n</code></pre>\n<h2>Design Trends</h2>\n<p>Just so you know, most of the websites today (save the traditional and unmaintained) <a href=\"http://thenextweb.com/dd/2013/12/29/10-web-design-trends-can-expect-see-2014/10/\" rel=\"nofollow noreferrer\">are dropping sidebars</a> because people today design for mobile too. You don't want an annoying sidebar all the time, it just takes up space.</p>\n<h1>HTML5 Tags</h1>\n<p>It would be better if you start adopting the new HTML5 tags. <code><header></code>, <code><nav></code>, <code><section></code> and <code><footer></code> would be good for starters.</p>\n<h1>Floats force <code>display:block</code></h1>\n<p>Yes, if you set <code>float</code> for an element, it will force the element to be a block element. There's no use assigning a <code>display</code> property anymore after you do that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T07:30:45.860",
"Id": "38483",
"ParentId": "38472",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38483",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T02:56:01.540",
"Id": "38472",
"Score": "4",
"Tags": [
"html",
"css",
"html5",
"layout"
],
"Title": "Webpage Template"
}
|
38472
|
<p>I'm working on a simple game in which I need to track the cardinal direction of an object. I experimented with using the enum's ordinal value, as well as using switches for the rotation, but both seemed wrong. This is what I ended up with. Is the following an adequate solution?</p>
<pre><code>// Defines cardinal direction
public enum Direction {
NORTH(0) {
@Override
public String getMessage() {
return getDegrees() + " degrees due north";
}
},
EAST(90) {
@Override
public String getMessage() {
return getDegrees() + " degrees due east";
}
},
SOUTH(180) {
@Override
public String getMessage() {
return getDegrees() + " degrees due south";
}
},
WEST(270) {
@Override
public String getMessage() {
return getDegrees() + " degrees due west";
}
};
private final int degrees;
public abstract String getMessage();
private Direction(final int degrees) {
this.degrees = degrees;
}
public int getDegrees() {
return degrees;
}
private static final Map<Integer, Direction> lookup = new HashMap<Integer, Direction>();
static {
for (Direction d : EnumSet.allOf(Direction.class))
lookup.put(d.getDegrees(), d);
}
public static Direction get(int degrees) {
return lookup.get(degrees);
}
public Direction rotateRight() {
return Direction.get((degrees + 90) % 360);
}
public Direction rotateLeft() {
return Direction.get((degrees + 270) % 360);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Conceptually it is a great solution. I can suggest some changes, but in reality they are minor. It would also be 'fun' to tune it abit, but in the bigger picture the changes would be miniscule... still...</p>\n\n<p>My biggest observation is that the constructors can be simplified a lot. Instead of having each Enum member create a unique method implementation (and that method builds a String each time - though the compiler will probably fix that), you could simplify it a lot with:</p>\n\n<pre><code>private final int degrees;\nprivate final String message;\n\nprivate Direction(final int degrees, final String name) {\n this.degrees = degrees;\n this.message = degrees + \" degrees due \" + name;\n}\n\npublic int getDegrees() {\n return degrees;\n}\n\npublic String getMessage() {\n return message;\n}\n</code></pre>\n\n<p>With the change to the constructor, you have:</p>\n\n<ol>\n<li>no abstract methods to implement</li>\n<li>simple message which is a constant, instead of re-creating it each time you call <code>getMessage()</code></li>\n<li><p>Your enums are initialized in a simpler way:</p>\n\n<pre><code>NORTH(0, \"North\"),\nEAST(90, \"East\"),\nSOUTH(180, \"South\"),\nWEST(270, \"West\")\n</code></pre></li>\n</ol>\n\n<p>Apart from this, the code is pretty good, but, there is a way you can 'play' with the lookup system to use the ordinals only.... consider the following code (I'll leave it to you to figure out.... ;-):</p>\n\n<pre><code>public static Direction get(final int degrees) {\n int ordinal = ((degrees % 360) / 90) - ( 4 * (degrees % 90));\n return ordinal < 0 ? null : values()[ordinal];\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:51:35.243",
"Id": "64199",
"Score": "0",
"body": "@weare138 Just noticed a not-so-little bug in the lookups.... it would have returned `North` for any 0 <= degrees < 90"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T06:22:44.390",
"Id": "38482",
"ParentId": "38473",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "38482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T03:45:32.263",
"Id": "38473",
"Score": "6",
"Tags": [
"java",
"enum",
"lookup"
],
"Title": "Critique of Cardinal Direction Enum"
}
|
38473
|
<p>This is a simple <a href="https://en.wikipedia.org/wiki/Brute-force_search" rel="nofollow noreferrer">brute force algorithm</a> that I have programmed in C. All the program does is print out every possible combination of the given <code>alphabet</code> for the given length.</p>
<p>I would prefer suggestions on how to improve the algorithm, or decrease run-time. Any other suggestions are acceptable though.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static const char alphabet[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
static const int alphabetSize = sizeof(alphabet) - 1;
void bruteImpl(char* str, int index, int maxDepth)
{
for (int i = 0; i < alphabetSize; ++i)
{
str[index] = alphabet[i];
if (index == maxDepth - 1) printf("%s\n", str);
else bruteImpl(str, index + 1, maxDepth);
}
}
void bruteSequential(int maxLen)
{
char* buf = malloc(maxLen + 1);
for (int i = 1; i <= maxLen; ++i)
{
memset(buf, 0, maxLen + 1);
bruteImpl(buf, 0, i);
}
free(buf);
}
int main(void)
{
bruteSequential(3);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T04:41:30.980",
"Id": "64111",
"Score": "4",
"body": "Brute force is a category, not an algorithm. It might be useful to specify what this code is supposed to do rather than just saying it's brute force. Might save the next person to read through it a minute or two :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T04:48:19.587",
"Id": "64112",
"Score": "1",
"body": "@Corbin I edited in the purpose of the code. Also [Wikipedia says it is an algorithm](https://en.wikipedia.org/wiki/Brute-force_search#Basic_algorithm) ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:00:09.457",
"Id": "64231",
"Score": "3",
"body": "Another way to think about the problem is as counting in base 62. However, that doesn't necessarily yield better code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T15:19:48.810",
"Id": "86018",
"Score": "0",
"body": "just a small idea, untested. For large maxLen firstly get all possible strings for maxLen/2 and then create all combinations. This will use a lot more memory but might be faster in time. The challenge would be to determine when to use this approach and when to simply brute force as you are doing now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-19T19:10:55.870",
"Id": "379173",
"Score": "2",
"body": "You should change the title of this thread to something more meaningful. `Brute force` is not an algorithm, `Brute force search` is (cf [your reference](https://en.wikipedia.org/wiki/Brute-force_search#Basic_algorithm))"
}
] |
[
{
"body": "<p>I would say that this is pretty much impeccable as a recursive solution.</p>\n\n<p>In <code>bruteSequential()</code>, I would rename <code>i</code> to <code>len</code> for clarity. As a slightly hackish optimization, you could move the <code>memset()</code> call before the for-loop, since you know that the output string lengths will never decrease. You could then combine it with the <code>malloc()</code> for</p>\n\n<pre><code>char* buf = calloc(maxLen + 1, sizeof(char));\n</code></pre>\n\n<p>As a helper function, <code>bruteImpl()</code> should be declared <code>static</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:08:55.487",
"Id": "38490",
"ParentId": "38474",
"Score": "14"
}
},
{
"body": "<p>you don't need the memset in the for of <code>bruteSequential</code> you just need to add a <code>'\\0'</code> to the end when max depth has been reached:</p>\n\n<pre><code>void bruteImpl(char* str, int index, int maxDepth)\n{\n for (int i = 0; i < alphabetSize; ++i)\n {\n str[index] = alphabet[i];\n\n if (index == maxDepth - 1) \n printf(\"%s\\n\", str);\n else bruteImpl(str, index + 1, maxDepth);\n }\n}\n\nvoid bruteSequential(int maxLen)\n{\n char* buf = malloc(maxLen + 1);\n\n for (int i = 1; i <= maxLen; ++i)\n {\n buf[i]='\\0';\n bruteImpl(buf, 0, i);\n }\n\n free(buf);\n}\n</code></pre>\n\n<p><s>frankly you don't even need that as a simple <code>buf[i]='\\0';</code> in the <code>for</code> of <code>bruteSequential</code> will suffice, but that may over simplify it</s></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:26:36.793",
"Id": "64143",
"Score": "0",
"body": "You don't need to put the `str[maxDepth]='\\0';` in the loops either. You can move it out to after the malloc since it only needs to run once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:15:27.267",
"Id": "64151",
"Score": "0",
"body": "@rolfl no because he creates shorter strings as well, so in that case 200_success' answer is correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:25:24.810",
"Id": "64154",
"Score": "2",
"body": "Fair point, but, you can move it outside the recursion at least, and call it just `maxLen` times, instead of gazillions!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:23:36.940",
"Id": "38497",
"ParentId": "38474",
"Score": "7"
}
},
{
"body": "<p>In this program, <code>bruteImpl</code> is a tight loop. I wouldn't bother optimizing anything else, even if it would save some time, because most of time will be wasted running <code>bruteImpl</code> anyway. Running <code>memset</code> one time won't save your time, as it's ran... length times. However, with length set to 5, <code>bruteImpl</code> is called... 15264777 times. This is definitely something worth optimizing.</p>\n\n<p>The biggest limitation in performance is <code>printf</code> in my opinion. Console output is usually somewhat slow. If I remove <code>printf</code>, and instead make small loop counter, I get 2 seconds for length set to 5 (I added global <code>count</code> variable to force the loop to do anything, increased every time you would use <code>puts</code>).</p>\n\n<p>The other problem is recursion that cannot be removed by compiler. However, in this case recursion appears to be needed (iterative algorithm that doesn't use the stack suggested by @200_success is 9 times slower than yours), so it's not worth removing it (you would have to simulate stack structure anyway). Recursion is slower than iteration in many algorithms, but sometimes it's just needed.</p>\n\n<p>Also, the biggest problem is actually using the variables (it's not problem with your algorithm, just something worth mentioning). Practically doing anything involving values from your algorithm is slower. For example, I tried to add <code>memcmp</code> and <code>strcmp</code> in place of <code>puts</code>. <code>memcmp</code> makes your algorithm 6 times slower, and <code>strcmp</code> makes your algorithm 10 times slower. Your algorithm is already fast enough, if <code>memcmp</code> is already rather slow. Sometimes optimizing is just not worth it - compilers already do that really well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:18:02.770",
"Id": "64372",
"Score": "3",
"body": "I like all the points you made, but adding some code examples to *show* what you mean would really make this answer rock. I get what you are saying though, so +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T08:58:00.060",
"Id": "38562",
"ParentId": "38474",
"Score": "15"
}
},
{
"body": "<p>There are some things I've seen that may help you improve your code.</p>\n\n<h2>Prefer iterations to recursion</h2>\n\n<p>Recursive functions are often a good way to approach a programming task, but there is a tradeoff in terms of memory and time. Specifically, one can often reduce or eliminate the computational cost of a function call and reduce or eliminate the memory overhead as well by converting from a recursive to an interative function.</p>\n\n<h2>Use pointers rather than indexing</h2>\n\n<p>Code that uses indexing often has the benefit that it's easy to read and understand:</p>\n\n<pre><code>for (int i = 0; i < alphabetSize; ++i) {\n str[index] = alphabet[i];\n // ...\n</code></pre>\n\n<p>However, code is often faster to use pointers instead. So for example, that code might be rendered like this:</p>\n\n<pre><code>for (const char *a = alphabet; *a; ++a) {\n str[index] = *a;\n // ...\n</code></pre>\n\n<p>It's likely that one could obtain even more time savings by converting the left hand side to use pointers as well.</p>\n\n<h2>Use the lowest level I/O that's practical</h2>\n\n<p>Using library functions like <code>printf</code> is convenient, but they aren't necessarily the most efficient. Something like <code>printf(\"%s\\n\", str);</code> has to go through the memory of <code>str</code> looking for the terminating <code>NUL</code> character which might not be needed if you already know the length. </p>\n\n<h2>Reduce I/O if practical</h2>\n\n<p>The usual bottleneck in programs like this is the input/output part. When you can replace I/O with memory access instead, it <em>may</em> lead to time savings. However, the underlying operating system might buffer I/O already, so the only way to check for sure is to measure it.</p>\n\n<h2>Putting it all together</h2>\n\n<p>Here's what I came up with as an alternative implementation that uses all of these suggestions:</p>\n\n<pre><code>// create a large buffer\nstatic const int BUFFLEN=1024*100;\n\nvoid brute2(int maxLen)\n{\n char* indices = malloc(maxLen + 1);\n char* terminal = indices+maxLen;\n char *printbuff = malloc(BUFFLEN);\n char *pbend = &printbuff[BUFFLEN-1];\n char *b = printbuff;\n *pbend = '\\0';\n ++indices[0];\n char *p;\n\n while (*terminal == 0) {\n // print value\n for (p = indices; *p; ++p)\n ;\n for (--p ; p >= indices; --p) {\n *b++ = alphabet[*p-1];\n if (b == pbend) {\n fwrite(printbuff, 1, b-printbuff, stdout);\n b = printbuff;\n }\n }\n *b++ = '\\n';\n if (b == pbend) {\n fwrite(printbuff, 1, b-printbuff, stdout);\n b = printbuff;\n }\n // increment values\n int carry = 1;\n for (++p ; carry; ++p) {\n if ((*p += carry) > alphabetSize) {\n *p = 1;\n carry = 1;\n } else {\n carry = 0;\n }\n }\n }\n fwrite(printbuff, 1, b-printbuff, stdout);\n\n free(indices);\n free(printbuff);\n}\n</code></pre>\n\n<h2>Results</h2>\n\n<p>I modified your original driver program as follows:</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n if (argc != 3) {\n puts(\"Usage: brute iterations old|new\\n\");\n return 1;\n }\n int iterations = atoi(argv[1]);\n if (argv[2][0] == 'o')\n bruteSequential(iterations);\n else\n brute2(iterations);\n}\n</code></pre>\n\n<p>This allowed me to time various combinations. For example, on my computer, calculating all of the 5-character combinations took 55 seconds with this version and over 65 seconds for the original. Redirecting the output to <code>/dev/null</code> eliminates the overhead of actual disk I/O (5.2 gigabytes in this case) and reveals that the new version takes about 8.9 s on my machine, and the original version takes 18 seconds or about twice as long.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-20T09:18:12.443",
"Id": "294962",
"Score": "0",
"body": "A modern optimising compiler will optimise iterating over an array with an index into iterating directly via pointers instead"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-20T13:33:27.503",
"Id": "294990",
"Score": "0",
"body": "@MarkKCowan: I think you'll find that the compiler produces different code. When making the suggestion, I also timed the results and found that the use of pointers consistently provides a speed advantage. Other compilers and machines may produce different results; measuring is the way to find out which produces faster code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-20T14:13:45.243",
"Id": "294998",
"Score": "0",
"body": "It depends on the compiler of course, I'm using GCC v6.3.1 and checking the assembly it produces rather than benchmarking"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-20T02:58:10.527",
"Id": "74233",
"ParentId": "38474",
"Score": "11"
}
},
{
"body": "<p>I'm going to skip reviewing the OP's code, which has already been reviewed quite nicely by others. Instead I'm just going to show a much faster version and explain it.</p>\n<h2>What is the algorithm?</h2>\n<p>Basically the way the algorithm works is that a buffer is created that holds <code>alphaLen^2</code> patterns, where <code>alphaLen</code> is the length of the alphabet. A pattern is one combination, such as <code>"aaaaa\\n"</code>. The reason that <code>alphaLen^2</code> patterns are used is because the buffer is prepopulated with the last 2 letters already set to all possible combinations. So for example, the buffer initially looks like (for length 5 patterns):</p>\n<pre class=\"lang-none prettyprint-override\"><code>"aaaaa\\naaaab\\naaaac\\n ... aaa99\\n" (62*62 patterns, 23064 bytes in length)\n</code></pre>\n<p>On every iteration, the function uses <code>write()</code> to output the buffer, and then increments the third to last letter. This involves writing that letter <code>alphaLen^2</code> times (once per pattern). So the first iteration goes like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>"aabaa\\naabab\\naabac\\n ... aab99\\n"\n ^ ^ ^ ^\n | | | |\n +------+------+-----------+----- Characters written to buffer (62*62 changes)\n</code></pre>\n<p>Whenever the third to last character wraps around, then we also need to update the fourth to last letter. If that wraps around, the fifth to last letter is also updated, etc. This continues until the first letter wraps around, at which point we are done.</p>\n<h2>How fast is it?</h2>\n<p>For all testing, I outputted to <code>/dev/null</code> so that my hard drive speed would not be the limiting factor. I tried the OP's program for 5 letter patterns but for me it took way too long (203 seconds). So I'll use Edward's estimate of 18 seconds for the OP's program instead. I also tested Edward's program on my machine, as well as a second program I wrote where I extended the algorithm to hardcode the last 3 characters instead of 2. I am using Cygwin gcc (32-bit) with <code>-O4</code> on a Windows desktop. Here are the results:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Time (secs) Length Program\n----------- ------ -------\n 18.0 5 syb0rg\n 9.6 5 Edward\n 0.4 5 JS1 (2 characters)\n 0.4 5 JS1 (3 characters)\n\n 665.0 6 Edward\n 26.0 6 JS1 (2 characters)\n 24.2 6 JS1 (3 characters)\n\n 1513.7 7 JS1 (3 characters)\n</code></pre>\n<p>As you can see, this algorithm is very fast.</p>\n<h2>The code</h2>\n<p>Both programs <a href=\"https://github.com/Jsdemonsim/Stackoverflow/tree/master/alphabet\" rel=\"noreferrer\">are available here on GitHub</a>. I'll show the 2 character variation below:</p>\n<pre class=\"lang-c prettyprint-override\"><code>static void generate(int maxlen)\n{\n int alphaLen = strlen(alphabet);\n int len = 0;\n char *buffer = malloc((maxlen + 1) * alphaLen * alphaLen);\n int *letters = malloc(maxlen * sizeof(int));\n\n if (buffer == NULL || letters == NULL) {\n fprintf(stderr, "Not enough memory.\\n");\n exit(1);\n }\n\n // This for loop generates all 1 letter patterns, then 2 letters, etc,\n // up to the given maxlen.\n for (len=1;len<=maxlen;len++) {\n // The stride is one larger than len because each line has a '\\n'.\n int i;\n int stride = len+1;\n int bufLen = stride * alphaLen * alphaLen;\n\n if (len == 1) {\n // Special case. The main algorithm hardcodes the last two\n // letters, so this case needs to be handled separately.\n int j = 0;\n bufLen = (len + 1) * alphaLen;\n for (i=0;i<alphaLen;i++) {\n buffer[j++] = alphabet[i];\n buffer[j++] = '\\n';\n }\n write(STDOUT_FILENO, buffer, bufLen);\n continue;\n }\n\n // Initialize buffer to contain all first letters.\n memset(buffer, alphabet[0], bufLen);\n\n // Now in buffer, write all the last 2 letters and newlines, which\n // will after this not change during the main algorithm.\n {\n // Let0 is the 2nd to last letter. Let1 is the last letter.\n int let0 = 0;\n int let1 = 0;\n for (i=len-2;i<bufLen;i+=stride) {\n buffer[i] = alphabet[let0];\n buffer[i+1] = alphabet[let1++];\n buffer[i+2] = '\\n';\n if (let1 == alphaLen) {\n let1 = 0;\n let0++;\n if (let0 == alphaLen)\n let0 = 0;\n }\n }\n }\n\n // Write the first sequence out.\n write(STDOUT_FILENO, buffer, bufLen);\n\n // Special case for length 2, we're already done.\n if (len == 2)\n continue;\n\n // Set all the letters to 0.\n for (i=0;i<len;i++)\n letters[i] = 0;\n\n // Now on each iteration, increment the the third to last letter.\n i = len-3;\n do {\n char c;\n int j;\n\n // Increment this letter.\n letters[i]++;\n\n // Handle wraparound.\n if (letters[i] >= alphaLen)\n letters[i] = 0;\n\n // Set this letter in the proper places in the buffer.\n c = alphabet[letters[i]];\n for (j=i;j<bufLen;j+=stride)\n buffer[j] = c;\n\n if (letters[i] != 0) {\n // No wraparound, so we finally finished incrementing.\n // Write out this set. Reset i back to third to last letter.\n write(STDOUT_FILENO, buffer, bufLen);\n i = len - 3;\n continue;\n }\n\n // The letter wrapped around ("carried"). Set up to increment\n // the next letter on the left.\n i--;\n // If we carried past last letter, we're done with this\n // whole length.\n if (i < 0)\n break;\n } while(1);\n }\n\n // Clean up.\n free(letters);\n free(buffer);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T18:13:14.330",
"Id": "135308",
"Score": "0",
"body": "Could you include some tests in there dealing with more character permutations? Some algorithms perform well with smaller sets of data than larger sets, so I'm curious as to how this will do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T21:15:51.333",
"Id": "135344",
"Score": "0",
"body": "@syb0rg Do you mean more characters in the alphabet or longer length pattern? Tell me how long of an alphabet and/or what pattern length you want me to test, and I'll test it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T22:49:33.613",
"Id": "135350",
"Score": "0",
"body": "A longer length pattern please. I'm quite certain your code will still perform well compared to others, but I'm still curious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-22T02:45:41.550",
"Id": "135360",
"Score": "1",
"body": "@syb0rg I added a length 7 time. Note that this is generating over 28 terabytes of data. The time was as expected, around 62x the length 6 time. I'm not going to run it for length 8 because it would take over a day to run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-26T13:07:50.953",
"Id": "136134",
"Score": "0",
"body": "+1 - nice job! I confirmed the accuracy with the other two algorithms and also noted that even when I bump up the buffer size in my version to similar size, this algorithm is significantly faster (0.5 s vs. 9.1 s on my machine)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T10:12:25.757",
"Id": "74379",
"ParentId": "38474",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": "74379",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-03T04:09:29.717",
"Id": "38474",
"Score": "32",
"Tags": [
"performance",
"algorithm",
"c",
"combinatorics"
],
"Title": "Brute Force Algorithm in C"
}
|
38474
|
<p>I have a string util method for finding potential "wrapping points" in a string.</p>
<p>For example, if <code>" "</code> and <code>"-"</code> are considered wrapping chars, then for input string<br>
<code>"Antoni Gil-Bao"</code> the method would return the sorted set <code>[6, 10]</code>.</p>
<pre><code>private static final String WRAPPING_CHARS = " -";
private static final CharMatcher WRAP_CHAR_MATCHER = CharMatcher.anyOf(WRAPPING_CHARS);
public static SortedSet<Integer> findWrappingIndices(String s) {
SortedSet<Integer> indices = Sets.newTreeSet();
while (WRAP_CHAR_MATCHER.indexIn(s) != -1) {
int index = WRAP_CHAR_MATCHER.indexIn(s);
int indexInOriginalString = indices.isEmpty() ? index : index + indices.last() + 1;
indices.add(indexInOriginalString);
s = s.substring(index + 1);
}
return indices;
}
</code></pre>
<p>Question is, <strong>is there a simpler way to implement this method using Guava</strong>? (Besides trivialities like inlining <code>indexInOriginalString</code>.) Based on my unit tests, the above does the job, but it doesn't feel that elegant. Obviously <strong>pure Java</strong> solutions are welcome too, if they are simpler than my Guava version. In any case, the method should take a <code>String</code> and return <code>SortedSet<Integer></code>.</p>
<p>(Background: the reason I just want the indices, instead of doing any string wrapping here directly, is that eventually I'll be operating inside <a href="http://developer.android.com/reference/android/view/View.html#onDraw%28android.graphics.Canvas%29" rel="noreferrer">onDraw()</a>, on a char array, and I want to <a href="http://developer.android.com/reference/android/graphics/Paint.html#measureText%28char%5B%5D,%20int,%20int%29" rel="noreferrer"><em>measure</em></a> pieces of text in the actual font before making wrapping decisions.)</p>
|
[] |
[
{
"body": "<p><code>Simplify</code> is a relative term. If you want simple, then I would have:</p>\n\n<pre><code>public static int[] findWrappingIndices(final String s) {\n int pos = 0;\n int[] ret = new int[s.length()];\n for (int i = 0; i < s.length(); i++) {\n if (WRAPPING_CHARS.indexOf(s.charAt(i)) >= 0) {\n ret[pos++] = i;\n }\n }\n return Arrays.copyOf(ret, pos);\n}\n</code></pre>\n\n<p>But, you want to complexify it by using a SortedSet (because int[] is not easy to use?), so you can then convert the int[] to the SortedSet.</p>\n\n<p>I don't see why the SortedSet is a good idea, but, it is easy enough to convert to using it (even though it is bigger and slower than an int[] array).</p>\n\n<p>I don't think you will find a simpler (or faster) alternative.</p>\n\n<p>I would guess that you could quavify it with (note the data is being inserted in sorted order anyway):</p>\n\n<pre><code>public static SortedSet<Integer> findWrappingIndices(final String s) {\n SortedSet<Integer> indices = Sets.newTreeSet();\n for (int i = 0; i < s.length(); i++) {\n if (WRAPPING_CHARS.indexOf(s.charAt(i)) >= 0) {\n indices.add(i);\n }\n }\n return indices;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:58:57.977",
"Id": "64424",
"Score": "0",
"body": "I prefer collections over arrays whenever possible, as they provide a friendlier and more powerful API to work with. In this particular case however (rather low-level string handling), a plain old `int[]` could indeed be fine. Anyway, +1 for demonstrating that in this case Guava doesn't make the solution any simpler compared to pure Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:03:12.227",
"Id": "64425",
"Score": "0",
"body": "By the way, the reason I used SortedSet was not sorting, but the fact that it best describes the returned data and makes it very easy *for the user of the method* to e.g. find next wrapping index for any arbitrary index: `indices.tailSet(i + 1).first()`. To be able to call `tailSet()` the return type must be SortedSet, regardless of implementation details like whether the data was already ordered."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T05:26:26.040",
"Id": "38478",
"ParentId": "38477",
"Score": "4"
}
},
{
"body": "<p>I see two inefficiencies in your code:</p>\n\n<ul>\n<li>You call <code>.indexIn()</code> twice in quick succession. You should have saved the return value from the first call.</li>\n<li>You create a substring with each iteration. <a href=\"https://stackoverflow.com/q/16123446/1157100\">Starting with Java 7</a>, that would be a performance problem, since each substring is a copy of part of the original string.</li>\n</ul>\n\n<p>Also, it would be no additional work for you to generalize the method to accept any <code>CharSequence</code>.</p>\n\n<pre><code>public static SortedSet<Integer> findWrappingIndices(CharSequence s) {\n SortedSet<Integer> indices = Sets.newTreeSet();\n for (int i = -1; -1 != (i = WRAP_CHAR_MATCHER.indexIn(s, i + 1)); ) {\n indices.add(i); \n }\n return indices;\n}\n</code></pre>\n\n<p>Another option, using just the built-in Java library, would be to use a regex, with <code>[- ]</code> as the pattern.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T07:31:39.387",
"Id": "38484",
"ParentId": "38477",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38484",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T05:03:05.540",
"Id": "38477",
"Score": "5",
"Tags": [
"java",
"algorithm",
"strings",
"guava"
],
"Title": "Simplify finding indices of all instances of certain characters in a string"
}
|
38477
|
<p>I'm attempting to write a Progress Dialog that I can instantiate, show and then pass a task to complete to. I'm pretty new to Task Based Patterns, so please bear with me.</p>
<p>Ideally my goal is to be able to show the progress of a task in a popup window, similar to the VS "Background Operation in Progress" dialog that you may know. Hopefully this can be fairly generic, or at very least define some sort of pattern that I can reuse.</p>
<p>What I have is below. Any suggestions are welcome!</p>
<pre><code>private CancellationTokenSource _CancellationTokenSource;
/// <summary>
/// Constructor.
/// </summary>
public frmThreadProgress()
{
InitializeComponent();
}
public static frmThreadProgress ShowProgress()
{
frmThreadProgress f = new frmThreadProgress();
f.Show();
f.BringToFront();
return f;
}
public void Cancel()
{
// Cancel the background task.
_CancellationTokenSource.Cancel();
// The UI will be updated by the cancellation handler.
}
public delegate Task<TResult> GenericTask<TResult, in TInput>(
TInput input, IProgress<int> progress, CancellationToken cancel);
/// <summary>
/// Run a Task Asynchronously and display its progress
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <typeparam name="TInput"></typeparam>
/// <param name="generictask"></param>
/// <param name="input"></param>
/// <param name="description"></param>
/// <returns></returns>
public Task<TResult> RunAsync<TInput, TResult>(GenericTask<TResult, TInput> generictask, TInput input, string description)
{
TaskIsRunning();
Information = description;
_CancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _CancellationTokenSource.Token;
var progressReporter = new ProgressReporter();
IProgress<int> onProgress = new Progress<int>((x) => pb.Position = x);
Task<TResult> t = generictask(input, onProgress, cancellationToken);
//configure completion handlers
progressReporter.RegisterCancelledHandler(t, TaskIsCancelled);
progressReporter.RegisterSucceededHandler(t, TaskIsComplete);
progressReporter.RegisterFaultedHandler(t, TaskErrored);
return t;
}
/// <summary>
/// Iterate a List of items and apply a function to produce a list of results
/// Reports progress of the task
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <typeparam name="TInput"></typeparam>
/// <param name="input"></param>
/// <param name="operation"></param>
/// <param name="description"></param>
/// <returns></returns>
public Task<IList<TResult>> IterateAsync<TInput, TResult>(IList<TInput> input, Func<TInput, TResult> operation, string description)
{
TaskIsRunning();
Information = description;
_CancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _CancellationTokenSource.Token;
var progressReporter = new ProgressReporter();
//delegate to update the progress
IProgress<int> onProgress = new Progress<int>((x) => pb.Position = x);
//Start the task
Task<IList<TResult>> t = Task.Factory.StartNew(() =>
{
IList<TResult> output = new List<TResult>();
for (int i = 0; i < input.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
TResult r = operation(input[i]);
output.Add(r);
onProgress.Report(100 * i / input.Count);
}
return output;
}, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
//Register completion/error/cancel handlers
progressReporter.RegisterCancelledHandler(t, TaskIsCancelled);
progressReporter.RegisterSucceededHandler(t, TaskIsComplete);
progressReporter.RegisterFaultedHandler(t, TaskErrored);
return t;
}
private void TaskIsRunning()
{
// Update UI to reflect background task.
btnOk.Enabled = false;
btnCancel.Enabled = true;
}
private void TaskIsComplete()
{
// Reset UI.
pb.Position = 100;
btnOk.Enabled = true;
btnCancel.Enabled = false;
}
private void TaskIsCancelled()
{
btnOk.Enabled = true;
btnCancel.Enabled = false;
Information = "User cancelled the operation!";
}
private void TaskErrored(Exception e)
{
btnOk.Enabled = true;
btnCancel.Enabled = false;
Information = "Error";
frmMessage.Show("Error running task", e);
}
///// <summary>
///// Information Text
///// </summary>
public string Information
{
set { lblInformation.AsyncUpdate(() => lblInformation.Text = value); }
}
private void buttonCancel_Click(object sender, EventArgs e)
{
//notify the background worker we want to cancel
Cancel();
}
private void btnOk_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
</code></pre>
|
[] |
[
{
"body": "<p>I think there is a design problem here.</p>\n\n<p>If your window is truly generic, <em>it need not know</em> how the tasks are being launched/queued. I don't think it's a good idea to schedule operations inside <code>Task.Factory.StartNew</code>—your window has no idea what kind of operations they might be.</p>\n\n<p>For example, these operations might interact with UI—or just with shared non-threadsafe variables—and it wouldn't be immediately obvious to the client code that operations run on another thread. Moreover, the client code might <em>not</em> want to schedule them on another thread (consider waiting for several asynchronous operations already represented as <code>Task</code>s). You're also constraining the operations to run sequentially (instead of running e.g. in parallel, which can be mapped to progress bar just as well).</p>\n\n<p>I'm also very sceptical about the whole <code>TInput</code>/<code>TResult</code> generic thing here; you aren't using these types, are you? This seems <strong>way</strong> overcomplicated for a fairly simple task. What if operation needs more than one parameter? Returns no result?</p>\n\n<p>Instead, I think you should <strong>let window accept an array of non-generic <code>Task</code>s, track them and that's it</strong>. No <code>TInput</code>/<code>TResult</code>. Of course you may want to keep <code>IProgress</code>—in this case, I'd suggest packing it in a struct together with <code>Task</code>. As in</p>\n\n<pre><code>public struct TaskWithProgress {\n public Task Task { get; set; }\n public IProgress<double> Progress { get; set; }\n}\n\npublic Task ObserveAsync(TaskWithProgress[] tasks, string description) \n</code></pre>\n\n<p>After all, your window only needs to know how may tasks there are and how many of them have completed. It doesn't need to know any parameters or results. The client code can trivially build an array of results with <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Task.WhenAll</code></a> if it needs to.</p>\n\n<p>It would then be client's code responsibility to schedule tasks (via <code>Task.Factory.StartNew</code> or any other mechanism).</p>\n\n<p>As an aside, <code>GenericTask</code> is a bad name because it assumes some relation to <code>Task</code> (which you unfortunately do not use—but you should!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:42:59.430",
"Id": "64435",
"Score": "1",
"body": "Thanks for the input. This is true that at the moment, its not very generic. I frequently find myself needing to run a block of code that takes a while to run, and I simply would like a fairly simple framework to be able to show a progress dialog, and provide feedback on progress. Could you suggest a useful mechanism/pattern to allow a task to supply the progress information?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T13:12:02.020",
"Id": "64440",
"Score": "0",
"body": "@Simon: I missed this bit—and now amended the answer. I'd use `IProgress` too, but with `double` (from 0 to 1) instead of `int` to avoid divisions and multiplications by 100 everywhere."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:23:13.863",
"Id": "38506",
"ParentId": "38479",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T05:44:58.910",
"Id": "38479",
"Score": "3",
"Tags": [
"c#",
"asynchronous",
"task-parallel-library"
],
"Title": "Generic Task Progress Dialog"
}
|
38479
|
<p>I am working on an ASP.NET MVC 5 project, using the code-first approach for database design. I have a question about my code design.</p>
<p>I have an Entity in my database schema called <code>Student</code>:</p>
<pre><code>public partial class Student
{
public int Id { get; set; }
public string RollNumber { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
}
</code></pre>
<p>Notice that I have declared this as partial because I extend it and include all the data access and processing functions for a student, like this:</p>
<pre><code>public partial class Student
{
[NotMapped]
private MyDbContext context = new MyDbContext();
public static Student Get(int id)
{
Student student;
using(MyDbContext context = new MyDbContext())
{
student = context.Students.SingleOrDefault(s => s.Id == id)
}
return student;
}
public void Student Create()
{
context.Students.Add(this);
context.SaveChanges();
}
//....
//and similarly many other
}
</code></pre>
<p>Notice that I have declared a static <code>Get</code> function which takes an <code>id</code> and returns a <code>Student</code> object if it exists, otherwise <code>null</code>. I have declared this static because it already returns a <code>Student</code> object, so calling it on an object seems unreasonable to me (please correct me if I am wrong). </p>
<p>The second thing to notice is the <code>NotMapped</code> attribute which I've used to exclude this property from mapping to database when running migrations.</p>
<p>I am using the above mentioned design with my all entities (i.e. wrapping data and function processing over that data into a single object).</p>
<p>Is this design approach good? Is there any other better approach exist, or am I on the wrong path?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:59:41.463",
"Id": "64131",
"Score": "4",
"body": "Take a look at [Repository pattern](http://www.remondo.net/repository-pattern-example-csharp/). Instead of static methods on each type of entity, declare a class that handles retrieval/creation/updates. One advantage is that you can [mock it in tests](http://stackoverflow.com/q/2098937/458193), which you can't easily do with static methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-27T02:25:55.923",
"Id": "179808",
"Score": "0",
"body": "I'm voting to close this question as off-topic because it's mostly a design review."
}
] |
[
{
"body": "<p>I'm no big fan of using partial classes because I find it less readable. Like the other commenter I think you should look at the repository pattern for a cleaner solution.\nIt seems a bit odd that you give Student the responsibility to save itself to the context. </p>\n\n<p>Something in the same neighbourhood is the UnitOfWorkPattern. That said the DbContext is an implementation of UnitOfWork and Repository Pattern. You could use the DbContext directly or with a wrapper of your own, but if your wrapper doesn't add value to the DbContext you could skip it.</p>\n\n<p>You are initializing your DbContext multiple times which seems redundant. Most likely you get the same instance since it implements the UnitOfWork pattern, but the \"new\" and private variables combined with static methods will make it very hard to write unit-tests. For testability you should avoid having MyDbContext in a private variable. You can use constructor injection to make it available to the class, or keep it in a property that you can substitute in tests later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:56:02.943",
"Id": "38491",
"ParentId": "38480",
"Score": "4"
}
},
{
"body": "<p>To add my 2ct worth:</p>\n\n<p>What you have started to implement is the <a href=\"http://en.wikipedia.org/wiki/Active_record_pattern\" rel=\"nofollow\">Active Record pattern</a>. We have used it in a Winforms/WPF application and ended up changing it to a Repository pattern due to the fact that it was annoying to unit test and we started having session scoping issues (but those were probably a result of bad application of the AR pattern rather than a problem with the AR pattern itself).</p>\n\n<p>In the end we found the Repository pattern much easier to deal with and unit test. It also keeps your model classes like <code>Student</code> very simple which makes it easier for serialization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:03:18.187",
"Id": "38525",
"ParentId": "38480",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T05:59:19.497",
"Id": "38480",
"Score": "2",
"Tags": [
"c#",
"asp.net-mvc-5"
],
"Title": "Student data in a database"
}
|
38480
|
<p>I have written a method for removing a link from a linked list for a phonebook project I'm currently working on and it works perfectly. However, I want to know whether or not my code is acceptable from a programmer's perspective. I tried to systematically structure it in a way such that it's understandable, but by doing so, this results in multiple if statements being nested inside one another.</p>
<p>Is this considered bad coding? Also, should I have used a recursive implementation instead? What do you think? Are there any ways to improve this code? Any constructive criticism is certainly welcome.</p>
<pre><code>public Link removeLink(String surname, String firstName)
{
Link currentLink = firstLink;
Link previousLink = firstLink;
if(isEmpty())
{
return null; // Name was not found
}
// customer to delete is first element in the list
else if((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))
{
firstLink = firstLink.next;
}
// customer is not the first element in the list
else
{
// search until either the end of list is reached or a match is found
while(currentLink.next!=null && !((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName)))
{
previousLink = currentLink;
currentLink = currentLink.next;
}
// if end of list is reached
if(currentLink.next == null)
{
// check if there is a match with last element in list
if((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))
{
previousLink.next = currentLink.next;
}
else
{
return null;
}
}
// match is found somewhere in the middle of list
else
{
previousLink.next = currentLink.next;
}
}
numEntries--; // number of entries decrements each time a customer is deleted
return currentLink; // return the entry that was deleted
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:56:36.273",
"Id": "64129",
"Score": "0",
"body": "Why do you need to reimplement linked list yourself? There's plenty implementations available, and I'm sure Java runtime has one as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:59:15.827",
"Id": "64130",
"Score": "0",
"body": "There's a lot to be learned from implementing common data structures such as linked lists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:00:30.257",
"Id": "64132",
"Score": "1",
"body": "@Dan Abramov It's part of the learning process"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:08:17.557",
"Id": "64133",
"Score": "2",
"body": "me likes curly braces on new line!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:10:55.897",
"Id": "64134",
"Score": "1",
"body": "could be written recursively. slower but probably less code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:14:21.590",
"Id": "64136",
"Score": "1",
"body": "if my phonebook had a million entries, that stack build-up is going to be huge, so I decided not to write it recursively"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:18:40.653",
"Id": "64137",
"Score": "0",
"body": "yes you can't do that for real stuff. just a fun and interesting exercise."
}
] |
[
{
"body": "<p>Code is fine I think, although according to <a href=\"http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882\" rel=\"nofollow\">Robert C. Martin</a>, generally, if you need to add a comment then you have failed to write readable code.</p>\n\n<p>For example, this could be made a little easier to read and understand by extracting the block </p>\n\n<pre><code>else //customer is not the first element in the list \n</code></pre>\n\n<p>into a separate method. Also the long tests such as </p>\n\n<pre><code>if ((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))\nwhile (currentLink.next!=null && !((currentLink.surname).equals(surname) && ((currentLink.firstName).equals(firstName)))\nif (currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))\n</code></pre>\n\n<p>...contain duplicated code, namely</p>\n\n<pre><code>(currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName)\n</code></pre>\n\n<p>which would be better extracted into, say <code>testForMatch()</code></p>\n\n<p><strong>In Summary</strong></p>\n\n<ul>\n<li>Long methods are frowned upon</li>\n<li>Repeated code is hard to understand and harder to maintain</li>\n<li>Extracting into well named methods beats good comments any day (comments can be left behind during updates and cause more confusion than is necessary with just code)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:14:15.103",
"Id": "64135",
"Score": "0",
"body": "I noticed my own mistake and edited ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T11:20:17.427",
"Id": "64138",
"Score": "1",
"body": "Uncle Bob would want to break this up into several more methods also. And maybe move stuff to the Link class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:55:21.647",
"Id": "38489",
"ParentId": "38488",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38489",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T10:31:58.490",
"Id": "38488",
"Score": "3",
"Tags": [
"java",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Removing a link from a linked list"
}
|
38488
|
<p>I am currently in a challenge with my buddy to see who can code a simple paint program in the least lines. The only requirement, is that the program must include an eraser. How can I possibly shorten this code, while still using proper, beautiful syntax?</p>
<pre><code>import sys, pygame
from pygame.locals import *
pygame.init() #Starts pygame
screen = pygame.display.set_mode((1000,720)) #window, and sets the size
screen.fill((255,255,255)) # Fills background color
brush = pygame.image.load("brush.jpg") #Loads the image into a variable
eraser = pygame.image.load("white.png") #Loads the image into a variable
brush = pygame.transform.scale(brush, (10,10)) #Scales the image into a more useable
eraser = pygame.transform.scale(eraser, (100,100)) #Scales the image into a more
clock = pygame.time.Clock() #Makes a clock to track the ticks within the game
z = 0
while True:
clock.tick(60) #Limits the ticks to 60 (FPS)
x,y = pygame.mouse.get_pos() #Sets two variables for the mouse position
for event in pygame.event.get(): #Recieves events
if event.type == QUIT: #Checks if the event is a QUIT event
pygame.quit() ##Quits##
sys.exit() ##Quits##
elif event.type == MOUSEBUTTONDOWN:
z = 1 #If you press the mouse button down, it sets the screen blit to true
elif event.type == MOUSEBUTTONUP:
z = z - 1 #Does the opposite of the above elif statement
if z == 1: #Cheks if the variable z is true, if it is; updates the screen with the brush
screen.blit(brush,(x-5,y-5))
if event.type == KEYDOWN:
screen.blit(eraser,(x-5,y-5))
pygame.display.update()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:11:30.100",
"Id": "64142",
"Score": "0",
"body": "The indentation seems to have gone wrong. Can you fix, please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:35:42.907",
"Id": "64144",
"Score": "0",
"body": "I honestly dont know how? It always messes it up when I post on stack overflow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:43:09.337",
"Id": "64146",
"Score": "0",
"body": "CodeReviews is not about 'CodeGolfing', and this question is off-topic: `4. Do I want the code to be good code, (i.e. not code-golfing, obfuscation, or similar)` in the [help/on-topic] pages"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:44:34.433",
"Id": "64147",
"Score": "3",
"body": "This question appears to be off-topic because it is about making the code as compact as possible (fewest lines)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:28:11.210",
"Id": "64155",
"Score": "6",
"body": "@rolfl: OP wants to shorten the code \"while still using proper, beautiful syntax\". So I think there is something here for Code Review. Ungifted: I fixed the indentation for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T03:58:26.880",
"Id": "65170",
"Score": "0",
"body": "@rolfl, I agree with Gareth on this one"
}
] |
[
{
"body": "<p>I didn't really try to understand much but I reckon this does the same thing as your code :</p>\n\n<pre><code>import sys, pygame\nfrom pygame.locals import *\n\npygame.init() \nscreen = pygame.display.set_mode((1000,720)) \nscreen.fill((255,255,255)) \nbrush = pygame.transform.scale(pygame.image.load(\"brush.jpg\"), (10,10)) \neraser = pygame.transform.scale(pygame.image.load(\"white.png\"), (100,100)) \nclock = pygame.time.Clock() \nz = False\nwhile True:\n clock.tick(60)\n x,y = pygame.mouse.get_pos()\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit() \n if event.type in [MOUSEBUTTONDOWN, MOUSEBUTTONUP]:\n z = (event.type==MOUSEBUTTONDOWN)\n if z:\n screen.blit(brush,(x-5,y-5))\n if event.type == KEYDOWN:\n screen.blit(eraser,(x-5,y-5))\n pygame.display.update()\n</code></pre>\n\n<p><strong>Hilights :</strong></p>\n\n<ul>\n<li>You don't need that many comments. Comments should explain why, not how.</li>\n<li>You can use the <code>boolean</code> type instead of playing with integers.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:14:34.487",
"Id": "38496",
"ParentId": "38494",
"Score": "0"
}
},
{
"body": "<p>Here's my best effort (8 lines):</p>\n\n<pre><code>from pygame import *\ninit()\nscreen = display.set_mode((1000,720))\nfor e in iter(event.wait, event.Event(QUIT)):\n col = {(1, 0, 0): 'white', (0, 0, 1): 'black'}.get(mouse.get_pressed())\n if col and e.type in (MOUSEBUTTONDOWN, MOUSEMOTION):\n display.update(screen.fill(Color(col), Rect(mouse.get_pos(), (20, 20))))\nquit()\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p><code>from module import *</code> is normally deprecated because you don't know all the names you're importing, and some of these might conflict with or shadow names from other modules. But in simple cases like this, with no other dependencies, it's justified because it results in code that's easy to read. You can always go through and change <code>X</code> to <code>pygame.X</code> if you want.</p></li>\n<li><p>In this program there's nothing that animates, so there's no need for a clock, and the display only needs to be updated when it changes.</p></li>\n<li><p>You didn't post your images <code>brush.jpg</code> and <code>white.png</code> so I've used solid colour rectangles. (Also, why a JPEG? JPEGs are lossy, so not appropriate for bitmap graphics.)</p></li>\n<li><p>By changing the program to draw white-on-black I can avoid the initial <code>screen.fill</code> and save a line.</p></li>\n<li><p>I've used colour names <code>'white'</code> and <code>'black'</code> which are clearer than RGB tuples like <code>(255, 255, 255)</code>.</p></li>\n<li><p>I've used the two-argument form of <a href=\"http://docs.python.org/3/library/functions.html#iter\"><code>iter</code></a> to avoid the test for <code>event.type == QUIT</code>. (This feature is useful when you want to exit an iteration on a special value.)</p></li>\n<li><p>By using <a href=\"http://www.pygame.org/docs/ref/event.html#pygame.event.wait\"><code>event.wait</code></a> instead of <a href=\"http://www.pygame.org/docs/ref/event.html#pygame.event.get\"><code>event.get</code></a> I can reduce the two loops to one.</p></li>\n<li><p>I've changed the user interface so that the left mouse button draws and the right mouse button erases. This is done by looking up the tuple returned by <a href=\"http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed\"><code>mouse.get_pressed</code></a> in a dictionary, to get the colour for the fill.</p></li>\n<li><p><a href=\"http://www.pygame.org/docs/ref/surface.html#pygame.Surface.fill\"><code>Surface.fill</code></a> returns the rectangle that was filled, which is exactly the part of the display that needs to be updated, so I can pass it directly to <a href=\"http://www.pygame.org/docs/ref/display.html#pygame.display.update\"><code>display.update</code></a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:05:59.017",
"Id": "64584",
"Score": "0",
"body": "That's kind of an amazing factorization ! oO I'm really impressed by that one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:12:37.343",
"Id": "38499",
"ParentId": "38494",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T12:44:56.213",
"Id": "38494",
"Score": "8",
"Tags": [
"python",
"pygame"
],
"Title": "How can I shorten this paint program?"
}
|
38494
|
<p>After reading <a href="http://gigasquidsoftware.com/blog/2013/12/02/neural-networks-in-clojure-with-core-dot-matrix/">this</a> article about Neural Networks I was inspired to write my own implementation that allows for more than one hidden layer. </p>
<p>I am interested in how to make this code more idiomatic - for example I read somewhere that in Clojure you should rarely need to use the for macro (not sure if this is true or not) due to the functions in the standard library - and if there are any performance improvements. For the simple example below it runs fairly quickly but it is a very small (an XOR network). </p>
<p><strong>Implementation:</strong></p>
<pre><code>(ns neural-net-again.ann
(:refer-clojure :exclude [+ - * == /])
(:use clojure.core.matrix)
(:use clojure.core.matrix.operators))
(set-current-implementation :vectorz)
(defn activation-fn [x] (Math/tanh x))
(defn dactivation-fn [y] (- 1.0 (* y y)))
(defn get-layers
[network]
(conj (apply (partial conj [(:inputs network)]) (:hidden network)) (:outputs network)))
(defn generate-layer
[neurons next-neurons]
(let [values (vec (repeat neurons 1))
weights (vec (for [i (range neurons)] (vec (repeatedly next-neurons rand))))]
{:values values :weights weights}))
(defn generate-network
[& {:keys [inputs hidden outputs]}]
(if (empty? hidden)
{:inputs (generate-layer (inc inputs) outputs) :outputs (generate-layer outputs 1)} ; add one to inputs for a extra bias neuron
(loop [current-layer (first hidden)
next-layer (first (rest hidden))
others (rest (rest hidden))
network {:inputs (generate-layer (inc inputs) (first hidden))}] ; add one to inputs for extra bias neuron
(if (nil? next-layer)
(-> network
(update-in [:hidden] #(conj % (generate-layer current-layer outputs)))
(assoc :outputs (generate-layer outputs 1)))
(recur next-layer (first others) (rest others) (update-in network [:hidden] #(conj % (generate-layer current-layer next-layer))))))))
(defn activate-layer
[{:keys [values weights]}]
(->> (transpose weights) ; group weights by neuron they point to
(mapv #(* values %))
(mapv #(reduce + %))
(mapv activation-fn)))
(defn forward-propagate
[network inputs]
(let [network (assoc-in network [:inputs :values] (conj inputs 1)) ; add one to the inputs for the bias neuron
layers (get-layers network)]
(loop [current-layer (first layers)
layers (rest layers)
all-layers []]
(if (empty? layers) ; we are at the output layer. Stop forward propagating
{:inputs (first all-layers) :hidden (rest all-layers) :outputs current-layer}
(let [layers (assoc-in (vec layers) [0 :values] (activate-layer current-layer))] ; sets the layer aboves values
(recur (first layers) (rest layers) (conj all-layers current-layer)))))))
(defn threshold-outputs
[network]
(update-in network [:outputs :values] (partial mapv #(if (< % 0.1) 0 (if (> % 0.9) 1 %)))))
(defn output-deltas
[network expected]
(let [outputs (get-in network [:outputs :values])]
(assoc-in network [:outputs :deltas] (* (mapv dactivation-fn outputs) (- expected outputs)))))
(defn layer-deltas
[layer layer-above]
(assoc layer :deltas (* (mapv dactivation-fn (:values layer)) (mapv #(reduce + %)
(* (:deltas layer-above) (:weights layer))))))
(defn adjust-layer-weights
[layer layer-above rate]
(assoc layer :weights (+ (:weights layer) (* rate (mapv #(* (:deltas layer-above) %) (:values layer))))))
(defn back-propagate
[network expected rate]
(let [layers (get-layers (output-deltas network expected))]
(loop [layer (last (butlast layers))
layer-above (last layers)
layers (butlast layers)
all-layers [layer-above]]
(if (nil? layer)
{:inputs (last all-layers) :hidden (reverse (rest (butlast all-layers))) :outputs (first all-layers)}
(let [updated-layer (-> layer
(layer-deltas layer-above)
(adjust-layer-weights layer-above rate))]
(recur (last (butlast layers)) updated-layer (butlast layers) (conj all-layers updated-layer)))))))
(defn train
[network data times rate]
(loop [i 0
net network]
(if (< i times)
(recur (inc i) (reduce (fn [network sample] (-> network
(forward-propagate (:inputs sample))
(back-propagate (:outputs sample) rate))) net data))
net)))
</code></pre>
<p><strong>Example usage:</strong></p>
<pre><code>(def xor-data [{:inputs [1 0] :outputs [1]}
{:inputs [0 1] :outputs [1]}
{:inputs [1 1] :outputs [0]}
{:inputs [0 0] :outputs [0]}])
(-> (generate-network :inputs 2 :hidden [2] :outputs 1)
(train xor-data 500 0.2)
(forward-propagate [1 0]))
</code></pre>
|
[] |
[
{
"body": "<p>I'm the author of <code>core.matrix</code>, so hopefully I can give you some tips from that perspective.</p>\n\n<p>If you want to improve performance, it's much better to use vectors in an optimised format throughout (<a href=\"https://github.com/mikera/vectorz-clj\">vectorz-clj</a> is a fine choice) rather than mixing in Clojure vectors everywhere. This saves the overhead of converting to/from Clojure vectors all the time, which is possibly your biggest performance bottleneck in this code. Typically, these will be significantly (probably 10-30x) faster than regular Clojure vectors for numerical operations with <code>core.matrix</code></p>\n\n<p>Here's an illustration of the difference:</p>\n\n<pre><code>;; add with regular Clojure vectors\n=> (let [v (vec (range 1000))] (time (dotimes [i 1000] (add v v))))\n\"Elapsed time: 625.66391 msecs\"\n\n;; add with Vectorz vectors\n(let [v (array (range 1000))] (time (dotimes [i 1000] (add v v))))\n\"Elapsed time: 18.917637 msecs\"\n</code></pre>\n\n<p>Some more specific tips:</p>\n\n<ul>\n<li>Use <code>(array ....)</code> instead of <code>(vec ....)</code> to produce Vectorz format vectors (actually it will produce whatever format you have set as your current implementation, so you can switch back and forth as needed)</li>\n<li>Use the core.matrix function <code>emap</code> (element map) rather than <code>mapv</code>. This should produce vectors in the format of the first vector argument, so will maintain Vectorz types. Even better, find a specialised function that does what you want: <code>(add x y)</code> is likely to be much faster than <code>(emap + x y)</code></li>\n<li><code>activate-layer</code> looks like a big bottleneck. It would be much better written as an array operation that exploits matrix multiplication. I think <code>(mmul (transpose weights) value)</code> should do the trick. To make this extra quick, I suggest storing the weights in pre-transposed format, then you can just do <code>(mmul transposed-weights value)</code></li>\n<li>I see you are using the <code>core.matrix</code> operators for <code>+</code>, <code>-</code>, <code>*</code> etc. That's fine, but be aware that they are somewhat slower than the equivalent <code>clojure.core</code> operators if you are applying them to single numbers rather than whole arrays. Normally I use the named <code>core.matrix</code> functions instead (<code>add</code>, <code>sub</code>, <code>mul</code> etc.) if there is any risk of confusion.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-13T03:17:47.963",
"Id": "184107",
"Score": "0",
"body": "Hi Mikera, I am also trying to write a neural network, using Clojure and wish to understand the role of the activation function. When I try to take your mmul approach, I find that it requires each layer to have a specific length ratio to the one that it feeds into, to make it amenable to matrix multiplication. What is the best way to deal with layers of arbitrary length in a network? Please check out the question that I asked [here](http://programmers.stackexchange.com/questions/293364/how-can-you-write-an-activation-function-in-a-neural-network-to-handle-a-layer-a)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:50:00.573",
"Id": "38628",
"ParentId": "38498",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "38628",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T13:32:42.373",
"Id": "38498",
"Score": "13",
"Tags": [
"functional-programming",
"clojure",
"lisp",
"machine-learning",
"neural-network"
],
"Title": "Clojure Neural Network"
}
|
38498
|
<p>About a year ago when I was applying to jobs for the first time, I had an interview at a company and they posed the following problem to me, which I preceded to bomb. </p>
<p>A year later I actually came up with a solution to the problem, and I couldn't be happier. However, I would love for some critiques as to the design of my solution or other feedback about: style, OOP practices, etc..</p>
<blockquote>
<p><strong>Problem Statement</strong></p>
<p>A group of farmers has some elevation data, and we're going to help
them understand how rainfall flows over their farmland. </p>
<p>We'll represent the land as a two-dimensional array of altitudes and
use the following model, based on the idea that water flows downhill: </p>
<p>If a cell’s four neighboring cells all have higher altitudes, we call
this cell a sink; water collects in sinks. </p>
<p>Otherwise, water will flow to the neighboring cell with the lowest
altitude. If a cell is not a sink, you may assume it has a unique
lowest neighbor and that this neighbor will be lower than the cell. </p>
<p>Cells that drain into the same sink – directly or indirectly – are
said to be part of the same basin. </p>
<p>Your challenge is to partition the map into basins. In particular,
given a map of elevations, your code should partition the map into
basins and output the sizes of the basins, in descending order. </p>
<p>Assume the elevation maps are square. Input will begin with a line
with one integer, S, the height (and width) of the map. The next S
lines will each contain a row of the map, each with S integers – the
elevations of the S cells in the row. Some farmers have small land
plots such as the examples below, while some have larger plots.
However, in no case will a farmer have a plot of land larger than S =
5000. </p>
<p>Your code should output a space-separated list of the basin sizes, in
descending order. (Trailing spaces are ignored.) </p>
<p>A few examples are below:</p>
<pre class="lang-none prettyprint-override"><code>-----------------------------------------
Input: Output:
3 7 2
1 5 2
2 4 7
3 6 9
The basins, labeled with A’s and B’s, are:
A A B
A A B
A A A
-----------------------------------------
Input: Output:
1 1
10
There is only one basin in this case.
The basin, labeled with A’s is:
A
-----------------------------------------
Input: Output:
5 11 7 7
1 0 2 5 8
2 3 4 7 9
3 5 7 8 9
1 2 5 4 3
3 3 5 2 1
The basins, labeled with A’s, B’s, and C’s, are:
A A A A A
A A A A A
B B A C C
B B B C C
B B C C C
-----------------------------------------
Input: Output:
4 7 5 4
0 2 1 3
2 1 0 4
3 3 3 3
5 5 2 1
The basins, labeled with A’s, B’s, and C’s, are:
A A B B
A B B B
A B B C
A C C C
-----------------------------------------
</code></pre>
</blockquote>
<p>My solution, written in Perl, is as follows: </p>
<p><code>Cell</code> class (models individual cells in the matrix):</p>
<pre class="lang-perl prettyprint-override"><code>{
package Cell;
use List::MoreUtils qw(all);
# models 4 nearest neighbors to position i,j forall i,j
my $neighbors = [ [ 0, -1], # left
[-1, 0], # top
[ 0, 1], # right
[+1, 0], # bottom
];
sub new {
my ($class, %attrs) = @_;
$attrs{is_sink} ||= 0;
bless \%attrs, $class;
}
# accessor/setter methods
sub elevation {
return shift->{elevation};
}
sub x {
return shift->{x};
}
sub y {
return shift->{y};
}
sub is_sink {
return shift->{is_sink};
}
sub set_sink {
shift->{is_sink} = 1;
}
sub xy {
my $self = shift;
return [$self->x, $self->y];
}
# string representation of a Cell
sub to_s {
my ($self) = @_;
return "(" . $self->x . "," . $self->y . ") = " . $self->elevation;
}
# returns the neighbors that flow into this Cell
sub get_flowing_neighbors {
my ($self, $rainfall) = @_;
# the neighbors of this cell flow into it
# iff this cell's elevation is less than their neighbors
# AND the neighboring cell has no other neighbors
# (that are not this cell) that have a lower (or equal) elevation
return grep {
$self->elevation < $_->elevation
&& all { $self->elevation <= $_->elevation } $_->get_neighbors($rainfall)
} $self->get_neighbors($rainfall);
}
# returns the neighbors of this Cell
sub get_neighbors {
my ($self, $rainfall) = @_;
my ($rows, $cols) = ($rainfall->rows, $rainfall->cols);
my ($x, $y) = ($self->x, $self->y);
my @adjs;
NEIGHBORS:
for my $neighbor ( @$neighbors ) {
my ($xmod, $ymod) = ($x + $neighbor->[0], $y + $neighbor->[1]);
# x and y must be in the bounds of the matrix
next NEIGHBORS
if $xmod > $rows - 1 || $ymod > $cols - 1 || $xmod < 0 || $ymod < 0;
push @adjs,
$rainfall->cell($xmod, $ymod);
}
return @adjs;
}
1;
} # end Cell
</code></pre>
<p><code>Rainfall</code> class (models the entire matrix and operations across it):</p>
<pre class="lang-perl prettyprint-override"><code>{
package Rainfall;
sub new {
my ($class, %attrs) = @_;
# initialize all elements of the matrix to cells O(n)
for my $i ( 0 .. @{ $attrs{field} } - 1) {
for my $j ( 0 .. @{ $attrs{field}->[$i] } - 1 ) {
$attrs{field}->[$i]->[$j] =
Cell->new( x => $i,
y => $j,
elevation => $attrs{field}->[$i]->[$j],
);
}
}
bless \%attrs, $class;
}
# accessor methods
sub field {
my $self = shift;
return $self->{field};
}
sub cell {
my ($self, $i, $j) = @_;
return $self->field->[$i]->[$j];
}
sub rows {
my $self = shift;
return $self->{rows};
}
sub cols {
my $self = shift;
return $self->{cols};
}
# determines if a given Cell is a sink
sub is_sink {
my ($self, $cell) = @_;
my $min = $cell->elevation;
my @neighbors = $cell->get_neighbors($self);
for my $neighbor ( @neighbors ) {
$min = ($min, $neighbor->elevation)[$min > $neighbor->elevation];
}
# found a sink, mark it
if( $min == $cell->elevation ) {
$cell->set_sink;
return 1;
}
return 0;
}
# returns a list of all Sinks in the matrix
# O(N * M) where N = # of rows and M = # of cols
sub find_sinks {
my ($self) = @_;
my @sinks;
for my $row ( 0 .. $self->rows - 1 ) {
for my $cell ( @{ $self->field->[$row] } ) {
push @sinks, $cell
if $self->is_sink($cell);
}
}
return @sinks;
}
# given an Array of Sinks, find the Basins in this field
# O(n)
sub find_basins_from_sinks {
my ($self, @sinks) = @_;
my %basin;
my $basin_marker = 'A';
# determine how many cells eventually flow into this one
for my $sink ( @sinks ) {
$basin{$basin_marker++} = $self->basin_size($sink);
}
return %basin;
}
# recursively find the number of Cells in the Basin
# attached to the given Cell
sub basin_size {
my ($self, $cell) = @_;
my $size = 1;
for my $neighbor ( $cell->get_flowing_neighbors($self) ) {
$size += $self->basin_size($neighbor);
}
return $size;
}
1;
} # end Rainfall
</code></pre>
<p>Unit tests that verify results to match the example cases above:</p>
<pre class="lang-perl prettyprint-override"><code>{ # Tests
use Test::More tests => 4;
{ # 3x3 field
my $r = Rainfall->new( rows => 3,
cols => 3,
field => [ [1, 5, 2],
[2, 4, 7],
[3, 6, 9] ]);
my @sinks = $r->find_sinks;
my %basin = $r->find_basins_from_sinks(@sinks);
is_deeply(
[sort { $b <=> $a } values %basin],
[7, 2],
'Correctly divided 3x3 field into 2 basins'
);
}
{ # 1x1 field
my $r = Rainfall->new( rows => 1,
cols => 1,
field => [ [1] ]);
my @sinks = $r->find_sinks;
my %basin = $r->find_basins_from_sinks(@sinks);
is_deeply(
[sort { $b <=> $a } values %basin],
[1],
'Correctly divided 1v1 field into 1 basin'
);
}
{ # 5x5 field
my $r = Rainfall->new( rows => 5,
cols => 5,
field => [ [1, 0, 2, 5, 8],
[2, 3, 4, 7, 9],
[3, 5, 7, 8, 9],
[1, 2, 5, 4, 3],
[3, 3, 5, 2, 1] ]);
my @sinks = $r->find_sinks;
my %basin = $r->find_basins_from_sinks(@sinks);
is_deeply(
[sort { $b <=> $a } values %basin],
[11, 7, 7],
'Correctly divided 5v5 field into 3 basins'
);
}
{ # Test 4x4 field
my $r = Rainfall->new( rows => 4,
cols => 4,
field => [ [0, 2, 1, 3],
[2, 1, 0, 4],
[3, 3, 3, 3],
[5, 5, 2, 1] ]);
my @sinks = $r->find_sinks;
my %basin = $r->find_basins_from_sinks(@sinks);
is_deeply(
[sort { $b <=> $a } values %basin],
[7, 5, 4],
'Correctly divided 4v4 field into 3 basins'
);
}
}
</code></pre>
<p>The basic algorithm searches through each element in the matrix and determines if that element is a sink (meaning that all of its neighbors flow into it). </p>
<pre class="lang-perl prettyprint-override"><code>sinks = []
for i in matrix: # rows
for j in matrix[i]: # columns
if matrix[i][j] is a sink:
sinks.add( matrix[i][j] )
</code></pre>
<p>From the problem description you can tell that there will be one <code>Basin</code> per sink, so after you have the sinks you need to find the <code>Basin</code>s. To find <code>Basin</code>s you start at the <code>Sink</code>s and search outward, adding elements to the basin if they A) flow into the sink or B) flow into a cell that flows into a sink. You stop searching outward when there are no more flow paths to consider.</p>
<pre class="lang-perl prettyprint-override"><code>def find_basins_from_sinks(sinks):
basins = {} # map
marker = 'A'
for sink in sinks:
basins[marker++] = basin_size(sink)
def basin_size(cell):
size = 1
for neighbor in cell.neighbors:
size += basin_size(neighbor)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:47:09.603",
"Id": "64160",
"Score": "0",
"body": "Would you mind describing the algorithm in pseudo-code ? The problem does seem interesting but I am not very familiar with the Perl syntax anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:01:03.403",
"Id": "64163",
"Score": "2",
"body": "@Josay sure, I outlined the basic algorithm in a less Perly fashion above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:18:01.847",
"Id": "64165",
"Score": "0",
"body": "How much time was given for solving the task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:40:53.693",
"Id": "64169",
"Score": "0",
"body": "@mpapec I think in the interview 100 minutes was allotted, I wasn't able to finish in time. This 2nd time around I finished in ~ 1 hour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:44:06.890",
"Id": "64195",
"Score": "0",
"body": "An idea: This looks like a good use for a union-find data structure. But that's just a cursory glance... (for a different-I think-approach to the problem)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-28T13:48:10.747",
"Id": "360147",
"Score": "0",
"body": "Recursion for this problem is not only unnecessary but extemely inefficent. If you are interested, I can show you a more effective non-recursive solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-01T15:03:04.587",
"Id": "360362",
"Score": "0",
"body": "@Ant_222 The only part that is computed recursively is the basin size. If you think you think your answer adds something that the others lack you are of course more than welcome to add it. That being said this question is 4 years old :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-01T20:22:50.413",
"Id": "360426",
"Score": "1",
"body": "Have you made certain that your algorithm runs in *O* (area)? My comment is not so much on style as on method. Will the proposal of an alternative solution qualify as an on-topic answer here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-02T14:08:06.670",
"Id": "360534",
"Score": "0",
"body": "Definitely on topic"
}
] |
[
{
"body": "<p>There are a few things I see in here that I would suggest could be different.</p>\n\n<p>I don't like that the logic for determining whether a cell is a sink is on both <code>Rainfall</code> and <code>Cell</code>. In fact, both classes have the method called <code>is_sink</code>...</p>\n\n<p>My preference would be to move the logic on to the Cell, which already knows how to calculate it's neighbours.... and then the Rainfall class can just call:</p>\n\n<pre><code>push @sinks, $cell\n if $cell->is_sink($self);\n</code></pre>\n\n<p>This indicates a larger problem though, that a fair amount of code is repeated (calculating neighbours, etc.). My suggestion is that you should have an initial pass of the field after creating each cell. This inialization pass should get each cell to compute, and store their neighbour list, as well as compute whether the cell is a sink. Putting it in the constructor of the Rainfall class seems like the right idea, but, since the initalization can also record the sinks, it seems quite a lot for a constructor. I am on the fence. The up-side is that it will make the execution faster.... Consider the RainFall constructor:</p>\n\n<pre><code> sub new { \n my ($class, %attrs) = @_; \n\n # initialize all elements of the matrix to cells O(n)\n for my $i ( 0 .. @{ $attrs{field} } - 1) {\n for my $j ( 0 .. @{ $attrs{field}->[$i] } - 1 ) { \n $attrs{field}->[$i]->[$j] =\n Cell->new( x => $i, \n y => $j, \n elevation => $attrs{field}->[$i]->[$j],\n );\n }\n }\n\n my @sinks;\n for my $i ( 0 .. @{ $attrs{field} } - 1) {\n for my $j ( 0 .. @{ $attrs{field}->[$i] } - 1 ) { \n my $cell = $attrs{field}->[$i]->[$j];\n $cell.initialize($self);\n push @sinks if $cell->is_sink;\n }\n }\n $attrs{sinks} = @sinks;\n\n bless \\%attrs, $class;\n } \n</code></pre>\n\n<p>The initialize method on the Cell will calculate, and store, the array of neighbours. This will substantially reduce the number of times they need to be calculated.</p>\n\n<p>If you have the one-off initialization then Cell->is_sink can take no parameters again.</p>\n\n<p>Apart from the restructuring of the is_sink, and the persistence of the neighbours array, I have a nit-pick about some of your loop-conditions.... you often have code like:</p>\n\n<pre><code>for my $row ( 0 .. $self->rows - 1 ) {\n ..\n</code></pre>\n\n<p>You should rather be using the last-index operator rather than the scalar one:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>for my $row ( 0 .. $#{$self->rows} ) {\n</code></pre>\n\n<p>Similarly with things like:</p>\n\n<pre><code>for my $i ( 0 .. @{ $attrs{field} } - 1) {\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>for my $i ( 0 .. $#{ $attrs{field} }) {\n</code></pre>\n\n<p>one last nit-pick, why do the subtraction when >= works fine too:</p>\n\n<pre><code>next NEIGHBORS \n if $xmod > $rows - 1 || $ymod > $cols - 1 || $xmod < 0 || $ymod < 0; \n</code></pre>\n\n<p>This could easily be:</p>\n\n<pre><code>next NEIGHBORS \n if $xmod >= $rows || $ymod >= $cols || $xmod < 0 || $ymod < 0;\n</code></pre>\n\n<p>Although, again, it is unclear that $rows and $columns are arrays here, and I would prefer:</p>\n\n<pre><code>next NEIGHBORS \n if $xmod > $#{$rows} || $ymod > $#{$cols} || $xmod < 0 || $ymod < 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:07:17.200",
"Id": "64170",
"Score": "1",
"body": "Thanks for the reply, I totally agree about determining sinks in the constructor for Rainfall, that makes a lot of sense and will allow me to decouple Rainfall and Cell from `get_neighbors` and `get_flowing_neighbors`. I also agree about the `for my $i ( 0 .. $#{ $attrs{field} } )` statement, but `$row` and `$col` are actually just integers that denote the size of the matrix, so the sizeof operator on then returns `-1`. Your comment about `<=` vs `<` makes sense though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:57:57.957",
"Id": "38505",
"ParentId": "38500",
"Score": "13"
}
},
{
"body": "<p>This is some very nice-looking code, and it looks like it is working. My criticism falls into the following topics:</p>\n\n<ul>\n<li>Discussions about style, naming, tools used etc. I assume you have consciously settled on a certain style, but some aspects strike me as so unusual that I would like to talk about them.</li>\n<li>I too, like to overengineer. But there are some parts of the design which I feel could be improved.</li>\n</ul>\n\n<h2><code>Cell</code></h2>\n\n<ul>\n<li><p><strong>Style</strong> I was surprised to see that you did all your OOP yourself. Where is Moo/Mouse/Moose? What are your reasons for not using any of them? There <em>are</em> valid reasons like less dependencies, but they are becoming rare.</p></li>\n<li><p><strong>Style</strong> Two-space indent is very debatable. I (along with <a href=\"http://perldoc.perl.org/perlstyle.html\">perlstyle</a>) recommend 4 columns.</p></li>\n<li><p><strong>Style</strong> I noticed you are using <code>{ package Foo; ... }</code>.</p>\n\n<ul>\n<li>It is recommendable to put different classes in different files so this isn't necessary.</li>\n<li>In v5.14 or later (IIRC) there is the <code>package Foo { ... }</code> form which reads nicer. Unless you are targeting older perls, you might want to use that instead.</li>\n</ul></li>\n<li><p><strong>Style</strong> You have the array reference <code>$neighbors</code>. This is OK if as a personal style decision you prefer references over non-scalar variables. This does not appear to be the case, and the only usage of that variables is as <code>@$neighbors</code>. </p></li>\n<li><p><strong>Note</strong> Avoid subroutines called <code>y</code> whenever possible, as that is also a transliteration operator. Of course this is no issue when only used as a method.</p></li>\n<li><p><strong>Design</strong> The <code>is_sink</code> method just returns a state value. It would be better if it would (lazily?) search the neighbors to see whether it's a sink. Currently, this is implemented in the confusingly named <code>Rainfall::is_sink</code> which arguably brakes encapsulation. There is no good reason to do that outside of the <code>Cell</code> class.</p></li>\n<li><p><strong>Style</strong> The <code>xy</code> method is not used anywhere. It also returns an arrayref which makes it harder to use the values. It would be more Perlish to return a flat list, so that we could do <code>my ($x, $y) = $cell->xy</code>. But as we already have accessors, we might as well remove that method.</p></li>\n<li><p><strong>Style</strong> <code>to_s</code> strikes me as a rather Ruby-ish name. In Perl there is no convention for naming a <code>toString</code> method. However, it is possible to override the stringification operator which is arguably a better thing to do:</p>\n\n<pre><code>use overload '\"\"' => sub { ... };\n</code></pre></li>\n<li><p><strong>Design</strong> Some of your methods require a <code>Rainfall</code> instance to be passed in. As each cell belongs to a certain grid, it might be better to store the grid in each cell. To avoid cyclic references you should use <a href=\"https://metacpan.org/pod/Scalar%3a%3aUtil#weaken-REF\"><code>Scalar::Util::weaken</code></a> to use weak references. Or if you've switched to an object system: <code>has grid => (weak => 1)</code>.</p></li>\n<li><p><strong>Style</strong> A <code>grep</code> is not always the best solution:</p>\n\n<pre><code>grep { \n $self->elevation < $_->elevation\n && all { $self->elevation <= $_->elevation } $_->get_neighbors($rainfall)\n} $self->get_neighbors($rainfall);\n</code></pre>\n\n<p>What this code expresses: <em>Select all neighbors who are higher than me and where I am the lowest neighbour</em>. But it's rather hard to read as <code>$_</code> is bound to many different values. <em>Never</em> nest multiple meanings of <code>$_</code>. A simple solution would be to add a <code>lowest_neighbor</code> method. Then:</p>\n\n<pre><code>grep { !$_->is_sink && $self == $_->lowest_neighbor } $self->get_neighbors;\n</code></pre>\n\n<p>Otherwise, using explicit loops can improve readability:</p>\n\n<pre><code>my @flowing_neighbors;\nfor my $neighbor ($self->get_neighbors) {\n next if not $self->elevation < $neighbor->elevation;\n next if not all { $self->elevation <= $_->elevation } $neighbor->get_neighbors;\n push @flowing_neighbors, $neighbor;\n}\nreturn @flowing_neighbors;\n</code></pre></li>\n<li><p><strong>Style</strong> Using <code>@adjs</code> as an abbreviation for <code>@adjacents</code> is unnecessary obfuscation.</p></li>\n<li><p>To do the bounds checking, it might be clearer to do instead of</p>\n\n<pre><code>next NEIGHBORS \n if $xmod > $rows - 1 || $ymod > $cols - 1 || $xmod < 0 || $ymod < 0;\n</code></pre>\n\n<p>this:</p>\n\n<pre><code>next NEIGHBORS if not 0 <= $xmod && $xmod < $rows;\nnext NEIGHBORS if not 0 <= $ymod && $xmod < $cols;\n</code></pre>\n\n<p>It's sad that Perl does not support chaining comparison operators, but this is the best way to show that a variable is in a specific range. Compare also range specifications in C-style <code>for</code> loops:</p>\n\n<pre><code>for (my $i = 0; $i < 10; $i++) {...} # 0..9\n</code></pre></li>\n</ul>\n\n<h2><code>Rainfall</code></h2>\n\n<ul>\n<li><p><strong>Design</strong> You build a grid of cell objects. It might be more fun to use the <a href=\"https://en.wikipedia.org/wiki/Flyweight_pattern\"><em>Flyweight Pattern</em></a>, as each cell only contains very little state (whether it's a sink, which can be checked rather cheaply).</p></li>\n<li><p><strong>Design</strong> To find all sinks, you look at each cell in the grid. If we forget for a moment that you wanted to write object-oriented code, we could consider this algorithm:</p>\n\n<pre><code>create a set of all cells.\nwhile the set contains elements:\n pick one element from the set.\n until the element is a sink:\n element = element->lowest_neighbor\n calculate the size of the basin,\n remove each member of the basin from the cells-set\n</code></pre>\n\n<p>While can construct a pathological case where this is as a loop through all cells, this will usually find the next sink much faster.</p>\n\n<p>In Perl the set of cells could be implemented as a hash that maps the coordinates to the cell object.</p></li>\n<li><p><strong>Design</strong> <code>basin_size</code> has <em>no</em> business being in <code>Rainfall</code>. It is a method on a <code>Cell</code>. Indicator: You don't use anything from the Rainfall instance <code>$self</code>. Ergo it should be a static method or ordinary subroutine. You always pass a <code>Cell</code> as first argument, so it should probably be a method on a <code>Cell</code> instance instead.</p></li>\n<li><p><strong>Design</strong> your constructor has both a <code>rows</code> and <code>cols</code> argument which is always the same <em>per defintion</em>. A single size would suffice, as would be deriving this information from the grid itself!</p></li>\n<li><p><strong>Style</strong> you perform zero validation on input (e.g. to assure that it actually has the requested size, that all required parameter are actually there, or that no unknown parameters were used). I often use a</p>\n\n<pre><code>my $thing = delete $args{thing} // die q(\"thing\" required);\n</code></pre>\n\n<p>pattern for this, followed by a <code>die \"Unknown arguments @{[sort keys %args]}\" if keys %args</code> check. The alternative is to use an object system and specify an attribute with</p>\n\n<pre><code>has thing => (required => 1);\n</code></pre></li>\n</ul>\n\n<h2>Tests</h2>\n\n<p>This looks very nice, no comments here. However, there is a massive amount of code duplication between the tests which could have been removed with a single loop.</p>\n\n<h2>Conclusion</h2>\n\n<p>This is very good code which shows the work of an experienced, careful programmer. The algorithm is OK. The design is slightly confused which indicates a code-first, design-later approach (which is OK, as it can be easily refactored).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:04:08.233",
"Id": "64173",
"Score": "1",
"body": "I wish I could upvote this twice. This has been extremely helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:07:28.377",
"Id": "64175",
"Score": "2",
"body": "To answer a few of your questions, the company I work for is still using Perl 5.12 (a few versions back), so I don't get the nice encapsulated package syntax of 5.14. In a similar fashion, we also don't `use Moose;` (or Moo; something I hope to change), instead we have our own object system. I decided to just use a blessed hash for this small program, had it been of a greater size I probably would have used Moose. I still might re-factor the could into a Moose package after I take everyone's comments into consideration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:13:41.487",
"Id": "64176",
"Score": "1",
"body": "You are right about `basin_size()`, I moved that into the Cell class and the could looks much cleaner, now I don't have to pass around the Rainfall state. You are write about error checking, and even though I am the only user of program I need to include it (I imagine interviewers' look for that). Regarding `to_s` That was just for debugging, but thanks for the overload suggestion, I didn't even know that feature existed. Thanks again for all of your suggestions, the Flyweight pattern looks particularly applicable, especially if I allow each Cell to hold a reference to its own neighbors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:29:37.180",
"Id": "64183",
"Score": "0",
"body": "I have posted a revised version (still w/o error checking to Github), take a look if you have a moment: https://github.com/mcmillhj/Rainfall"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:33:09.127",
"Id": "38507",
"ParentId": "38500",
"Score": "23"
}
},
{
"body": "<p>The fact that this was an interview question changes how I look at the code. The interviewer was almost certainly looking for one answer: \"union-find data structure\" or \"disjoint sets data structure\". You were being judged by whether you said those magic words within the first few seconds, could come up with something similar on your own, could come up with something similar with the interviewer's guidance, or not at all.</p>\n\n<p>Your solution could use either the abstract terminology (e.g. <code>Member</code> and <code>DisjointSet</code>) or the domain-specific terminology (<code>Cell</code> and <code>Basin</code>). You are therefore missing the Basin class in your modelling. Using the domain-specific terminology would be better, in my opinion. I would also prefer to rename <code>Rainfall</code> to <code>Topography</code>, since the problem is to analyze a topographic map.</p>\n\n<p>Here is the outline of the solution:</p>\n\n<ol>\n<li>Each <code>Cell</code> keeps track of which <code>Basin</code> it belongs to; each <code>Cell</code> is initially assume to be in its own <code>Basin</code>. Each <code>Basin</code> has a <code>sink</code>, or lowest <code>Cell</code>, which acts as a \"representative element\" of the <code>Basin</code>, as well as a member count. <code>Topography</code> keeps track of all <code>Basin</code>s.</li>\n<li>For each <code>Basin</code>, find lowest of the sink's neighbours. If the lowest is not already a member of this <code>Basin</code>, transfer its cells into the lowest neighbour's <code>Basin</code>, and notify <code>Topography</code> that the higher basin no longer exists.</li>\n<li>Repeat step 2 until no further action is necessary.</li>\n<li>Have <code>Topography</code> enumerate the <code>Basin</code>s and their counts.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:06:04.527",
"Id": "64353",
"Score": "2",
"body": "+1 for explicitly modeling basin, and for using names specific to the domain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:23:56.620",
"Id": "64354",
"Score": "0",
"body": "Thanks for your reply, this was really helpful. I will probably attempt this solution and compare my previous one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:12:58.343",
"Id": "38526",
"ParentId": "38500",
"Score": "22"
}
},
{
"body": "<p>I see the following three lines:</p>\n\n<pre><code>my $self = shift;\nmy ($self) = @_;\nmy ($self, $rainfall) = @_;\n</code></pre>\n\n<p>It's generally better if you choose one style and stick with it. It may make sense to mix the first and third lines in the same program, but the first two lines should not coexist. I would use the second and third versions, but if you like the first, you could use the following with it:</p>\n\n<pre><code>my $self = shift;\nmy $rainfall = shift;\n</code></pre>\n\n<p>That's somewhat longer but makes the code consistent. </p>\n\n<p>Perl has many ways to do things (TIMTOWTDI). It's still helpful though if you can choose just one way to do it in any given program (BSCINABTE). </p>\n\n<p>Similarly, in the following code:</p>\n\n<pre><code>sub x {\n return shift->{x};\n}\n</code></pre>\n\n<p>It's worth thinking about what is happening:</p>\n\n<pre><code>sub x {\n my $self = shift @_;\n\n return $self->{x};\n}\n</code></pre>\n\n<p>Hopefully you know that the former is a shorthand for the latter but think about the next person maintaining your code. What if this is that person's first time using Perl. People in that situation will see your code and think that <code>shift</code> is some kind of special variable name in Perl classes (once they realize that it's not defined in the class). How does such a person get from there to the latter version? </p>\n\n<p>The <code>shift</code> is a Perl built-in function which is defaulting to the <code>@_</code> variable. In that context, <code>@_</code> is set to the arguments to the <code>x</code> function with the object as the first argument. The <code>shift</code> built-in takes an array as the first argument, removes the first entry, and returns that entry. Then you dereference the result with the <code>-></code> operator and grab the value for the <code>x</code> key with a hash lookup (since classes are generally built on hashes in Perl). </p>\n\n<p>Also, <code>x</code> seems a confusing name for a function. I would find <code>get_x</code> or even <code>get_x_coordinate</code> to be easier to read and understand. </p>\n\n<p>If I were the one evaluating your interview code, then I would give points for writing clean, consistent, readable code. It's often worth taking a little extra time to make the code pretty. Most of my employed time is spent maintaining existing code, not writing new code. Writing the original code correctly is important. I don't care as much about quickly. The most important part is that it should be easy for me to debug and modify. That's where most of the time goes. If you save fifteen minutes writing code but I spend fifteen hours trying to make it work, then that's not a good tradeoff. </p>\n\n<p>As always, other reviewers may vary. The fact that they were asking you to write substantial code with a deadline may be a sign that they have different priorities than me. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-18T05:54:39.383",
"Id": "67086",
"ParentId": "38500",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38507",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T14:26:53.967",
"Id": "38500",
"Score": "40",
"Tags": [
"recursion",
"unit-testing",
"interview-questions",
"perl"
],
"Title": "Rainfall challenge"
}
|
38500
|
<p>I just created a sample project using Spring 3.x, Jetty 9.x, GWT 2.5.1 and Gradle <a href="https://github.com/krishnaraj/JettyGwtSpringSample" rel="nofollow">here</a>. It's a slightly modified version of the 'Greeting' GWT application from Google, the only change being that RPC calls are handled by a spring controller. </p>
<p>It would be really great if someone can review it, I am particularly apprehensive of injecting the <code>GwtRpcController</code> into the <code>GreetingServiceImpl</code>. Should I be worried about any thread safety issues?</p>
<p><strong>Main Controller</strong></p>
<pre><code>@Controller
public class GwtRpcController extends RemoteServiceServlet {
@Autowired
private ServletContext servletContext;
@Autowired
private RemoteService remoteService;
private Class<?> remoteServiceClass;
private HttpServletRequest request;
@RequestMapping(value = "/jettygwtspringsampleapp/*.rpc")
public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response ) throws Exception {
super.doPost( request, response );
return null;
}
@Override
public String processCall( String payload ) throws SerializationException {
try {
RPCRequest rpcRequest = RPC.decodeRequest( payload, this.remoteServiceClass );
// delegate work to the spring injected service
return RPC.invokeAndEncodeResponse( this.remoteService, rpcRequest.getMethod(), rpcRequest.getParameters() );
} catch ( IncompatibleRemoteServiceException ex ) {
getServletContext().log( "An IncompatibleRemoteServiceException was thrown while processing this call.", ex );
return RPC.encodeResponseForFailure( null, ex );
}
}
@Override
public ServletContext getServletContext() {
return servletContext;
}
public void setServletContext( ServletContext servletContext ) {
this.servletContext = servletContext;
}
public void setRemoteService( RemoteService remoteService ) {
this.remoteService = remoteService;
this.remoteServiceClass = this.remoteService.getClass();
}
public HttpServletRequest getThreadLocalHttpRequest() {
return getThreadLocalRequest();
}
}
</code></pre>
<p><strong>Service implementation</strong></p>
<pre><code>@Configuration
public class GreetingServiceImpl implements GreetingService {
@Autowired
GwtRpcController rpcController;
public String greetServer( String input ) throws IllegalArgumentException {
// Verify that the input is valid.
if ( !FieldVerifier.isValidName( input ) ) {
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException( "Name must be at least 4 characters long" );
}
String serverInfo = rpcController.getServletContext().getServerInfo();
String userAgent = rpcController.getThreadLocalHttpRequest().getHeader( "User-Agent" );
// Escape data from the client to avoid cross-site script vulnerabilities.
input = escapeHtml( input );
userAgent = escapeHtml( userAgent );
return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent;
}
.....
.....
</code></pre>
|
[] |
[
{
"body": "<p>Just some generic note about the code:</p>\n\n<ol>\n<li><p>If the parameter called <code>input</code> contains a name you should rename it to <code>name</code> to express its purpose.</p></li>\n<li><p>Method names should be verbs. I would rename <code>greetServer</code> to <code>serveGreeting</code> or <code>doGreeting</code>. (Check <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"nofollow\">Code Conventions for the Java Programming Language, Naming Conventions</a> and <em>Clean Code</em>, page 25.)</p></li>\n<li><p>Comments like this are rather just noise: </p>\n\n<pre><code>// If the input is not valid, throw an IllegalArgumentException back to\n// the client.\n</code></pre>\n\n<p>It's pretty obvious from the code itself, so I'd remove the comment. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>I'd move the complete validation logic to the <code>FieldVerifier</code> class (or another helper class or helper method) for better reusability and higher abstraction. It also would make the <code>greetServer</code> method more compact.</p></li>\n<li><p>The <code>isValidName</code> could be a little bit shorter with the null-safe Apache Commons Lang <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#length%28java.lang.CharSequence%29\" rel=\"nofollow\"><code>StringUtils.length</code></a>:</p>\n\n<pre><code>public static boolean isValidName(String name) {\n return StringUtils.length(name) > 3;\n}\n</code></pre></li>\n<li><p>Usage of Google Guava would make <code>checkName</code> more compact:</p>\n\n<pre><code>public static void checkName(final String name) {\n checkArgument(isValidName(name), \n \"Name must be at least 4 characters long\");\n}\n</code></pre>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><pre><code>public String greetServer(String name) throws IllegalArgumentException {\n ...\n}\n</code></pre>\n\n<p><code>IllegalArgumentException</code> is a <code>RuntimeException</code>, so declaring them in the method signature is not mandatory, you could omit it:</p>\n\n<pre><code>public String greetServer(String name) {\n ...\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T15:28:04.360",
"Id": "42512",
"ParentId": "38503",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T15:12:01.827",
"Id": "38503",
"Score": "2",
"Tags": [
"java",
"thread-safety",
"spring",
"gradle",
"gwt"
],
"Title": "JettyGwtSpringSample web application"
}
|
38503
|
<p>Say you have a Python class for something that has an optional gender field. You'd like a helper property/method to get the appropriate pronoun for an instance. You'd also like to be able to get the possessive version of the pronoun. The use for these helpers will be in creating human-readable emails and other such messages related to the object.</p>
<p>Below are three ways to do it. Which is best in terms of style and design and why?</p>
<p><strong>Option 1</strong></p>
<pre><code>@property
def pronoun(self):
return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they"
@property
def possessive_pronoun(self):
return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their"
</code></pre>
<p><strong>Option 2</strong></p>
<pre><code>def pronoun(self, possessive=False):
if possessive:
return "his" if self.gender == 'male' else "her" if self.gender == 'female' else "their"
else:
return "he" if self.gender == 'male' else "she" if self.gender == 'female' else "they"
</code></pre>
<p><strong>Option 3</strong></p>
<pre><code>def pronoun(self, possessive=False):
pronouns = ("he", "his") if self.gender == 'male' else ("she", "her") if self.gender == 'female' \
else ("they", "their")
return pronouns[1] if possessive else pronouns[0]
</code></pre>
<p>Feel free to suggest an even better fourth option. </p>
<p>P.S. In case you are wondering, I like to use double quotes for strings meant for human consumption, single quotes otherwise.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:20:00.680",
"Id": "64178",
"Score": "0",
"body": "In any case, the correct spelling seems to be \"possessive\" and not \"possesive\"."
}
] |
[
{
"body": "<p>I usually try to use data structure over code whenever it's possible.\nIt usually make things shorter, easier to read and easier to update.</p>\n\n<p>If I had to write such a thing, I'd probably write something like (untested code but just to show the idea) :</p>\n\n<pre><code>pronouns = {\n 'male' => (\"he\",\"his\"),\n 'female' => (\"she\", \"her\")\n}\n\ndef pronoun(self, possessive=False):\n return pronouns.get(self.gender, default=(\"they\",\"their\"))[possessive]\n</code></pre>\n\n<p>If we could be sure that self.gender has only 3 different values, the default value could be put in the <code>pronouns</code> dictionnary straightaway (associated to <code>\"plural\"</code> for instance).</p>\n\n<p>Different variations could be written. I guess one could use <code>defaultdict</code> to ensure that we always retrieve the default value. I don't like this solution that much as the dictionnary would get bigger as we try to retrieve using invalid keys.</p>\n\n<p>I don't know if there's a (simple) way to have a dictionnary which returns a default value when the key is not present without updating the dictionnary but I'd be interested in such a thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:57:16.537",
"Id": "64253",
"Score": "0",
"body": "`=>` should be `:`? and can't use `possessive` directly as a key value, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T02:35:51.257",
"Id": "64292",
"Score": "1",
"body": "That's Ruby syntax."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:31:22.203",
"Id": "38521",
"ParentId": "38508",
"Score": "2"
}
},
{
"body": "<p>Option 1 looks to be best in my opinion as it enforces readability of the intent in the instance usage, e.g.</p>\n\n<pre><code>u.subject_pronoun.capitalize() + \" is buying the new widget for \" + u.possesive_pronoun + \" own use.\"\n</code></pre>\n\n<p>Versus:</p>\n\n<pre><code>u.pronoun().capitalize() + \" is buying the new widget for \" + u.pronoun(True) + \" own use.\"\n</code></pre>\n\n<p>In the latter case the meaning is lost on the possessive pronoun since the consumer of the class didn't supply the argument name.</p>\n\n<p>Another approach to getting the values by a nested dictionary (similar to the Ruby way suggested by Josay) would be:</p>\n\n<pre><code>self._pronouns = {\n 'male': {\n 'possessive': 'his',\n 'object': 'him',\n 'subject': 'he'\n },\n\n 'female': {\n 'possessive': 'hers',\n 'object': 'her',\n 'subject': 'she'\n },\n\n 'unspecified': {\n 'possessive': 'theirs',\n 'object': 'them',\n 'subject': 'they'\n }\n }\n@property\ndef object_pronoun(self):\n return self._pronouns[self.gender]['object'] if self.gender else self._pronouns['unspecified']['object']\ndef possessive_pronoun(self):\n return self._pronouns[self.gender]['possessive'] if self.gender else self._pronouns['unspecified']['possessive']\ndef subject_pronoun(self):\n return self._pronouns[self.gender]['subject'] if self.gender else self._pronouns['unspecified']['subject']\n</code></pre>\n\n<p>This approach allows for more types to be added easily as shown by adding the subject type.</p>\n\n<p>Edit: Updated per comment suggestions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:46:24.037",
"Id": "64241",
"Score": "0",
"body": "I agree, option 1 is the best of the three interfaces. I would go even further and rename `pronoun` → `nominative_pronoun`. There should be another case as well: [`object_pronoun`](http://en.wikipedia.org/wiki/Object_pronoun). (You seem to have changed nominative case in the question to objective case in your answer.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:51:41.140",
"Id": "64242",
"Score": "0",
"body": "You've used the key `plural` for the third case (*their* / *theirs*). But the OP indicates that the gender field is optional, so the third case is really *unspecified* or *other*, not *plural*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T18:47:34.947",
"Id": "38529",
"ParentId": "38508",
"Score": "2"
}
},
{
"body": "<p>From a style perspective I like the first option; if you're treating this as a property its clear what you intend</p>\n\n<p>For implementation, I'd try a class level default with an instance override to provide the right words to allow for specialization or extension (for other languages than English, say, or use at Oberlin College). Whatever your gender politics this implementation is extensible to new cases and one offs.</p>\n\n<pre><code>class Gendered(object):\n NOMINATIVE = {'m':('he', 'they'), 'f': ('she','they'), 'n':('it', 'they')}\n ACCUSATIVE = {'m':('him', 'them'), 'f': ('her','them'), 'n':('it', 'them')}\n POSSESSIVE = {'m':('his', 'their'), 'f': ('hers', 'their'), 'n':('its', 'their')}\n\n def __init__(self, word, gender = 'n', plural = 0, **kwargs):\n self.Word = word\n self.Gender = gender.lower()[0]\n self.Plural = 0 if not plural else 1\n self.Nominative = kwargs.get('nominative', self.NOMINATIVE)\n self.Accusative = kwargs.get('accusative', self.ACCUSATIVE)\n self.Posessive = kwargs.get('possessive', self.POSSESSIVE)\n\n def get_pronoun(self, case ): # where case will be one of self.Nominative. self.Accusative, self.Possesive\n return case.get(self.Gender, ('',''))[self.Plural]\n # using get rather than if-checking lets you specify a default\n\n @property\n def pronoun(self):\n return self.get_pronoun(self.Nominative);\n\n @property\n def accusative_pronoun(self):\n return self.get_pronoun(self.Accusative);\n @property\n def possessive_pronoun(self):\n return self.get_pronoun(self.Posessive);\n\n\nexample = Gendered(\"battleship\", \"f\", False)\nprint example.pronoun\nprint example.accusative_pronoun\nprint example.possessive_pronoun\n\nexample = Gendered(\"king\", \"m\", possessive = {'m':('his royal', 'their royal'), 'f':('her royal', 'their royal'), 'n':('their', 'their royal')})\nprint example.pronoun\nprint example.accusative_pronoun\nprint example.possessive_pronoun\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:48:14.257",
"Id": "38539",
"ParentId": "38508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38529",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:36:25.613",
"Id": "38508",
"Score": "1",
"Tags": [
"python"
],
"Title": "Three ways to add pronoun method/property to gendered class in Python"
}
|
38508
|
<p>The Levenshtein distance is applied specifically to two string values. The result describes the number of differences between two strings. More specifically, it is the count of the smallest number of operations that can transform one string into the other string. Operations include the insertion, deletion, substitution, or transposition of a character in the string. Operations can be considered in combinations and may have different costs.</p>
<p>Here is <a href="http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance" rel="nofollow">a comprehensive list of Levenshtein functions</a> in a variety of languages, however note that some languages have a standard utility function do to the same job.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:37:07.210",
"Id": "38509",
"Score": "0",
"Tags": null,
"Title": null
}
|
38509
|
A class of problems concerned with finding or minimizing the sequence of change operations (such as insertion, deletion, substitution, or transposition) to convert one list or string into another
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:37:07.210",
"Id": "38510",
"Score": "0",
"Tags": null,
"Title": null
}
|
38510
|
<p>I'm learning JS/jQuery at the moment and have built the following standalone script but I feel that it can probably be improved in some ways?</p>
<p>For example - is there a better way of switching the selected text on the <code>.dropdown-menu li a</code> click event rather than needing to replace the entire HTML?</p>
<p>Constructive advice welcome.</p>
<p>EDIT: Added HTML to help with context:</p>
<pre><code><div class="dropdowncontain">
<button type="button" class="button defaultbutton">Default Value <span class="caret invert"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Katie</a></li>
<li><a href="#">Richard</a></li>
<li><a href="#">Matthew</a></li>
<li><a href="#">Sophie</a></li>
<li class="dropdown-divider"></li>
<li><a href="#">Default Value</a></li>
</ul>
</div>
<div class="dropdowncontain">
<button type="button" class="button primarybutton">Click Me <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Katie</a></li>
<li><a href="#">Richard</a></li>
<li><a href="#">Matthew</a></li>
<li><a href="#">Sophie</a></li>
</ul>
</div>
</code></pre>
<p>So currently the script checks if the user is clicking in a dropdown menu that needs an inverted caret.</p>
<pre><code>$(function() {
// Handles initial dropdown click event, if any dropdown menu is visible close it
$('.dropdowncontain').click(function(e){
if (!$('.dropdown-menu', this).is(':visible')) {
$('.dropdown-menu').hide();
}
$('.dropdown-menu', this).toggle();
// Stop the bubbling of the event to the document level
e.stopPropagation();
});
// Handles hiding the dropdown menu's when the user clicks elsewhere in the document
$(document).click(function() {
$('.dropdown-menu').hide();
});
// Handles updating the text in the button and highlighting the selected option
$('.dropdown-menu li a').click(function(e){
var parentBtn = $(this).parents('.dropdowncontain').find('.defaultbutton');
var that = $(this).parents('.dropdowncontain').find('.dropdown-menu li a');
var selectedText = $(this).text();
if (that.hasClass('highlightdropdown')){
that.removeClass('highlightdropdown');
}
$(this).addClass('highlightdropdown');
// If the containing parent div has a class with 'defaultbutton' add the invert class to the caret
if (parentBtn.hasClass('defaultbutton')) {
$(this).parents('.dropdowncontain').find('.button').html(selectedText+' <span class="caret invert"></span>');
}
else {
$(this).parents('.dropdowncontain').find('.button').html(selectedText+' <span class="caret"></span>');
}
// Prevent the page jumping to the top when a link with no source is selected
e.preventDefault();
});
});
</code></pre>
|
[] |
[
{
"body": "<p>There is no reason to swap the text, find the span in the button and toggle the class</p>\n\n<pre><code>var isDefault = parentBtn.hasClass('defaultbutton')\n$(this).parents('.dropdowncontain').find('.button .caret').toggleClass(\"invert\", isDefault);\n</code></pre>\n\n<p>The context selector is a bad idea</p>\n\n<pre><code>$('.dropdown-menu', this)\n</code></pre>\n\n<p>It is slow. Use <code>find()</code></p>\n\n<pre><code>$(this).find('.dropdown-menu')\n</code></pre>\n\n<p>Another thing, <code>$(this)</code> is used over and over again. That is bad practice. It creates a new jQuery object each time. Store it in a variable and reuse that variable.</p>\n\n<pre><code>var myElement = $(this);\nmyElement.find('.dropdown-menu')...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:21:02.653",
"Id": "64179",
"Score": "0",
"body": "Thanks for the advice I didn't realise .find() is more perfomant! I am swapping the text in order to update the button's text with what the user selected (increased UX).\n\nAlso there is a missing semicolon in isDefault var - thought I'd just let you know!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:56:28.670",
"Id": "38512",
"ParentId": "38511",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:45:33.750",
"Id": "38511",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Drop-down menu button highlighting and hiding"
}
|
38511
|
<p><em>Moved to Code Review as per comments received on <a href="https://stackoverflow.com/questions/20907502/can-this-while-loop-be-made-cleaner">https://stackoverflow.com/questions/20907502/can-this-while-loop-be-made-cleaner</a></em></p>
<p>Is there a way to make the following while loop a little more optimized? What bugs me in particular is the fact that I have to repeat code (closing buffers and returning a value) both inside and outside the if condition and I wanted to get opinions on whether there might be a better /more performance-oriented way to handle such code.</p>
<p>While I've posted the entire method, the part I'm more interested in comments on is how the while loop can be optimized. Ofcourse, comments on the remainder of the code are also welcome, but not essential.</p>
<pre><code> private String getRandomQuote(int lineToFetch)
throws IOException {
//1. get path
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
//2. open assets
InputStream stream = assets.open(path);
InputStreamReader randomQuote = new InputStreamReader(stream);
//3. Get BufferedReader object
BufferedReader buf = new BufferedReader(randomQuote);
String quote = null;
String line = null;
int currLine = 0;
//4. Loop through using the new InputStreamReader until a match is found
while ((line = buf.readLine()) != null) {
// Get a random line number
if (currLine == lineToFetch) {
quote = line;
Log.v("LINE", line);
randomQuote.close();
buf.close();
return quote;
} else
currLine++;
}
randomQuote.close();
buf.close();
return quote;
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice little system, I understand though why you think this code could be better.</p>\n\n<p>I think there are a few things which would make a difference. The first is a try-finally block, and the second is a simpler loop</p>\n\n<p>First, the try-finally:</p>\n\n<pre><code> InputStream stream = assets.open(path);\n try {\n //3. Get BufferedReader object\n BufferedReader buf = new BufferedReader(new InputStreamReader(stream));\n .... do things with the buffer.\n } finally {\n stream.close();\n }\n</code></pre>\n\n<p>This is a bit of a pre-Java7 cheat I use. It is safe to close the inner stream, and let the outer Readers (BufferedReader,InputStreamReader) not be explicitly closed. In Java7 I would put them all in a try-with-resources, but, Android, alas!.</p>\n\n<p>With the above code you don't need to worry about closing the stream at all inside the try block.</p>\n\n<p>OK, so now the try-block is simple, I would put two conditions (the readLine first!) in to the read-loop:</p>\n\n<pre><code>String line = null;\nint currLine = 0;\n\n//4. Loop through using the new InputStreamReader until a match is found\nwhile ((line = buf.readLine()) != null && currLine < lineToFetch) {\n currLine++;\n}\n\n// OK, at this point, line is either null,\n// or the actual line to fetch.... Whatever it is, return it,\nreturn line;\n</code></pre>\n\n<p>Putting it all together, I would have something like:</p>\n\n<pre><code>private String getRandomQuote(int lineToFetch)\n throws IOException {\n //1. get path\n AssetManager assets = getApplicationAssets();\n String path = null;\n path = getAssetPath(assets);\n\n //2. open assets\n InputStream stream = assets.open(path);\n try {\n //3. Get BufferedReader object\n BufferedReader buf = new BufferedReader(new InputStreamReader(stream));\n String line = null;\n int currLine = 0;\n\n //4. Loop through using the new InputStreamReader until a match is found\n while ((line = buf.readLine()) != null && currLine < lineToFetch) {\n currLine++;\n }\n\n // OK, at this point, line is either null,\n // or the actual line to fetch.... Whatever it is, return it,\n return line;\n\n } finally {\n stream.close();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:05:20.617",
"Id": "64447",
"Score": "0",
"body": "returning inside try block is good ? i felt it was bad (just a student )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:45:39.050",
"Id": "64474",
"Score": "0",
"body": "returning inside a try block is neither good nor bad. Creating a new variable to handle things is not good though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T17:12:33.403",
"Id": "38514",
"ParentId": "38513",
"Score": "6"
}
},
{
"body": "<p>There are simplifications that can be made to rolfl's answer:</p>\n\n<pre><code>private String getRandomQuote(int lineToFetch) throws IOException {\n Reader buf = getQuoteDataSource();\n\n try {\n String line = buf.readLine();\n\n while( --lineToFetch > 0 && line != null ) {\n line = buf.readLine();\n }\n\n return line == null ? \"\" : line;\n } finally {\n buf.close();\n }\n}\n</code></pre>\n\n<p>How the assets are opened is superfluous. Maybe the quotes come from a database, maybe they come from a file, or maybe they are downloaded across an HTTP connection.</p>\n\n<p>I seldom return <code>null</code> values, preferring valid objects that won't inadvertently cause a NullPointerException when referenced. (See also Tony Hoare's Billion Dollar mistake.)</p>\n\n<p>If a <code>null</code> value is truly unexpected, throw an exception instead. Force the calling code to handle missing quotes at compile time, rather than relying on developer memory.</p>\n\n<p>Note: There might be an off-by-one error, so test.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:30:04.617",
"Id": "38542",
"ParentId": "38513",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T16:59:11.217",
"Id": "38513",
"Score": "8",
"Tags": [
"java",
"performance",
"android"
],
"Title": "Can this while loop be made cleaner"
}
|
38513
|
<p>How will this example affect the using implementation in GetSite?</p>
<pre><code>public abstract class SPSiteBase
{
protected abstract string Url { get; set; }
public abstract SPSite GetSite(string url = null);
}
public class SPSiteFactory : SPSiteBase
{
protected override sealed string Url { get; set; }
public override SPSite GetSite(string url = null)
{
using (SPSite site = new SPSite(string.IsNullOrEmpty(url) ? Url : url))
{
return site;
}
}
public SPSiteFactory() { }
public SPSiteFactory(string url)
{
Url = url;
}
}
</code></pre>
<p>I call it like this</p>
<pre><code>SPSiteFactory siteFactory = new SPSiteFactory("http://portalurl/");
SPSite site = siteFactory.GetSite();
</code></pre>
<p>I've noticed that the code steps out of the using after I run the <code>siteFactory.GetSite()</code> method but will the <code>site</code> ever be disposed?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:10:22.043",
"Id": "64225",
"Score": "0",
"body": "`using { return }` is the same as `try { return }`—it won't magically handle errors the calling code. Thus `using` will dispose right away."
}
] |
[
{
"body": "<p>No, you can't use a factory to dispose your objects, your code is creating and immediately disposing the SPSite as soon as it steps out of your method. </p>\n\n<pre><code>public override SPSite GetSite(string url = null)\n{\n return new SPSite(string.IsNullOrEmpty(url) ? Url : url))\n}\n</code></pre>\n\n<p>Have the disposing be handled by the calling code. You can't handle the disposing from a factory method.</p>\n\n<p>If you want to check it out, build your own disposable type, put a breakpoint in the Dispose method and check for yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:43:55.760",
"Id": "64250",
"Score": "0",
"body": "That would make returning disposable variables by using `using` in a factory pattern to an antipattern, that's all I needed, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T22:59:09.250",
"Id": "64480",
"Score": "2",
"body": "@EricHerlitz I wouldn't say it's an anti-pattern. Anti-pattern is something that works, but is bad design. This code simply doesn't work, it returns an object that's already disposed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T08:12:55.510",
"Id": "64534",
"Score": "0",
"body": "The instance of `site` still works but the site in the factory is disposed"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T19:14:27.810",
"Id": "38534",
"ParentId": "38531",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "38534",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T19:03:15.333",
"Id": "38531",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
"factory-method",
"sharepoint"
],
"Title": "using (IDisposable) in c# factory pattern"
}
|
38531
|
<p>I have a <code>Dictionary<string, object></code> (named <code>tableDict</code>) that has been parsed from JSON. The <code>string</code> describes the intended construction of a class <code>T</code> which is defined within the housing class of this code. The <code>object</code> is the numerical probability value that pairs up with the generated reference of <code>T</code>.</p>
<p>The <code>string</code> can be in either of two formats. Something encased in brackets, i.e. <code>"(arg0, arg1, arg2, ...)"</code>, will call the constructor with these arguments. Anything else is assumed to be a name of a property of type <code>T</code> that returns a predefined <code>T</code>, i.e when <code>T</code> is of type <code>Color</code>, <code>"Black"</code> would lead to looking for <code>Color.Black</code>.</p>
<p>I managed to get something to work however I pieced this together from googling each problem I encountered. A lot of what I have used is new to me, it's highly likely I have gone about it in an inefficient roundabout fashion.</p>
<pre><code>for (int i = 0; i < tableDict.Count; i++)
{
KeyValuePair<string, object> kvp = tableDict.ElementAt(i);
string s = kvp.Key;
if (Regex.IsMatch(s, @"\(([^\)]+)\)", RegexOptions.None))
// Key is "( something )" - entry is constructor
{
string sCon = s.WhitespaceRemoved();
sCon = sCon.Substring(1, sCon.Length - 2); // Remove brackets
string[] argsAsStrings = sCon.Split(',');
object[] args = argsAsStrings.Select(num => (object)int.Parse(num)).ToArray();
// I have only implemented this for the Color class.
// I assume the constructor is comprised of ints.
T item = (T)Activator.CreateInstance(typeof(T), args);
double prob = Convert.ToDouble(kvp.Value);
var entry = new RawChanceTableEntry<T>(item, prob);
list.Add(entry);
}
else // Parse string as a property of T instead
{
string sProp = s;
Type type = typeof(T);
PropertyInfo propInfo = type.GetProperty(sProp);
object obj = Activator.CreateInstance(type);
T item = (T)propInfo.GetValue(obj, null);
double prob = Convert.ToDouble(kvp.Value);
var entry = new RawChanceTableEntry<T>(item, prob);
list.Add(entry);
}
}
</code></pre>
<p>Note the struct <code>RawChanceTableEntry</code> is just a container for the item / probability pair.</p>
<p>Code in class: <a href="http://pastebin.com/bvJaS8Se" rel="noreferrer">http://pastebin.com/bvJaS8Se</a> (class is incomplete)</p>
<p>Parsed JSON: <a href="http://pastebin.com/HS6eSABQ" rel="noreferrer">http://pastebin.com/HS6eSABQ</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:45:50.773",
"Id": "64229",
"Score": "0",
"body": "So why would you want to do this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:50:00.320",
"Id": "64230",
"Score": "0",
"body": "@jessehouwing I don't know how to to respond to that in any other way than \"because I do\". I don't understand your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:00:22.740",
"Id": "64232",
"Score": "0",
"body": "Well you could actually send the parameters as a json object with actual ints and strings... Makes the parsing a lot easier. You could even name these the same name as the constructor expects for easier matching..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:04:23.070",
"Id": "64233",
"Score": "0",
"body": "@jessehouwing The JSON data files are created manually, not with code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:20:24.867",
"Id": "64245",
"Score": "0",
"body": "There's no reason you couldn't hand-write easier to parse json..."
}
] |
[
{
"body": "<p>I'd compact the main loop as such:</p>\n\n<pre><code> for (var i = 0; i < tableDict.Count; i++)\n {\n var kvp = tableDict.ElementAt(i);\n var s = kvp.Key;\n\n // Key is \"( something )\" - entry is constructor\n if (brackets.IsMatch(s))\n {\n var constructor = s.WhitespaceRemoved();\n\n constructor = constructor.Substring(1, constructor.Length - 2); // Remove brackets\n\n var argsAsStrings = constructor.Split(',');\n var args = argsAsStrings.Select(num => (object)int.Parse(num)).ToArray();\n\n // I have only implemented this for the Color class.\n // I assume the constructor is comprised of ints.\n list.Add(new RawChanceTableEntry<T>(\n (T)Activator.CreateInstance(typeof(T), args),\n Convert.ToDouble(kvp.Value)));\n }\n else\n {\n // Parse string as a property of T instead\n var type = typeof(T);\n\n list.Add(new RawChanceTableEntry<T>(\n (T)type.GetProperty(s).GetValue(Activator.CreateInstance(type), null),\n Convert.ToDouble(kvp.Value)));\n }\n }\n</code></pre>\n\n<p>I also create a specific RegEx for the bracket matching that should be faster as it's compiled at the class level:</p>\n\n<pre><code> private static readonly Regex brackets = new Regex(@\"\\(([^\\)]+)\\)\", RegexOptions.Compiled);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:16:50.313",
"Id": "64244",
"Score": "0",
"body": "It's probably a lot faster to just check the first and last character using `string.Equals` than using a regex..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:47:58.030",
"Id": "64268",
"Score": "0",
"body": "Probably? Have you measured?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:10:26.007",
"Id": "64274",
"Score": "0",
"body": "I've just whipped up a program to measure this, and the regex wins out over 100,000 iterations for the string \"(192, 168, 0)\" - 75% faster. If I remove the closing parenthesis, the regex is 50% slower. If I remove the opening parenthesis, the regex is 75% faster again. Removing both parenthesis, the regex is still 75% faster. So, I think, over the long term, regex will perform pretty well. Looks like (on my computer) that ~2500 iterations is the tipping point where it performs better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T07:54:26.127",
"Id": "64310",
"Score": "0",
"body": "You seem to be correct. Turns out that the following is even faster: `var trimmed = text.Trim();\n if (trimmed[0] == '(' && trimmed[text.Length-1] == ')')`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T21:33:31.840",
"Id": "38538",
"ParentId": "38536",
"Score": "4"
}
},
{
"body": "<ol>\n<li>As you don't actually need the index of your <code>tableDict</code>, the more idiomatic way would be to use a <code>foreach</code> loop.</li>\n<li>From your earlier review requests I do remember that the properties are static properties on the <code>Color</code> class in which case you do not need to create an instance in order to obtain the value for the property.</li>\n<li>When using a regular expression you should make use of the grouping which will remove the need to split it up afterwards. Alternatively use <code>StartsWith</code> and <code>EndsWith</code> which would probably be faster than regex matching.\n<ul>\n<li>With grouping the regex could look like this: <code>\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)\\s*</code> (the <code>\\s*</code> is to match any whitespaces), then you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.groups%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Group</code> property of the <code>Match</code></a> to get the 3 numbers directly.</li>\n</ul></li>\n<li>You have code duplication in both code paths for parsing the probability and adding the new entry to the list.</li>\n</ol>\n\n<p>So the code could look like this (based on <code>StartsWith</code> and <code>EndsWith</code>):</p>\n\n<pre><code>foreach (var kvp in tableDict)\n{\n string s = kvp.Key.Trim(); // remove leading and trailing white spaces\n\n T item;\n\n if (s.StartsWith(\"(\") && s.EndsWith(\")\")) \n // Key is \"( something )\" - entry is constructor\n {\n var sCon = s.Substring(1, s.Length - 2); // Remove brackets \n\n var args = sCon.Split(',')\n .Select(num => (object)int.Parse(num))\n .ToArray();\n // I have only implemented this for the Color class.\n // I assume the constructor is comprised of ints.\n\n T item = (T)Activator.CreateInstance(typeof(T), args);\n }\n else // Parse string as a static property of T instead\n {\n T item = typeof(T).GetProperty(s).GetValue(null);\n }\n\n double prob = Convert.ToDouble(kvp.Value);\n var entry = new RawChanceTableEntry<T>(item, prob);\n list.Add(entry);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:19:50.307",
"Id": "38540",
"ParentId": "38536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T20:12:27.867",
"Id": "38536",
"Score": "4",
"Tags": [
"c#",
"reflection"
],
"Title": "Can my string to instance construction be improved?"
}
|
38536
|
<p>I'm attempting to create a final array with data pulled from 3 functions. The first two functions have all the data but then the 3rd function needs to run looping through one of the fields from function 2 in order to have the complete array at the end.</p>
<p>I'm looking for some advice and examples on how to fix this and or do it better. I have been advised promises would be a good solution, but could someone throw together a quick example so I can better get my head around it?</p>
<ol>
<li><p>In my services controller I have this as the page <a href="http://domain.com/services/all" rel="nofollow">here</a> and checks if the user is logged in.</p>
<pre><code>exports.all = function(req, res){
if (!req.isAuthenticated()){
res.redirect('login');
} else {
</code></pre></li>
<li><p>It uses the services database schema in the model to connect to the database and pull out the info I need:</p>
<pre><code>Database
.find()
.exec(function (err, services) {
if (err) {
return console.log(err);
}
if (!services) {
console.log('Failed to load any Services');
}
</code></pre></li>
<li><p>Once the services are found (multiple RPC/API services that have the same commands but different data returned), I async through each and connect.</p>
<pre><code> async.mapSeries(services, function(service, cb) {
connect(service);
client.getBalance(req.user._id, 6, function(err, balance) {
console.log(balance);
if (err) balance = "Offline";
client.getAddressesByAccount(req.user._id, function(err, address) {
console.log(address);
if (err) address = "Offline";
</code></pre></li>
<li><p>Once the first two lots of data is returned (the first is just a string number and the second is an array of addresses then for each address I want too async again and run a third command and then map the result of each to the corresponding address from above and output a final array to pass to the view.</p>
<pre><code> if(address != "Offline") {
async.mapSeries(address, function (item, callback){
// print the key
client.cmd('getreceivedbyaddress', item, 6, function(err, addressrecevied) {
if (err) console.log(err);
console.log(item + " = " + addressrecevied);
// console.log(JSON.stringify(addressrecevied, null, 4));
});
callback(); // tell async that the iterator has completed
}, function(err) {
console.log('iterating done');
});
};
// console.log(service.abr + " address = " + address);
console.log(service.abr + " balance = " + balance);
</code></pre></li>
<li><p>Callback that outputs the current top two results to the view variables:</p>
<pre><code> return cb(null, {
name: service.name,
display: service.display,
address: address,
balance: balance,
abr: service.abr,
});
});
});
</code></pre></li>
<li><p>Function to call the view and pass variables when done:</p>
<pre><code> }, function(err, services) {
// console.log(services);
if (err) {
return console.log(err);
}
req.breadcrumbs('Services', '/services/all');
res.render('services/index', {
title: 'Services',
icon: 'iconfa-cog',
summary: 'Services information',
services: services,
path : req.path,
breadcrumbs: req.breadcrumbs(),
udata : req.session.user
});
});
});
}
}
</code></pre></li>
</ol>
<p><strong>Work in progress</strong></p>
<pre><code>exports.all = function(req, res){
if (!req.isAuthenticated()){
res.redirect('login');
} else {
Wallet
.find()
.exec(function (err, wallets) {
if (err) {
return console.log(err);
}
if (!wallets) {
console.log('Failed to load any Wallets');
}
async.mapSeries(wallets, function(coin, cb) {
//
// Q FUNCTION START
//
function getServiceBalance(service) {
connect(service);
cmd = Q.denodeify(client.cmd.bind(client)),
getBalance = Q.denodeify(client.getBalance.bind(client)),
getAddressesByAccount = Q.denodeify(client.getAddressesByAccount.bind(client));
client.getBalance(req.user._id, 6, function(err, balance) {
console.log("Service: " + service.name + " - Balance: " + balance);
if (err) balance = "Offline";
});
// We're going to fill this in step by step...
var result = {
name: service.name,
display: service.display,
abr: service.abr
};
return getBalance(req.user._id, 6)
.then(function (balance) {
result.balance = balance;
console.log("Balance:" + balance);
console.log("User ID: " + req.user._id);
return getAddressesByAccount(req.user._id);
})
.then(function (addresses) {
result.address = addresses;
console.log("Addresses:" + result.address);
if (!_.isArray(addresses)) {
// Throwing errors inside `then` is fine: they will get caught in `catch` below
throw new Error('Could not get addresses array');
}
// For each address, call getreceivedbyaddress and gather results in array
return Q.all(_.map(addresses, function (address) {
return cmd('getreceivedbyaddress', address, 6);
}));
}).then(function (addressesReceived) {
result.addressReceived = addressesReceived;
}).catch(function (err) {
// Here's the catch method--the *one and only* place all errors propagate to.
console.log(err);
result.balance = 'Offline';
result.address = 'Offline';
result.addressReceived = 'Offline';
}).thenResolve(result);
}
exec().then(function (services) {
if (!services) {
throw new Error('Failed to load any Services');
}
return Q.all(_.map(services, getServiceBalance), function (serviceBalances) {
req.breadcrumbs('Services', '/services/all');
res.render('services/index', {
title: 'Services',
icon: 'iconfa-cog',
summary: 'Services information',
services: serviceBalances,
path : req.path,
breadcrumbs: req.breadcrumbs(),
udata : req.session.user
});
});
}).done();
//
// Q FUNCTION END
//
});
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:56:15.767",
"Id": "64252",
"Score": "1",
"body": "Have you considered ditching async/callbacks for promises, e.g. with [Q](https://github.com/kriskowal/q)? Edit: Sorry, I haven't noticed you already said that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:20:31.563",
"Id": "64259",
"Score": "0",
"body": "Just wrote you an example. Let me know if something ain't clear."
}
] |
[
{
"body": "<p>With <a href=\"https://github.com/kriskowal/q\" rel=\"nofollow\">Q promises</a> it would look more or less like this (taking <a href=\"http://chat.stackexchange.com/rooms/12303/discussion-between-dan-abramov-and-medoix\">this chat</a> into account):</p>\n\n<pre><code>var mongoose = require('mongoose') \n, Q = require('q')\n, Wallet = mongoose.model('Wallet')\n, _ = require('underscore')\n, bitcoin = require('bitcoin');\n\nfunction connect(coin) { \n return new bitcoin.Client({ \n host: coin.host, \n port: coin.port, \n user: coin.user, \n pass: coin.pass, \n }); \n}\n\nvar wallet = Wallet.find(),\n exec = Q.denodeify(wallet.exec.bind(wallet));\n\nfunction getServiceBalance(service, userID) {\n var client = connect(service)\n , cmd = Q.denodeify(client.cmd.bind(client))\n , getBalance = Q.denodeify(client.getBalance.bind(client))\n , getAddressesByAccount = Q.denodeify(client.getAddressesByAccount.bind(client));\n\n // We're going to fill this in step by step...\n var result = {\n name: service.name,\n display: service.display,\n abr: service.abr\n };\n\n return getBalance(userID, 6)\n .then(function (balance) {\n result.balance = balance;\n console.log(\"Balance:\" + balance);\n console.log(\"User ID: \" + userID);\n return getAddressesByAccount(userID);\n })\n .then(function (addresses) {\n console.log(\"Addresses:\", address);\n\n if (!_.isArray(addresses)) {\n // Throwing errors inside `then` is fine: they will get caught in `catch` below\n throw new Error('Could not get addresses array');\n }\n\n // For each address, call getreceivedbyaddress and gather results in array\n return Q.all(_.map(addresses, function (address) {\n return cmd('getreceivedbyaddress', address, 6).then(function (received) {\n return [address, received];\n });\n }));\n }).then(function (addressesReceived) {\n result.address = _.object(addressesReceived);\n }).catch(function (err) {\n // Here's the catch method--the *one and only* place all errors propagate to.\n console.log(err);\n\n result.balance = 'Offline';\n result.address = 'Offline';\n }).thenResolve(result);\n}\n\nexports.all = function (req, res) {\n if (!req.isAuthenticated()){\n res.redirect('login');\n } else {\n exec().then(function (services) {\n if (!services) {\n throw new Error('Failed to load any Services');\n }\n\n var promises = _.map(services, function (service) {\n return getServiceBalance(service, req.user._id);\n });\n\n return Q.all(promises);\n }).then(function (serviceBalances) {\n req.breadcrumbs('Services', '/services/all');\n res.render('services/index', {\n title: 'Services',\n icon: 'iconfa-cog',\n summary: 'Services information',\n services: serviceBalances,\n path : req.path,\n breadcrumbs: req.breadcrumbs(),\n udata : req.session.user\n });\n }).catch(function (err) {\n console.log('Error:', err);\n // TODO: render an error message?\n }).done();\n }\n}\n</code></pre>\n\n<p>Note that we could've gone side-effect-free and remove captured <code>result</code> variable from <code>getServiceBalance</code> but I don't think it's worth the hassle, and in fact debugging with state is more convenient, as long as the state is properly isolated.</p>\n\n<p>If you're looking to Q-style alternative to <code>mapSeries</code>, check out <a href=\"https://github.com/kriskowal/q/wiki/API-Reference#promiseall\" rel=\"nofollow\"><code>Q.all</code></a> and <a href=\"https://github.com/kriskowal/q/wiki/API-Reference#promiseallsettled\" rel=\"nofollow\"><code>Q.allSettled</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:49:28.963",
"Id": "64271",
"Score": "0",
"body": "Thanks Dan! I take it this is just a function and i will still need the top part of my page function to find the services and use async to go through each and run this function you have created? the getreceivedbyaddress in the code os the third function i could not get working and basically i need to run that command for each address returned in the previous function (returned in an array) and then add the result as a sub item in the array to the address above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:09:03.767",
"Id": "64273",
"Score": "0",
"body": "@medoix I've extracted some code in `getServiceBalance` but my code should be equivalent to yours (I'm also calling `exec` and “gathering” results into a single array below by virtue of `Q.all`). See code below `getServiceBalance`, on the very bottom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:10:59.077",
"Id": "64275",
"Score": "0",
"body": "@medoix Do you need to gather an array of results of calling `getreceivedbyaddress` for each item in `address` and then put it into `service` (my `result`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:12:34.333",
"Id": "64276",
"Score": "0",
"body": "@medoix So `getAddressesByAccount` may return an `\"Offline\"` string *or* an array? That's a bad design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:16:49.970",
"Id": "64277",
"Score": "0",
"body": "@medoix I fixed the code to call `getreceivedbyaddress` for each item in `addresses` (I think naming it `address` is misleading if this is an array...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T05:09:50.540",
"Id": "64300",
"Score": "0",
"body": "1. getServiceBalance returns a single value for each service (i believe it is a string.) eg. \"5.0001\" 2. getAddressesByAccount returns an array of addresses from each service as above (array) eg. ['fdkngkngdsgnlsdg', 'fdsfdsfdsfsds', 'dsfdsfdsfsdfs'] 3. getReceivedByAddress returns a single value as the first and needs to be run against each address from step 2 above. eg. \"6.00002\" 4. A new array needs to be created and past to the view that has the balance, the addresses and the balance of each address."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T05:55:17.357",
"Id": "64302",
"Score": "0",
"body": "@medoix: If I'm not mistaken, this is exactly what my code is doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:07:42.397",
"Id": "64305",
"Score": "0",
"body": "awesome, i have it compiling and i am just trying to debug as there are now no addresses being returned by getAddressesByAccount(req.user._id); so cannot see if the next part is working. The balance is collected and i can see the userID is right but the returned array of addresses is just []"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:12:20.777",
"Id": "64307",
"Score": "0",
"body": "I have attached my current code in progress with your changes to the bottom of my post above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T10:02:35.530",
"Id": "64315",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12303/discussion-between-dan-abramov-and-medoix)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:15:41.847",
"Id": "38545",
"ParentId": "38543",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38545",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T22:47:58.507",
"Id": "38543",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"callback"
],
"Title": "Node.js async callback hell"
}
|
38543
|
<p>I am not really having any problems with this. I'm just wondering if anybody has any ideas for a path for me to look down for bettering this little FF turn-based style of game in my free time.</p>
<p>I know somebody is going to complain about my global variables and the fact that I am not using object-oriented programming, but it will eventually get there. This is a boredom project that I'm plunking through.</p>
<p>Any advice or insight on any issues or ideas would be cool. And if somebody is looking into making a turn-based style of game, they can feel free to use up my code. Sorry about any bad formatting as well; I haven't really learned that yet.</p>
<pre><code>// random.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<ctime>
using namespace std;
int main()
{
int eHealth=100; //initial Enemy Health(based on enemy)
int pHealth=100; //initial Player Health
int eAttack=0; //Enemy Attack Strength(based on enemy)
int pAttack=0; //Player Attack Strength(based on level and items)
int selection=0; //Selection Variable for Battle Menue
int hPower=0; //Healing power Variable(random number)
int eSelection=0; //Enemies battle menu selection variable
int counter=0; //Counter to establish whos turn it is
int itemSelect=0; //Item inventory selection
int eMagic=50; //Enemies magic meter
int pMagic=50; //Players magic meter
cout<<pHealth<<" "<<eHealth<<endl; //player and enemy health levels
cout<<pMagic<<" "<<eMagic<<endl; //player and enemy magic levels
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl; //lines 31-33 are the battle menu appears frequently throught game
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
do //start of post test loop that runs the game until somebody is dead
{
if(counter==0)// if the counter variable is 0 it is the players turn
{
cin>>selection;
srand(static_cast<int>(time(0)));//randomize all the random variables
switch(selection)
{
case 1:// player chooses to ATTACK
pAttack=1+rand()%(35-1+1);//attack power can be between 1-35
cout<<"ATTACK "<<pAttack<<endl;
system("pause");
system("cls");
eHealth=eHealth-pAttack;
cout<<pHealth<<" "<<eHealth<<endl;
cout<<pMagic<<" "<<eMagic<<endl;
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl;
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
break;
case 2://Player chooses to heal, it costs 10 magic to heal so if you dont have enough magic you loose a turn
if(pMagic>9)
{
hPower=1+rand()%(35-1+1);//healing power can be any number between 1-35
cout<<"HEAL"<<hPower<<endl;
system("pause");
system("cls");
pHealth=pHealth+hPower;
pMagic=pMagic-10;
cout<<pHealth<<" "<<eHealth<<endl;
cout<<pMagic<<" "<<eMagic<<endl;
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl;
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
}//endIF
break;
case 3:// if player chooses to use item inventory system
cout<<"ITEM INVENTORY"<<endl;
cout<<"1.Potion Restores HP"<<endl;
cout<<"2.Ether Restores MP"<<endl;
cout<<"3.Bomb Causes Damage to all players"<<endl;
cout<<"4.Big Purple Dildo ?????"<<endl;
cout<<"5.Sticky Bomb Freezes oponent for 3 Truns"<<endl;
cin>>itemSelect;
switch(itemSelect)
{
case 1:
pHealth=pHealth+75;
system("cls");
cout<<pHealth<<" "<<eHealth<<endl;
cout<<pMagic<<" "<<eMagic<<endl;
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl;
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
break;
case 2:
break;
}//endItemSwitch
}//endSelectionSwitch
counter=1;// advances the counter to 1 to allow the enemies turn
}//endif
eSelection=rand() % 2+1;
switch(eSelection)
{
case 1:
eAttack=1+rand()%(35-1+1);
cout<<"ATTACK "<<eAttack<<endl;
system("pause");
system("cls");
pHealth=pHealth-eAttack;
cout<<pHealth<<" "<<eHealth<<endl;
cout<<pMagic<<" "<<eMagic<<endl;
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl;
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
break;
case 2:
if(eMagic>10)
{
hPower=1+rand()%(35-1+1);
cout<<"HEAL"<<hPower<<endl;
system("pause");
system("cls");
eMagic=eMagic-10;
eHealth=eHealth+hPower;
cout<<pHealth<<" "<<eHealth<<endl;
cout<<pMagic<<" "<<eMagic<<endl;
cout<<endl;
cout<<endl;
cout<<"1.Attack"<<endl;
cout<<"2.Heal"<<endl;
cout<<"3.Item"<<endl;
}
break;
}//endeSelectionSwitch
counter=0;
}while(eHealth > 1 && pHealth > 1);//loops while both players life is over 1 ends postest loop when players life or enemies falls below 1
system("pause");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:14:22.800",
"Id": "64256",
"Score": "5",
"body": "Learn how to write a function in C++!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:16:03.933",
"Id": "64257",
"Score": "0",
"body": "Havent gotten that far yet but I assume that turning my menu into a function would clean this up quite a bit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:17:56.523",
"Id": "64258",
"Score": "1",
"body": "Those variables aren't actually global; they're just all at the top of `main()`."
}
] |
[
{
"body": "<ul>\n<li><p><code>system(\"PAUSE\")</code> is entirely unnecessary here. You could do the same thing by simply clearing out <code>cin</code> and then reading a char.</p></li>\n<li><p>You should generally call <code>srand</code> once, at the beginning of the program. Once you've seeded the PRNG, it'll be good for a while -- probably much longer than this program will run. :) The way you're doing it, if the loop runs twice in the same second, and the user makes the same choices, the same outcome will occur.</p></li>\n<li><p>You are doing an awful lot of similar I/O over and over -- particularly, outputting a menu and getting a response. You should look at creating a function to do that, and then just call it whenever you want the user to choose something.</p></li>\n<li><p><code>using namespace std;</code> is laziness. :) If you don't want to type <code>std::</code> before that stuff, i'd recommend at least only <code>using</code> the names you actually use. Otherwise, you could run into interesting issues later when you decide to use the same names that the standard library used (which is not at all uncommon).</p></li>\n<li><p>You have a bunch of magic numbers. You'd do better to make those constants; then you could use them by name, and wouldn't need comments telling people what they mean. :)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:20:37.017",
"Id": "64260",
"Score": "0",
"body": "Thats what I figured I havent written functions yet just simple I/O stuff. I just learned about the rand function today so that was the inspiration that got me playing around. Im in between programming semesters so Im bored."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:23:01.807",
"Id": "64261",
"Score": "1",
"body": "@cHao: Obligatory post regarding `using namespace std`: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:29:43.483",
"Id": "64264",
"Score": "0",
"body": "Did not know tht was bad practice thats the way C++ was broken down to me... Thanks for the link Jamal. Makes sense"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:41:34.463",
"Id": "64267",
"Score": "0",
"body": "@JohnSnow: Also see http://codereview.stackexchange.com/questions/27986/text-based-rpg-game-using-classes/28065#28065 (my advice to someone who was working on a project a bit like yours). Includes a bit about the benefits of OOP near the end."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:16:51.593",
"Id": "38546",
"ParentId": "38544",
"Score": "7"
}
},
{
"body": "<ul>\n<li><p>Do not call <a href=\"http://en.cppreference.com/w/cpp/numeric/random/srand\" rel=\"nofollow noreferrer\"><code>std::srand()</code></a> repeatedly in a program. This will reset the seed at each call, causing <code>std::rand()</code> to produce the same random number. It's best to put this at the top of <code>main()</code> where it'll be called only once. It's also easier to maintain this way.</p>\n\n<p>Also prefer to call it like this (assuming you receive \"loss of data\" warnings from not having a cast):</p>\n\n<pre><code>std::srand(static_cast<unsigned int>(std::time(NULL)));\n</code></pre>\n\n<p>If you're using C++11, use <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> instead of <code>NULL</code>.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/8311058/n-or-n-or-stdendl-to-stdcout\">Prefer to use \"\\n\" when outputting a newline <em>without a buffer flush</em></a>. <code>std::endl</code> does both, so using it quite often could slow down your program.</p>\n\n<p>Here's an example of how it's used:</p>\n\n<pre><code>std::cout << \"\\nthis message contains two newlines\\n\";\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:34:55.760",
"Id": "64266",
"Score": "0",
"body": "Awesome tip fixed a problem that was in the back of my head every time I ran the program."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:29:56.677",
"Id": "38548",
"ParentId": "38544",
"Score": "5"
}
},
{
"body": "<p>Your code is repetitive; it looks like you are trying to \"unroll\" the entire storyline. Ideally, you should write each chunk of code just once. Figure out where the storyline rejoins itself — draw a <a href=\"https://www.google.com/search?q=flowchart&tbm=isch\" rel=\"nofollow\">flowchart</a>. Then write a function for each action (e.g. attack).</p>\n\n<p>Before you try to write the whole game, start small. Try to implement simple primitives first.</p>\n\n<p>You need to be able to pass values to a function, and using global variables would be a bad idea. Instead, group related variables into a <code>struct</code>:</p>\n\n<pre><code>struct Character {\n int health;\n int attack;\n int magic;\n};\n\nvoid heal(Character &c) {\n int healingPower = 1 + rand() % 35;\n c.magic -= 10;\n c.health += healingPower;\n}\n\nvoid print(const Character &c, std::ostream &out) {\n // TODO\n}\n\nint main() {\n Character self, enemy;\n\n print(self, std::cout);\n heal(self);\n print(self, std::cout);\n}\n</code></pre>\n\n<p>Verify that the healing process works. Debug that, and build from there!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T21:31:56.720",
"Id": "133604",
"Score": "0",
"body": "Using `self` like that sent my snake-senses tingling... :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:47:55.960",
"Id": "38550",
"ParentId": "38544",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T23:07:05.420",
"Id": "38544",
"Score": "6",
"Tags": [
"c++",
"beginner",
"console",
"battle-simulation",
"role-playing-game"
],
"Title": "Battle system in C++"
}
|
38544
|
<p>I am working on a website and I've created four text/image news blocks. I am not sure if it's the right / most efficient way to do this.</p>
<p>See <a href="http://jsfiddle.net/cTM3L/" rel="nofollow">my code here</a> at jsfiddle</p>
<p><strong>HTML:</strong></p>
<pre><code><div id="wrapper">
<div id="header">
<div id="logo">
<a href="index.html"><img src="img/logo.png" alt="logo"></a>
</div>
</div>
<div id="headNews">
<div class="headNewsItem">
<a href="#">
<div class="imageContainer">
<img src="img/headNews1.jpg" width="242" height="124" alt="headNewsImage1">
</div>
<div class="textContainer">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
</a>
</div>
<div class="headNewsItem">
<a href="#">
<div class="imageContainer">
<img src="img/headNews2.jpg" width="242" height="124" alt="headNewsImage2">
</div>
<div class="textContainer">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
</a>
</div>
<div class="headNewsItem">
<a href="#">
<div class="imageContainer">
<img src="img/headNews3.jpg" width="242" height="124" alt="headNewsImage3">
</div>
<div class="textContainer">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
</a>
</div>
<div id="headNewsItemLast">
<a href="#">
<div id="imageContainer">
<img src="img/headNews4.jpg" width="242" height="124" alt="headNewsImage4">
</div>
<div class="textContainer">Lorem ipsum dolor sit amet, consectetur adipisicing elit</div>
</a>
</div>
</div>
<div id="midSection">
fasdfasf
</div>
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>body{
background: url("../img/bg.jpg") repeat-x;
}
#wrapper{
margin: 0 auto;
width: 980px;
}
#header{
float: left;
width: 100%;
height: 70px;
}
#logo img{
float: left;
margin-top: 20px;
}
#headNews{
float: left;
margin-top: 20px
}
.headNewsItem{
float: left;
margin-right: 4px;
width: 242px;
height: 184px;
}
#headNewsItemLast{
float: left;
width: 242px;
height: 184px;
}
.headNewsItem img {
display: block;
}
#headNewsItemLast img{
display: block;
}
.textContainer{
font-family: Arial;
line-height: 21px;
font-size: 14px;
color: #c8cbcb;
height: 40px;
padding: 10px 15px;
background-image: linear-gradient(#262828,#1c1e1e);
}
#midSection{
float:left;
width: 100%;
height: 800px;
margin-top: 20px;
background-color: #FFF;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T02:17:37.957",
"Id": "64290",
"Score": "1",
"body": "Honestly, what you have looks fine to me. It may be worth looking at some of the frameworks like Bootstrap to see if either they do what you want and you can just use them or if their CSS gives you any ideas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T10:21:06.047",
"Id": "64317",
"Score": "0",
"body": "Ok nice to hear, but is there no way to get rid of the styling of the last news block, because it is almost the same except the right-margin?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:28:17.380",
"Id": "64330",
"Score": "0",
"body": "But this will cause strange behaviour because there are no dimensions set..\nIs there no way to inherit all properties from .headNewsItem except the margin?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:22:08.647",
"Id": "64350",
"Score": "0",
"body": "Honestly, when it looks like a table, use <table>. The 'Table considered harmful' meme has to be taken with a grain of salt. It will be less html, less css and easier to maintain."
}
] |
[
{
"body": "<p>As I mentioned in a comment, those blocks look like a 1 row table.</p>\n\n<p>I redid your code with a table and it is actually shorter ( I could take out a few divs ) and it does require less css. I also extracted the style on the image into a css rule.</p>\n\n<p><a href=\"http://jsfiddle.net/konijn_gmail_com/w9f6F/4/\" rel=\"nofollow\">http://jsfiddle.net/konijn_gmail_com/w9f6F/4/</a></p>\n\n<p>HTML:</p>\n\n<pre><code><div id=\"wrapper\">\n <div id=\"header\">\n <div id=\"logo\"> <a href=\"index.html\"><img src=\"img/logo.png\" alt=\"logo\"/></a>\n\n </div>\n </div>\n <table>\n <tr>\n <td class=\"headNewsItem\"> <a href=\"#\">\n <img src=\"img/headNews1.jpg\" alt=\"headNewsImage1\"/>\n <div class=\"textContainer\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit\n </div>\n </a> \n </td>\n <td class=\"headNewsItem\"> <a href=\"#\">\n <img src=\"img/headNews2.jpg\" alt=\"headNewsImage2\"/>\n <div class=\"textContainer\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit\n </div>\n </a> \n </td>\n <td class=\"headNewsItem\"> <a href=\"#\">\n <img src=\"img/headNews3.jpg\" alt=\"headNewsImage3\"/>\n <div class=\"textContainer\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit\n </div>\n </a> \n </td>\n <td class=\"headNewsItem\"> <a href=\"#\">\n <img src=\"img/headNews4.jpg\" alt=\"headNewsImage4\"/>\n <div class=\"textContainer\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit\n </div>\n </a> \n </td>\n </tr>\n </table>\n <div id=\"midSection\">fasdfasf</div>\n</div>\n</code></pre>\n\n<p>CSS : </p>\n\n<pre><code>@import url(reset.css);\n body {\n background: url(\"../img/bg.jpg\") repeat-x;\n}\n#wrapper {\n margin: 0 auto;\n width: 980px;\n}\n#header {\n float: left;\n width: 100%;\n height: 70px;\n}\n#logo img {\n float: left;\n margin-top: 20px;\n}\n#headNews {\n float: left;\n margin-top: 20px\n}\n.headNewsItem {\n float: left;\n width: 242px;\n height: 184px;\n}\n.headNewsItem img {\n width: 242px;\n height:124px;\n}\n.textContainer {\n font-family: Arial;\n line-height: 21px;\n font-size: 14px;\n color: #c8cbcb;\n height: 40px;\n padding: 10px 15px;\n background-image: linear-gradient(#262828, #1c1e1e);\n}\n#midSection {\n float:left;\n width: 100%;\n height: 800px;\n margin-top: 20px;\n background-color: #FFF;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T13:55:24.620",
"Id": "64442",
"Score": "0",
"body": "Is it justified to use tables in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T19:46:06.677",
"Id": "64466",
"Score": "0",
"body": "In my opinion, yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:27:41.807",
"Id": "64594",
"Score": "0",
"body": "Wrong. Tables are for tabular data, not layout. If you had to come up with labels for each of your table's columns, what would they be? If each column has the same label, then you should not be using a table. When you have tags that have specific meaning, you can't just use them just because you like how they look. Assistive devices such as screen readers treat tables in a special way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:43:18.200",
"Id": "64596",
"Score": "0",
"body": "Tables go both ways, row 1 is image, row 2 is text, I merged the rows because I could. How would a screen reader go wrong with this table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T16:29:17.397",
"Id": "64601",
"Score": "0",
"body": "The only way this data could be presented as tabular data is for there to be one news item per row, with the title in one column and the image in the other. What you have is a misuse of the table element."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:54:40.023",
"Id": "38575",
"ParentId": "38552",
"Score": "-1"
}
},
{
"body": "<p>I wouldn't say that there's a right or a wrong way to do it. The only problem with what you're doing is that it only works well when you have a device that is wide enough to display all of those items on one line (ie. it doesn't work so well for handheld devices).</p>\n\n<p>My recommendation would be to use the CSS multi-column module, which is responsive by default without having to use media queries.</p>\n\n<p><a href=\"http://jsfiddle.net/cTM3L/1/\" rel=\"nofollow\">http://jsfiddle.net/cTM3L/1/</a></p>\n\n<pre><code><div id=\"wrapper\">\n <div id=\"header\">\n <div id=\"logo\"> <a href=\"index.html\"><img src=\"img/logo.png\" alt=\"logo\"></a>\n\n </div>\n </div>\n <ul id=\"headNews\">\n <li class=\"headNewsItem\">\n <a href=\"#\">\n <div class=\"imageContainer\">\n <img src=\"img/headNews1.jpg\" width=\"242\" height=\"124\" alt=\"headNewsImage1\">\n </div>\n <p class=\"textContainer\">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>\n </a>\n </li>\n\n <li class=\"headNewsItem\">\n <a href=\"#\">\n <div class=\"imageContainer\">\n <img src=\"img/headNews2.jpg\" width=\"242\" height=\"124\" alt=\"headNewsImage2\"> \n </div>\n <p class=\"textContainer\">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>\n </a>\n </li>\n\n <li class=\"headNewsItem\">\n <a href=\"#\">\n <div class=\"imageContainer\">\n <img src=\"img/headNews3.jpg\" width=\"242\" height=\"124\" alt=\"headNewsImage3\">\n </div>\n <p class=\"textContainer\">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>\n </a>\n </li>\n\n <li class=\"headNewsItem\">\n <a href=\"#\">\n <div id=\"imageContainer\">\n <img src=\"img/headNews4.jpg\" width=\"242\" height=\"124\" alt=\"headNewsImage4\">\n </div>\n <p class=\"textContainer\">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>\n </a>\n </li>\n </ul>\n <div id=\"midSection\">fasdfasf</div>\n</div>\n</code></pre>\n\n<p>The CSS:</p>\n\n<pre><code>@import url(reset.css);\n body {\n background: url(\"../img/bg.jpg\") repeat-x;\n}\n#wrapper {\n margin: 0 auto;\n}\n#header {\n height: 70px;\n}\n#logo img {\n float: left;\n margin-top: 20px;\n}\n#headNews {\n margin-top: 20px;\n -webkit-columns: 242px;\n -moz-columns: 242px;\n columns: 242px;\n -webkit-column-gap: 10px;\n -moz-column-gap: 10px;\n column-gap: 10px;\n list-style: none;\n padding-left: 0;\n}\n.headNewsItem {\n margin-right: 4px;\n width: 242px;\n -webkit-column-break-inside: avoid;\n page-break-inside: avoid; /* Moz is weird */\n break-inside: avoid;\n margin-top: 10px;\n}\n.headNewsItem:first-child {\n margin-top: 0;\n}\n.headNewsItem a, .headNewsItem img {\n display: block;\n}\n.textContainer {\n font-family: Arial;\n line-height: 21px;\n font-size: 14px;\n color: #c8cbcb;\n height: 40px;\n padding: 10px 15px;\n background-image: linear-gradient(#262828, #1c1e1e);\n}\n#midSection {\n width: 100%;\n margin-top: 20px;\n background-color: #FFF;\n}\n</code></pre>\n\n<p>There's quite a few other things I would change here, but most of them are not relevant to the requested reviewed. Just make sure you're using the most specific tag that appropriately describes your content: avoid using div for everything (check out some of those HTML5 tags you seem to have missed such as header, figure/figcaption, aside, etc.). Also, there are better ways to clear floats than to use more floats.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T16:45:50.577",
"Id": "38705",
"ParentId": "38552",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38705",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T00:07:15.890",
"Id": "38552",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "Is this the right way to space four news blocks right from each other?"
}
|
38552
|
<p>I was reading about opaque pointers and decided to try it with queues. Please review my code and let me know if there are any errors and how to improve code quality and performance.</p>
<p>It uses lines to enqueue and dequeue. All lines have fixed sizes and dequeue/enqueue never share a line. New lines are added only when all lines are full, not counting the dequeue line. The lines are stored in a linked list.</p>
<p><strong>queue.h</strong></p>
<pre><code>#ifndef QUEUE_H
#define QUEUE_H
#include <stdlib.h>
#include <assert.h>
#define QU_SUCCESS 0
#define QU_ERROR 1
typedef struct Queue Queue;
Queue *qu_allocate_custom(size_t lines, size_t capacity);
Queue *qu_allocate(void);
void qu_free(Queue *queue);
int qu_enqueue(Queue *queue, void *content);
void *qu_dequeue(Queue *queue);
size_t qu_get_count(Queue *queue);
void qu_shrink_to_fit(Queue *queue);
#endif
</code></pre>
<p><strong>queue.c</strong></p>
<pre><code>#include "queue.h"
#define QU_DEFAULT_LINES 4
#define QU_DEFAULT_LINE_CAPACITY 50
//Data structures
/*
The line has a fixed size. It contains a link to the next and can hold void *.
I'm using double pointers because I expect it to act like an array of void *.
So, when I do position++ it will move sizeof(void *) and point to the next
stored address. Also the end of the line, if it's not full, can be delimited by
simply doing *position = NULL.
*/
typedef struct Line Line;
struct Line {
void **start;
void **position;
void **end;
Line *next;
};
/*
The queue structure just stores meta info and points to lines. The member index
is there because I thought it would make the the other functions simpler since
they won't have to deal with special cases. They just treat it as if it were a
regular line. And that's ok because most functions take the line that comes before
the one they are operating on as an argument so they don't have to walk through
the list to find that node in order to update the pointer to the next;
The queue stores only elements of sizeof(void *), whatever is received by enqueue
will be sent back by dequeue, so it can store a pointer to anything and
also work with other data types of size up to sizeof(void *).
The queue works like this:
1 - When it's created, lines of fixed sizes are allocated
2 - Dequeue is set to the first position, enqueue to the second
3 - Both just walk along the list and never share a Line
4 - If dequeue moves to the same line as enqueue, enqueue will go to the next.
If the line is not full, one past the last element will contain NULL to indicate
that's the end.
5 - If enqueue finishes filling a line, it will check if the next is empty. If
that's the case, it will go there. Otherwise dequeue is certainly using the line.
So enqueue will try to create a new line.
*/
struct Queue {
Line index; //just a pointer to the first line
Line *enqueue;
Line *dequeue;
size_t count;
size_t line_capacity;
};
//Internal methods
//Take the element that comes before, so it doesn't have to walk through the list
static void free_line_after( Line *previous )
{
assert(previous->next != NULL);
Line *line = previous->next;
previous->next = line->next;
free(line);
}
static void free_all_lines( Line *first )
{
void *next;
for(Line *ite = first; ite != NULL; ite = next){
next = ite->next;
free(ite);
}
}
/*
Allocate a line and space for its contents in a single call to malloc since the
lines have fixed sizes. There's no point in calling malloc twice here.
*/
static Line *push_line_after( Line *previous, size_t capacity )
{
assert(previous != NULL && capacity > 0);
//Allocate space for Line and its contents
Line *new_line = malloc(sizeof(Line) + capacity * sizeof(void **));
if(new_line == NULL)
return NULL;
//Put on the list
new_line->next = previous->next;
previous->next = new_line;
//Set all pointers and add a NULL delimiter so dequeue will be able to recognize
//this line has nothing to dequeue
new_line->start = (void **)(new_line + 1);
new_line->position = new_line->start;
new_line->end = new_line->start + capacity;
*new_line->position = NULL;
return new_line;
}
static inline Line *next_line( Queue *queue, Line *current )
{
return (current->next != NULL) ? current->next : queue->index.next;
}
//Since it's an opaque pointer, setters/getters
size_t qu_set_capacity(Queue *queue, size_t new_capacity)
{
if(new_capacity > 0)
queue->line_capacity = new_capacity;
return queue->line_capacity;
}
size_t qu_get_count(Queue *queue)
{
return queue->count;
}
//Public methods
/*
Create a new queue with `lines` starting lines, each with `capacity` for pointers
*/
Queue *qu_allocate_custom( size_t lines, size_t capacity )
{
if(lines < 2 || capacity < 1)
return NULL;
Queue *new_queue = malloc(sizeof(Queue));
if(new_queue == NULL)
return NULL;
//If the value is garbage, push_line_after will break the list
new_queue->index.next = NULL;
//Create all starting lines or cancel the operation
Line *previous = &new_queue->index;
while(lines-- > 0){
previous = push_line_after(previous, capacity);
if(previous == NULL){
free_all_lines(new_queue->index.next);
free(new_queue);
return NULL;
}
}
//Dequeue starts behind so it doesn't have to iterate through the whole list
//on the first call
new_queue->dequeue = new_queue->index.next;
new_queue->enqueue = new_queue->dequeue->next;
new_queue->count = 0;
new_queue->line_capacity = capacity;
return new_queue;
}
Queue *qu_allocate( void )
{
return qu_allocate_custom( QU_DEFAULT_LINES, QU_DEFAULT_LINE_CAPACITY );
}
void qu_free(Queue *queue)
{
free_all_lines(queue->index.next);
free(queue);
}
int qu_enqueue( Queue *queue, void *content )
{
//First enqueue will check if the current line is full.
if(queue->enqueue->end == queue->enqueue->position){
//If it is it will check if the next line if empty and go there if it is
Line *next = next_line(queue, queue->enqueue);
if(next != queue->dequeue)
queue->enqueue = next;
//If the next line is not empty, it will try to create a new line
else {
next = push_line_after(queue->enqueue, queue->line_capacity);
if(next == NULL)
return QU_ERROR;
queue->enqueue = next;
}
}
//Store, update position, update count
*queue->enqueue->position++ = content;
++queue->count;
return QU_SUCCESS;
}
/*Dequeue sets position back to zero when it starts working on a line. NULL also
delimits the line end when enqueue is moved before the line is full (when dequeue
tells it to move).*/
void *qu_dequeue( Queue *queue )
{
//If this line is empty
if(queue->dequeue->end == queue->dequeue->position
|| *queue->dequeue->position == NULL){
//Check if there's something on the next line
Line *next = next_line(queue, queue->dequeue);
if(next->start == next->position)
return NULL;
//Finish here and go there
queue->dequeue->position = queue->dequeue->start;
queue->dequeue = next;
//Move enqueue if it's on this new line
if(queue->dequeue == queue->enqueue){
queue->enqueue = next_line(queue, queue->enqueue);
//And add a delimiter if it's not full
if(queue->dequeue->end != queue->dequeue->position)
*queue->dequeue->position = NULL;
}
//Don't forget to set the position to 0 so it can be processed
queue->dequeue->position = queue->dequeue->start;
}
//There's something to return
--queue->count;
return *queue->dequeue->position++;
}
//Since dequeue is always behind enqueue, all lines between enqueue and dequeue
//must be empty and thus safe to free
void qu_shrink_to_fit( Queue *queue )
{
//First process all lines after enqueue
Line *last = queue->enqueue;
while(last->next != NULL){
if(last->next == queue->dequeue)
return;
free_line_after(last);
}
//Now process all starting lines behind dequeue
last = &queue->index;
while(last->next != queue->dequeue)
free_line_after(last);
}
</code></pre>
<p><strong>And some code to perform simple tests</strong></p>
<pre><code>#include <stdio.h>
#include "queue.h"
int main(void)
{
Queue *queue = qu_allocate();
if(queue == NULL){
return 1;
}
char *words[] = {
"Highest Priority",
"High Priority",
"Almost High Priority",
"Regular Priority",
"Almost Low Priority",
"Low Priority",
"Lowest Priority",
"He who laughs last, laughs best.",
""
};
for(char **ite = words; **ite != '\0'; ++ite){
qu_enqueue(queue, *ite);
}
qu_enqueue(queue, "About the middle.");
printf("Count is: %zu\n", qu_get_count(queue));
qu_dequeue(queue);
qu_dequeue(queue);
printf("Count is: %zu after dequeuing 2 elements\n\n", qu_get_count(queue));
for(char **ite = words; **ite != '\0'; ++ite){
qu_enqueue(queue, *ite);
}
qu_enqueue(queue, "Before last.");
qu_enqueue(queue, "Last.");
qu_shrink_to_fit(queue);
for(char *location; (location = qu_dequeue(queue)) != NULL;){
puts(location);
}
for(int i = 0; i < 500; ++i)
qu_dequeue(queue);
printf("Count is: %zu\n", qu_get_count(queue));
qu_free(queue);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your header looks fine - opaque pointers are as simple as that. Don't forget\nthe <code>const</code> on function parameters (pointers) where possible.</p>\n\n<p>Hmmm, a <code>Line</code> structure with double-pointers. That looks suspect. Double\npointers are usually unnecessary. We'll see what becomes of these later...\nIt would have been kind to the reader to give a line or two of comment to\ndescribe the queue and its components and the purpose of these double\npointers.</p>\n\n<p>The use of <code>previous</code> as a parameter name is unsatisfying, somehow\nconfusing. In <code>free_line_after</code> I'm expecting it to free the line after 'this'\none or the 'current' one, so <code>previous</code> jars a bit. I would avoid 'this'\nthough and call it just <code>l</code>.</p>\n\n<p>The <code>start</code> parameter to <code>free_all_lines</code> is misnamed as there is a <code>start</code>\nfield in <code>Line</code>. The two are unrelated (I think) and should have different\nnames.</p>\n\n<p>In <code>push_line_after</code> you are allocating</p>\n\n<pre><code>Line *new_line = malloc(sizeof(Line) + capacity * sizeof(void **));\n</code></pre>\n\n<p>So this makes me think that your Line structure is intended to hold the line\ndata beyond the end of the structure, as in:</p>\n\n<pre><code>struct Line {\n ...\n Line *next;\n char data[];\n};\n</code></pre>\n\n<p>You instantiate <code>Line</code> in <code>Queue</code> for some reason (I imagine from your comment\nthat you just need a pointer to a <code>Line</code> but I haven't checked) so you'd have\nto have <code>char data[1]</code> to keep that. But this is the normal way to extend a\nstructure with variable data. If you do this, you don't need the double\npointers but instead just keep indices. </p>\n\n<p>Maybe I have misinterpreted your intentions, so I will stop there. I haven't\nread through the rest (as I say double pointers are normally unnecessary and\nmake reading code difficult).\n<hr>\n<strong>EDIT</strong> I don't have time to look in detail at the code, but the explanations you \nadded certainly help. I do think the mechanism is rather odd - having two queue mechanisms in one. Your tests only test one of the mechanisms with the code in \nconditional in <code>qu_enqueue</code>:</p>\n\n<pre><code>if(queue->enqueue->end == queue->enqueue->position){\n ....\n}\n</code></pre>\n\n<p>never entered. Setting <code>QU_DEFAULT_LINE_CAPACITY</code> to something small rectifies this and the code seems to work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T23:06:28.713",
"Id": "64389",
"Score": "0",
"body": "Thank you for replying, I added comments to explain my reasoning."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T19:39:40.897",
"Id": "38586",
"ParentId": "38556",
"Score": "3"
}
},
{
"body": "<p>I did something very similar to this in assembly a looooong long time ago, so I'm going to compare and contrast for the sake of nostalgia. And helping you out, that too.</p>\n\n<p>The main difference in our top level designs is that I was storing <em>values</em> as elements of the <code>Line</code>, whereas you are storing <code>void*</code>. The reason I didn't always store <code>void*</code> was that it didn't require any additional memory management for consuming code by default. If I needed to do memory management separately, I could do that by making it a queue of pointers. In your code, you <em>must</em> either store pointers to static data or <code>malloc</code> and <code>mfree</code> each element separately. I see those two possibilities as a hazard in the case that the consumer doesn't yet know whether dynamic allocation is necessary, or worse, if <code>void*</code> to static data and <code>void*</code> to something on the heap have been mixed in the same <code>Queue</code> somehow. The end result will be an error (trying to <code>mfree</code> static data) or memory leaks (not <code>mfree</code>ing heap data). It's especially error prone because if you need to <code>mfree</code>, you have to do it soon after you dequeue it (possibly happening in many functions) or it leaks, so switching between static data and heap will be hazardous.</p>\n\n<p>On the other hand, believe me when I say you've avoided the following headaches by storing only <code>void*</code>:</p>\n\n<ul>\n<li><p>Destructors. You can handle disposal of the structure when it's dequeued or instead store that pointer elsewhere and not dispose of it in your consuming code. My ASM version had to be initialized with an optional pointer to a destructor function, yours leaves that up to the consumer.</p></li>\n<li><p>Lots of pointer math internally. It is waaaay simpler to allocate an array of a <code>void*</code> and come up with a pointer to element <code>i</code> than it is to allocate an array of arbitrary sized structures, which may need to have their element size adjusted for alignment, etc. etc.</p></li>\n</ul>\n\n<p>That would be a really tough thing to change, and ultimately a matter of documentation more than quality, so let's move on.</p>\n\n<p>The fact that your <code>Queue</code> involves a <code>Line</code> by value that doesn't have an accompanying buffer of elements is somewhat of a misuse of the structure. I can see where it looks like it might be necessary in order to have <code>free_line_after</code> and <code>push_line_after</code> take and/or return a <code>Line*</code>, but you can make those functions and the <code>Queue</code> structure simpler and clearer by eliminating the <code>index</code> from <code>Queue</code>. Instead:</p>\n\n<pre><code>\n\nstruct Queue {\n Line* enqueue;\n Line* dequeue;\n size_t count;\n size_t line_capacity;\n}\n\nstatic void free_line( Line** ppLine ) {\n Line* toFree = *ppLine;\n assert(toFree !== NULL);\n *ppLine = toFree->next;\n free(toFree);\n}\n\n// theoretically could make this return a bool indicating error/no error,\n// but it's easier to remember that NULL means error.\nstatic Line* push_line_before( Line** ppLine, size_t capacity ) {\n Line* before = *ppLine;\n Line* new_line = malloc(sizeof(Line) + capacity * sizeof(void **));\n if (new_line == NULL)\n return NULL;\n\n new_line->next = before;\n *ppLine = new_line;\n /* do initialization the same way you did it... */\n return new_line;\n}\n\nstatic void why_this_way_is_better(Queue* someQueue) {\n // Queue has no Line-valued member, and yet we can still use the same\n // functions for a Queue member...\n free_line( &(someQueue->dequeue) );\n push_line_before( &(someQueue->enqueue) );\n // ... as the ones for a line member\n free_line( &(someQueue->dequeue->next) );\n push_line_before( &(someQueue->enqueue->next) );\n}\n\n</code></pre>\n\n<p>Again, that will change a few things logically throughout your code and header, but it will end up far cleaner and clearer than it started. You've got pointers to pointers in C, an often underestimated advantage over other languages, and so far you're doing great with them. If you can handle using them for pointers to arrays of pointers, you can handle using pointers to members as objects.</p>\n\n<p>Other than that, the nature of the task demands a bunch of hairy pointer-chasing and a little bit of pointer math, which is tough to read. Stuff like <code>return *queue->dequeue->position++;</code> takes a second for me to digest fully. If your comments were at all lacking, I would want some of the longer statements to be broken up and have some intermediates made into local variables with names. However, your comments spell out what's going on very clearly, so I don't think that counts against you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T08:50:05.387",
"Id": "38614",
"ParentId": "38556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T05:29:29.163",
"Id": "38556",
"Score": "5",
"Tags": [
"c",
"queue"
],
"Title": "Queue implementation in C"
}
|
38556
|
<p>I have an application that essentially "pings" all of the servers on my network. I have about 100 servers, and this ping will happen every 10 seconds.</p>
<pre><code>public class HealthChecker {
private static List<InetSocketAddress> servers = new ArrayList<InetSocketAddress>();
public static void main(String[] args){
// not shown: populating servers list
new Thread(){
public void run(){
while (true){
try {
Thread.sleep(10*1000);
for (final InetSocketAddress server : servers){
new Thread(){
public void run(){
Socket connection = new Socket();
try {
connection.connect(server, 5*1000);
} catch (IOException e) {
servers.remove(server);
}
}
}.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
</code></pre>
<p>So, do you think this code can be improved? I really feel like opening a new thread every time I make a connection isn't a good thing. </p>
<p><strong>EDIT:</strong>
So looking over all the proposed solutions, they are all very good, and I will over the next week try and all and see which one appears to be the most efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:13:41.143",
"Id": "64342",
"Score": "0",
"body": "I have added an answer with an example which utilizes ThreadPoolExecutor"
}
] |
[
{
"body": "<ol>\n<li><p>Instead of spawning a new thread every time you probably should execute them on <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool%28int%29\" rel=\"nofollow\">a thread pool</a>.</p></li>\n<li><p>You want to wrap your <code>servers</code> list in a <code>Collections.synchronizedList()</code> or else you might run into unexpected race conditions when removing multiple servers at the same time from the list from two different threads.</p></li>\n</ol>\n\n<p><strong>Update</strong></p>\n\n<p>Disclaimer: I don't write much Java so the below is mostly put together from the Java docs and might not compile and could certainly be improved but should illustrate the idea of using a threadpool for executing the network check.</p>\n\n<p>Apparently there is no way of stopping it nicely but I leave that to you.</p>\n\n<pre><code>public class ServerTester implements Runnable {\n\n private InetSocketAddress server;\n List<InetSocketAddress> servers;\n\n public ServerTester(InetSocketAddress server, List<InetSocketAddress> servers){\n this.server = server;\n this.servers = servers;\n }\n\n @Override\n public void run() {\n Socket connection = new Socket();\n try {\n connection.connect(server, 5*1000);\n } catch (IOException e) {\n servers.remove(server);\n }\n }\n}\n\npublic class HealthChecker {\n private static List<InetSocketAddress> servers = Collections.synchronizedList(new ArrayList<InetSocketAddress>());\n\n public static void main(String[] args) {\n // not shown: populating servers list\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n new Thread() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(10*1000);\n for (final InetSocketAddress server : servers){\n Runnable tester = new ServerTester(server, servers);\n executor.execute(tester);\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }.start();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:49:55.000",
"Id": "64309",
"Score": "0",
"body": "Would you mind showing an example of using a Thread Pool (if you can provide one)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T09:54:40.320",
"Id": "64313",
"Score": "0",
"body": "@Dyla: Updated my answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:43:19.847",
"Id": "38558",
"ParentId": "38557",
"Score": "3"
}
},
{
"body": "<p>You are not pinging, you are establishing a TCP connection. The three way handshake is way more overhead than a simple ICMP ECHO_REQUEST (aka ping). Have a look at <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#isReachable%28int%29\" rel=\"nofollow\"><code>InetAddress.isReachable(int)</code></a>.</p>\n\n<p>Using a threadpool was already stated. But it would be best to avoid threading completely. Unfortunately I didn't find a non blocking ICMP implementation for Java. But if you go the protocol stack a bit up (TCP or better UDP) you can use Java NIO.</p>\n\n<p>Personally I wouldn't write a dedicated monitor application, I would use existing stable software like Nagios or OpenNMS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T08:03:08.673",
"Id": "64311",
"Score": "0",
"body": "Unfortunately I have to write my own application, unless you are aware of an application with an API... not much of help to me. As mentioned before, I would love an example of thread pooling if you could, or link me possibly to some sources if that isn't too much trouble. Finally, I've read that InetAdress.isReachable doesn't work, is that false?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T08:10:06.587",
"Id": "64312",
"Score": "0",
"body": "InetAdress.isReachable() has restrictions. Read the API. If you can't use ICMP then go the NIO way (preferably over UDP). BTW OpenNMS might have a Java API."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T07:36:05.423",
"Id": "38559",
"ParentId": "38557",
"Score": "3"
}
},
{
"body": "<p>Here's an example adapted to your case which uses ThreadPoolExecutor.</p>\n\n<p>This example allows a configurable throughput while establishing TCP connections to servers.</p>\n\n<p>Checking <em>Future.get()</em> for each submitted worker thread ensures that no servers are checked more than others.</p>\n\n<p>What happens here:</p>\n\n<ol>\n<li>Target domains are added to a list</li>\n<li>If the domain is an unknown host (DNS unreachable) than it's skipped.</li>\n<li>Resolvable domains are submitted as 1 domain per 1 thread into the pool.</li>\n<li>If the pool gets overflown by <em>PingWork</em> threads, that submission is delayed for 3 seconds until the pool is ready to accept.</li>\n<li>Each TCP port 80 connection has a timeout of 5 seconds. </li>\n<li>When there are no exceptions thrown by a TCP connection to a certain host, it is assumed reachable and not reported.</li>\n<li>When all <em>PingWork</em> threads finish, main thread waits for 10 seconds until next round.</li>\n</ol>\n\n<p>Here's the source</p>\n\n<pre><code>// package\n// imports\n\npublic class Main {\n private static List<InetSocketAddress> servers = \n new ArrayList<InetSocketAddress>();\n\n public static void main(String[] args) \n throws InterruptedException, ExecutionException {\n String[] domains = new String[]{\n \"3Com.com\",\n // etc. etc.\n \"Kai.com\"\n };\n\n for (String hostname : domains) {\n try {\n servers.add(\n new InetSocketAddress(\n InetAddress.getByName(hostname), \n 80\n )\n );\n } catch (UnknownHostException e) {\n System.out.println(\"Unknown host: \" + hostname);\n }\n }\n\n System.out.println(\n \"Total number of target servers: \" + servers.size()\n );\n\n BlockingQueue<Runnable> work = \n new ArrayBlockingQueue<Runnable>(5);\n\n ThreadPoolExecutor pool = new ThreadPoolExecutor(\n 5, // corePoolSize\n 10, // maximumPoolSize\n 5000, // keepAliveTime\n TimeUnit.MILLISECONDS, // TimeUnit\n work // workQueue\n );\n\n pool.prestartAllCoreThreads();\n\n pool.setRejectedExecutionHandler(\n new RejectedExecutionHandler() {\n @Override\n public void rejectedExecution(\n Runnable r, \n ThreadPoolExecutor executor\n ) {\n System.out.println(\"Work queue is currently full\");\n try {\n Thread.sleep(3000);\n } catch (InterruptedException ignore) {\n\n }\n executor.submit(r);\n }\n }\n );\n\n Collection<Future<?>> futures = new LinkedList<Future<?>>();\n\n while (true) {\n for (InetSocketAddress server : servers) {\n futures.add(pool.submit(new PingWork(server)));\n }\n for (Future<?> future : futures) {\n future.get();\n }\n System.out.println(\n \"All servers checked. Will wait for 10 seconds until next round\"\n );\n Thread.sleep(10000);\n }\n\n }\n\n private static class PingWork implements Runnable {\n private static final int TIMEOUT = 5000;\n private InetSocketAddress target;\n\n private PingWork(InetSocketAddress target) {\n this.target = target;\n }\n\n @Override\n public void run() {\n Socket connection = new Socket();\n boolean reachable;\n\n try {\n try {\n connection.connect(target, TIMEOUT);\n } finally {\n connection.close();\n }\n reachable = true;\n } catch (Exception e) {\n reachable = false;\n }\n\n if (!reachable) {\n System.out.println(\n String.format(\n \"%s:%d was UNREACHABLE\",\n target.getAddress(),\n target.getPort()\n )\n );\n }\n }\n }\n}\n</code></pre>\n\n<p>Here's the output of 30 domain sample</p>\n\n<pre><code> Total number of target servers: 30\n Work queue is currently full\n Work queue is currently full\n Amdahl.com/129.212.11.21:80 was UNREACHABLE\n All servers checked. Will wait for 10 seconds until next round\n Work queue is currently full\n Work queue is currently full\n Amdahl.com/129.212.11.21:80 was UNREACHABLE\n All servers checked. Will wait for 10 seconds until next round \n</code></pre>\n\n<p>You can increase the <em>maximumPoolSize</em> of <em>ThreadPoolExecutor</em> in order to get all domains into queue in just one iteration. However I left that part for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:01:25.837",
"Id": "38568",
"ParentId": "38557",
"Score": "6"
}
},
{
"body": "<p>ICMP does not appear to be an option for you... you say you are pinging 'servers', but I think what you mean is that you are pinging 'services' (actual applications running on the server). You connect to the host:port combination. You could even have multiple services running on a single server.</p>\n\n<p>A brief run-down of your code suggests:</p>\n\n<ol>\n<li>every 10 seconds (or so) you create a bunch of threads.</li>\n<li>each thread tries to connect to a server:port combination.</li>\n<li>if the connect fails, you remove the server</li>\n</ol>\n\n<p>It has already been pointed out to you that the remove process should use some form of locking... using a simple ArrayList will lead to corrupt lists as each of the 100 threads may try to modify the list at the same time.</p>\n\n<p>I suggest a different approach.</p>\n\n<p>I recommend creating a thread for each server you want to monitor. As the server comes available, it adds the server to the 'alive' list. As the server 'drops', it removes it from the alive list.</p>\n\n<p>The simple Socket connection to the server is all you need to worry about when it is alive. The monitor thread can sit there waiting for the socket to die. If it dies, it tries to reconnect. You can choose a different approach for monitoring the TCP state, but, the model of having a separate continuous thread for each monitored server, and the concept of having a maintained collection of 'alive' threads is the important part.</p>\n\n<p>Consider the following class, which has a convenient Main method:</p>\n\n<pre><code>package ping;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class ServiceMonitor {\n\n private final class Monitor implements Runnable {\n\n private final InetSocketAddress tomonitor;\n\n public Monitor(InetSocketAddress service) {\n super();\n this.tomonitor = service;\n }\n\n\n @Override\n public void run() {\n while (true) {\n try (Socket remote = new Socket()) {\n System.out.println(\"Trying to Connect to \" + tomonitor);\n remote.connect(tomonitor, 5*1000);\n if (registerRemote(tomonitor, this)) {\n try (InputStream is = remote.getInputStream()) {\n byte[] buffer = new byte[512];\n // This will likely never loop, simply wait for it to close.\n while (is.read(buffer) >= 0) {\n // still alive ...\n }\n } catch (IOException ioe) {\n // unexpected condition, but this means the server is dead... that's all we need to know.\n //ioe.printStackTrace();\n } finally {\n deregisterRemote(tomonitor, this);\n }\n }\n } catch (SocketTimeoutException ste) {\n // simply try again....\n } catch (IOException e) {\n // could not connect to remote?\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e1) {\n return;\n }\n //e.printStackTrace();\n }\n }\n\n\n }\n\n\n }\n\n private final ConcurrentHashMap<InetSocketAddress, Monitor> alive = new ConcurrentHashMap<>();\n private final ThreadGroup tgroup = new ThreadGroup(\"Server Monitor Group\");\n private final Lock monlock = new ReentrantLock();\n private final Condition idlecondition = monlock.newCondition();\n private final Condition busycondition = monlock.newCondition();\n\n\n public ServiceMonitor() {\n\n }\n\n public void monitorService(InetSocketAddress remote) {\n if (!alive.containsKey(remote)) {\n Thread mthread = new Thread(tgroup, new Monitor(remote), \"Monitor Thread: \" + remote.toString());\n mthread.setDaemon(true);\n mthread.start();\n }\n }\n\n private boolean registerRemote(InetSocketAddress tomonitor, Monitor monitor) {\n if (null == alive.putIfAbsent(tomonitor, monitor)) {\n // do any notification if you need to that a server is available....\n System.out.println(\"Register \" + tomonitor + \" Currently \" + alive.size() + \" alive\");\n monlock.lock();\n try {\n busycondition.signalAll();\n } finally {\n monlock.unlock();\n }\n return true;\n }\n return false;\n }\n\n private void deregisterRemote(InetSocketAddress tomonitor, Monitor monitor) {\n if (alive.replace(tomonitor, monitor, monitor)) {\n // we are currently the holder... good.\n alive.remove(tomonitor);\n // do any notification if you need to that a server is 'down'.\n System.out.println(\"Deregister \" + tomonitor + \" Currently \" + alive.size() + \" alive\");\n monlock.lock();\n try {\n if (alive.isEmpty()) {\n idlecondition.signalAll();\n }\n } finally {\n monlock.unlock();\n }\n }\n }\n\n public void waitAllDead() {\n monlock.lock();\n try {\n while (!alive.isEmpty()) {\n idlecondition.await();\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n Thread.currentThread().interrupt();\n } finally {\n monlock.unlock();\n }\n }\n\n public void waitBusy() {\n monlock.lock();\n try {\n while (alive.isEmpty()) {\n busycondition.await();\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n Thread.currentThread().interrupt();\n } finally {\n monlock.unlock();\n }\n }\n\n public static void main(String[] args) {\n ServiceMonitor monitor = new ServiceMonitor();\n for (int i = 0; i < 10; i++) {\n monitor.monitorService(new InetSocketAddress(\"localhost\", 40000 + i));\n }\n monitor.waitBusy();\n monitor.waitAllDead();\n System.out.println(\"Complete!\");\n }\n}\n</code></pre>\n\n<p>This class monitors services simply by their active TCP socket. It has a main method which monitors 10 ports from 40000 through 40009.</p>\n\n<p>Here is a simple dummy server that creates services on those ports.... (and I used it for testing).</p>\n\n<pre><code>package ping;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.util.Random;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic class Service extends Thread {\n\n private final Socket socket;\n\n public Service(int port, Socket socket) {\n super(\"Service for local:\" + port + \" remote:\" + socket.getInetAddress().toString());\n this.socket = socket;\n }\n\n @Override\n public void run() {\n try (\n OutputStream os = socket.getOutputStream();\n InputStream is = socket.getInputStream();\n ) {\n final int delay = (1 + (int)(Math.random() * 5));\n Thread.sleep(delay * 1000);\n System.out.println(Thread.currentThread().getName() + \" Sleeping for \" + delay + \" seconds.\");\n os.flush();\n } catch (IOException | InterruptedException ioe) {\n ioe.printStackTrace();\n } finally {\n System.out.println(\"Closing \" + Thread.currentThread().getName());\n }\n }\n\n public static void main(String[] args) throws NumberFormatException, IOException {\n int cnt = 10;\n for (int i = 0; i < cnt; i++) {\n final int port = 40000 + i;\n Runnable controller = new Runnable() {\n public void run() {\n try (\n ServerSocket ss = new ServerSocket(port);\n ) {\n int port = ss.getLocalPort();\n System.out.println(\"Listening on port \" + port);\n Socket sock = null;\n Random rand = ThreadLocalRandom.current();\n while ((sock = ss.accept()) != null) {\n Service service = new Service(port, sock);\n sock = null;\n service.start();\n Thread.sleep(5000 + rand.nextInt(15000));\n }\n } catch (IOException | InterruptedException ioe) {\n ioe.printStackTrace();\n }\n };\n };\n Thread thread = new Thread(controller, \"Controller \" + i);\n thread.start();\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:47:17.720",
"Id": "38577",
"ParentId": "38557",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T06:05:29.763",
"Id": "38557",
"Score": "10",
"Tags": [
"java",
"concurrency",
"server"
],
"Title": "Concurrent multi-server pinging in Java"
}
|
38557
|
<p>I was hoping to get some general feedback and thoughts about my implementation of a generic priority queue. Please feel free to be as critical as you want or see fit.</p>
<p>Generic priority queue implementation (please note that the <code>PriorityConvention</code> can be <code>None</code>, <code>HighestPriorityInFront</code>, <code>LowestPriorityInFront</code>):</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using Utilities.Enums.Generics;
using Utilities.Interfaces;
namespace Utilities.Classes.Generics
{
/// <summary> A generic priority queue implementation. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <seealso> cref="T:System.Collections.Generic.IEnumerable{T}". </seealso>
/// <seealso> cref="T:Utilities.Interfaces.IPriorityQueue{T}". </seealso>
/// <typeparam name="T"> Generic type parameter, where T
/// must implement the IComparable interface. </typeparam>
[Serializable]
public class PriorityQueue<T> : IEnumerable<T>, IPriorityQueue<T>
where T : IComparable<T>
{
#region Private Member Variables
private readonly List<T> items; /* The items in the queue */
#endregion
#region Properties
/// <summary> Gets the convention this priority queue uses to sort and insert items. </summary>
/// <value> The ordering convention. </value>
public PriorityConvention OrderingConvention { get; private set; }
/// <summary> Gets the number of items that are in the priority queue. </summary>
/// <value> The number of items in the priority queue. </value>
public Int32 Count
{
get { return items.Count; }
}
#endregion
#region Constructors
/// <summary> Initializes a new instance of the PriorityQueue class. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="ArgumentException"> Thrown when the convention is specified
/// as PriorityConvention.None. </exception>
/// <param name="convention">
/// (Optional) the convention to use when sorting and inserting items (this cannot be changed
/// after the priority queue is created).
/// </param>
public PriorityQueue(PriorityConvention convention = PriorityConvention.HighestPriorityInFront)
{
if (convention == PriorityConvention.None)
{
throw new ArgumentException("No valid ordering convention was specified", "convention");
}
OrderingConvention = convention;
items = new List<T>();
}
/// <summary> Initializes a new instance of the PriorityQueue class. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="ArgumentException"> Thrown when the convention is specified
/// as PriorityConvention.None. </exception>
/// <param name="priorityItems"> The items to initialize the priority queue with. </param>
/// <param name="convention">
/// (Optional) the convention to use when sorting and inserting items (this cannot be changed
/// after the priority queue is created).
/// </param>
public PriorityQueue(IEnumerable<T> priorityItems,
PriorityConvention convention = PriorityConvention.HighestPriorityInFront)
: this(convention)
{
if (convention == PriorityConvention.None)
{
throw new ArgumentException("No valid ordering convention was specified", "convention");
}
AddRange(priorityItems);
}
#endregion
#region Public Methods
/// <summary> Gets the enumerator for the priority queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <returns> The enumerator for the priority queue. </returns>
public IEnumerator<T> GetEnumerator()
{
return items.GetEnumerator();
}
/// <summary> Gets the enumerator for the priority queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <returns> The enumerator for the priority queue. </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary> Adds an item to the priority queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to add. </param>
public void Add(T item)
{
Insert(item);
}
/// <summary>
/// Adds the items to the priority queue. This method checks if the enumerable is null
/// and only iterates of the items once.
/// </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="itemsToAdd"> An IEnumerable&lt;T&gt; of items to add to the priority queue. </param>
public void AddRange(IEnumerable<T> itemsToAdd)
{
if (itemsToAdd == null)
{
return;
}
foreach (T item in itemsToAdd)
{
Insert(item);
}
}
/// <summary> Clears all the items from the priority queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
public void Clear()
{
items.Clear();
}
/// <summary> Clears all the items starting at the specified start index. </summary>
/// <remarks> David Venegoni, Jan 03 2014. </remarks>
/// <param name="startIndex"> The start index. </param>
/// <returns> The number of items that were removed from the priority queue. </returns>
public Int32 Clear(Int32 startIndex)
{
Int32 numberOfItems = items.Count - 1 - startIndex;
items.RemoveRange(startIndex, numberOfItems);
return numberOfItems;
}
/// <summary> Clears the number of items specified by count
/// from the priority queue starting at specified start index. </summary>
/// <remarks> David Venegoni, Jan 03 2014. </remarks>
/// <param name="startIndex"> The start index. </param>
/// <param name="count"> Number of items to remove. </param>
public void Clear(Int32 startIndex, Int32 count)
{
items.RemoveRange(startIndex, count);
}
/// <summary> Clears all the items that satisfy the specified predicate function. </summary>
/// <remarks> David Venegoni, Jan 03 2014. </remarks>
/// <param name="predicateFunction"> The predicate function to use in determining
/// which items should be removed. </param>
/// <returns> The number of items that were removed from the priority queue. </returns>
public Int32 ClearWhere(Func<T, Boolean> predicateFunction)
{
return items.RemoveAll(predicateFunction.Invoke);
}
/// <summary> Pops an item from the front of the queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="InvalidOperationException"> Thrown when no items exist
/// in the priority queue. </exception>
/// <returns> An item from the front of the queue. </returns>
public T PopFront()
{
if (items.Count == 0)
{
throw new InvalidOperationException("No elements exist in the queue");
}
T item = items[0];
items.RemoveAt(0);
return item;
}
/// <summary> Pops an item from the back of the queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="InvalidOperationException"> Thrown when no items exist
/// in the priority queue. </exception>
/// <returns> An item from the back of the queue. </returns>
public T PopBack()
{
if (items.Count == 0)
{
throw new InvalidOperationException("No elements exist in the queue");
}
Int32 tail = items.Count - 1;
T item = items[tail];
items.RemoveAt(tail);
return item;
}
/// <summary> Peeks at the item at the front queue without removing the item. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="InvalidOperationException"> Thrown when no items exist
/// in the priority queue. </exception>
/// <returns> The item at the front of the queue. </returns>
public T PeekFront()
{
if (items.Count == 0)
{
throw new InvalidOperationException("No elements exist in the queue");
}
return items[0];
}
/// <summary> Peeks at the item at the back of the queue without removing the item. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="InvalidOperationException"> Thrown when no items exist
/// in the priority queue. </exception>
/// <returns> The item at the back of the queue. </returns>
public T PeekBack()
{
if (items.Count == 0)
{
throw new InvalidOperationException("No elements exist in the queue");
}
return items[items.Count - 1];
}
/// <summary> Pops the specified number of items from the front of the queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the number of items to pop exceeds the number of items in the priority
/// queue.
/// </exception>
/// <param name="numberToPop"> Number of items to pop from the front of the queue. </param>
/// <returns> The items from the front of the queue. </returns>
public IEnumerable<T> PopFront(Int32 numberToPop)
{
if (numberToPop > items.Count)
{
throw new ArgumentException(@"The numberToPop exceeds the number
of elements in the queue", "numberToPop");
}
var poppedItems = new List<T>();
while (poppedItems.Count < numberToPop)
{
poppedItems.Add(PopFront());
}
return poppedItems;
}
/// <summary> Pops the specified number of items from the back of the queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <exception cref="ArgumentException">
/// Thrown when the number of items to pop exceeds the number of items in the priority
/// queue.
/// </exception>
/// <param name="numberToPop"> Number of items to pop from the back of the queue. </param>
/// <returns> The items from the back of the queue. </returns>
public IEnumerable<T> PopBack(Int32 numberToPop)
{
if (numberToPop > items.Count)
{
throw new ArgumentException(@"The numberToPop exceeds the number
of elements in the queue", "numberToPop");
}
var poppedItems = new List<T>();
while (poppedItems.Count < numberToPop)
{
poppedItems.Add(PopBack());
}
return poppedItems;
}
/// <summary> Queries if the priority queue is empty. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <returns> true if the priority queue empty, false if not. </returns>
public Boolean IsEmpty()
{
return items.Count == 0;
}
#endregion
#region Private Methods
/// <summary> Inserts the given item into the queue. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to insert into the queue. </param>
private void Insert(T item)
{
if (items.Count == 0)
{
items.Add(item);
}
else if (OrderingConvention == PriorityConvention.HighestPriorityInFront)
{
InsertAscending(item);
}
else
{
InsertDescending(item);
}
}
/// <summary>
/// Inserts the specified item into the priority queue
/// (using the PriorityConvention.HighestPriorityInFront convention).
/// </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to insert into the queue. </param>
private void InsertAscending(T item)
{
T tail = items[items.Count - 1];
Int32 comparedToTail = item.CompareTo(tail);
if (comparedToTail <= 0) // Less or equal to the than the current minimum
{
items.Add(item);
}
else if (items.Count == 1)
{
/*
* Must assume that since there is only one item
* in the list and that the function has reached
* this point, that the current item is greater
* than the item in the queue, so needs to be
* inserted in front
*/
items.Insert(0, item);
}
else
{
FindIndexAndInsertItemAscending(item);
}
}
/// <summary>
/// Inserts the specified item into the priority queue
/// (using the PriorityConvention.LowestPriorityInFront convention).
/// </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to insert into the queue. </param>
private void InsertDescending(T item)
{
T tail = items[items.Count - 1];
Int32 comparedToTail = item.CompareTo(tail);
if (comparedToTail >= 0) // Greater than or equal to current maximum
{
items.Add(item);
}
else if (items.Count == 1) // See InsertAscending for explanation
{
items.Insert(0, item);
}
else
{
FindIndexAndInsertItemDescending(item);
}
}
/// <summary>
/// Searches for the index where the given item should be place in the queue and,
/// subsequently, inserts the item at the specified index.
/// </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to insert into the queue. </param>
private void FindIndexAndInsertItemAscending(T item)
{
Int32 lowerBoundIndex = 0;
Int32 upperBoundIndex = items.Count - 1;
Int32 currentMedianIndex = upperBoundIndex / 2; // No need to floor, integers will always round towards 0
/*
* Will determine which side of the median the current item should be placed,
* then updating the lower and upper bounds accordingly until the proper index
* is found, at which the point the item will be inserted.
*/
while (true)
{
Int32 comparisonResult = item.CompareTo(items[currentMedianIndex]);
switch (comparisonResult)
{
case 1:
upperBoundIndex = currentMedianIndex;
break;
case -1:
lowerBoundIndex = currentMedianIndex;
break;
default:
FindIndexAndInsertItem(item,
currentMedianIndex,
PriorityConvention.HighestPriorityInFront);
return;
}
if (AreEndConditionsMet(item, lowerBoundIndex, upperBoundIndex, ref currentMedianIndex))
{
break;
}
}
}
/// <summary>
/// Searches for the index where the given item should be place in the queue and,
/// subsequently, inserts the item at the specified index.
/// </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <param name="item"> The item to insert into the queue. </param>
private void FindIndexAndInsertItemDescending(T item)
{
// See FindIndexAndInsertItemAscending for explanation
Int32 lowerBoundIndex = 0;
Int32 upperBoundIndex = items.Count - 1;
Int32 currentMedianIndex = upperBoundIndex / 2;
while (true)
{
Int32 comparisonResult = item.CompareTo(items[currentMedianIndex]);
switch (comparisonResult)
{
case 1:
lowerBoundIndex = currentMedianIndex;
break;
case -1:
upperBoundIndex = currentMedianIndex;
break;
default:
FindIndexAndInsertItem(item,
currentMedianIndex,
PriorityConvention.LowestPriorityInFront);
return;
}
if (AreEndConditionsMet(item, lowerBoundIndex, upperBoundIndex, ref currentMedianIndex))
{
break;
}
}
}
/// <summary>
/// Searches for the index where the given item should be place in the queue and,
/// subsequently, inserts the item at the specified index.
/// </summary>
/// <remarks>
/// This method will be called when the specified item equals
/// another item (can be more than one) within the queue.
/// David Venegoni, Jan 02 2014.
/// </remarks>
/// <param name="item"> The item to insert into the queue. </param>
/// <param name="currentIndex"> The index in which to start at. </param>
/// <param name="priorityConvention"> The priority convention to use when finding the index. </param>
private void FindIndexAndInsertItem(T item, Int32 currentIndex, PriorityConvention priorityConvention)
{
Int32 currentPosition = currentIndex;
Int32 condition = priorityConvention == PriorityConvention.HighestPriorityInFront ? 1 : -1;
Boolean isLastElement = false;
while (item.CompareTo(items[currentPosition]) != condition)
{
++currentPosition;
if (currentPosition < items.Count) // Make sure the index does not go out of range
{
continue;
}
isLastElement = true;
break;
}
if (isLastElement)
{
items.Add(item);
}
else
{
items.Insert(currentPosition, item);
}
}
/// <summary>
/// Determines if the current lower bound, upper bound, and median index are
/// at the end conditions, if not, the current median index is updated
/// using the lower and upper bound indices.
/// </summary>
/// <remarks>
/// The end conditions are:
/// 1) Is the upper bound index 0?
/// 2) Is the lower bound index the last index in the queue?
/// 3) Is the new median index (calculated using lower and
/// upper bound indices) the same as the current median index?
/// David Venegoni, Jan 02 2014.
/// </remarks>
/// <param name="item"> The item to insert if the end conditions are met. </param>
/// <param name="lowerBoundIndex"> Zero-based index of the lower bound. </param>
/// <param name="upperBoundIndex"> Zero-based index of the upper bound. </param>
/// <param name="currentMedianIndex"> [in,out] The current median index. </param>
/// <returns> true if end conditions met, false if not. </returns>
private Boolean AreEndConditionsMet(T item, Int32 lowerBoundIndex,
Int32 upperBoundIndex, ref Int32 currentMedianIndex)
{
if (upperBoundIndex == 0)
{
items.Insert(0, item);
return true;
}
if (lowerBoundIndex == items.Count - 1)
{
items.Add(item);
return true;
}
/*
* If the new median is the same as the old median,
* then this item's priority will always be +1 from
* the median's priority, not to mention that continuing
* to use that median will result in an infinite loop
*/
Int32 newMedianIndex = (upperBoundIndex + lowerBoundIndex) / 2;
if (currentMedianIndex == newMedianIndex)
{
items.Insert(currentMedianIndex + 1, item);
return true;
}
currentMedianIndex = newMedianIndex;
return false;
}
#endregion
}
}
</code></pre>
<p>Interface (<code>IPriorityQueue<T></code>):</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Utilities.Interfaces
{
/// <summary> Generic priority queue interface. </summary>
/// <remarks> David Venegoni, Jan 02 2014. </remarks>
/// <typeparam name="T"> Generic type parameter. Must implement the IComparable interface. </typeparam>
public interface IPriorityQueue<T>
where T : IComparable<T>
{
/// <summary> Gets the number of items in the priority queue. </summary>
/// <value> The number of items in the priority queue. </value>
Int32 Count { get; }
/// <summary> Adds an item to the priority queue, inserting it with respect to its priority. </summary>
/// <param name="item"> The item to add. </param>
void Add(T item);
/// <summary> Adds a range of items to the priority queue, inserting them with respect to their priority. </summary>
/// <param name="itemsToAdd"> An IEnumerable&lt;T&gt; of items to add to the priority queue. </param>
void AddRange(IEnumerable<T> itemsToAdd);
/// <summary> Clears all the items from the priority queue. </summary>
void Clear();
/// <summary> Clears all the items starting at the specified start index. </summary>
/// <param name="startIndex"> The start index. </param>
/// <returns> The number of items that were removed from the priority queue. </returns>
Int32 Clear(Int32 startIndex);
/// <summary> Clears the number of items specified by count from the priority queue starting at specified start index. </summary>
/// <param name="startIndex"> The start index. </param>
/// <param name="count"> Number of items to remove. </param>
void Clear(Int32 startIndex, Int32 count);
/// <summary> Clears all the items that satisfy the specified predicate function. </summary>
/// <param name="predicateFunction"> The predicate function to use in determining which items should be removed. </param>
/// <returns> The number of items that were removed from the priority queue. </returns>
Int32 ClearWhere(Func<T, Boolean> predicateFunction);
/// <summary> Pops an item from the front of the queue. </summary>
/// <returns> An item from the front of the queue. </returns>
T PopFront();
/// <summary> Pops an item from the back of the queue. </summary>
/// <returns> An item from the back of the queue. </returns>
T PopBack();
/// <summary> Peeks at the item at the front of the queue, but does not remove it from the queue. </summary>
/// <returns> The item that is at the front of the queue. </returns>
T PeekFront();
/// <summary> Peek at the item at the back of the queue, but does not remove it from the queue. </summary>
/// <returns> The item that is at the back of the queue. </returns>
T PeekBack();
/// <summary> Pops the specified number of items from the front of the queue. </summary>
/// <param name="numberToPop"> Number of items to pop from the front of the queue. </param>
/// <returns> The items that were popped from the front of the queue. </returns>
IEnumerable<T> PopFront(Int32 numberToPop);
/// <summary> Pops the specified number of items from the back of the queue. </summary>
/// <param name="numberToPop"> Number of items to pop from the back of the queue. </param>
/// <returns> The items that were popped from the back of the queue. </returns>
IEnumerable<T> PopBack(Int32 numberToPop);
/// <summary> Queries if the priority queue is empty. </summary>
/// <returns> true if the priority queue is empty, false if not. </returns>
Boolean IsEmpty();
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>General</strong></p>\n\n<p>Priority queues in general keep a queue per priority. While your implementation achieves that, it is associated with a lot of copying when inserting and removing data due to the array backing structure of <code>List</code>. Using a <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.sortedlist%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>SortedList</code></a> with the priority as key and <code>Queue<T></code> as values would probably be faster and less code.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/10613186/priority-queue-implementation-in-c-sharp\">This question on SO</a> shows a basic implementation based on a SortedDictionary.</p>\n\n<p><strong>Technical</strong></p>\n\n<ol>\n<li><p>For consistency I would consider implementing all three <code>Clear</code> methods with the same interface (returning the number of elements removed) and all go through one method. Something like this:</p>\n\n<pre><code>public int Clear()\n{\n return Clear(0);\n}\n\npublic int Clear(int startIndex)\n{\n return Clear(startIndex, Count - 1 - startIndex);\n}\n\npublic int Clear(int startIndex, int count)\n{\n // Note: RemoveRange will throw if index and count are not a valid range within the list\n list.RemoveRange(startIndex, count);\n return count;\n}\n</code></pre></li>\n<li><p>Consider changing <code>PopFront</code> to use an enumerator which avoids creating a temporary copy:</p>\n\n<pre><code>public IEnumerable<T> PopFront(Int32 numberToPop)\n{\n if (numberToPop > items.Count)\n {\n throw new ArgumentException(@\"The numberToPop exceeds the number \n of elements in the queue\", \"numberToPop\");\n }\n\n while (numberToPop-- > 0)\n {\n yield return PopFront();\n }\n}\n</code></pre>\n\n<p>Same for <code>PopBack</code></p></li>\n<li><p><code>FindIndexAndInsertItemAscending</code> and <code>FindIndexAndInsertItemDescending</code> are almost exactly the same except for the <code>PriorityConvention</code> passed to <code>FindIndexAndInsertItem</code> so they should be refactored into one method.</p>\n\n<p>Also <a href=\"http://msdn.microsoft.com/en-us/library/w4e7fxsh%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>List</code> defines a <code>BinarySearch</code></a> method which should simplify your code somewhat. No need to reinvent the wheel.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:06:10.917",
"Id": "64378",
"Score": "0",
"body": "Thanks Chris for your feedback, especially #2, it never occurred to me to use yield. It is interesting that you mentioned #1 because originally I did return an int for the Clear(), but later changed it to void because I was using three lines of code for Clear() as I used a local variable to store items.Count, then cleared the items, and returned the local variable, it just was not very clean and/or elegant. Your implementation however, is very clean, and probably would not have thought of it had you not mentioned it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:14:55.857",
"Id": "64380",
"Score": "0",
"body": "I do have a few questions in regards to using a SortedList<K, V>. The way I am reading it, it seems like you are suggesting that I should implement it with the key (K) = the priority, and the value (V) = Queue<T>, is this correct? Additionally, if the key is the priority, then it would seem that I would need to change the generic type parameters to PriorityQueue<TKey, TValue> much like it is seen here http://www.codeproject.com/Articles/126751/Priority-queue-in-C-with-the-help-of-heap-data-str."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:15:29.060",
"Id": "64381",
"Score": "0",
"body": "The main motivation behind having the single type parameter is to make the class act as much like a queue as possible, I will do some benchmarking tests and post the results, interesting to see which is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T07:11:32.527",
"Id": "64413",
"Score": "1",
"body": "@DavidVenegoni: Yes the idea is that you have a key which is the priority and the value which is your entity. Right now it is expected that the entity knows it's own priority value through the `IComparable` which can be problematic because now the entity is comparing itself solely on priority and not other attributes. You effectively intermingle two properties of the entities (what it represents and it's priority)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T10:50:16.707",
"Id": "38564",
"ParentId": "38560",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "38564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T07:36:19.717",
"Id": "38560",
"Score": "7",
"Tags": [
"c#",
"generics",
"queue"
],
"Title": "PriorityQueue<T> implementation"
}
|
38560
|
<p>I asked <a href="https://stackoverflow.com/questions/20908568/calculating-daily-and-monthly-sales-from-text-file">this question</a> yesterday, and now I have come up with this code:</p>
<p><strong>stock.h</strong></p>
<pre><code>#ifndef stock_stock_h
#define stock_stock_h
#include <iostream>
class stock {
public:
stock() {
itemName = " ";
unitPrice = " ";
quantityPurchased = " ";
day = " ";
month = " ";
year = " ";
}
stock(std::string itemName,std::string unitPrice,std::string quantityPurchased,
std::string day,std::string month,std::string year);
std::string getItemName();
std::string getUnitPrice();
std::string getQuantityPurchased();
std::string getDateDay();
std::string getDateMonth();
std::string getDateYear();
void setItemDescription(std::string itemName);
void setUnitPrice(std::string unitPrice);
void setQuantityPurchased(std::string quantityPurchased);
void setDateDay(std::string day);
void setDateMonth(std::string month);
void setDateYear(std::string year);
private:
std::string itemName,unitPrice,quantityPurchased,day,month,year;
};
#endif
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "stock.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
#include <cassert>
#include <vector>
#include <iomanip>
using namespace std;
stock::stock(string itemName,string unitPrice,string quantityPurchased,string day,string month,string year) {
setItemDescription(itemName);
setUnitPrice(unitPrice);
setQuantityPurchased(quantityPurchased);
setDateDay(day);
setDateMonth(month);
setDateYear(year);
};
string stock::getItemName() {
return itemName;
}
string stock::getUnitPrice() {
return unitPrice;
}
string stock::getQuantityPurchased() {
return quantityPurchased;
}
string stock::getDateDay() {
return day;
}
string stock::getDateMonth() {
return month;
}
string stock::getDateYear() {
return year;
}
void stock::setItemDescription(std::string itemName) {
this->itemName = itemName;
}
void stock::setUnitPrice(std::string unitPrice) {
this->unitPrice = unitPrice;
}
void stock::setQuantityPurchased(std::string quantityPurchased) {
this->quantityPurchased = quantityPurchased;
}
void stock::setDateDay(std::string day) {
this->day = day;
}
void stock::setDateMonth(std::string month) {
this->month = month;
}
void stock::setDateYear(std::string year) {
this->year = year;
}
int main(){
vector<stock> itemDetails;
string line;
string itemName;
string unitPrice;
string quantityPurchased;
string inputMonth;
string day;
string month;
string year;
double uPrice;
int qPurchased;
double totalIndividualItemSales;
double totalSalesOfMonthDec = 0.0;
double totalSalesOfMonthJan = 0.0;
double totalSalesOfMonthFeb = 0.0;
//put your text file name inside the ""
ifstream readFile("/Users/jeremykeh/Desktop/stock.txt");
while(getline(readFile,line)) {
stringstream iss(line);
getline(iss, itemName,':');
getline(iss, unitPrice, ':');
getline(iss, quantityPurchased, ':');
getline(iss, day, '-');
getline(iss, month, '-');
getline(iss, year, '-');
//consturctor
stock splitedColumns(itemName,
unitPrice,
quantityPurchased,
day,
month,
year
);
itemDetails.push_back(splitedColumns);
}
readFile.close();
cout << "Info reterived from file" << endl;
for (int i =0; i<itemDetails.size(); i++) {
if(itemDetails[i].getDateMonth() == "Dec" && itemDetails[i].getDateYear() == "2013") {
istringstream uPbuffer(itemDetails[i].getUnitPrice());
istringstream qPbuffer(itemDetails[i].getQuantityPurchased());
uPbuffer >> uPrice;
qPbuffer >> qPurchased;
totalIndividualItemSales = uPrice * qPurchased;
totalSalesOfMonthDec += totalIndividualItemSales;
}
if(itemDetails[i].getDateMonth() == "Jan" && itemDetails[i].getDateYear() == "2014") {
istringstream uPbuffer(itemDetails[i].getUnitPrice());
istringstream qPbuffer(itemDetails[i].getQuantityPurchased());
uPbuffer >> uPrice;
qPbuffer >> qPurchased;
totalIndividualItemSales = uPrice * qPurchased;
totalSalesOfMonthJan += totalIndividualItemSales;
}
if(itemDetails[i].getDateMonth() == "Feb" && itemDetails[i].getDateYear() == "2014") {
istringstream uPbuffer(itemDetails[i].getUnitPrice());
istringstream qPbuffer(itemDetails[i].getQuantityPurchased());
uPbuffer >> unitPrice;
qPbuffer >> quantityPurchased;
totalIndividualItemSales = uPrice * qPurchased;
totalSalesOfMonthFeb += totalIndividualItemSales;
}
}
cout << "Report Summary of sales(Monthly)" << endl;
cout << setw(10) << left << "Month" <<setw(5) << "Sales" <<endl;
cout <<setw(10) << left << "Dec 13" <<setw(5) << totalSalesOfMonthDec <<endl;
cout <<setw(10) << left << "Jan 14" <<setw(5) << totalSalesOfMonthJan <<endl;
cout <<setw(10) << left << "Feb 14" <<setw(5) << totalSalesOfMonthFeb <<endl;
}
</code></pre>
<p>Although I've achieved the results I wanted, I feel that I am hard-coding it badly to achieve my results. I wish to know/learn how I can further improve my code from you all.</p>
<p><strong>My output</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Info reterived from file
Report Summary of sales(Monthly)
Month Sales
Dec 13 16
Jan 14 46
Feb 14 25
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<ul>\n<li><p><code>stock</code> doesn't need a default constructor if the starting values won't be useful. If you'll never need to create a <code>stock</code> object with default values, then you can just leave this out.</p></li>\n<li><p>In <code>private</code>, declare each member once per line:</p>\n\n<pre><code>std::string itemName;\nstd::string unitPrice;\nstd::string quantityPurchased;\nstd::string day;\nstd::string month;\nstd::string year;\n</code></pre>\n\n<p>This should also be done in general as it helps maintain readability and maintainability.</p></li>\n<li><p>Consider finding an alternative to all those accessors and mutators. They're not good for encapsulation as they can expose implementation details. It's best to have member functions that modify these data members within the class.</p></li>\n<li><p>It seems that <code>qualtityPurchased</code>, <code>day</code>, <code>month</code>, and <code>year</code> should be of integer types, unless they specifically need to be strings.</p></li>\n<li><p>It looks like you're including both <code>stock</code>'s implementation and <code>main()</code> in <code>main.cpp</code>. As the file name suggests, only <code>main()</code> should be in this file. There should then be an additional .cpp file just for <code>stock</code>'s implementation.</p></li>\n<li><p>After you construct a <code>stock</code> object in <code>main()</code>, it's not quite clear what you're doing. Consider putting the contents of that <code>for</code> loop in a function with a descriptive name. The output after that could also be put into a separate display function or just stay in <code>main()</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T18:31:25.593",
"Id": "38581",
"ParentId": "38561",
"Score": "6"
}
},
{
"body": "<p>Agree with everything Jamal said.</p>\n\n<p>In addition.</p>\n\n<ul>\n<li><p>Consider finding an alternative to all those accessors and mutators.<hr>Can't emphasis enough how bad this makes your design. get/set pattern is terrible for breaking encapsulation. You are exposing the internal types and thus tightly binding your implementation to providing those types.<hr>Your object should be self contained with actions that can be performed on the type represented as methods (verb like) that interact with the object.</p></li>\n<li><p>Write a stream operator for your class<hr>\nThis will make your reading of the object extremely compact.</p>\n\n<p>ie:</p>\n\n<pre><code>std::istream& operator>>(std::istream& stream, stock& item) {\n // Your stuff for reading in here.\n}\n</code></pre>\n\n<p>This makes the code much simpler to write.</p>\n\n<pre><code>vector<stock> itemDetails;\nstock item;\nwhile(readFile >> item)) {\n itemDetails.push_back(splitedColumns);\n}\n</code></pre>\n\n<p>Or if you want to look bad ass you can then use tricks to do it in one line.</p>\n\n<pre><code>// Or even this single line.\nvector<stock> itemDetails(std::istream_iterator<stock>(readFile), std::istream_iterator<stock>());\n</code></pre></li>\n<li><p>Distinguish type names from variable/member names.<hr>Personally I use an initial capitol letter for all my types (everything else starts with a lower case letter). It makes it easier to spot a type. But that is just a personal preference.</p></li>\n<li><p>Declare variables as close to the point of usage as possable. This is not C you don't need to put everything at the top of a function. Declare them just before you use them. This locality of use helps you spot the type of a variable without having to scroll around looking for it.</p></li>\n<li><p>If you must use getters. declare them const. And return a const ref to the internal member. That way you prevent copying.</p>\n\n<pre><code>string const& stock::getDateYear() const\n{ // ^^^^^^ const reference. ^^^^^ the function is const.\n return year; i.e. does not mutate the class.\n}\n</code></pre></li>\n<li><p>Why are you storing the year as a string?<hr>Store time as a unix timestamp (in UTC time. Convert it to the appropriate time zone for display but <strong>store</strong> all times as UTC)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:57:55.643",
"Id": "64651",
"Score": "0",
"body": "Ah, so const-ref *is* good for accessors. I've been doing it wrong all this time by returning copies (for when I've really needed an accessor). I've tested this by adding const-ref and purposely mutating within the function, and I received a warning. So that much works for me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:26:19.040",
"Id": "38720",
"ParentId": "38561",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T08:29:34.050",
"Id": "38561",
"Score": "6",
"Tags": [
"c++",
"parsing",
"io"
],
"Title": "Parsing store sales content from a text file"
}
|
38561
|
<p>I just submitted <a href="https://github.com/statsmodels/statsmodels/pull/1287" rel="nofollow">this pull request</a> to <a href="https://github.com/statsmodels/statsmodels" rel="nofollow"><code>statsmodels</code></a> (a Python toolkit for statistical and econometric modeling). It adds support for <a href="https://en.wikipedia.org/wiki/Exponential_smoothing" rel="nofollow">exponential smoothing</a> of time series.</p>
<p>I have only been programming for a few months. I am not very good with Numpy, and just learning classes and decorators, so any help would be appreciated.</p>
<p>The main part of the code is below. Can anyone help with shortening this so it is more efficient? Especially around the <code>for</code> loop. <a href="https://github.com/ccsv/statsmodels/blob/81f99f5b87f57ed5f6942a9b8582257558c3722f/statsmodels/tsa/Expsmoothing" rel="nofollow">The complete file is here.</a></p>
<pre><code>import numpy as np
import statsmodels.tools.eval_measures as em
#debug use
numpy.set_printoptions(suppress=True)
def exp_smoothing(y, alpha, gamma, delta=0, cycle=None, damp=1, initial=None,
trend='additive', forecast=None, season='additive', output='data'):
'''
Exponential Smoothing
This function handles 15 different Standard Exponential Smoothing models
Parameters
----------
y: array
Time series data
alpha: float
Smoothing factor for data between 0 and 1.
gamma: non zero integer or float
Smoothing factor for trend generally between 0 and 1
delta: non zero integer or float
Smoothing factor for season generally between 0 and 1
cycle: int
Length of cycles in a season. (ie: 12 for months, 4 for quarters)
damp: non zero integer or float {default = 1}
Autoregressive or damping parameter specifies a rate of decay
in the trend. Generally 0>d>1
initial: str, {'3avg'}(Optional)
Indicate initial point for bt and y
default: bt = y[0]-y[1], st = y[0]
3avg: Yields the average of the first 3 differences for bt.
trend: str, {'additive','multiplicative', 'brown'}
Indicate model type of trend default is 'additive'
additive: uses additive models such as Holt's linear & Damped-Trend
Linear Exponential Smoothing. Generalized as:
s_t = a * y_t + (1-a) * (s_t-1 + b_t-1)
b_t = g *(s_t - s_t-1) + (1 - g) * b_t-1
multiplicative: uses multiplicative models such as Exponential trend &
Taylor's modification of Pegels' model. Generalized as:
s_t = a * y_t + (1-a) * (s_t-1 * b_t-1)
b_t = g *(s_t / s_t-1) + (1 - g) * b_t-1
brown: used to deal with the special cases in Brown linear smoothing
forecast: int (Optional)
Number of periods ahead.
season: str, {'additive','multiplicative'}
Indicate type of season default is 'additive'
output: str, {'data', 'describe','forecast'}(Not implemented)
Returns
-------
pdata: array
Data that is smoothened using model chosen
Notes
-----
This function is able to perform the following algorithms:
Simple Exponential Smoothing(SES)
Simple Seasonal models (both multiplicative and additive)
Brown's Linear Exponential Smoothing
Holt's Double Exponential Smoothing
Exponential trend method
Damped-Trend Linear Exponential Smoothing
Multiplicative damped trend (Taylor 2003)
Holt-Winters Exponential Smoothing:
multiplicative trend, additive trend, and damped models for both
multiplicative season, additive season, and damped models for both
References
----------
*Wikipedia
*Forecasting: principles and practice by Hyndman & Athanasopoulos
*NIST.gov http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc433.htm
*Oklahoma State SAS chapter 30 section 11
*IBM SPSS Custom Exponential Smoothing Models
'''
#Initialize data
y = np.asarray(y)
ylen = len(y)
if ylen <= 3:
raise ValueError("Cannot implement model, must have at least 4 data points")
if alpha == 0:
raise ValueError("Cannot fit model, alpha must not be 0")
#forcast length
if forecast >= 1:
ylen += 1
#Setup array lengths
sdata = np.zeros(ylen - 2)
bdata = np.zeros(ylen - 2)
# Setup seasonal values
if type(cycle) is int:
if ylen < 2 * cycle:
raise ValueError("Cannot implement model, must be 2 at least cycles long")
#Setting b1 value
bdata[0] = np.mean((y[cycle:2 * cycle] - y[:cycle]) / float(cycle))
#Setup initial seasonal indicies
#coerce cycle start lengths
if len(y) % cycle != 0:
cdata = y[:len(y) % cycle*-1].reshape(-1, cycle)
else:
cdata = y.reshape(-1, cycle)
cdata = (cdata / cdata.mean(axis=1).reshape(-1, 1)).mean(axis=0)
cdata = np.concatenate([cdata, np.zeros(ylen - 3)])
else:
#Initialize to bypass delta function with 0
cycle = 0
cdata = np.zeros(ylen)
#Setting b1 value
if gamma == 0:
bdata[0] = 0
elif initial == '3avg':
bdata[0] = np.mean(abs(np.diff(y[:4])))
else:
bdata[0] = abs(y[0] - y[1])
#Setting s1 value
sdata[0] = y[0]
#Equations & Update ylen to align array
ylen -= 3
for i in range(ylen):
s = sdata[i]
b = bdata[i]
#handles multiplicative seasons
if season == 'multiplicative':
if trend == 'multiplicative':
sdata[i + 1] = alpha * (y[i + 2] / cdata[i]) + (1 - alpha) * s * (b**damp)
bdata[i + 1] = gamma * (sdata[i + 1] / s) + (1 - gamma) * (b ** damp)
cdata[i + cycle] = delta * (y[i + 2] / sdata[i + 1]) + (1 - delta) * cdata[i]
#handles additive models
else:
sdata[i + 1] = alpha * (y[i + 2] / cdata[i]) + (1 - alpha) * (s + damp * b)
bdata[i + 1] = gamma * (sdata[i + 1] - s) + (1 - gamma) * damp * b
cdata[i + cycle] = delta * (y[i + 2] / sdata[i + 1]) + (1 - delta) * cdata[i]
else:
if trend == 'multiplicative':
sdata[i + 1] = alpha * (y[i + 2] - cdata[i]) + (1 - alpha) * s * (b**damp)
bdata[i + 1] = gamma * (sdata[i + 1] / s) + (1 - gamma) * (b ** damp)
cdata[i + cycle] = delta * (y[i + 2] - sdata[i + 1]) + (1 - delta) * cdata[i]
#handles additive models
else:
sdata[i + 1] = alpha * (y[i + 2] - cdata[i]) + (1 - alpha) * (s + damp * b)
bdata[i + 1] = gamma * (sdata[i + 1] - s) + (1 - gamma) * damp * b
cdata[i + cycle] = delta * (y[i + 2] - sdata[i + 1]) + (1 - delta) * cdata[i]
#debug
## print 'period=', i ,'cdata=', cdata[i+cycle],'sdata=', sdata[i]
#Temporary fix: back fill data with Nan to align with y
filx = [np.nan,np.nan]
bdata = np.concatenate([filx, bdata])
sdata = np.concatenate([filx, sdata])
if season == 'multiplicative':
if trend == 'multiplicative':
pdata = (sdata * bdata) * cdata[:len(cdata) - cycle+3]
else:
pdata = (sdata + bdata) * cdata[:len(cdata) - cycle+3]
else:
if trend == 'multiplicative':
pdata = sdata * bdata + cdata[:len(cdata) - cycle+3]
#Handles special case for Brown linear
elif trend == 'brown':
at = 2 * sdata - bdata
bt = alpha / (1 - alpha) * (sdata - bdata)
sdata = at
bdata = bt
pdata = sdata + bdata + cdata[:len(cdata) - cycle+3]
else:
pdata = sdata + bdata + cdata[:len(cdata) - cycle+3]
#Calculations for summary items (NOT USED YET)
x1 = y[2:]
x2 = pdata[2:len(y)]
rmse = em.rmse(x1,x2)
#forcast
if forecast >= 2:
#Configure damp
if damp == 1:
m = np.arange(2, forecast+1)
else:
m = np.cumsum(damp ** np.arange(1, forecast+1))
m = m[1:]
#Config season
if cycle == 0:
if season == 'multiplicative':
c = 1
else:
c = 0
elif forecast > cycle:
raise NotImplementedError("Forecast beyond cycle length is unavailable")
else:
c = cdata[ylen+1:]
c = c[:forecast-1]
#Config trend
if season == 'multiplicative':
if trend == 'multiplicative':
fdata = sdata[ylen] * (bdata[ylen] ** m) * c
else:
fdata = sdata[ylen] + m * bdata[ylen] * c
else:
if trend == 'multiplicative':
fdata = sdata[ylen] * (bdata[ylen] ** m) + c
else:
fdata = sdata[ylen] + m * bdata[ylen] + c
#debug
## print 'fdata=', fdata, 'sdata=', sdata[ylen], 'm=', m, 'bdata', bdata[ylen], 'c=', c
pdata = np.append(pdata, fdata)
#debug
print 'fdata=', fdata
print 'sdata=', sdata
print 'bdata=', bdata
print 'cdata=', cdata
print 'pdata=', pdata
return pdata
else:
print 'sdata=', sdata
print 'bdata=', bdata
print 'cdata=', cdata
print 'pdata=', pdata
return pdata
</code></pre>
<p>Here is the test data and to check it is <a href="http://analysights.wordpress.com/2010/05/20/forecast-friday-topic-double-exponential-smoothing/" rel="nofollow">here</a> everything in blue</p>
<pre><code>#-------Test-------
#(y, alpha, gamma, delta = 0, cycle = None, damp = 1, initial = None,
# trend = 'additive', forecast=None, season = 'additive', output='data')
y=[152,176,160,192,220,272,256,280,300,280,312,328]
exp_smoothing(y,0.2, 0.3,0,None,1, None, 'additive', 3)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T10:59:45.837",
"Id": "64320",
"Score": "0",
"body": "You have cut out all the documentation from the code you posted. How do you expect us to review it without knowing what it is supposed to do or how to use it? Please restore the documentation!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:02:51.583",
"Id": "64322",
"Score": "0",
"body": "@Gareth Rees You can download the code at github where the pull is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:04:52.997",
"Id": "64323",
"Score": "0",
"body": "We'd like you to post all the code that you want reviewing here. [See the help](http://codereview.stackexchange.com/help/on-topic): \"If you want a code review, you must post the relevant snippets of code in your question.\" And obviously the documentation is a relevant part of what you want us to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:09:52.063",
"Id": "64324",
"Score": "0",
"body": "@GarethRees Alright I will post the documentation for the main function that does all the work. But I am not posting the wrappers because they just make it easier to implement specific conditions. It would be too long."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:10:56.640",
"Id": "64325",
"Score": "0",
"body": "Thank you — documentation for `exp_smoothing` is fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T11:14:11.430",
"Id": "64326",
"Score": "0",
"body": "@GarethRees Just a basic question would something like this be better for a class? I never really wrote classes or decorators much so I am not very familiar with implementing them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T12:24:59.567",
"Id": "64340",
"Score": "0",
"body": "I would say that a function is a better fit that a class for this; generally, functions do something and classes are something, and your code is doing something."
}
] |
[
{
"body": "<p>Some quick comments just based on reading the documentation and the first few lines:</p>\n\n<ol>\n<li><p>Typos, inconsistencies, and omissions:</p>\n\n<ul>\n<li>The first line should be a summary of the behaviour of the function, not a title, so something like \"Exponentially smooth a time series\".</li>\n<li>There's no need for capital letters in \"Standard Exponential Smoothing\" or in \"Damped-Trend Linear Exponential Smoothing\". </li>\n<li>There's an extra space in \"alpha: float\".</li>\n<li>In \"Smoothing factor for data between 0 and 1\" there needs to be punctuation between \"data\" and \"between\". (A similar comment applies to some other parameters.)</li>\n<li>Does \"between 0 and 1\" include the endpoints or not?</li>\n<li>Sometimes you have a full stop at the end of sentences and sometimes you don't.</li>\n<li>\"non-zero\" needs a hyphen.</li>\n<li>\"Length of cycles in a season\" should be \"<em>Number</em> of cycles in a season\".</li>\n<li>Write \"i.e.,\" instead of \"ie:\", but in this case I think \"for example,\" would be better.</li>\n<li>What does \"generally between 0 and 1\" mean?</li>\n<li>\"0>d>1\" is an impossible condition.</li>\n<li>What is \"bt\"?</li>\n<li>\"Indicate model type of trend default is 'additive'\" make no sense in English.</li>\n<li>\"used to deal with the special cases\" — deal with them how?</li>\n<li>\"Number of periods ahead\" — ahead of what?</li>\n<li>\"Not implemented\" — suggests that this code is not ready for merge.</li>\n</ul></li>\n<li><p>You write, \"This function is able to perform the following algorithms\" but you don't say how. It would be worth explaining what parameters to pass in order to get each of these behaviours.</p></li>\n<li><p>I don't like the way you've used the word \"season\". In English a \"season\" is one fourth of a year, or, metaphorically, one part of a cycle. But in \"Length of cycles in a season\" you appear to be using the word to mean the whole cycle. This can only be confusing to the reader.</p></li>\n<li><p>You've left in a lot of debugging print statements. But these should surely be removed before issuing the pull request. It looks as though it would be worth your while learning to use Python's debugging facilities, then you wouldn't need to use debugging print statements.</p></li>\n<li><p><code>alpha</code> needs to be \"between 0 and 1\", but all you actually check is <code>alpha == 0</code>.</p></li>\n<li><p>Some of the other parameters have restricted values. For example, <code>trend</code> must be <code>'additive'</code>, <code>'multiplicative'</code>, or <code>'brown'</code>, but you don't actually check its value.</p></li>\n<li><p>Generally it's best to check all your parameters first, rather than doing half the computation and then checking some of the parameters.</p></li>\n<li><p>You asked whether \"something like this [would] be better for a class?\" A class represents a group of <em>things</em> with common behaviour. But you don't seem to have any thing here, so there's no need for a class.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:08:55.597",
"Id": "38569",
"ParentId": "38563",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T10:07:26.557",
"Id": "38563",
"Score": "3",
"Tags": [
"python",
"numpy",
"iteration",
"statistics"
],
"Title": "Help improve my my python code for Exponential Smoothing Sumitted to Statsmodel"
}
|
38563
|
<p>I am implementing a library in C/C++11 and I have chosen to follow <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="nofollow" title="Google C++ Style Guide">Google C++ Style Guide</a> as I also use this style guide in my code.</p>
<p>As such all classes and types (including <code>typedefs</code> and <code>using</code>) start with a capital letter.</p>
<p>However I have reached a conflict when implementing some traits.</p>
<p>For instance I have a <code>RemoveOptional</code> trait:</p>
<pre><code>template <class T>
struct RemoveOptional {
using Type = T;
};
template <class T>
struct RemoveOptional<utils::Optional<T>> {
using Type = T;
};
</code></pre>
<p>that I can use like this:</p>
<pre><code>utils::RemoveOptional<utils::Optinal<int>>::Type
</code></pre>
<p>But for the traits like IsXXX I have chosen to inherit <code>std::true_type</code> or <code>std::false_type</code> in order to be used like the <code>std</code> traits:</p>
<pre><code>template <class T>
struct IsOptional : std::false_type {
};
template <class T>
struct IsOptional<Optional<T>> : std::true_type {
};
</code></pre>
<p>so this trait is used like this:</p>
<pre><code>utils::IsOptional<utils::Optional<int>>::value
utils::IsOptional<utils::Optional<int>>::value_type
</code></pre>
<p>And <code>value_type</code> conflicts with my naming conventions as it should be <code>ValueType</code>.</p>
<p>As far as I see I have 3 options:</p>
<ul>
<li><p>Modify all of my traits to follow the <code>std</code> convention.</p>
<ul>
<li>Advantages: my traits can be checked against the <code>std::true_type</code> and <code>std::false_type</code>.</li>
<li>Disadvantages: my library is inconsistent.</li>
</ul></li>
<li><p>Discard the <code>std::true_type</code> and <code>std::false_type</code> and make all my traits following my convention.</p>
<ul>
<li>Advantages: my library is consistent.</li>
<li>Disadvantages: my traits can't be checked against <code>std::true_type</code> and <code>std::false_type</code>.</li>
</ul></li>
<li><p>Leave as it is now.</p>
<ul>
<li>Advantages: my traits can be checked against <code>std::true_type</code> and <code>std::false_type</code>.</li>
<li>Disadvantages: my library is inconsistent (even my traits are inconsistent between each other).</li>
</ul></li>
</ul>
<p>What should I do?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:50:54.280",
"Id": "64355",
"Score": "0",
"body": "I am not certain this question belongs on CodeReview. Perhaps [Programmers](http://programmers.stackexchange.com/help/on-topic) is a better site?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:58:21.383",
"Id": "64446",
"Score": "0",
"body": "When that guide isn't discussing small stuff like naming conventions and indentation, it promotes some of the worst coding practices imaginable. Don't use it for your code if you want to be taken seriously (or at least make a disclaimer like \"naming convention follows GSG C++\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:34:01.963",
"Id": "64637",
"Score": "0",
"body": "**Don't** use the \"Googel Style Guide\". It is good for internal google usage only. Its guidance is outdated and bad in many places for use with real C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:35:10.013",
"Id": "64638",
"Score": "0",
"body": "Though I do agree with using a capitol letter as the first letter of a type name. It helps distinguish types from other identifiers. But follow the standard conventions when mirroring standard types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:22:11.910",
"Id": "64655",
"Score": "0",
"body": "@LokiAstari What guides do you recommend for C++? I know it's a subjective question, and that's why I don't post a formal question on SO, but I am really interested in a good (and fairly used) C++ style guide."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:22:56.227",
"Id": "64657",
"Score": "0",
"body": "@Cubbi What guides do you recommend for C++?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T00:17:24.903",
"Id": "64666",
"Score": "0",
"body": "Sutter/Alexandrescu's book is decent"
}
] |
[
{
"body": "<p>There is no single correct answer in all circumstances. You have to weigh the costs and benefits of the alternatives. Oddly enough my analysis seems to match yours, but here's one additional alternative you didn't explicitly cover:</p>\n\n<ul>\n<li><p>Add redundant typedefs. All types you create will follow your standard, and those from the standard library will not. However you can easily provide aliases that expose parts of the standard library using names of your choosing. This is a little more code than the first option, and provides an opportunity for users of your class to use either name they like. If more than one name is used, the readability of the code can suffer. As such, while this initially may look like it combines the best of both extremes, in reality it also offers the worst.</p>\n\n<pre><code>template <class T>\nstruct IsOptional : std::false_type {\n using Type = std::false_type::value_type;\n using Value = std::false_type::value;\n};\n\ntemplate <class T>\nstruct IsOptional<Optional<T>> : std::true_type {\n using Type = std::true_type::value_type;\n using Value = std::true_type::value;\n};\n</code></pre></li>\n</ul>\n\n<p>However, once you're done writing the library, I would posit this is not all that important. I do not routinely use <code>std::true_type</code> or <code>std::false_type</code> when consuming a library. Template specialization is typically used to achieve two objectives at the same time:</p>\n\n<ul>\n<li>Make the classes easy to use in flexible ways</li>\n<li>Make the code that uses the classes really fast</li>\n</ul>\n\n<p>Neither of these objectives really involve the consumers of the library having to care about the names of the types used in specializing its templates.</p>\n\n<p>And thus my answer is this: <strong>don't sweat it</strong>. Do what makes you, and anyone else who is helping to implement your library, happy. This probably means choose the least amount of work, leaving you with mismatched conventions, but the ability to leverage knowledge of working with the standard library, but could mean writing your own <code>TrueType</code> and <code>FalseType</code> classes that follow your chosen naming conventions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:32:38.177",
"Id": "64351",
"Score": "0",
"body": "Thank you. I work alone on it so I am the only one who needs to be happy :). I know I tend to overthink this kind of things so I will leave it now as it is. I think I will write my own `TrueType` and `FalseType` later on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:18:54.430",
"Id": "38573",
"ParentId": "38566",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38573",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T12:04:11.660",
"Id": "38566",
"Score": "2",
"Tags": [
"c++",
"c++11",
"library"
],
"Title": "Library with Optional traits"
}
|
38566
|
<p>I'm doing a <a href="http://codingbat.com/prob/p181646">CodingBat exercise</a> and would like to learn to write code in the most efficient way. On this exercise, I was just wondering if there's a shorter way to write this code.</p>
<pre><code>monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false
</code></pre>
<pre><code>public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
if (aSmile && bSmile) {
return true;
}
if (!aSmile && !bSmile) {
return true;
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T13:54:58.077",
"Id": "65063",
"Score": "0",
"body": "there is \"Show Solution\" button that shows 3 solutions on the page you linked"
}
] |
[
{
"body": "<p>Sometimes it is easy to forget that the simplest logical constructs like boolean are comparable with the <code>==</code> operator, and that, in Java, <code>(false == false)</code> is <code>true</code>.</p>\n\n<p>With this in mind, your code could become:</p>\n\n<pre><code>public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {\n return aSmile == bSmile;\n}\n</code></pre>\n\n<hr>\n\n<p>It may be easier to see how to get there if you first transform your original code into</p>\n\n<pre><code>public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {\n if ((aSmile && bSmile) || (!aSmile && !bSmile)) {\n return true;\n } else {\n return false; \n }\n}\n</code></pre>\n\n<p>… which could become</p>\n\n<pre><code>public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {\n return (aSmile && bSmile) || (!aSmile && !bSmile);\n}\n</code></pre>\n\n<p>From there, you may come to the realization that \"both true or both false\" is equivalent to \"both the same\".</p>\n\n<hr>\n\n<p>Here is a verification of the output:</p>\n\n<pre><code>public static boolean monkeyTrouble(boolean aSmile, boolean bSmile) {\n return aSmile == bSmile;\n}\n\nprivate static void testTruth(boolean a, boolean b) {\n System.out.printf(\"monkeyTrouble(%s, %s) = %s\\n\", a, b, monkeyTrouble(a, b));\n}\n\npublic static void main(String[] args) {\n testTruth(true, true);\n testTruth(true, false);\n testTruth(false, true);\n testTruth(false, false);\n}\n</code></pre>\n\n<p>This produces:</p>\n\n<pre><code>monkeyTrouble(true, true) = true\nmonkeyTrouble(true, false) = false\nmonkeyTrouble(false, true) = false\nmonkeyTrouble(false, false) = true\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:38:19.530",
"Id": "64343",
"Score": "0",
"body": "But there are two conditions there. The one states that if both monkeys are smiling or if neither of them are smiling, return 'true'. So wouldn't simply making aSmile == bSmile ignore those two conditions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:45:10.440",
"Id": "64344",
"Score": "4",
"body": "if both are smiling then `aSmile == bSmile` is `true == true`, and that is `true`. If neither are smiling then `aSmile == bSmile` is `false == false`, and that resolves to `true`. If only one is smiling, then `aSmile == bSmile` is `false == true`, and that resolves to `false`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:51:45.200",
"Id": "64345",
"Score": "6",
"body": "Trust me, I'm a monkey, and I know `monkeyTrouble()` ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:54:18.360",
"Id": "64352",
"Score": "0",
"body": "*truth of false and false is true* - doesn't that sound like monkey business? `(false && false) == false` returns `true`, no? Then false *and* false is... false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:56:49.533",
"Id": "64358",
"Score": "1",
"body": "@retailcoder : big difference between `false == false` and `false && false`.... ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:55:16.790",
"Id": "64376",
"Score": "0",
"body": "@200 fixed it :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:25:20.077",
"Id": "38571",
"ParentId": "38570",
"Score": "26"
}
},
{
"body": "<p>This is the <strong>exclusive-or</strong> <em>(or XOR)</em> condition negated.</p>\n\n<p>You can simply do this:</p>\n\n<pre><code>public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {\n return !(aSmile ^ bSmile);\n}\n</code></pre>\n\n<p>or, as it is so simply, you can use it in your code without the function.</p>\n\n<hr>\n\n<p>Explanation of <strong>XOR</strong> operator <code>^</code>:</p>\n\n<pre><code>a ^ b = c\n\n1 0 1\n0 1 1\n0 0 0\n1 1 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T17:32:19.517",
"Id": "64360",
"Score": "4",
"body": "The negation of XOR is also known as [XNOR](http://mathworld.wolfram.com/XNOR.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T01:11:40.587",
"Id": "64392",
"Score": "2",
"body": "Wrong precedence there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:16:14.510",
"Id": "64431",
"Score": "0",
"body": "Shouldn't this be: `!(aSmile ^ bSmile)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T14:39:36.883",
"Id": "64443",
"Score": "0",
"body": "@WayneConrad, you are right, Its corrected! It also works the other way, but this is the correct one, thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T14:02:47.520",
"Id": "38572",
"ParentId": "38570",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T13:20:16.067",
"Id": "38570",
"Score": "12",
"Tags": [
"java"
],
"Title": "Simpler boolean truth table?"
}
|
38570
|
<p>I have JSON files of size <code>data_large(150.1mb)</code>. The content inside the file is of type <code>[{"score": 68},{"score": 78}]</code>. I need to find the list of unique scores from each file. </p>
<p>This is what I'm doing:</p>
<pre><code>import ijson # since JSON file is large, hence making use of ijson
f = open ('data_large')
content = ijson.items(f, 'item') # json loads quickly here as compared to when json.load(f) is used.
print set(i['score'] for i in content) #this line is actually taking a long time to get processed.
</code></pre>
<p>Can I make the last line more efficient? It's currently taking 201 secs to execute.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:35:09.893",
"Id": "64375",
"Score": "0",
"body": "`ijson` is an *iterative* parser, so `ijson.items` will *not* load the whole file. The `set` creation likely isn’t the bottleneck; reading the huge file is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:57:11.860",
"Id": "64407",
"Score": "0",
"body": "@poke - When I remove the print statement, it executes within no time. But when applying the logic for unique value it takes time there. Can I make it any more efficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:28:16.903",
"Id": "64445",
"Score": "0",
"body": "You mean when you just remove the `print` or the whole line (including the `set(…)`)? If you remove the whole line, then of course nothing is processed because ultimately, the file is only opened but never read from. And no, I doubt you can make it more efficient than this; you do have to read a 150 MB file after all, and that’s always slow."
}
] |
[
{
"body": "<p>So… I have spent a bit time on this and generated myself a random JSON file matching your format. Mine is 167 MB in size, so not too far off from yours.</p>\n\n<p>First of all, <code>ijson</code>’s performance is terrible. I’ve tried it multiple times and it’s very slow for me (much slower than your results actually). While the idea sounds great, it took very long to read and parse the file.</p>\n\n<p>Using the normal <code>json</code> module gave me much better results. In fact, reading and parsing the file took only ~20 seconds, of which reading the file was just a very small fraction. Most of the time was actually spent on extracting the scores; generating the set from them again is very quick.</p>\n\n<p>So to speed this up, we obviously want to avoid creating all those intermediary objects in between, and just extract the data we are interested in. In your case where the file has a rather simple structure, we don’t really need to parse it as a JSON object but we can just operate on the string directly and search for the scores.</p>\n\n<p>As we discussed this on the SO Python chat, <a href=\"https://stackoverflow.com/users/1252759/jon-clements\">Jon Clements</a> came up with this solution:</p>\n\n<pre><code>with open('file.json') as f:\n content = f.read()\n print len(set(m.group(1) for m in re.finditer('\"score\": (\\d+)', content)))\n</code></pre>\n\n<p>This in fact runs in a few seconds, 8 on my machine, and is a multitude faster than anything that utilizes JSON. Of course this highly depends on the format of the file, so if you have additional data inside (which you left out in the question) you might need to adjust this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-21T16:35:17.243",
"Id": "165899",
"Score": "0",
"body": "Ijson is slow by default because it uses the native Python backend. But it can use the C library \"yajl\" if available. The yajl backend can be imported directly: `import ijson.backends.yajl2 as ijson`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:48:24.210",
"Id": "38640",
"ParentId": "38574",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T15:51:36.037",
"Id": "38574",
"Score": "2",
"Tags": [
"python",
"performance",
"json"
],
"Title": "How to find the unique values from the JSON file?"
}
|
38574
|
<p>I'm pretty new to C++. I'm trying to design a <code>EntityManager</code> system, and so far this is what I have:</p>
<pre><code>#ifndef ENTITY_MANAGER
#define ENTITY_MANAGER
#include "Entity.h"
#include "Airplane.h"
#include "Runway.h"
#include "Customer.h"
#include <unordered_map>
class EntityManager
{
private:
typedef std::unordered_map<int, Entity*> EntityMap;
EntityMap entityMap;
public:
/*
Gets an instance of the EntityManager
*/
static EntityManager* instance();
/*
Creation and Deletion
*/
/*
Registers an Entity
*/
void registerEntity(Entity* entity)
{
entityMap.insert(std::pair<int, Entity*>(entity->getId(), entity));
}
/*
Removes an Entity by its ID
*/
void removeEntity(int id)
{
entityMap.erase(id);
}
/*
Removes an Entity by its instance
*/
void removeEntity(Entity* entity)
{
removeEntity(entity->getId());
}
/*
Gets an Entity by its id
*/
Entity* getById(int id)
{
return entityMap.at(id);
}
/*
Gets all the Airplanes
*/
std::set<Airplane*> getAirplanes()
{
std::set<Airplane*> result;
for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
{
Entity* e = it->second;
Airplane* plane = dynamic_cast<Airplane*>(e);
if (plane)
{
result.insert(plane);
}
}
return result;
}
/*
Gets all the Runways
*/
std::set<Runway*> getRunways()
{
std::set<Runway*> result;
for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
{
Entity* e = it->second;
Runway* runway = dynamic_cast<Runway*>(e);
if (runway)
{
result.insert(runway);
}
}
return result;
}
/*
Gets all the Customers
*/
std::set<Customer*> getCustomers()
{
std::set<Customer*> result;
for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
{
Entity* e = it->second;
Customer* customer = dynamic_cast<Customer*>(e);
if (customer)
{
result.insert(customer);
}
}
return result;
}
};
#endif
</code></pre>
<p>A little background:</p>
<ul>
<li><code>Entity</code> is my base class, which handles assigning itself an id, etc.</li>
<li><code>Airplane</code> is a subclass of Entity, which has methods that describe its size, fuel, etc</li>
<li><code>Runway</code> is a subclass of <code>Entity</code>, which also has methods to describe its size</li>
<li><code>Customer</code> is a subclass of <code>Entity</code>, which has methods describing its AI state, etc</li>
</ul>
<p>I'm looking for any help I can get in things like code correction and design flaws.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:39:12.417",
"Id": "64639",
"Score": "0",
"body": "There is no ownership associated with your code. Who owns a pointer? Is it the entity manager. PS. Stop using pointers. In modern C++ you should practically never see a pointer unless you are building a container and then it should all be internal. Pass things around with ownership symantics defined this means references or smart pointers."
}
] |
[
{
"body": "<p>Ahhhhhhhhh</p>\n<pre><code>static EntityManager* instance();\n</code></pre>\n<p>No ownership associated with even the manager.<br />\nIf I get a manager. Who is responsible for destroying it?</p>\n<pre><code>// Do this.\n// Use the classic singleton pattern.\nstatic EntityManager& instance()\n{\n static EntityManager managerInstance;\n return managerInstance;\n}\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289\">https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289</a></p>\n<p>Who owns the entity?</p>\n<pre><code>void registerEntity(Entity* entity)\n</code></pre>\n<p>Is the manager supposed to take ownership. Which means it will take responsibility for destroying the entity? Or are you giving the manager a reference it can use but does not own (thus it will not destroy).</p>\n<p>As it stands. This is completely the wrong way of doing it. Once you tell me how you want to define the semantics of the interface I can tell you how to proceed.</p>\n<hr />\n<h2>Update The manager is supposed to take ownership.</h2>\n<p>So lets continue:</p>\n<pre><code>void registerEntity(Entity* entity)\n{\n entityMap.insert(std::pair<int, Entity*>(entity->getId(), entity));\n}\n</code></pre>\n<p>From the interface you can tell that the manager takes ownership. As a result it can easily be called like this:</p>\n<pre><code>Airplane airplane;\nEntityManager::instance()->registerEntity(&airplane);\n</code></pre>\n<p>Now what will happen in your code. I suspect it will blow up at some point in the distant future. Try tracking that bug down.</p>\n<p>The way to do this is to tell the manager he is supposed to take ownership. To do this your interface is supposed to take a <code>std::unique_ptr</code>. Also a couple of potential bugs to watch out for. Somebody may pass you a NULL in which case calling <code>getId()</code> is going to generate undefined behavior (by that I mean crash).</p>\n<pre><code>int registerEntity(std::unique_ptr<Entity>&& entity)\n{\n if (!entity.get())\n { return -1;\n }\n\n entityMap.insert(std::pair<int, Entity*>(entity->getId(), std::move(entity)));\n return entity->getId();\n}\n</code></pre>\n<p>Notice I am moving the smart pointer into the <code>entityMap</code>. This shows that you are moving ownership into the map. It must also be smart enough to hold the smart pointers. So you have two options:</p>\n<pre><code>std::unordered_map<int, std::unique_ptr<Entity>> EntityMap;\n</code></pre>\n<p>Alternatively boost has a pointer container library, where the container takes ownership. Unfortunately they don't have unordered_map but they do have map.</p>\n<pre><code>boost::ptr_map<int, Entity> EntityMap;\n</code></pre>\n<p>Using the boost pointer containers has the advantage as access to the elements in the container make them look like objects (not pointers) thus using with any of the standard algorithms is trivial (Note: using algorithms on normal containers that hold pointers is a pain because of the extra de-reference involved).</p>\n<p>Anyway either technique will remove the problem of memory leaks.</p>\n<p>No check for NULL. Also I see no advantage of having this interface when the previous one <code>void removeEntity(int)</code> does exactly the same thing and does not have the disadvantage of ownership semantics.</p>\n<pre><code>void removeEntity(Entity* entity)\n{\n removeEntity(entity->getId());\n}\n</code></pre>\n<p>Returning a pointer here:</p>\n<pre><code>Entity* getById(int id)\n{\n return entityMap.at(id);\n}\n</code></pre>\n<p>Does this give you ownership of the object back?<br />\nI would think not. If you return a pointer you open yourself up to the user being confused and deleting the pointer.</p>\n<pre><code>Entity* plane = EntityManager::instance()->getById(12);\n// WORK on place\ndelete plane; // BANG\n</code></pre>\n<p>So return a reference to indicate the caller is not getting ownership back. This does open the question of how do do you handle values that would have returned NULL previously. I would handle this by having an existence test. So for ID that you are not sure about you can validate before a retrieval.</p>\n<pre><code>Entity& getById(int id) const\n{\n return *entityMap[id]; // de-reference the smart pointer.\n}\nbool checkById(int id)\n{\n return entityMap.find(id) != entityMap.end();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:56:52.603",
"Id": "64643",
"Score": "0",
"body": "I keep hearing that singleton shouldn't be used freely. Is this one situation where it could be used? I just want to make sure since I have very little understanding of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:05:37.023",
"Id": "64644",
"Score": "0",
"body": "Singeltons are bad if you do not disassociate creation from retrieval. Unfortunately most examples (including the one above) don't. This is ually because we try and trach one pattern at a time. But Singeltons are one of those patterns were you really need to disassociate creation from retrival from the start. So really you should use Singelton in association with a builder pattern so that you can introduce an alternative technique for creating the object (thus allowing you to use other objects for testing and validation)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:10:19.260",
"Id": "64645",
"Score": "0",
"body": "Okay. I should start reading your articles as well. I'm slowly trying to work up to more advanced C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:28:00.617",
"Id": "64646",
"Score": "0",
"body": "@Jamal: Hope the answer below helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:28:33.870",
"Id": "64647",
"Score": "0",
"body": "I'm taking a look at it now. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T04:35:44.647",
"Id": "64674",
"Score": "0",
"body": "The manager is supposed to take ownership."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T18:15:45.853",
"Id": "64758",
"Score": "0",
"body": "I've changed my code so that the entity gets deleted when it is removed from the map, hence stopping that memory leak"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:45:11.140",
"Id": "38721",
"ParentId": "38576",
"Score": "2"
}
},
{
"body": "<p>To answer @Jamal's comment:</p>\n<blockquote>\n<p>I keep hearing that singleton shouldn't be used freely. Is this one\nsituation where it could be used? I just want to make sure since I\nhave very little understanding of it.</p>\n</blockquote>\n<p><strong>Please do not vote on this.</strong></p>\n<h3>Singleton done correctly using a factory</h3>\n<p>This is done using a factory. But you can use any other builder technique.<br />\n<strong>Note</strong>: This does not answer the question whether Singetons are a good idea or should be used or even when they should be used. Only that <strong>if you use them</strong> you should disassociate creation from retrieval.</p>\n<pre><code>class MyManager\n{\n public:\n static void SetMyManagerFactory(MyManagerFactory& extraFact)\n {\n // If you are setting a manager then\n // your program is wrong if it is not going to be useful.\n if (alreadyBuilt(true))\n { throw std::runtime_error("Factory already useless");\n }\n factory = &extraFact;\n }\n static MyManager& getInstance()\n {\n // disassociate building from retrieval.\n static std::unique_ptr<MyManager> managerInstance = buildInstance();\n return *managerInstance;\n }\n private:\n static std::unique_ptr<MyManager> buildInstance()\n {\n // Create an instance.\n // Note that the only instance has been created.\n // Thus if you try and set a factory after this you are out of look.\n alreadyBuilt();\n return factory\n ? factory->buildMyManager();\n : std::unique_ptr<MyManager>(new MyManager);\n }\n static bool alreadyBuilt(bool test = false)\n {\n static bool alreadyBuild = false;\n\n // If this is just a test return the state.\n if (test) {return alreadyBuild;}\n\n // If you are not testing. We must want to set the state.\n // Set the built to true. And return it for good measure.\n alreadyBuild = true;\n return alreadyBuild;\n }\n static MyManagerFactory* factory;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:29:26.093",
"Id": "64648",
"Score": "0",
"body": "You're also welcome to make this CW in case you do get votes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:42:28.183",
"Id": "64650",
"Score": "0",
"body": "I think I can understand this after some time. I first need to understand the very basics of singleton. Thanks. :-) To ensure this answer in some way addresses the *OP*'s question, you may mention how it can or cannot be used to improve the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:20:29.903",
"Id": "38724",
"ParentId": "38576",
"Score": "0"
}
},
{
"body": "<p>Since it has been said already, I will leave the issue at \"figure out what's responsible for memory management\" without further explanation.</p>\n\n<p>I have a few things to add: DRY, DRY, DRY! (ha.. ha... tumbleweed)</p>\n\n<p>It is possible that some day, you will want to change your container type. Maybe you import a library, maybe you need different performance or thread safety, maybe you write something entirely new that better serves your purposes. You did half the work of protecting yourself from this change by making a <code>typedef</code> for <code>EntityMap</code>, but you also have <code>std::unordered_map</code> throughout your code, as well as its corresponding iterator. You can DRY that up by using the <code>EntityMap</code> instead of <code>std::unordered_map</code> in <em>all</em> cases.</p>\n\n<p>Possibly add another <code>typedef</code> for the iterator type. That's just to save some keystrokes, though, rather than typing out <code>EntityMap::iterator</code> every time. You probably won't ever change the fact that you need an iterator specific to your container, so <code>EntityMap::iterator</code> is also fine if you don't care for brevity.</p>\n\n<p>The other thing I see repeated over and over is the code to select a subset of your <code>Entity</code>s based on their subclass. I doubt that your <code>EntityManager</code>'s role includes enforcing the class hierarchy, so you don't want the manager coupling to it. That makes your manager brittle to any extensions of <code>Entity</code> you may make later - at best, every new type requires not only its own code and header, but also a change to the manager class, lest it remain un-queryable. </p>\n\n<p>There are two ways to go about reducing that coupling. Probably real OO gurus can think of more, but I'll stick with the simplest:</p>\n\n<pre><code>\nclass EntityManager {\n /*...*/\npublic:\n /*...*/\n template<class EntitySubclass> std::set<EntitySubclass*> getAllSubclass() {\n std::set<EntitySubclass*> result;\n for (EntityMap::iterator it = entityMap.begin(); it != entityMap.end(); it++) {\n Entity* e = it->second;\n EntitySubclass* specificThing = dynamic_cast<EntitySubclass>(e);\n if (specificThing) {\n result.insert(specificThing);\n }\n }\n return result;\n }\n}\n</code></pre>\n\n<p>That way, all of your consumers' subclass queries become:</p>\n\n<pre><code>\nstd::set<Airplane*> planes = myManager.getAllSubclass<Airplane>();\nstd::set<Customer*> customers = myManager.getAllSubclass<Customer>();\n/* supposing tomorrow, your entities include coconuts and two */\n/* varieties of swallows. */\nstd::set<Swallow*> swallows = myManager.getAllSubclass<Swallow>();\nstd::set<AfricanSwallow*> africanSwallows = myManager.getAllSubclass<AfricanSwallow>();\nstd::set<EuropeanSwallow*> europeanSwallows = myManager.getAllSubclass<EuropeanSwallow>();\nstd::set<Coconut*> coconuts = myManager.getAllSubclass<Coconut>();\n</code></pre>\n\n<p>Notice that in that example, I have expanded your set of <code>Entity</code> subclasses considerably and even added a level of hierarchy (the two types of <code>Swallow</code>), and the manager can handle them <em>without writing any additional code</em>.</p>\n\n<p>Alternatively, if you want to keep your existing queries as shortcuts, you should still write the template method shown above, but you can make it private, then invoke it from the non-template query functions. That would still require you to add a method every time you add a subclass, but it would be very easy to write and maintain those methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T11:27:48.107",
"Id": "65026",
"Score": "0",
"body": "No problem! We usually use a check mark and/or upvote to indicate \"exactly what I needed\" here =D. Good luck with your airplanes, and try to keep the customers DRY =D."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T10:42:35.660",
"Id": "38820",
"ParentId": "38576",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T16:14:38.260",
"Id": "38576",
"Score": "1",
"Tags": [
"c++",
"beginner"
],
"Title": "Is this a decent way to create an EntityManager?"
}
|
38576
|
<p>I wrote a function to calculate the gamma coefficient of a clustering. The bottleneck is the comparison of values from <code>dist_withing</code> to <code>dist_between</code>. To speed this up, I tried to adapt and compile it using Cython (I dealt with C only few times). But I don't know, how to rapidly iterate over numpy arrays or if its possible at all to do it faster than</p>
<pre><code>for i in range(len(arr)):
arr[i]
</code></pre>
<p>I thought I could use a pointer to the array data and indeed the code runs in only half of the time, but <code>pointer1[i]</code> and <code>pointer2[j]</code> in <code>cdef unsigned int countlower</code> won't give me the expected values from the arrays. So, how to properly and speedy iterate over an array? And where else can be made improvements, even if in this case it would not make such a difference concerning runtime-speed?</p>
<pre><code># cython: profile=True
import cython
import numpy as np
cimport numpy as np
from scipy.spatial.distance import squareform
DTYPE = np.float
DTYPEint = np.int
ctypedef np.float_t DTYPE_t
ctypedef np.int_t DTYPEint_t
@cython.profile(False)
cdef unsigned int countlower(np.ndarray[DTYPE_t, ndim=1] vec1,
np.ndarray[DTYPE_t, ndim=1] vec2,
int n1, int n2):
# Function output corresponds to np.bincount(v1 < v2)[1]
assert vec1.dtype == DTYPE and vec2.dtype == DTYPE
cdef unsigned int i, j
cdef unsigned int trues = 0
cdef unsigned int* pointer1 = <unsigned int*> vec1.data
cdef unsigned int* pointer2 = <unsigned int*> vec2.data
for i in range(n1):
for j in range(n2):
if pointer1[i] < pointer2[j]:
trues += 1
return trues
def gamma(np.ndarray[DTYPE_t, ndim=2] Y, np.ndarray[DTYPEint_t, ndim=1] part):
assert Y.dtype == DTYPE and part.dtype == DTYPEint
if len(Y) != len(part):
raise ValueError('Distance matrix and partition must have same shape')
# defined locals
cdef unsigned int K, c_label, n_, trues
cdef unsigned int s_plus = 0
cdef unsigned int s_minus = 0
# assigned locals
cdef np.ndarray n_in_ci = np.bincount(part)
cdef int num_clust = len(n_in_ci) - 1
cdef np.ndarray s = np.zeros(len(Y), dtype=DTYPE)
# Partition should have at least two clusters
K = len(set(part))
if K < 2:
return 0
# Loop through clusters
for c_label in range(1, K+1):
dist_within = squareform(Y[part == c_label][:, part == c_label])
dist_between = np.ravel(Y[part == c_label][:, part != c_label])
n1 = len(dist_within)
n2 = len(dist_between)
trues = countlower(dist_within, dist_between, n1, n2)
s_plus += trues
s_minus += n1 * n2 - trues
n_ = s_plus + s_minus
return (<double>s_plus - <double>s_minus) / <double>n_ if n_ != 0 else 0
</code></pre>
<p><strong>Edit1:</strong> Passing just the pointers, instead of the arrays to the time-critical function (>99% of time is spent there) made a ~ 10% speed-up. I guess some things just cannot be made faster</p>
<pre><code>@cython.profile(False)
@cython.boundscheck(False)
@cython.nonecheck(False)
cdef unsigned int countlower(double* v1, double* v2, int n1, int n2):
''' Function output corresponds to np.bincount(v1 < v2)[1]'''
''' The upper is not correct. It rather corresponds to
sum([np.bincount(v1[i] < v2)[1] for i in range(len(v1))])'''
cdef unsigned int trues = 0
cdef Py_ssize_t i, j
with nogil, parallel():
for i in prange(n1):
for j in prange(n2):
if v1[i] < v2[j]:
trues += 1
return trues
</code></pre>
|
[] |
[
{
"body": "<p>When you deal with performance in cython, I would suggest using the --annotate flag (or use IPython with cython magic that allow you quick iteration with anotate flag too), it will tell you which part of your code <strong>may</strong> be slow. It generates an Html report with highlighted lines. The more yellow, potentially the slower. You can also click on the line o see the generated C, and generally you just call out into Python world from C when things get slow, like checking array bounds, negative indexing, catching exceptions... So, you might want to use the following decorators on your functions if you know you won't have out of bounds errors, or negative indexing from the end :</p>\n\n<pre><code>@cython.boundscheck(False)\n@cython.wraparound(False)\n</code></pre>\n\n<p>Keep in mind that it you do have out of bounds, you will segfault.</p>\n\n<p><a href=\"http://nbviewer.ipython.org/url/jakevdp.github.com/downloads/notebooks/memview_bench.ipynb\" rel=\"nofollow\">This memview bench</a> might give you ideas.</p>\n\n<p>Yo might also want to look at numpy view, if you like to avoid copy and know things won't be muted (but I think it's the default now)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T16:19:26.490",
"Id": "64720",
"Score": "0",
"body": "The memview bench is quite helpful. Do understand a little bit better now. The -a option also is helpful, however checking for zero division produces some c-code but effects speed insignificantly. If I work with numpy types, should I always use smth like np.float_t instead of double? I need a line profiler, which works with cython!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T08:01:52.813",
"Id": "64839",
"Score": "0",
"body": "My knowledge of cython doesn't go that far. Though, it seem to me that division in C is generally much slower than multiplication. Quick search give me [`@cython.cdivision(True)` decorator](http://docs.cython.org/src/reference/compilation.html). looking at the def for `n_` I would say that you can simplify logics(`x+trues-trues=x`) ."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:12:59.723",
"Id": "38727",
"ParentId": "38580",
"Score": "3"
}
},
{
"body": "<h3>1. Introduction</h3>\n\n<p>This question is difficult because:</p>\n\n<ol>\n<li><p>It's not clear what the function <code>countlower</code> does. It's always a good idea to write a docstring for a function, specifying what it does, what arguments it takes, and what it returns. (And test cases are always appreciated.)</p></li>\n<li><p>It's not clear what the role of the arguments <code>n1</code> and <code>n2</code> is. The code in the post only ever passes <code>len(v1)</code> for <code>n1</code> and <code>len(v2)</code> for <code>n2</code>. So is that a requirement? Or is it sometimes possible to pass in other values?</p></li>\n</ol>\n\n<p>I am going to assume in what follows that:</p>\n\n<ol>\n<li><p>the specification of the <code>countlower</code> function is <code>Return the number of pairs i, j such that v1[i] < v2[j]</code>;</p></li>\n<li><p><code>n1</code> is always <code>len(v1)</code> and <code>n2</code> is always <code>len(v2)</code>;</p></li>\n<li><p>the Cython details are not essential to the problem, and that it's OK to work in plain Python.</p></li>\n</ol>\n\n<p>Here's my rewrite of the <code>countlower</code> function. Note the docstring, the <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctest</a>, and the simple implementation, which loops over the sequence elements rather than their indices:</p>\n\n<pre><code>def countlower1(v, w):\n \"\"\"Return the number of pairs i, j such that v[i] < w[j].\n\n >>> countlower1(list(range(0, 200, 2)), list(range(40, 140)))\n 4500\n\n \"\"\"\n return sum(x < y for x in v for y in w)\n</code></pre>\n\n<p>And here's a 1000-element test case, which I'll use in the rest of this answer to compare the performance of various implementations of this function:</p>\n\n<pre><code>>>> v = np.array(list(range(0, 2000, 2)))\n>>> w = np.array(list(range(400, 1400)))\n>>> from timeit import timeit\n>>> timeit(lambda:countlower1(v, w), number=1)\n8.449613849865273\n</code></pre>\n\n<h3>2. Vectorize</h3>\n\n<p>The whole reason for using NumPy is that it enables you to vectorize operations on arrays of fixed-size numeric data types. If you can successfully vectorize an operation, then it executes mostly in C, avoiding the substantial overhead of the Python interpreter.</p>\n\n<p>Whenever you find yourself iterating over the elements of an array, then you're not getting any benefit from NumPy, and this is a sign that it's time to rethink your approach.</p>\n\n<p>So let's vectorize the <code>countlower</code> function. This is easy using a sparse <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html\" rel=\"noreferrer\"><code>numpy.meshgrid</code></a>:</p>\n\n<pre><code>import numpy as np\n\ndef countlower2(v, w):\n \"\"\"Return the number of pairs i, j such that v[i] < w[j].\n\n >>> countlower2(np.arange(0, 2000, 2), np.arange(400, 1400))\n 450000\n\n \"\"\"\n grid = np.meshgrid(v, w, sparse=True)\n return np.sum(grid[0] < grid[1])\n</code></pre>\n\n<p>Let's see how fast that is on the 1000-element test case:</p>\n\n<pre><code>>>> timeit(lambda:countlower2(v, w), number=1)\n0.005706002004444599\n</code></pre>\n\n<p>That's about 1500 times faster than <code>countlower1</code>.</p>\n\n<h3>3. Improve the algorithm</h3>\n\n<p>The vectorized <code>countlower2</code> still takes \\$O(n^2)\\$ time on arrays of length \\$O(n)\\$, because it has to compare every pair of elements. Is it possible to do better than that?</p>\n\n<p>Suppose that I start by sorting the first array <code>v</code>. Then consider an element <code>y</code> from the second array <code>w</code>, and find the point where <code>y</code> would fit into the sorted first array, that is, find <code>i</code> such that <code>v[i - 1] < y <= v[i]</code>. Then <code>y</code> is greater than <code>i</code> elements from <code>v</code>. This position can be found in time \\$O(\\log n)\\$ using <a href=\"http://docs.python.org/3/library/bisect.html#bisect.bisect_left\" rel=\"noreferrer\"><code>bisect.bisect_left</code></a>, and so the algorithm as a whole has a runtime of \\$O(n \\log n)\\$.</p>\n\n<p>Here's a straightforward implementation:</p>\n\n<pre><code>from bisect import bisect_left\n\ndef countlower3(v, w):\n \"\"\"Return the number of pairs i, j such that v[i] < w[j].\n\n >>> countlower3(list(range(0, 2000, 2)), list(range(400, 1400)))\n 450000\n\n \"\"\"\n v = sorted(v)\n return sum(bisect_left(v, y) for y in w)\n</code></pre>\n\n<p>This implementation is about three times faster than <code>countlower3</code> on the 1000-element test case:</p>\n\n<pre><code>>>> timeit(lambda:countlower3(v, w), number=1)\n0.0021441911812871695\n</code></pre>\n\n<p>This shows the importance of finding the best algorithm, not just speeding up the algorithm you've got. Here an \\$O(n \\log n)\\$ algorithm in plain Python beats a vectorized \\$O(n^2)\\$ algorithm in NumPy.</p>\n\n<h3>4. Vectorize again</h3>\n\n<p>Now we can vectorize the improved algorithm, using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html\" rel=\"noreferrer\"><code>numpy.searchsorted</code></a>:</p>\n\n<pre><code>import numpy as np\n\ndef countlower4(v, w):\n \"\"\"Return the number of pairs i, j such that v[i] < w[j].\n\n >>> countlower4(np.arange(0, 20000, 2), np.arange(4000, 14000))\n 45000000\n\n \"\"\"\n return np.sum(np.searchsorted(np.sort(v), w))\n</code></pre>\n\n<p>And this is six times faster still:</p>\n\n<pre><code>>>> timeit(lambda:countlower4(v, w), number=1)\n0.0003434771206229925\n</code></pre>\n\n<h3>5. Answers to your questions</h3>\n\n<p>In comments, you asked:</p>\n\n<ol>\n<li><p>\"What does vectorizing mean?\" Please read the \"<a href=\"http://docs.scipy.org/doc/numpy/user/whatisnumpy.html\" rel=\"noreferrer\">What is NumPy?</a>\" section of the NumPy documentation, in particular the section starting:</p>\n\n<blockquote>\n <p>Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these things are taking place, of course, just “behind the scenes” (in optimized, pre-compiled C code).</p>\n</blockquote></li>\n<li><p>\"What is meshgrid?\" Please read the <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html\" rel=\"noreferrer\">documentation for <code>numpy.meshgrid</code></a>.</p>\n\n<p>I use <code>meshgrid</code> to create a NumPy array <code>grid</code> containing all pairs of elements <code>x, y</code> where <code>x</code> is an element of <code>v</code> and <code>y</code> is an element of <code>w</code>. Then I apply the <code><</code> function to those pairs, getting an array of Booleans, which I sum. Try it out in the interactive interpreter and see for yourself:</p>\n\n<pre><code>>>> import numpy as np\n>>> v = [2, 4, 6]\n>>> w = [1, 3, 5]\n>>> np.meshgrid(v, w)\n[array([[2, 4, 6],\n [2, 4, 6],\n [2, 4, 6]]), array([[1, 1, 1],\n [3, 3, 3],\n [5, 5, 5]])]\n>>> _[0] < _[1]\narray([[False, False, False],\n [ True, False, False],\n [ True, True, False]], dtype=bool)\n>>> np.sum(_)\n3\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:33:24.367",
"Id": "67726",
"Score": "0",
"body": "fuu, since for me reading code is quite hard, I'll try to do better documentation in future. The assumptions you made are correct. The sorting stuff broadens my way of thinking. What does vectorizing mean in general and in the case of NumPy? What did you do in Section 2 (what is meshgrid useful here)? The main function got about 30 times faster in comparison to when using my edit1 version. No need for using cython anymore. Anyway, if I make a cython file out of that it will take twice as much time. Any idea why is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:49:21.413",
"Id": "67750",
"Score": "1",
"body": "See revised answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T11:35:59.443",
"Id": "89174",
"Score": "0",
"body": "@embert \"if I make a cython file out of that it will take twice as much time. Any idea why is that?\" The Python→Cython→Python just adds indirection, where the Python type has to be cast into a \"special form\" for Cython, but that \"special form\" is never used. Plus, [it just ends up in a fast C routine anyway](https://github.com/numpy/numpy/blob/d1987d11dfe5101d3c0b12fecaae05570f361d44/numpy/core/src/multiarray/item_selection.c#L1911). I've found that inlining these routines into Cython *can* help by removing overhead, but don't always help *much*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T11:51:40.820",
"Id": "89175",
"Score": "0",
"body": "Also look [at this](https://github.com/numpy/numpy/blob/db198d5a3d31374985a24d3c44c88c356d0b3a3e/numpy/core/src/npysort/binsearch.c.src#L39) if you want to inline it. My guess is not, even if I wasn't months late."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T11:59:16.023",
"Id": "40258",
"ParentId": "38580",
"Score": "27"
}
}
] |
{
"AcceptedAnswerId": "40258",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T17:33:02.190",
"Id": "38580",
"Score": "17",
"Tags": [
"python",
"optimization",
"array",
"numpy",
"cython"
],
"Title": "Fastest way to iterate over Numpy array"
}
|
38580
|
<p>The Cython language is a superset of the Python language, used to quickly extend and optimize Python code.</p>
<p>The Cython compiler outputs a C or C++ representation of this Python superset, with all necessary boilerplate code in place, ready to be built and loaded as a Python extension.</p>
<p>Cython supplements the Python syntax with a selection of powerful C and C++ idioms (e.g. pointers and references, <code>struct</code> compands, <code>typedef</code> declarations, &c) and a suite of complementary keywords. Since it’s a superset, valid Python modules are also valid Cython extensions… existing code can there be optimized significantly by simply resaving it, and subsequently adding Cython structures to taste.</p>
<p>Cython is used across the Python ecosystem, from academic bespoke programming projects, on up through high-profile projects like Instagram.</p>
<p>Tutorials and technical information can be had from the official Cython website, <a href="http://cython.org" rel="nofollow">cython.org</a>. Practical examples are also available through <a href="http://stackoverflow.com/questions/tagged/cython">StackOverflow</a>.</p>
<p>Questions about Cython should also be tagged with [python].</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T19:22:44.987",
"Id": "38583",
"Score": "0",
"Tags": null,
"Title": null
}
|
38583
|
The Cython language is a superset of the Python language, used to quickly generate Python C extensions. You should also tag with Python when using this tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T19:22:44.987",
"Id": "38584",
"Score": "0",
"Tags": null,
"Title": null
}
|
38584
|
<p>Is there any way I can cut down on code? I'm new to this.</p>
<pre><code>Sub addtest()
Dim decision As Char
Dim fullline As String = " "
Dim word(9), def(9), minorerror1(49), minorerror2(49), minorerror3(49), minorerror4(49), minorerror5(49) As String
Console.Clear()
Console.WriteLine("Please select the year of students you wish to save the test for: ")
Console.WriteLine()
Console.WriteLine("3 - Year 3")
Console.WriteLine("4 - Year 4")
Console.WriteLine("5 - Year 5")
Console.WriteLine("6 - Year 6")
Console.WriteLine()
Dim testyear As Integer = Console.ReadLine()
Select Case testyear
Case 1
Case 2
Case 3
Case 4
End Select
Console.WriteLine("Please enter 10 of your selected words, defenitions and selected amount minor errors to be featured in the following test")
FileOpen(5, "F:\Computing\Spelling Bee\testtests.csv", OpenMode.Append)
Console.Clear()
Do
counter = counter + 1
Console.Write("Word: ")
word(counter) = Console.ReadLine
Console.Write("Defenition: ")
def(counter) = Console.ReadLine
Console.WriteLine("Type in a max of 5 minor errors")
Console.Write("Minor error 1: ")
minorerror1(counter) = Console.ReadLine
Console.Write("Minor error 2: ")
minorerror2(counter) = Console.ReadLine
Console.Write("Minor error 3: ")
minorerror3(counter) = Console.ReadLine
Console.Write("Minor error 4: ")
minorerror4(counter) = Console.ReadLine
Console.Write("Minor error 5: ")
minorerror5(counter) = Console.ReadLine
Loop Until counter = 9
Console.Clear()
Console.WriteLine("Are you sure you want to save this test? (y/n) ")
decision = Console.ReadLine
If decision = "y" Or decision = "Y" Then
For counter As Integer = 0 To 9
fullline = testyear & "," & word(counter) & "," & def(counter) & "," & minorerror1(counter) & "," & minorerror2(counter) & "," & minorerror3(counter) & "," & minorerror4(counter) & "," & minorerror5(counter)
PrintLine(5, fullline)
Console.WriteLine("Word: " & (word(counter.ToString)) & " Defenition: " & (def(counter.ToString)) & " Minor error 1: " & (minorerror1(counter.ToString)) & " Minor error 2: " & (minorerror2(counter.ToString)) & " Minor error 3: " & (minorerror3(counter.ToString)) & " Minor error 4: " & (minorerror4(counter.ToString)) & " Minor error 5: " & (minorerror5(counter.ToString)))
Next
FileClose(5)
Console.Clear()
staffmenu()
ElseIf decision = "n" Or decision = "N" Then
addtest()
End If
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T12:04:02.083",
"Id": "96279",
"Score": "0",
"body": "The obvious would be to ommit that case structure that appears to be unused"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T12:25:26.080",
"Id": "96280",
"Score": "0",
"body": "Also instead in Console.WriteLine() you could use: Console.WriteLine(vbCrLf & \"Please select the year of students you wish to save the test for: \" & vbCrLf)"
}
] |
[
{
"body": "<p>You should read up on arrays :</p>\n\n<pre><code> Console.Write(\"Minor error 1: \")\n minorerror1(counter) = Console.ReadLine\n Console.Write(\"Minor error 2: \")\n minorerror2(counter) = Console.ReadLine\n Console.Write(\"Minor error 3: \")\n minorerror3(counter) = Console.ReadLine\n Console.Write(\"Minor error 4: \")\n minorerror4(counter) = Console.ReadLine\n Console.Write(\"Minor error 5: \")\n minorerror5(counter) = Console.ReadLine\n</code></pre>\n\n<p>This should be a loop which writes to an array of strings.</p>\n\n<p>Proposed reading : <a href=\"http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx#BKMK_ArrayElements\" rel=\"nofollow\">MSDN link on arrays</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T14:46:46.840",
"Id": "38699",
"ParentId": "38585",
"Score": "3"
}
},
{
"body": "<p>Seems like your <code>counter</code> isn't initialized. Even if it works, you can do :</p>\n\n<p><code>Dim counter as Integer: counter = 0</code></p>\n\n<hr>\n\n<p>Instead of </p>\n\n<pre><code>If decision = \"y\" Or decision = \"Y\" Then\n</code></pre>\n\n<p>you can do something like:</p>\n\n<pre><code>If UCase(decision) = \"Y\" Then\n</code></pre>\n\n<hr>\n\n<p>At last, some people like to \"type\" their variables so that there is no ambiguity after all. Something like:</p>\n\n<pre><code>Dim sDecision as String\nDim iCounter as Integer\n</code></pre>\n\n<hr>\n\n<p>Last but not least, be sure to have all your variables declared with:</p>\n\n<pre><code>Option Explicit\n</code></pre>\n\n<p>At the beginning of your module</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:18:00.503",
"Id": "81982",
"Score": "0",
"body": "This is the first time I've ever seen a code review tell someone they *ought* to use typing in the variable name. Please don't use hungarian notation as there are much clearer ways to identify type (namely a good IDE). Read more about it here: (http://c2.com/cgi/wiki?HungarianNotation)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T09:08:41.630",
"Id": "82721",
"Score": "0",
"body": "I didn't say the OP *ought* to use. I just said some coders do (and some good ones). Interesting article though. And I won't fight juste quote the article _Hungarian notation inspires some of the most bitter religious wars among programmers_ :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T08:40:39.987",
"Id": "38982",
"ParentId": "38585",
"Score": "0"
}
},
{
"body": "<p>Two things you should probably consider, classes and lists. </p>\n\n<p>When the collections are going to be of variable length, it's usually more efficient on resources to use a list instead of an array</p>\n\n<p>When you have items that are related it makes sense to encapsulate them into a structure such as a class.</p>\n\n<p>Here's an example that shows both:</p>\n\n<pre><code>Class TestItem\n Private _word As String = \"\"\n Public Property Word As String\n Get\n Return _word\n End Get\n Set(value As String)\n _word = value\n End Set\n End Property\n Private _def As String = \"\"\n Public Property Def As String\n Get\n Return _def\n End Get\n Set(value As String)\n _def = value\n End Set\n End Property\n Public ReadOnly MinorErrors As New List(Of String)\n Public Sub New()\n\n End Sub\n 'To get the fomratted output of each TestItem just call it's ToString method with\n ' a True for .csv format or a False for console display\n Public Overloads Function ToString(csv As Boolean) As String\n Dim retval As New System.Text.StringBuilder\n If csv Then\n retval.Append(_word & \",\" & _def)\n For Each item As String In MinorErrors\n retval.Append(\",\" & item)\n Next\n Else\n retval.Append(\"Word: \" & _word & \" Defenition: \" & _def)\n For I = 0 To MinorErrors.Count - 1\n retval.Append(\" Minor error \" & I.ToString & \": \" & MinorErrors(I))\n Next\n End If\n Return retval.ToString\n End Function\nEnd Class\nClass Test\n Private _year As Integer = 0\n Public Property Year As Integer\n Get\n Return _year\n End Get\n Set(value As Integer)\n If value >= 3 AndAlso value <= 6 Then\n _year = value\n Else\n Console.WriteLine(vbNewLine & \"Invalid number\")\n End If\n End Set\n End Property\n Public ReadOnly TestItems As New List(Of TestItem)\n Public Sub New()\n\n End Sub\nEnd Class\n</code></pre>\n\n<p>On the surface this might look like you're adding a lot of code, but you simplify the rest of your code tremendously. Also if in a later revision you decide to add a property or a method to a class the rest of your code isn't automatically broken.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:58:08.067",
"Id": "39314",
"ParentId": "38585",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T19:29:21.730",
"Id": "38585",
"Score": "2",
"Tags": [
"beginner",
"vb.net"
],
"Title": "Spelling bee test writer"
}
|
38585
|
<p>I wrote a helper to limit <a href="http://github.com/kriskowal/q" rel="nofollow">Q</a> promise concurrency.<br>
If I have a promise-returning function <code>promiseSomething</code>, writing</p>
<pre><code>promiseSomething = PromiseScheduler.limitConcurrency(promiseSomething, 5);
</code></pre>
<p>ensures no more than 5 promises are pending at the same time.</p>
<p>I'm coming to JS from .NET world, and I welcome critique of this code.<br>
It seems to work fine, but I wonder if it can be made shorter / more concise / plain better.</p>
<p>One of the thing worth remembering is that Q always schedules continuations on the next tick.</p>
<pre><code>'use strict';
var q = require('q');
/**
* Constructs a function that proxies to promiseFactory
* limiting the count of promises that can run simultaneously.
* @param promiseFactory function that returns promises.
* @param limit how many promises are allowed to be running at the same time.
* @returns function that returns a promise that eventually proxies to promiseFactory.
*/
function limitConcurrency(promiseFactory, limit) {
var running = 0,
semaphore;
function scheduleNextJob() {
if (running < limit) {
running++;
return q();
}
if (!semaphore) {
semaphore = q.defer();
}
return semaphore.promise
.finally(scheduleNextJob);
}
function processScheduledJobs() {
running--;
if (semaphore && running < limit) {
semaphore.resolve();
semaphore = null;
}
}
return function () {
var _this = this,
args = arguments;
function runJob() {
return promiseFactory.apply(_this, args);
}
return scheduleNextJob()
.then(runJob)
.finally(processScheduledJobs);
};
}
module.exports = {
limitConcurrency: limitConcurrency
};
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks good to me. Promises/A are a great pattern - however it can be hard to grasp in the beginning, I personally still got problems in understanding the Q library and Promises/A spec to wrap my head around</p>\n\n<p>Your implementation looks familiar to control flow patterns presented here:\n<a href=\"http://book.mixu.net/node/ch7.html\" rel=\"nofollow\">http://book.mixu.net/node/ch7.html</a></p>\n\n<p>Here is another nice presentation on Promises and control flow issues:\n<a href=\"http://trevorburnham.com/presentations/flow-control-with-promises/#/\" rel=\"nofollow\">http://trevorburnham.com/presentations/flow-control-with-promises/#/</a></p>\n\n<p>and here is a list of other Promise/A spec implementations:</p>\n\n<p><strong>JQuery</strong></p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/promise\" rel=\"nofollow\">http://api.jquery.com/promise</a> The #1 choice in jQuery-land</li>\n</ul>\n\n<p><strong>Promises/A+</strong></p>\n\n<ul>\n<li><a href=\"http://github.com/kriskowal/\" rel=\"nofollow\">http://github.com/kriskowal/</a> The #1 choice in Node-land</li>\n<li><a href=\"http://github.com/tildeio/rsvp.js\" rel=\"nofollow\">http://github.com/tildeio/rsvp.js</a> The most lightweight choice</li>\n<li><a href=\"http://github.com/cujojs/when\" rel=\"nofollow\">http://github.com/cujojs/when</a> The speediest choice</li>\n<li><a href=\"http://github.com/promises-aplus/promises-spec/blob/master/implementations.md\" rel=\"nofollow\">http://github.com/promises-aplus/promises-spec/blob/master/implementations.md</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T17:28:32.650",
"Id": "40625",
"ParentId": "38588",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:38:46.897",
"Id": "38588",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"promise"
],
"Title": "Limiting Q promise concurrency in JavaScript"
}
|
38588
|
<p><a href="https://en.wikipedia.org/wiki/Http" rel="nofollow noreferrer">Hypertext Transfer Protocol (HTTP)</a> uses a client-request/server-response model. HTTP is a stateless protocol, which means it does not require the server to retain information or status about each user for the duration of multiple requests.</p>
<p>The request is sent with an HTTP method:</p>
<ul>
<li>GET - used to retrieve data, the request body should be ignored.</li>
<li>POST - used to send data to the server, the body should hold the data </li>
</ul>
<p>These are all the methods supported by older browsers, but the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="nofollow noreferrer">HTTP 1.1 specification</a> includes a few more: HEAD, PUT, DELETE, TRACE, OPTIONS, CONNECT and PATCH</p>
<p>The response is returned with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="nofollow noreferrer">status code</a>:</p>
<ul>
<li>1xx are informational</li>
<li>2xx indicates success, most pages will have a 200 status</li>
<li>3xx are used for redirections</li>
<li>4xx are used for errors with the request, the commonest being 404 for a page not found</li>
<li>5xx are used for server errors</li>
</ul>
<p>Both the request and response are made up of a header and an optional body.</p>
<p>The header contains a list of key-value pairs, separated using new lines and colons; for instance, a request may have headers like this:</p>
<pre><code>Proxy-Connection: keep-alive
Referer: url
User-Agent: browser name or client application
Accept-Encoding: gzip,deflate
Accept-Language: en-GB
</code></pre>
<p>Note that in the example the request is telling the server that the response can be sent with the body compressed with either gzip or deflate encoding.</p>
<p>The request needs a body if it's sending additional data to the server; for instance, when sending information entered to a form.</p>
<p>The response headers will include information telling the client how to deal with the response data - whether they can cache the data (and for how long), for instance. </p>
<p>The response body will have the requested data, such as the HTML of a web page or image data.</p>
<p>HTTP is used by browsers to retrieve web content, but can also be used for data APIs. For instance as a <a href="https://codereview.stackexchange.com/tags/soap/info">SOAP</a> or <a href="https://codereview.stackexchange.com/tags/rest/info">REST</a> service.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:25:40.747",
"Id": "38589",
"Score": "0",
"Tags": null,
"Title": null
}
|
38589
|
HyperText Transfer Protocol (HTTP) is an application level network protocol used for the transfer of content on the World Wide Web.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:25:40.747",
"Id": "38590",
"Score": "0",
"Tags": null,
"Title": null
}
|
38590
|
HAML is a markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:27:05.617",
"Id": "38592",
"Score": "0",
"Tags": null,
"Title": null
}
|
38592
|
<p>Use this tag for questions involving visual presentations, whether they are generated using bitmap or vector techniques. For questions involving the manipulation and use of stored pictures, use the related tag <a href="/questions/tagged/image" class="post-tag" title="show questions tagged 'image'" rel="tag">image</a> instead.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:36:31.153",
"Id": "38593",
"Score": "0",
"Tags": null,
"Title": null
}
|
38593
|
Use this tag for questions involving visual presentations, whether they are generated using bitmap or vector techniques.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T21:36:31.153",
"Id": "38594",
"Score": "0",
"Tags": null,
"Title": null
}
|
38594
|
<p>This is a game I made in Python. While it is not my first, I am not happy with the result. I would like suggestions on ways I can make it better, more user-friendly, and more enjoyable. Also, if you have suggestions on how to get the same effect, but with cleaner, more organized code, please make them.</p>
<p>Please feel free to make any suggestions you feel will help me, except to use a GUI.</p>
<p>(P.S. I am fourteen and self-taught, so my coding style and abilities may be hugely less than yours. Please forgive my ignorance.)</p>
<pre><code>#!/usr/bin/python
import curses
import random
import time
import math
class game:
''' game by ben miller '''
def __init__(self):
self.instuctmsg = ['use a and d to move left and right','use w to jump if you are on the bottom',
'dont fall once you get high up','bounce on platforms to get higher',
'go through platforms from the bottom to jump higher','','hit any key to play the game']
self.ratio = {'plat':30,'player':6,'update':15}
self.platlen = 5
self.numlevels = 5
def __call__(self):
self.quit = False
self.screen.nodelay(1)
curses.noecho()
self.screen.clear()
self.gameover = False
self.scorea = [self.dims[0]-1]
self.score = 0
self.upc = 0
self.oupc = 0
self.x = self.dims[1]/2
self.y = self.dims[0]-1
self.platforms = [[1,self.dims[1]/2+5]]
self.draw()
self.screen.refresh()
self.screen.getch()
self.oq = -1
self.q = -1
i = 0
for i in range(15):
self.makeplat()
self.update()
self.update()
self.update()
while 1:
if i % self.ratio['plat'] == 0:
self.makeplat()
if i % self.ratio['player'] == 0:
if self.oupc != int(bool(self.upc)):
self.oupc = (int(bool(self.upc))+1)%2
if self.upc > 0:
if i % 15 == 0:
if self.y != self.dims[0]-1:
self.y += 1
if self.y == 0:
self.screen.clear()
self.screen.addstr(self.dims[0]/2-1,self.dims[1]/2-9,'you win that level')
self.screen.addstr(self.dims[0]/2,self.dims[1]/2-11,'press space to continue')
self.screen.nodelay(0)
p = -1
while p != ord(' '):
p = self.screen.getch()
break
if self.screen.inch(self.y-1,self.x) == ord('#'):
self.upc += 2
self.move(self.y-1,self.x)
self.upc-=1
elif self.y != self.dims[0]-1:
if self.screen.inch(self.y+1,self.x) == ord('#'):
self.upc = 8
else:
self.move(self.y+1,self.x)
if i % self.ratio['update'] == 0:
self.update()
self.score = self.dims[0]-1-min(self.scorea)
if self.score > 15 and self.y > self.dims[0]-5:
self.screen.clear()
self.screen.addstr(self.dims[0]/2-1,self.dims[1]/2-4,'game over')
self.screen.addstr(self.dims[0]/2,self.dims[1]/2-8,'your score is: '+str(self.score))
self.screen.addstr(self.dims[0]/2+1,self.dims[1]/2-11,'press space to continue')
self.screen.nodelay(0)
p = -1
while p != ord(' '):
p = self.screen.getch()
self.gameover = True
break
self.screen.clear()
self.draw()
self.screen.refresh()
self.q = self.screen.getch()
if self.q != self.oq:
self.oq = self.q
self.key()
if self.q == ord('q'):
self.gameover = True
self.quit = True
break
i+=1
time.sleep(0.02)
def move(self,y,x):
''' this moves the player '''
if x >= 0 and x <= self.dims[1]-1:
self.screen.addch(self.y,self.x,' ')
self.y = y
self.x = x
self.scorea.append(self.y)
def makeplat(self):
''' this makes a random platform '''
y = 1
time.sleep(0.0005)
x = random.randrange(1,self.dims[1]-7)
self.platforms.append([y,x])
def draw(self):
''' this displays the game '''
for platform in self.platforms:
for i in range(self.platlen):
self.screen.addch(platform[0],platform[1]+i,'#')
self.screen.move(self.dims[0]-1,self.dims[1]-1)
self.screen.addch(self.y,self.x,'@')
self.screen.move(self.dims[0]-1,self.dims[1]-1)
def update(self):
''' moves platforms down a line '''
for platform in self.platforms:
platform[0]+=1
if platform[0] == self.dims[0]:
del self.platforms[self.platforms.index(platform)]
def key(self):
#left
if self.q == ord('a'):
if self.x == 0:
self.move(self.y,self.dims[1]-1)
else:
self.move(self.y,self.x-1)
#right
elif self.q == ord('d'):
if self.x == self.dims[1]-1:
self.move(self.y,0)
else:
self.move(self.y,self.x+1)
#jump
elif self.q == ord('w') and self.y == self.dims[0]-1:
self.upc = 7
#drop
elif self.q == ord('s') and self.y not in [self.dims[0]-1,self.dims[0]-2]:
if ord('#') not in [self.screen.inch(self.y+1,self.x),self.screen.inch(self.y+2,self.x)]:
self.upc = 0
self.move(self.y+2,self.x)
#else:
#i dont like this for now
#self.remove()
def remove(self):
'''this removes any platforms the player drops onto'''
for platform in self.platforms:
if platform[0] in [self.y+1,self.y+2]:
for j in range(self.platlen):
if self.x == platform[1]+j:
del self.platforms[self.platforms.index(platform)]
def instructions(self):
self.screen.nodelay(0)
self.screen.clear()
for i in range(len(self.instuctmsg)):
self.screen.addstr(self.dims[0]/2-int(round(len(self.instuctmsg)))/2+i,self.dims[1]/2-len(self.instuctmsg[i])/2-1,self.instuctmsg[i])
self.screen.move(self.dims[0]-1,self.dims[1]-1)
self.screen.refresh()
self.screen.getch()
def start(self):
self.screen = curses.initscr()
self.dims = self.screen.getmaxyx()
self.dims = [self.dims[0],self.dims[1]]
if self.dims[1] > 80:
self.dims[1] = 80
self.instructions()
for z in range(0,self.numlevels-1,10/(self.numlevels-1)):
self.ratio = {'plat':30+z,'player':6,'update':15-z}
self()
if self.gameover: break
if not self.gameover:
self.screen.clear()
self.screen.addstr(self.dims[0]/2-1,self.dims[1]/2-3,'YOU WIN')
self.screen.addstr(self.dims[0]/2,self.dims[1]/2-11,'press space to continue')
p = -1
while p != ord(' '):
p = self.screen.getch()
elif self.quit:
self.screen.clear()
else:
self.screen.clear()
self.screen.addstr(self.dims[0]/2-1,self.dims[1]/2-4,'YOU LOSE')
self.screen.addstr(self.dims[0]/2,self.dims[1]/2-11,'press space to continue')
p = -1
while p != ord(' '):
p = self.screen.getch()
curses.endwin()
jump = game()
jump = jump.start
if __name__ == '__main__': jump()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T13:03:14.787",
"Id": "224041",
"Score": "0",
"body": "your indentations are a bit to big"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-24T23:29:05.657",
"Id": "272509",
"Score": "0",
"body": "they are only four characters which is common...?"
}
] |
[
{
"body": "<p>A few suggestions:</p>\n\n<ol>\n<li>Follow <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>'s code conventions (e.g. spaces after commas, line lengths);</li>\n<li>Put your <code>start()</code> instance method immediately after <code>__init__()</code>; it took me a while to work out where <code>self.dims</code> had come from! Or, even better, combine the two methods;</li>\n<li>Take your opportunities to make functions. For example, you repeatedly use <code>self.screen.addstr</code> to put some lines of centred text on the <code>screen</code>, you could make a function <code>centred_text(list_of_lines)</code> to save some duplication;</li>\n<li>If you call something (e.g. <code>self.update</code>) repeatedly, consider refactoring it - <code>self.update(3)</code> or <code>for _ in range(3): self.update()</code> would be neater;</li>\n<li>Keep going with the OOP - try refactoring to create a <code>Platform</code> class and a <code>Player</code> class (the latter paves the way to two-player mode!);</li>\n<li>Try to factor out <a href=\"http://en.m.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow\">magic numbers</a>, like the initial 15 platforms; and</li>\n<li>Use clearer variable names than <code>oq</code> and <code>upc</code>.</li>\n</ol>\n\n<p>Hope that's useful!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T18:52:12.503",
"Id": "64917",
"Score": "0",
"body": "im confused about number 4. what do you mean? and number 6. other than that, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T19:05:35.880",
"Id": "64921",
"Score": "1",
"body": "Number 6, see \"unnamed numerical constants\": http://en.m.wikipedia.org/wiki/Magic_number_(programming). `initial_platforms=15` would be clearer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T19:09:03.407",
"Id": "64923",
"Score": "1",
"body": "Number 4, `self.update(); self.update(); self.update()` is a bit awkward, try `for _ in range(3): self.update()` or give `self.update` an argument for the number of times to run"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-24T23:28:25.933",
"Id": "272508",
"Score": "0",
"body": "sorry to respond years later, but i wanted to thank you, your simple suggestions completely changed my coding style, and helped me write much better code. thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:19:32.227",
"Id": "38723",
"ParentId": "38601",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38723",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T02:44:53.793",
"Id": "38601",
"Score": "6",
"Tags": [
"python",
"game",
"python-2.x"
],
"Title": "Improvements on Python game?"
}
|
38601
|
<p>For my junior high, IT final project, I decided to make a C++ program which functions as a simple library manager. The functions of the manager are to check your own library, view the store's library and buy from it, and check your transaction history. </p>
<p>I made separate arrays for each of the three above, and use it as a main database storage system. I added some extra functions such as to check if the data already has been purchased and if the person has sufficient funds to buy the data. The code is can be read at : <a href="http://pastebin.com/UQW0sAaQ">http://pastebin.com/UQW0sAaQ</a></p>
<pre><code>/* dycesM */
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int money = 5000; // Global Variable
struct database
{
string songName;
int songPrice;
int songNumber;
int songID;
}userStorage[30], storeStorage[30];
struct transaction
{
string songName;
int songPrice;
}transactionStorage[30];
void userStorageDisplay()
{
for (int i = 0; i <= 30; i++)
{
if (userStorage[i].songID != NULL)
{
cout << "\n" << i << ". " << userStorage[i].songName << "\n" << endl;
}
}
}
void storeStorageDisplay()
{
for (int i = 0; i <= 30; i++)
{
if (storeStorage[i].songID != NULL)
{
cout << "\n" << i << ". " << storeStorage[i].songName << endl;
cout << "\t" << "Price: $" << storeStorage[i].songPrice << "\n" << endl;
}
}
}
void transactionStorageDisplay()
{
for (int i = 0; i < 30; i++)
{
if (transactionStorage[i].songPrice != NULL)
{
cout << "\n" << transactionStorage[i].songName << " $:" << transactionStorage[i].songPrice << "\n" << endl;
}
}
}
int checkDuplicate(int songStorageValue)
{
for (int j = 0; j <= 30; j++)
{
if (userStorage[j].songID == storeStorage[songStorageValue].songID)
{
return 0;
}
}
return 1;
}
int checkBankDetails(int songNumber)
{
if (storeStorage[songNumber].songPrice > money)
{
return 1;
}
}
void purchase(int songNumber)
{
int verification;
int &moneyBalance = money;
cout << "\nAre you sure you wish to purchase: " << storeStorage[songNumber].songName << " for a price of: " << storeStorage[songNumber].songPrice << " ?" << endl;
cout << "Press 1 to confirm or 2 to exit." << endl;
cin >> verification;
if (verification == 1)
{
if (checkBankDetails(songNumber) != 1)
{
if (checkDuplicate(songNumber) == 1)
{
for (int i = 0; i <= 30; i++)
{
if (userStorage[i].songID == NULL)
{
userStorage[i].songName = storeStorage[songNumber].songName;
userStorage[i].songNumber = i;
userStorage[i].songPrice = storeStorage[songNumber].songPrice;
userStorage[i].songID = storeStorage[songNumber].songID;
for (int a = 0; a <= 30; a++)
{
if (transactionStorage[a].songPrice == NULL)
{
transactionStorage[a].songName = storeStorage[songNumber].songName;
transactionStorage[a].songPrice = storeStorage[songNumber].songPrice;
money = money - transactionStorage[a].songPrice;
cout << "\nRemaining Value: $" << money << "\n";
a = 30; // To end the loop.
}
}
cout << "\n" << storeStorage[songNumber].songName << " has been added to your library at position number: " << i << "\n" << endl;
i = 30; // To end the loop.
}
}
}
else if (checkDuplicate(songNumber) == 0)
{
cout << "\nYou already own this song. Purchase Cancelled." << endl;
}
}
else if (checkBankDetails(songNumber) == 1)
{
cout << "\nInsufficient funds. Purchase cancelled." << endl;
}
}
else if (verification != 1)
{
cout << "Transaction Aborted.";
}
}
void main()
{
char rerun;
//Store Data added for demonstration purposes.
storeStorage[0].songName = "Daughter - Youth";
storeStorage[0].songPrice = 25;
storeStorage[0].songID = 2000;
storeStorage[1].songName = "Archive - Bullets";
storeStorage[1].songPrice = 25;
storeStorage[1].songID = 2001;
storeStorage[2].songName = "Swedish House Mafia - Don't you worry child";
storeStorage[2].songPrice = 25;
storeStorage[2].songID = 2002;
storeStorage[3].songName = "Roykossop - Running to the sea";
storeStorage[3].songPrice = 25;
storeStorage[3].songID = 2003;
storeStorage[4].songName = "French Teen Idol - Shouting can have different meanings";
storeStorage[4].songPrice = 25;
storeStorage[4].songID = 2004;
do
{
int userOperationChoice;
int userPurchaseQuery;
cout << "Hello and Welcome to the Dyces Song Library. \n\nPlease select one of the operations below. \n\n 1 - View your own library \n\n 2 - View the Store Library \n\n 3 - View your transactions. \n\n 4 - Check Bank Details \n\n Selection:";
cin >> userOperationChoice;
switch (userOperationChoice)
{
case(1) :
{
goto userLibrary;
break;
}
case(2) :
{
goto storeLibrary;
break;
}
case(3) :
{
goto transactionLibrary;
break;
}
case(4) :
{
goto bankDetails;
break;
}
}
userLibrary:
system("CLS");
cout << "\nThe current songs in your library are: \n\n";
userStorageDisplay();
goto programEnd;
storeLibrary:
system("CLS");
cout << "\nThe Store's library is: \n";
storeStorageDisplay();
cout << "\nPlease enter the song you wish to purchase. \n";
cin >> userPurchaseQuery;
purchase(userPurchaseQuery);
goto programEnd;
transactionLibrary:
system("CLS");
cout << "Your transactions are: \n";
transactionStorageDisplay();
goto programEnd;
bankDetails:
char viewTransactionHistory;
system("CLS");
cout << "You have: $" << money << " left in your bank account." << endl;
cout << "\nWould you like to check your transaction history? Y/N" << endl;
cin >> viewTransactionHistory;
if (viewTransactionHistory == 'y' || viewTransactionHistory == 'Y')
{
goto transactionLibrary;
}
goto programEnd;
programEnd:
cout << "\nWould you like to go back to the main menu? Y/N" << endl ;
cin >> rerun;
system("CLS");
} while (rerun == 'y' || rerun == 'Y');
}
</code></pre>
<p>Any suggestions / reviews are greatly welcome! </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:18:35.027",
"Id": "64395",
"Score": "0",
"body": "I'll take a better look at this later, but I can say this for now: global variables and `goto` are bad. Any future answers should address that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:22:07.657",
"Id": "64396",
"Score": "0",
"body": "@Jamal Yes, I've heard about them too. Personally, I think I didn't use `goto` to a great extent, just to make the code a bit more readable I guess. I'm trying to find a workaround for the global variable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:23:19.097",
"Id": "64397",
"Score": "0",
"body": "No problem. You're in the right place for that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:23:47.040",
"Id": "64400",
"Score": "2",
"body": "You really need to revise your taste in music ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T05:21:27.587",
"Id": "64408",
"Score": "3",
"body": "There's quite a few things that compiler warnings can catch on this. It's typically a good idea to crank warnings up as high as possible. For `g++`, I tend to use the flags `-Wall -Wextra -Weffc++ -Wstrict-aliasing -pedantic` as a minimum. I'm not very familiar with the flags on any other compilers unfortunately :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T08:59:31.170",
"Id": "64414",
"Score": "1",
"body": "@Corbin: I'm almost sure they (gender neutral pronoun) use Visual C++, as there is `CLS`, and `void main` (that none of Linux compilers accept). Enable at least `/W4` in project settings (or even `/Wall`, but this will be really strict - but that's good in my opinion). Fix _all_ warnings, this way you will learn to code properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:48:26.433",
"Id": "64640",
"Score": "0",
"body": "http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:51:23.600",
"Id": "64641",
"Score": "0",
"body": "You can increase warning level (even in VC). Also tell the compiler to treat all warnings as errors (-Werror) there is a check box in VC. All warnings are logical errors in your code. Fix them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T01:55:53.700",
"Id": "64671",
"Score": "0",
"body": "@Corbin: For me, even turning on `-Wall` spewed out tons of warnings, mostly from system header files. But if I just compile at `/W4`, I get none of these."
}
] |
[
{
"body": "<p>This is my first time reviewing C++ code! I'm may be a bit harsh since this is for a final grade. </p>\n\n<hr>\n\n<p>There is a place in your code where one of your methods could reach then end of a non-void function, and doesn't return anything. <strong>This was actually an error for me, and the code would not compile until I fixed it</strong> (maybe this is due to my strict compiler).</p>\n\n<pre><code>int checkBankDetails(int songNumber)\n{\n if (storeStorage[songNumber].songPrice > money)\n {\n return 1;\n }\n return money; // This needs to be here in case that if condition fails\n}\n</code></pre>\n\n<hr>\n\n<p>You should <strong><em>never</em></strong> declare <code>main()</code> so that it doesn't return a value. <a href=\"https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main\">This is not a \"proper declaration\".</a> The return value for <code>main()</code> should indicate how the program exited. Normal exit is generally represented by a 0 return value from <code>main()</code>. Abnormal termination is usually signalled by a non-zero return but there is no standard for how non-zero codes are interpreted. <em>Also, <code>void main()</code> is explicitly prohibited by the C++ standard and shouldn't be used.</em></p>\n\n<pre><code>int main()\n{\n ...\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>I rarely would use <code>goto</code>s. There is almost always a better option, and extreme use of them can make your code <a href=\"https://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"nofollow noreferrer\">spaghetti code</a>. In your program I see no purpose to keeping them around.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't use <code>using namespace std</code>.</a></p>\n\n<hr>\n\n<p>There is a consistent <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">magic-number</a> 30 lurking around your code. Define it somewhere and use the constant in the magic-number's place.</p>\n\n<pre><code>static int const ARRAYLENGTH = 30\n</code></pre>\n\n<hr>\n\n<p>To end a loop, you should <code>break</code> from it. You shouldn't be setting a variable like the way you are now to get out of it (there are certain conditions where this is not true, such as game loops, but that does not apply here).</p>\n\n<pre><code>i = 30; // Not the best way to break from a loop here.\nbreak; // Use this\n</code></pre>\n\n<hr>\n\n<p>I'm getting a lot of warnings about:</p>\n\n<pre><code>Comparison between NULL and non-pointer ('int' and NULL)\n</code></pre>\n\n<p>Let's get rid of those by comparing them to <code>0</code>. <a href=\"https://stackoverflow.com/a/924675/1937270\"><code>NULL</code> is actually defined as <code>0</code> in C++</a>, so this is the same comparison minus the warning.</p>\n\n<hr>\n\n<p>Going off of the last point, you have some comparisons that could be simplified.</p>\n\n<pre><code>if (storeStorage[i].songID != 0)\nif (storeStorage[i].songID) // Does the same thing\n</code></pre>\n\n<p>If you think about it, all <code>if</code> conditional tests will work if the value is not <code>0</code>, so testing if something is not equal to <code>0</code> is redundant and unneeded.</p>\n\n<hr>\n\n<p>You have an unused variable <code>moneyBalance</code></p>\n\n<hr>\n\n<p>You include the library <code><string.h></code> unnecessarily.</p>\n\n<hr>\n\n<p>Final code:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nstatic int const ARRAYLENGTH = 30\n\nint money = 5000; // Global Variable\n\nstruct database\n{\n std::string songName;\n int songPrice;\n int songNumber;\n int songID;\n} userStorage[ARRAYLENGTH], storeStorage[ARRAYLENGTH];\n\nstruct transaction\n{\n std::string songName;\n int songPrice;\n}transactionStorage[ARRAYLENGTH];\n\nvoid userStorageDisplay()\n{\n for (int i = 0; i <= ARRAYLENGTH; i++)\n {\n if (userStorage[i].songID)\n {\n std::cout << \"\\n\" << i << \". \" << userStorage[i].songName << \"\\n\" << std::endl;\n }\n }\n}\n\nvoid storeStorageDisplay()\n{\n for (int i = 0; i <= ARRAYLENGTH; i++)\n {\n if (storeStorage[i].songID)\n {\n std::cout << \"\\n\" << i << \". \" << storeStorage[i].songName << std::endl;\n std::cout << \"\\t\" << \"Price: $\" << storeStorage[i].songPrice << \"\\n\" << std::endl;\n }\n }\n}\n\nvoid transactionStorageDisplay()\n{\n for (int i = 0; i < ARRAYLENGTH; i++)\n {\n if (transactionStorage[i].songPrice)\n {\n std::cout << \"\\n\" << transactionStorage[i].songName << \" $:\" << transactionStorage[i].songPrice << \"\\n\" << std::endl;\n }\n }\n}\n\nint checkDuplicate(int songStorageValue)\n{\n for (int j = 0; j <= ARRAYLENGTH; j++)\n {\n if (userStorage[j].songID == storeStorage[songStorageValue].songID)\n {\n return 0;\n }\n }\n return 1;\n}\n\nint checkBankDetails(int songNumber)\n{\n if (storeStorage[songNumber].songPrice > money)\n {\n return 1;\n }\n return money;\n}\n\nvoid purchase(int songNumber)\n{\n int verification;\n\n std::cout << \"\\nAre you sure you wish to purchase: \" << storeStorage[songNumber].songName << \" for a price of: \" << storeStorage[songNumber].songPrice << \" ?\" << std::endl;\n std::cout << \"Press 1 to confirm or 2 to exit.\" << std::endl;\n std::cin >> verification;\n\n if (verification == 1)\n {\n if (checkBankDetails(songNumber) != 1)\n {\n\n if (checkDuplicate(songNumber) == 1)\n {\n for (int i = 0; i <= ARRAYLENGTH; i++)\n {\n if (userStorage[i].songID == 0)\n {\n userStorage[i].songName = storeStorage[songNumber].songName;\n userStorage[i].songNumber = i;\n userStorage[i].songPrice = storeStorage[songNumber].songPrice;\n userStorage[i].songID = storeStorage[songNumber].songID;\n\n for (int a = 0; a <= ARRAYLENGTH; a++)\n {\n if (transactionStorage[a].songPrice == 0)\n {\n transactionStorage[a].songName = storeStorage[songNumber].songName;\n transactionStorage[a].songPrice = storeStorage[songNumber].songPrice;\n\n money = money - transactionStorage[a].songPrice;\n\n std::cout << \"\\nRemaining Value: $\" << money << \"\\n\";\n\n break;\n }\n }\n\n std::cout << \"\\n\" << storeStorage[songNumber].songName << \" has been added to your library at position number: \" << i << \"\\n\" << std::endl;\n break;\n }\n }\n }\n else if (checkDuplicate(songNumber) == 0)\n {\n std::cout << \"\\nYou already own this song. Purchase Cancelled.\" << std::endl;\n }\n }\n else if (checkBankDetails(songNumber) == 1)\n {\n std::cout << \"\\nInsufficient funds. Purchase cancelled.\" << std::endl;\n }\n }\n else if (verification != 1)\n {\n std::cout << \"Transaction Aborted.\";\n }\n}\n\nint main()\n{\n\n char rerun;\n\n //Store Data added for demonstration purposes.\n\n storeStorage[0].songName = \"Daughter - Youth\";\n storeStorage[0].songPrice = 25;\n storeStorage[0].songID = 2000;\n storeStorage[1].songName = \"Archive - Bullets\";\n storeStorage[1].songPrice = 25;\n storeStorage[1].songID = 2001;\n storeStorage[2].songName = \"Swedish House Mafia - Don't you worry child\";\n storeStorage[2].songPrice = 25;\n storeStorage[2].songID = 2002;\n storeStorage[3].songName = \"Roykossop - Running to the sea\";\n storeStorage[3].songPrice = 25;\n storeStorage[3].songID = 2003;\n storeStorage[4].songName = \"French Teen Idol - Shouting can have different meanings\";\n storeStorage[4].songPrice = 25;\n storeStorage[4].songID = 2004;\n\n\n\n do\n {\n int userOperationChoice;\n int userPurchaseQuery;\n\n std::cout << \"Hello and Welcome to the Dyces Song Library. \\n\\nPlease select one of the operations below. \\n\\n 1 - View your own library \\n\\n 2 - View the Store Library \\n\\n 3 - View your transactions. \\n\\n 4 - Check Bank Details \\n\\n Selection:\";\n std::cin >> userOperationChoice;\n\n switch (userOperationChoice)\n {\n case(1) :\n {\n system(\"CLS\");\n std::cout << \"\\nThe current songs in your library are: \\n\\n\";\n userStorageDisplay();\n break;\n }\n case(2) :\n {\n system(\"CLS\");\n std::cout << \"\\nThe Store's library is: \\n\";\n storeStorageDisplay();\n\n std::cout << \"\\nPlease enter the song you wish to purchase. \\n\";\n std::cin >> userPurchaseQuery;\n\n purchase(userPurchaseQuery);\n break;\n }\n case(3) :\n {\n system(\"CLS\");\n std::cout << \"Your transactions are: \\n\";\n transactionStorageDisplay();\n break;\n }\n case(4) :\n {\n char viewTransactionHistory;\n\n system(\"CLS\");\n std::cout << \"You have: $\" << money << \" left in your bank account.\" << std::endl;\n\n std::cout << \"\\nWould you like to check your transaction history? Y/N\" << std::endl;\n std::cin >> viewTransactionHistory;\n\n if (viewTransactionHistory == 'y' || viewTransactionHistory == 'Y')\n {\n std::cout << \"Your transactions are: \\n\";\n transactionStorageDisplay();\n }\n break;\n }\n }\n\n\n std::cout << \"\\nWould you like to go back to the main menu? Y/N\" << std::endl;\n std::cin >> rerun;\n system(\"CLS\");\n\n } while (rerun == 'y' || rerun == 'Y');\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:12:25.227",
"Id": "64398",
"Score": "3",
"body": "`NULL` is actually often defined as `(void*)0`. Prefer using `nullptr` when comparing to a pointer in C++11."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:55:06.367",
"Id": "38607",
"ParentId": "38602",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p>Prefer to initialize a struct member by calling its constructor directly:</p>\n\n<pre><code>struct S\n{\n int number;\n std::string string;\n} structs[2];\n\nstructs[0] = { 1, \"hello\" };\nstructs[1] = { 2, \"world\" };\n</code></pre>\n\n<p>Note that the <code>S</code> is capitalized for a reason. This is because it's a <em>custom type</em>, which should be capitalized as per naming convention. <em>Instances</em>, on the other hand, should start with a lowercase.</p></li>\n<li><p>Prefer this type of pattern when using <code>for</code> loops in C++:</p>\n\n<pre><code>for (int i = 0; i < 5; i++) { }\n</code></pre>\n\n<p>This loop will still iterate five times (<code>i = 0</code> to <code>i = 4</code>).</p></li>\n<li><p>If your check functions just return <code>0</code> or <code>1</code>, have them return a <code>bool</code> instead:</p>\n\n<pre><code>bool areSameNumbers()\n{\n int a = 5;\n int b = 10;\n\n if (a == b)\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>I should also note that this particular method was shown just to illustrate the <code>true</code> and <code>false</code> keywords. I'd recommend the below form, which is much shorter and also preferred:</p>\n\n<pre><code>bool areSameNumbers()\n{\n int a = 5;\n int b = 10;\n\n return a == b;\n}\n</code></pre></li>\n<li><p>Consider using <code>while</code> loops instead of <code>do</code>-<code>while</code> as the former is more readable. That wouldn't work too well with the loop contents you have now, but it's still worth keeping in mind.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:32:25.083",
"Id": "64401",
"Score": "0",
"body": "Keep in mind that `do-while` loops will 1 or more times, where as `while` loops will run 0 or more times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:33:49.307",
"Id": "64403",
"Score": "1",
"body": "@syb0rg: I know. There are workarounds to that, although I haven't mentioned anything specific. I've mostly went the \"example route\" here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:26:52.917",
"Id": "38609",
"ParentId": "38602",
"Score": "4"
}
},
{
"body": "<p>Jamal and syb0rg have covered things well, but I have a few things to add.</p>\n\n<hr>\n\n<p>Globals are rather harmful to programs:</p>\n\n<ul>\n<li>They essentially murder any kind of independence any code that uses them could have had</li>\n<li>They encourage mysterious-side-effect based programming</li>\n<li>They can create annoying-to-manage namespace pollution</li>\n</ul>\n\n<p>Imagine down the road if you wanted to change your program to handle 2 users' libraries (or better yet, <code>n</code> users' libraries). How do you do that? Well, the obvious first step is to have 2 sets of arrays instead of a single set of arrays. Simple enough. But wait... Your functions all operate on a global variable. The rather nasty solution then is to just do something like:</p>\n\n<pre><code>struct simple { int x; }\n\nsimple global_simple;\n\nvoid double_x() {\n global_simple.x *= 2;\n}\n\nvoid some_code() {\n simple some_simple = {3};\n simple some_other_simple = {5};\n\n global_simple = some_simple;\n double_x();\n some_simple = global_simple;\n\n global_simple = some_other_simple;\n double_x();\n some_other_simple = global_simple;\n}\n</code></pre>\n\n<p>This has a few <em>very</em> bad problems though:</p>\n\n<ul>\n<li>It directly couples double_x to something. That defeats the purpose of a function.\n<ul>\n<li>Functions are meant to be little black boxes of code that take one or more things in, operate on them, and synthesize some kind of result</li>\n</ul></li>\n<li>It's extremely error prone since it relies on a human remembering to always do the proper assignments</li>\n<li>It requires a performance hit for no reason due to the constant assignments</li>\n</ul>\n\n<p>Consider this instead:</p>\n\n<pre><code>void double_x(simple& s) {\n s.x *= 2;\n}\n\nvoid some_code() {\n simple some_simple = {3};\n simple some_other_simple = {5};\n\n double_x(some_simple);\n double_x(some_other_simple);\n}\n</code></pre>\n\n<p>It's clearer, it's less error prone, and it has higher performance. Yes, for the singular version, you do have to type an annoying extra some_simple rather than just <code>double_x()</code>, but the benefits far outweigh that one tiny drawback.</p>\n\n<p><strong>Note:</strong> As Loki Astari pointed out, this only applies to mutable globals. Immutable globals (sometimes called constants) are usually quite useful and a different beast altogether (with their own, smaller, set of concerns). The reason globals are bad is that they can be changed from anywhere. Taking away the ability to change them negates that concern.</p>\n\n<hr>\n\n<p>When using non-standard C or C++, I like to abstract it away into a wrapper function. For example, your <code>system(\"CLS\")</code> is platform specific in that the <code>cls</code> command is specific to the Windows command line (it's <code>clear</code> on <code>sh</code> based systems).</p>\n\n<p>I would do something like this (untested):</p>\n\n<pre><code>void clear_console() {\n #ifdef _WIN32\n std::system(\"cls\");\n #elif linux\n std::system(\"clear\");\n #else\n #error Unknown system\n #endif\n}\n</code></pre>\n\n<p>This means that your program can now work on more than one system. More importantly though, it centralizes your dependency. Let's say you want to add support for yet another operating system. You could either <code>Control + F</code> to find all <code>system(\"cls\")</code> and hope you didn't miss any corner cases, or you could go to your one function for it and add it.</p>\n\n<p>Also, this avoids code duplication since some OS specific code can be a lot more than 1 function call.</p>\n\n<p>For what it's worth by the way, this is a very (very, very, very) simplified version of what any kind of cross platform library does. Abstract away the platform specificity enough, and your non-utility code will never have to worry about whether it's running on Windows, linux, Mac, or a calculator.</p>\n\n<p>Then again, it's always a valid decision to decide \"you know, we don't really care about any system/environment other than X.\" Just make sure that you <em>really, really</em> mean it :).</p>\n\n<hr>\n\n<p>There's no point to have a switch that all it does is execute a jump. Just put your content inside of the switch directly. It has the exact same effect. There are a few legitimate uses of <code>goto</code>, but this is not one of them. (And really the usefulness of <code>goto</code> in C++ rather than C is questionable.)</p>\n\n<hr>\n\n<p>Your switch doesn't cover every case. What if the user enters 5? You should likely have a default fall through case that spits out some kind of error.</p>\n\n<hr>\n\n<p><code>case (x)</code> sticks out a bit as odd. Just do <code>case x</code>. It's not a big deal though if <code>(x)</code> is your preference. It's just non-common.</p>\n\n<hr>\n\n<p>Instead of handling each cases' code in main, I would extract it into functions. Each function should have one and only one responsibility, and <code>main</code> is no exception. <code>main</code> should typically be responsible for handling program flow, not containing program flow.</p>\n\n<hr>\n\n<p>I would be tempted to use <code>std::vector</code> instead of an array for this. That way you don't have the awkwardness of using songID as a sentinel value.</p>\n\n<hr>\n\n<p>Existing reviews have touched on this, but I shall reiterate.</p>\n\n<p><code>if (songID == NULL)</code> is very wrong. Never compare a non-pointer to <code>NULL</code>. <code>NULL</code> is <em>not</em> <code>0</code>. Ok, it may be technically defined as <code>0</code>. Semantically though, it is much more. It is a pointer that does not point to anything. <code>0</code> is not a pointer, so their comparison makes no sense. Also, if you're using C++11, <code>nullptr</code> should be preferred over <code>NULL</code>.</p>\n\n<hr>\n\n<p>Logic and input should be completely separated. Asking a user about a purchase to be made and excuting a purchase are two separate concerns. Imagine if this were being used for a real record store. Now imagine that they want a feature where customers can sign up to buy a new album as soon as it's released (basically a pre-order system). Ok, great. You've already got the order processing done. Easy! But wait... Your ordering process expects a lot of user input. How do you schedule that? Suddenly someone has to be there to actually enter the orders since your program prompts them.</p>\n\n<p>What if the input of required information were handled separately from the ordering process? Suddenly your ordering process no longer depends on the input of the information and the information. It only depends on the information. This allows you to get the information from wherever you want and pass it on to the actual processing. It's no longer required that the actual processing also handle the input.</p>\n\n<p>It's always possible to have your code do the input grabbing and then processing if those two are handled separately. It's not possible to do only one of two if the two are tied together though. This is why it's crucial to only do one thing. This is the basic crux of the single responsibility principle (though the SRP was formulated and is typically applied in a object oriented context).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T06:52:14.993",
"Id": "64412",
"Score": "1",
"body": "+1 phenomenal review. I especially liked the review of the design, not just the syntax. I'm glad someone tackled the global issue, too. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:54:07.907",
"Id": "64642",
"Score": "2",
"body": "Lets distinguish between global mutable and global immutable state. global const variables are fine. The trouble is the term `variable` it implies that an object can change state but this is not always the case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:33:13.803",
"Id": "64659",
"Score": "0",
"body": "@LokiAstari Very good point. I got caught up in the global witch hunt and forgot that not all globals are mutable :). I'm too used to the \"constants\" terminology. I will update in a second."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T06:38:22.173",
"Id": "38610",
"ParentId": "38602",
"Score": "5"
}
},
{
"body": "<p>Let's analyze this line by line, because there are lots of issues. Generally, problems involve globals (pass class instances instead when they are needed), and <code>goto</code> (no, I'm not against goto - I sometimes use it (to make code more readable), but in this case, you simply tried to replace function calls with <code>goto</code>).</p>\n\n<blockquote>\n<pre><code>/* dycesM */\n\n#include <iostream>\n#include <string>\n#include <string.h>\n</code></pre>\n</blockquote>\n\n<p>Generally, in C++, it's preferred to use <code><cstring></code> instead of <code><string.h></code> from C.</p>\n\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Using <code>using namespace std</code> is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">generally considered harmful</a>.</p>\n\n<blockquote>\n<pre><code>int money = 5000; // Global Variable\n</code></pre>\n</blockquote>\n\n<p>Globals are generally a bad idea, and try to avoid them if possible. Instead, make <code>class</code> or <code>struct</code> called user_t (or something).</p>\n\n<blockquote>\n<pre><code>struct database\n{\n string songName;\n int songPrice;\n int songNumber;\n int songID;\n}userStorage[30], storeStorage[30];\n</code></pre>\n</blockquote>\n\n<p>That one is a tricky code. For me, declaring <code>struct</code>, at variables looks tricky. Instead, make a statement just declaring a <code>struct</code>, and move <code>userStorage</code> to <code>user_t</code> class, and <code>storeStorage</code> to <code>store_t</code> class. This class also needs a better name, as <code>database</code> could be anything. I would rename this to <code>song_data_t</code>, or something like that. Also, using C arrays is usually bad idea, as they cannot expand. Instead use <code>std::set</code> class from <code><set></code> (as it allows easy storage of values (without stupid limits), and checking if they exist in O(1) time). Also, <code>songID</code> gives me feeling of metadata that simply isn't needed.</p>\n\n<blockquote>\n<pre><code>struct transaction\n{\n string songName;\n int songPrice;\n}transactionStorage[30];\n</code></pre>\n</blockquote>\n\n<p>In my opinion, this should also use <code>song_t</code> type. It would use additional 4 bytes for transaction, but it doesn't matter much. Move this to <code>store_t</code> class.</p>\n\n<blockquote>\n<pre><code>void userStorageDisplay()\n</code></pre>\n</blockquote>\n\n<p>This method is duplicated multiple times. Instead, make a method inherited from <code>storage_t</code> for every storage class.</p>\n\n<blockquote>\n<pre><code>{\n for (int i = 0; i <= 30; i++)\n</code></pre>\n</blockquote>\n\n<p>Don't hardcode 30. Instead, store data properly, and use <code>for each</code> loop.</p>\n\n<blockquote>\n<pre><code> {\n if (userStorage[i].songID != NULL)\n</code></pre>\n</blockquote>\n\n<p><code>songID</code> is not a <code>NULL</code> pointer, so it's completely wrong to use it. Many C++ compilers compile <code>NULL</code> to <code>0</code> (because void pointers are useless in C++), but using <code>NULL</code> here doesn't mean it's valid semantically. Many C compilers would refuse this code, but this is C++...</p>\n\n<blockquote>\n<pre><code> {\n cout << \"\\n\" << i << \". \" << userStorage[i].songName << \"\\n\" << endl;\n</code></pre>\n</blockquote>\n\n<p>Oh, wow. If I read this correctly, you are outputing new line three times. You could use <code><< \"\\n\\n\"</code> instead. Well, it's just strange in my opinion. Also, in my opinion, outputing <code>\"\\n\"</code> at beginning of the line feels strange.</p>\n\n<blockquote>\n<pre><code> }\n }\n}\n\nvoid storeStorageDisplay()\n</code></pre>\n</blockquote>\n\n<p>Duplicate code is not a good idea. Make a class.</p>\n\n<blockquote>\n<pre><code>{\n for (int i = 0; i <= 30; i++)\n</code></pre>\n</blockquote>\n\n<p>Again, change this to <code>for each</code> loop.</p>\n\n<blockquote>\n<pre><code> {\n if (storeStorage[i].songID != NULL)\n {\n cout << \"\\n\" << i << \". \" << storeStorage[i].songName << endl;\n cout << \"\\t\" << \"Price: $\" << storeStorage[i].songPrice << \"\\n\" << endl;\n }\n }\n}\n\nvoid transactionStorageDisplay()\n{\n for (int i = 0; i < 30; i++)\n {\n if (transactionStorage[i].songPrice != NULL)\n {\n cout << \"\\n\" << transactionStorage[i].songName << \" $:\" << transactionStorage[i].songPrice << \"\\n\" << endl;\n }\n }\n}\n\nint checkDuplicate(int songStorageValue)\n</code></pre>\n</blockquote>\n\n<p>Move this to <code>user_storage_t</code> class. Also, functions returning booleans should return <code>bool</code>.</p>\n\n<blockquote>\n<pre><code>{\n for (int j = 0; j <= 30; j++)\n</code></pre>\n</blockquote>\n\n<p>With <code>std::set</code>, you can use <code>find</code> method.</p>\n\n<blockquote>\n<pre><code> {\n if (userStorage[j].songID == storeStorage[songStorageValue].songID)\n {\n return 0;\n }\n }\n return 1;\n}\n\nint checkBankDetails(int songNumber)\n</code></pre>\n</blockquote>\n\n<p>Make this <code>user_t</code> method that returns <code>bool</code>, and takes <code>song_t</code> as argument.</p>\n\n<blockquote>\n<pre><code>{\n if (storeStorage[songNumber].songPrice > money)\n {\n return 1;\n }\n}\n\nvoid purchase(int songNumber)\n</code></pre>\n</blockquote>\n\n<p>Make this <code>shop_t</code> method, and give it <code>song_t</code>, and <code>user_t</code> instance. Rename it to <code>ask_for_purchase</code>, or something.</p>\n\n<blockquote>\n<pre><code>{\n int verification;\n int &moneyBalance = money;\n\n cout << \"\\nAre you sure you wish to purchase: \" << storeStorage[songNumber].songName << \" for a price of: \" <<\n</code></pre>\n \n <p>storeStorage[songNumber].songPrice << \" ?\" << endl;\n cout << \"Press 1 to confirm or 2 to exit.\" << endl;\n cin >> verification;</p>\n\n<pre><code> if (verification == 1)\n {\n if (checkBankDetails(songNumber) != 1)\n</code></pre>\n</blockquote>\n\n<p>Move this to <code>verify_purchase</code> method.</p>\n\n<blockquote>\n<pre><code> {\n\n if (checkDuplicate(songNumber) == 1)\n {\n for (int i = 0; i <= 30; i++)\n {\n if (userStorage[i].songID == NULL)\n {\n userStorage[i].songName = storeStorage[songNumber].songName;\n userStorage[i].songNumber = i;\n userStorage[i].songPrice = storeStorage[songNumber].songPrice;\n userStorage[i].songID = storeStorage[songNumber].songID;\n</code></pre>\n</blockquote>\n\n<p>Assign <code>struct</code> directly, instead of reassigning directly. <code>struct</code>s are valid types to assign, you don't have to move every property arround. But I would move this code to <code>insert</code> method anyway.</p>\n\n<blockquote>\n<pre><code> for (int a = 0; a <= 30; a++)\n {\n if (transactionStorage[a].songPrice == NULL)\n {\n transactionStorage[a].songName = storeStorage[songNumber].songName;\n transactionStorage[a].songPrice = storeStorage[songNumber].songPrice;\n</code></pre>\n</blockquote>\n\n<p>Again, assign a struct, and use <code>insert</code> method for storage.</p>\n\n<blockquote>\n<pre><code> money = money - transactionStorage[a].songPrice;\n\n cout << \"\\nRemaining Value: $\" << money << \"\\n\";\n\n a = 30; // To end the loop. \n }\n }\n\n cout << \"\\n\" << storeStorage[songNumber].songName << \" has been added to your library at position number: \" << i << \"\\n\" << endl;\n</code></pre>\n</blockquote>\n\n<p>Again, a long statement, but I'm sure that if you would properly move stuff to methods, it would get shorter.</p>\n\n<blockquote>\n<pre><code> i = 30; // To end the loop.\n }\n }\n }\n else if (checkDuplicate(songNumber) == 0)\n {\n cout << \"\\nYou already own this song. Purchase Cancelled.\" << endl;\n }\n }\n else if (checkBankDetails(songNumber) == 1)\n {\n cout << \"\\nInsufficient funds. Purchase cancelled.\" << endl;\n }\n }\n else if (verification != 1)\n {\n cout << \"Transaction Aborted.\";\n }\n }\n\nvoid main()\n</code></pre>\n</blockquote>\n\n<p>This should be <code>int main</code>. I'm surprised that your compiler accepts such nonsense, as both g++ and clang++ would fail compilation here. C++ specification also requires to stop the compilation. In C++, unlike C, <code>main()</code> is a special method.</p>\n\n<blockquote>\n<pre><code>{\n\n char rerun;\n\n //Store Data added for demonstration purposes. \n\n storeStorage[0].songName = \"Daughter - Youth\";\n storeStorage[0].songPrice = 25;\n storeStorage[0].songID = 2000;\n storeStorage[1].songName = \"Archive - Bullets\";\n storeStorage[1].songPrice = 25;\n storeStorage[1].songID = 2001;\n storeStorage[2].songName = \"Swedish House Mafia - Don't you worry child\";\n storeStorage[2].songPrice = 25;\n storeStorage[2].songID = 2002;\n storeStorage[3].songName = \"Roykossop - Running to the sea\";\n storeStorage[3].songPrice = 25;\n storeStorage[3].songID = 2003;\n storeStorage[4].songName = \"French Teen Idol - Shouting can have different meanings\";\n storeStorage[4].songPrice = 25;\n storeStorage[4].songID = 2004;\n</code></pre>\n</blockquote>\n\n<p>Use <code>song_t</code> constructor here, to remove duplication.</p>\n\n<blockquote>\n<pre><code> do\n {\n int userOperationChoice;\n int userPurchaseQuery;\n\n cout << \"Hello and Welcome to the Dyces Song Library. \\n\\nPlease select one of the operations below. \\n\\n 1 - View your own library \\n\\n 2 - View the Store Library \\n\\n 3 - View your transactions. \\n\\n 4 - Check Bank Details \\n\\n Selection:\";\n</code></pre>\n</blockquote>\n\n<p>This is a long message. So long that Stack Exchange formatter moved it to multiple lines (incorrectly) after pressing quote button. Use string concatenation here, and split it between several lines.</p>\n\n<blockquote>\n<pre><code> cin >> userOperationChoice;\n\n switch (userOperationChoice)\n {\n case(1) :\n</code></pre>\n</blockquote>\n\n<p><code>case</code> statement doesn't require braces or parenthesis.</p>\n\n<blockquote>\n<pre><code> {\n goto userLibrary;\n</code></pre>\n</blockquote>\n\n<p>This design pattern is called \"I'm too cool for a function\". Just use a function. I'm not against <code>goto</code> (I'm one of those rare programmers who think that <code>goto</code> is sometimes useful), but it's not a case here. This can be easily replaced by a function.</p>\n\n<blockquote>\n<pre><code> break;\n }\n case(2) :\n {\n goto storeLibrary;\n break;\n }\n case(3) :\n {\n goto transactionLibrary;\n break;\n }\n case(4) :\n {\n goto bankDetails;\n break;\n }\n</code></pre>\n</blockquote>\n\n<p>There is no error handling. Make a <code>default</code> statement, or the flow will go to <code>userLibrary</code> automatically.</p>\n\n<blockquote>\n<pre><code> }\n\n\n userLibrary:\n\n system(\"CLS\");\n</code></pre>\n</blockquote>\n\n<p>This is not portable. Then again, considering this is Windows, well. I guess it's fine.</p>\n\n<blockquote>\n<pre><code> cout << \"\\nThe current songs in your library are: \\n\\n\";\n userStorageDisplay();\n\n goto programEnd;\n\n\n storeLibrary:\n\n system(\"CLS\");\n cout << \"\\nThe Store's library is: \\n\";\n storeStorageDisplay();\n\n cout << \"\\nPlease enter the song you wish to purchase. \\n\";\n cin >> userPurchaseQuery;\n\n purchase(userPurchaseQuery);\n goto programEnd;\n\n\n transactionLibrary:\n\n system(\"CLS\");\n cout << \"Your transactions are: \\n\";\n transactionStorageDisplay();\n goto programEnd;\n\n\n bankDetails:\n\n char viewTransactionHistory;\n\n system(\"CLS\");\n cout << \"You have: $\" << money << \" left in your bank account.\" << endl;\n\n cout << \"\\nWould you like to check your transaction history? Y/N\" << endl;\n cin >> viewTransactionHistory;\n\n if (viewTransactionHistory == 'y' || viewTransactionHistory == 'Y')\n {\n goto transactionLibrary;\n }\n goto programEnd;\n\n\n programEnd:\n\n cout << \"\\nWould you like to go back to the main menu? Y/N\" << endl ;\n cin >> rerun;\n system(\"CLS\");\n\n } while (rerun == 'y' || rerun == 'Y');\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:18:50.447",
"Id": "64458",
"Score": "1",
"body": "Only `<string.h>` is unneeded; `<string>` should stay. Also, `_t` is reserved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T03:29:54.367",
"Id": "64672",
"Score": "0",
"body": "@Jamal `_t` (as a name beginning with an underscore) is only reserved as a name in the global namespace. Names containing `__` (double underscore) or beginning with an underscore followed by an upper-case letter are reserved to the implementation for all purposes. Names like `storage_t` that contain `_t` are not reserved (unless they run afoul of one of the other rules listed, or one I haven't mentioned -- see [reserved.names] which is 17.6.4.3 in the C++11 standard)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T03:33:27.960",
"Id": "64673",
"Score": "0",
"body": "@ruds: Hm. I once used `_t` is one of my programs, and was told not to do so. I would refrain from using it in my own programs anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T06:36:29.213",
"Id": "64677",
"Score": "0",
"body": "This `_t` usage appears to be controversial. I decided to ask for this at https://codereview.stackexchange.com/questions/38733/how-should-i-mark-types-in-c-and-c-programs."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T08:57:43.847",
"Id": "38616",
"ParentId": "38602",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T02:58:31.313",
"Id": "38602",
"Score": "10",
"Tags": [
"c++"
],
"Title": "A simple array library program"
}
|
38602
|
<p>I'm designing in my spare time a game engine (for fun, not so much for profit, haha). I wanted to design the 'core pipeline' as efficiently as possible. Having a quad-core CPU, I decided to take advantage of parallel processing.</p>
<p>I wanted to implement a lock-free algorithm (or at least, low-locking) to make the pipeline as quick as possible (and to avoid expensive things like lock contention, kernel-mode locking, and context switching as much as possible).</p>
<p>Without further preamble, here is my implementation (slightly shortened):</p>
<p><strong>EnginePipeline.cs</strong></p>
<pre><code>public static partial class EnginePipeline {
private static EngineComponent[] componentPipeline;
private static volatile bool isRunning = false;
private static volatile bool exitFlag = false;
private static Thread[] threadPool;
private static EngineComponent currentComponent;
private static WorkloadSet currentWorkloads = new WorkloadSet(100);
private static void InitThreadPool() {
int numLogicalCores = Environment.ProcessorCount;
int poolSize = numLogicalCores;
if (PipelineConfig.MaxThreads > 0 && numLogicalCores > PipelineConfig.MaxThreads) poolSize = PipelineConfig.MaxThreads;
// One less than the number of cores because the master thread will be used too
poolSize -= 1;
if (poolSize < 0) poolSize = 0;
threadPool = new Thread[poolSize];
for (int i = 0; i < poolSize; i++) {
threadPool[i] = new Thread(ThreadWaitForWork) {
Name = "OphSlave-" + i,
IsBackground = true
};
threadPool[i].Start();
}
Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
Thread.CurrentThread.Name = "OphMaster";
}
/// <summary>
/// Run the pipeline. This method will block indefinitely until something calls
/// <see cref="Shutdown"/> or <see cref="TerminateWithError"/>.
/// </summary>
public static void Run() {
isRunning = true;
SpinWait completionWaiter = new SpinWait();
PipelineWorkload workload = new PipelineWorkload();
while (!exitFlag) {
for (int i = 0; i < componentPipeline.Length; ++i) {
// Set current component
Volatile.Write(ref currentComponent, componentPipeline[i]);
// Calculate the workloads
int range = currentComponent.GetRange();
int blockSize = currentComponent.actualBlockSize;
int numWorkloadsLessOne = range / blockSize - 1;
currentWorkloads.Reset(numWorkloadsLessOne + 1);
completionWaiter.Reset();
// Pre-execute
currentComponent.PreExecute();
// Add the work
for (int wl = 0; wl < numWorkloadsLessOne; ) {
workload.BlockStartInc = wl * blockSize;
workload.BlockEndEx = ++wl * blockSize;
currentWorkloads.Add(workload);
}
workload.BlockStartInc = numWorkloadsLessOne * blockSize;
workload.BlockEndEx = (range + 1);
currentWorkloads.Add(workload);
// Do the work
while (currentWorkloads.Reserve(ref workload)) {
currentComponent.Execute(workload.BlockStartInc, workload.BlockEndEx);
currentWorkloads.Complete();
}
// Wait for every thread to be done
while (!currentWorkloads.AllWorkloadsCompleted) {
completionWaiter.SpinOnce();
}
// Post-execute
currentComponent.PostExecute();
}
}
}
private static void ThreadWaitForWork() {
SpinWait workWaiter = new SpinWait();
PipelineWorkload workload = new PipelineWorkload();
while (!exitFlag) {
workWaiter.Reset();
while (!currentWorkloads.Reserve(ref workload)) {
workWaiter.SpinOnce();
}
EngineComponent currentComponentSnapshot = Volatile.Read(ref currentComponent);
do {
currentComponentSnapshot.Execute(workload.BlockStartInc, workload.BlockEndEx);
currentWorkloads.Complete();
} while (currentWorkloads.Reserve(ref workload));
}
}
}
</code></pre>
<p><strong>PipelineWorkload.cs</strong></p>
<pre><code>[StructLayout(LayoutKind.Explicit)]
public struct PipelineWorkload {
[FieldOffset(0)]
public int BlockStartInc;
[FieldOffset(4)]
public int BlockEndEx;
[FieldOffset(0)]
internal long AsLong;
}
</code></pre>
<p><strong>WorkloadSet.cs</strong></p>
<pre><code>/// <summary>
/// Represents a set of <see cref="PipelineWorkload"/>s that the master thread has created, and that are to be
/// consumed and executed by the master and its slaves.
/// </summary>
/// <remarks>
/// <para>The master adds all the work at the beginning of each tick by calling <see cref="Add"/> with each workload.
/// All the time, the slave threads will be calling <see cref="Reserve"/> to check for added work.</para>
///
/// <para>Once the master has added all work, it will keep calling <see cref="Reserve"/> to also chip in on remaining
/// work, until <see cref="Reserve"/> returns false; after which it will keep checking <see cref="AllWorkloadsCompleted"/>.
/// Each worker thread can decrement the number of workloads remaining by calling <see cref="Complete"/>.
/// Once all workloads are complete, the next tick begins, and the master thread will call <see cref="Reset"/>.</para>
/// </remarks>
public sealed class WorkloadSet {
private long[] workloads = new long[0];
private int producerNextIndex = 0;
private int consumerNextIndex = 0;
private int workloadsRemaining = 0;
/// <summary>
/// Returns true if all workloads have been completed, false if not.
/// </summary>
public bool AllWorkloadsCompleted {
get {
return Volatile.Read(ref workloadsRemaining) == 0;
}
}
/// <summary>
/// Creates a new Workload Set.
/// </summary>
/// <param name="capacity">The initial capacity to use.</param>
public WorkloadSet(int capacity) {
Reset(capacity);
}
/// <summary>
/// Resets the state of this set, and optionally re-sizes the internal buffer according to the requisite capacity.
/// The buffer will only be re-sized if necessary.
/// </summary>
/// <param name="capacity">The requisite capacity on this tick.</param>
public void Reset(int capacity) {
Assure.IsGreaterThan(capacity, 0, "WorkloadSet capacity must be at least 1.");
producerNextIndex = 0;
consumerNextIndex = 0;
Volatile.Write(ref workloadsRemaining, 0);
if (workloads.Length < capacity) workloads = new long[capacity * 2]; /* Double the capacity to eliminate the chance
* of the next call to Reset causing another
* resize if it is (workloads.Length + n) where
* n isn't double the size again.
*/
}
/// <summary>
/// Add a new element to the set.
/// </summary>
/// <param name="workload">The workload to add.</param>
public void Add(PipelineWorkload workload) {
Volatile.Write(ref workloads[producerNextIndex], workload.AsLong);
Interlocked.Increment(ref workloadsRemaining);
Interlocked.Increment(ref producerNextIndex);
}
/// <summary>
/// Lets the calling thread reserve a workload, if one is waiting, for its exclusive execution.
/// </summary>
/// <param name="workload">The workload struct to be set.</param>
/// <returns>True if the workload struct was set, false if not (i.e. false if there is no waiting work).</returns>
public bool Reserve(ref PipelineWorkload workload) {
int consumerNextIndexSnapshot;
do {
consumerNextIndexSnapshot = Volatile.Read(ref consumerNextIndex);
int producerNextIndexSnapshot = producerNextIndex;
if (consumerNextIndexSnapshot == producerNextIndexSnapshot) return false;
}
while (Interlocked.CompareExchange(ref consumerNextIndex, consumerNextIndexSnapshot + 1, consumerNextIndexSnapshot) != consumerNextIndexSnapshot);
workload.AsLong = workloads[consumerNextIndexSnapshot];
return true;
}
/// <summary>
/// Reports that a <see cref="PipelineWorkload"/> that was previously reserved by this thread has completed execution.
/// </summary>
public void Complete() {
Interlocked.Decrement(ref workloadsRemaining);
}
}
</code></pre>
<hr>
<p>I'm interested in two things:</p>
<ol>
<li>Efficiency: Is this implementation as fast as it could be (not considering things like choosing a different language etc.)</li>
<li>Correctness: Are there any parts of this implementation that could actually result in memory corruption or dead/live lock?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:32:38.837",
"Id": "64402",
"Score": "0",
"body": "You're confusing atomic safety with application thread safety, essentially - ie `Volatile.Read(ref workloadsRemaining)` _will_ get you the state of the variable, but your comparison (`==`) is **NOT** part of the guarantee; you can read an actual 0, but by the time you go to compare it, `workloadsRemaining` is now 1, so the condition should maybe be false... you still have timing issues, and aren't necessarily any better off. Same with `WorkloadSet.add(...)` - two entrances to an instance might have operations reordered/interleaved in fun ways. Shared mutable state is evil in threading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:37:16.950",
"Id": "64404",
"Score": "0",
"body": "@ WorkloadSet.add -> Only the master thread can add to the workload, so I didn't make that safe. I need to digest the other stuff you said though :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:39:35.240",
"Id": "64405",
"Score": "0",
"body": "Ah okay I get you - I see your point but the 'workloads remaining' variable can only ever go down (not up) unless someone calls .Add() - and only the master thread can do that. The master thread will not check for completion until it knows its added all the workloads. So I think that's safe?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:50:46.613",
"Id": "64406",
"Score": "3",
"body": "If there's one thing I've heard continuously, it's that you can't anticipate how your code is going to be used - and this includes **by you**. Unless you make it actually safe by design (so that it can only be put together a specific way), it's going to be \"misused\"; for instance, what if a workload processor decides that a result requires more work-sets - simple, just call `Add(...)`! Given current processor trends, I too want a multithreaded engine; however, I'm thinking more along the lines of immutable/functional code so I don't have to worry about locks **at all**.... (ish...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T21:37:44.190",
"Id": "110187",
"Score": "0",
"body": "\"and context switching as much as possible\" - forgive me, I don't pay attention to threading as much as I should, but isn't switching a thread a context switch?"
}
] |
[
{
"body": "<p>you have a little bit of rewriting that can be done on this chunk of code</p>\n\n<pre><code>private static void InitThreadPool() {\n int numLogicalCores = Environment.ProcessorCount;\n int poolSize = numLogicalCores;\n if (PipelineConfig.MaxThreads > 0 && numLogicalCores > PipelineConfig.MaxThreads) poolSize = PipelineConfig.MaxThreads;\n\n // One less than the number of cores because the master thread will be used too\n poolSize -= 1;\n if (poolSize < 0) poolSize = 0;\n\n threadPool = new Thread[poolSize];\n for (int i = 0; i < poolSize; i++) {\n threadPool[i] = new Thread(ThreadWaitForWork) {\n Name = \"OphSlave-\" + i,\n IsBackground = true\n };\n threadPool[i].Start();\n }\n\n Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;\n Thread.CurrentThread.Name = \"OphMaster\";\n}\n</code></pre>\n\n<p>I want to change a Variable name, and I am sure that there are more than should be changed as well. but I have only singled out this method so far.</p>\n\n<p>so this</p>\n\n<pre><code>private static Thread[] threadPool;\n</code></pre>\n\n<p>should be this </p>\n\n<pre><code>private static Thread[] threads;\n</code></pre>\n\n<p>and then instead of counting the logical cores/processors and changing the <code>poolSize</code> variable so many times, just use a ternary statement to assign the value you want to the <code>poolSize</code> variable like this</p>\n\n<pre><code>// One less than the number of cores because the master thread will be used too\nint poolSize = (PipelineConfig.MaxThreads > 0 && Environment.ProcessorCount > PipelineConfig.MaxThreads) ? PipelinConfig.MaxThreads - 1 : Environment.ProcessorCount - 1;\nif (poolSize < 0) poolSize = 0;\n</code></pre>\n\n<p>And then following the logic of that ternary statement <code>MaxThreads</code> is greater than 0 meaning 1 or more and <code>ProcessorCount</code> has to be greater than <code>MaxThreads</code>, so you could get rid of this:</p>\n\n<pre><code>if (poolSize < 0) poolSize = 0;\n</code></pre>\n\n<p>but, I think there will be issues. What if <code>PipelineConfig.MaxThreads</code> is the same as <code>Environment.ProcessorCount</code> ?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T21:32:56.770",
"Id": "60754",
"ParentId": "38604",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:23:08.977",
"Id": "38604",
"Score": "8",
"Tags": [
"c#",
"multithreading",
"lock-free"
],
"Title": "Low-lock Multi-threading Implementation"
}
|
38604
|
<p>I wrote this code to handle a fixed number of priority levels. I believe performance will depend on the number of priority levels.</p>
<p>Considering only a few levels (3 to 5), is there a more efficient way of doing this? I would also like to know how to improve code quality.</p>
<p>I'm just storing the elements in separate queues based on their priority. And to retrieve, looking for the first queue with <code>element_count > 0</code> in ascending or descending order depending on the function being called.</p>
<p>For the queues I'm using the code I posted before: <a href="https://codereview.stackexchange.com/questions/38556/queue-implementation-in-c">Queue implementation in C</a></p>
<p><strong>priority_queue.h</strong></p>
<pre><code>#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
#include <stdlib.h>
#include <stdint.h>
#include "queue.h"
#define PQ_SUCCESS 0
#define PQ_ERROR 1
#define VERY_HIGH_PRIORITY 4
#define HIGH_PRIORITY 3
#define NORMAL_PRIORITY 2
#define LOW_PRIORITY 1
#define VERY_LOW_PRIORITY 0
typedef struct Priority_Queue Priority_Queue;
Priority_Queue *pq_allocate_custom( uint8_t priority_levels,
size_t lines_per_priority_level,
size_t line_capacity );
Priority_Queue *pq_allocate(void);
void pq_free(Priority_Queue *pq);
int pq_insert(Priority_Queue *pq, void *content, uint8_t priority);
int pq_insert_with_default_priority(Priority_Queue *pq, void *content);
void *pq_dequeue_highest(Priority_Queue *pq);
void *pq_dequeue_lowest(Priority_Queue *pq);
void pq_shrink_to_fit(Priority_Queue *pq);
#endif
</code></pre>
<p><strong>priority_queue.c</strong></p>
<pre><code>#include "priority_queue.h"
#define PQ_PRIORITY_LEVELS 5
#define PQ_LINES 4
#define PQ_LINE_CAPACITY 50
//It just keeps separate queues based on priority.
struct Priority_Queue {
Queue **index; //Queue array
size_t element_count;
uint8_t priority_levels;
};
//Internal methods
static void deallocate_all_queues(Priority_Queue *pq)
{
for(uint8_t i = 0; i < pq->priority_levels; ++i)
qu_free(pq->index[i]);
}
//Public methods
//Allocate all data structures according to given values
Priority_Queue *pq_allocate_custom( uint8_t priority_levels,
size_t lines_per_priority_level,
size_t line_capacity )
{
if(priority_levels < 2
|| lines_per_priority_level < 2
|| line_capacity < 1)
return NULL;
//Allocate queue and index
Priority_Queue *pq = malloc(sizeof(Priority_Queue)
+ sizeof(Queue *) * priority_levels);
if(pq == NULL)
return NULL;
//Point the index to the right location
pq->index = (Queue **)(pq + 1);
//Create the queues
for(uint8_t i = 0; i < priority_levels; ++i){
pq->index[i] = qu_allocate_custom(lines_per_priority_level, line_capacity);
//Handle error
if(pq->index[i] == NULL){
//set successfully created queues so deallocation will work
pq->priority_levels = i;
deallocate_all_queues(pq);
free(pq);
return NULL;
}
}
//Set values
pq->element_count = 0;
pq->priority_levels = priority_levels;
return pq;
}
Priority_Queue *pq_allocate(void)
{
return pq_allocate_custom(PQ_PRIORITY_LEVELS, PQ_LINES, PQ_LINE_CAPACITY);
}
void pq_free(Priority_Queue *pq)
{
if(pq == NULL)
return;
deallocate_all_queues(pq);
free(pq);
}
//Will break if priority is not in range
int pq_insert(Priority_Queue *pq, void *content, uint8_t priority)
{
//Try to insert at the correct queue
if(qu_enqueue(pq->index[priority], content) == QU_ERROR)
return PQ_ERROR;
++pq->element_count;
return PQ_SUCCESS;
}
int pq_insert_with_default_priority(Priority_Queue *pq, void *content)
{
return pq_insert(pq, content, pq->priority_levels / 2);
}
void *pq_dequeue_highest(Priority_Queue *pq)
{
if(pq->element_count == 0)
return NULL;
//Find the first queue with element count > 0
uint8_t i;
for(i = pq->priority_levels - 1; qu_get_count(pq->index[i]) == 0; --i)
;
--pq->element_count;
return qu_dequeue(pq->index[i]);
}
void *pq_dequeue_lowest(Priority_Queue *pq)
{
if(pq->element_count == 0)
return NULL;
//Find the first queue with element count > 0
uint8_t i;
for(i = 0; qu_get_count(pq->index[i]) == 0; ++i)
;
--pq->element_count;
return qu_dequeue(pq->index[i]);
}
void pq_shrink_to_fit(Priority_Queue *pq)
{
for(uint8_t i = 0; i < pq->priority_levels; ++i)
qu_shrink_to_fit(pq->index[i]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T09:00:03.363",
"Id": "64415",
"Score": "2",
"body": "`Considering only a few levels (3 to 5), is there a more efficient way of doing this?` Short answer: no. A PQ is typically implemented as some type of heap (binary or Fibonacci primarily). A heap-backed PQ has `O(1)` time to see the top element and `O(lg n)` time to dequeue the top element. With `p = number of priorities`, your queue has `O(p)` time to look and `O(p)` time to dequeue (assuming I've analyzed your queue implementation correctly for `O(1) and O(1)`). Your implementation is basically as fast as it can get for small `p`. When `lg n < p`, a traditional queue is asymptotically faster"
}
] |
[
{
"body": "<p>Like @Corbin said, there is little that can be done to improve the efficiency of your code. But there are a few things I can do to improve the code quality.</p>\n\n<ul>\n<li><p>You list define a lot of priorities in your header file.</p>\n\n<pre><code>#define VERY_HIGH_PRIORITY 4\n#define HIGH_PRIORITY 3\n#define NORMAL_PRIORITY 2\n#define LOW_PRIORITY 1\n#define VERY_LOW_PRIORITY 0\n</code></pre>\n\n<p>Put them in an <code>enum</code> instead.</p>\n\n<pre><code>typedef enum {VERY_LOW, LOW, NORMAL, HIGH, VERY_HIGH} priority_t;\n</code></pre>\n\n<p>You will have to change your struct definition though (and perhaps some other definitions in other areas).</p>\n\n<pre><code>struct Priority_Queue\n{\n Queue **index; //Queue array\n size_t element_count;\n enum priority_t priority_levels;\n};\n</code></pre></li>\n<li><p>This is an odd line that may need re-writing. You should change the overall queue <code>struct</code> to be defined as <code>queue_t</code> in my opinion</p>\n\n<pre><code>typedef struct Priority_Queue Priority_Queue; // can be confusing\ntypedef struct queue_t Priority_Queue; // goes from abstract to concrete, readable\n</code></pre></li>\n<li><p>You have some very long name definition such as <code>pq_insert_with_default_priority</code>. That can be a task to type without an IDE, and annoying if you misspell it. Perhaps you should make the name shorter.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:37:12.783",
"Id": "67742",
"Score": "0",
"body": "Thank you for your remarks. Isn't using the suffix _t considered bad since it's reserved by POSIX?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:39:06.973",
"Id": "67743",
"Score": "0",
"body": "@2013Asker I don't think so, it's used to indicate that a `struct` is a `typedef`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T02:35:03.343",
"Id": "40231",
"ParentId": "38605",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40231",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:26:43.863",
"Id": "38605",
"Score": "5",
"Tags": [
"c",
"queue"
],
"Title": "Very simple priority queue"
}
|
38605
|
<p>I have the following scenario: </p>
<pre><code> class Product < ActiveRecord::Base
belongs_to :categories
end
class Category < ActiveRecord::Base
has_many :products
end
</code></pre>
<p>Categories table has 2 level nesting, for example.
Main category is 'Men', sub-category is 'Accessories' and sub-sub-category is 'Watches'.
<img src="https://i.stack.imgur.com/mKA7R.png" alt="enter image description here"></p>
<p>Now when user creates new product he must choose category(<strong>only main category is required</strong>, but he can also chose sub and sub-sub category optional).</p>
<p>My idea is this: I created 3 different select boxes with same name "product[category_id]", so only the last selected value will be sent to the server through params[:product][:category_id].</p>
<pre><code><div class="col-md-2 main-category">
<small> Main category? required </small>
<%= f.select :category_id,
Category.where('category_id IS ?', nil).collect {|c| [c.name, c.id]},
{ include_blank: "Select category..." },
id: 'main-category', class: 'form-control' %>
</div>
<div class="col-md-2 category-level-1">
<small> What type? optional </small>
<%= f.select :category_id, {}, {}, class: 'form-control' %>
</div>
<div class="col-md-2 category-level-2">
<small> What type? optional </small>
<%= f.select :category_id, {}, {}, class: 'form-control' %>
</div>
</code></pre>
<p>2nd(sub-categories) and 3rd(sub-sub-categories) are initial empty ({}, {}) and hidden through CSS(display: none) and will be populated through Ajax call.</p>
<pre><code>$('#main-category, .category-level-1 > select').change(function() {
var selectBox = this.id;
var selectedValue = $(this).val();
var url = '/categories/' + selectedValue + '/subcategories';
$.get(url, function(data) { createSelect(data, selectBox); });
});
function createSelect(data, selectBox) {
var $currentSelect = null;
if (selectBox == 'main-category') {
$('.category-level-1').show();
$('.category-level-2').hide();
$('.category-level-1 > select').find('option').remove();
$currentSelect = $('.category-level-1 > select');
}
else {
$('.category-level-2').show();
$('.category-level-2 > select').find('option').remove();
$currentSelect = $('.category-level-2 > select');
}
$currentSelect.append('<option selected disabled>Select Category...</option>');
for(var i=0; i<data.length; i++) {
$currentSelect.append('<option value="' + data[i].id + '">' + data[i].name +
'</option>');
}
}
</code></pre>
<p>Where Ajax call is sent to following route (categories controller)</p>
<pre><code>def subcategories
id = params[:id]
@subcategories = Category.where('category_id = ?', id)
render json: @subcategories
end
</code></pre>
<p>So for final result i have following:
<img src="https://i.stack.imgur.com/emm8L.png" alt="enter image description here"></p>
<p>First of all, is it normal to have different inputs in one form with same names created manually like I did in this example? For some reason, it seem like 'code-smell' to me. I'm relatively new to Rails, so I wanted to ask if I am violating some good practices with this code. Can you suggest better ways of achieving the same results?</p>
|
[] |
[
{
"body": "<p>These are nested selects, you can try <a href=\"https://github.com/collectiveidea/awesome_nested_set\" rel=\"nofollow\">awesome_nested_set</a>, and use it like this:</p>\n\n<pre><code><%= f.select :parent_id, \n nested_set_options(Category, @category) {|i| \"#{'-' * i.level} #{i.name}\" } %>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T21:13:20.527",
"Id": "42811",
"ParentId": "38606",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T03:32:01.917",
"Id": "38606",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ruby-on-rails",
"ajax"
],
"Title": "Different selects in one form with same name attribute?"
}
|
38606
|
<p>I'm creating a custom <code>MembershipProvider</code> for an ASP.NET MVC5 application and am wanting to know if this code is acceptable for creating hashed and salted passwords. Is there anything I can do to improve it?</p>
<p><code>EncodePassword</code> is passed the plaintext password from the override functions. </p>
<p>I picked 38 hash iterations arbitrarily and I honestly don't know if it's even necessary or valuable. Should it be higher?</p>
<p><code>_machineKey</code> is auto generated by ASP.NET for each machine/VM the software runs on. I will probably remove this to allow a distributed system and use an application key instead. Though, looking through the documentation for <code>HMACSHA1</code>, would it even seem like this key may be necessary? </p>
<p><code>EncodePassword()</code> result will be stored directly in the database.</p>
<pre><code> private bool CheckPassword(string password, string dbpassword)
{
var salt = GetSalt(dbpassword);
password = EncodePassword(password, salt);
if (password == dbpassword)
{
return true;
}
return false;
}
private string EncodePassword(string password, string salt = "")
{
if (string.IsNullOrEmpty(salt))
salt = CreateSalt();
var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
var bytePassword = hash.ComputeHash(Encoding.Unicode.GetBytes(password + salt));
for (int i = 0; i < 38; i++)
{
bytePassword = hash.ComputeHash(bytePassword);
}
return String.Format("{0}:{1}", bytePassword, salt);
}
private static string CreateSalt(int size = 64)
{
using (var rng = new RNGCryptoServiceProvider())
{
var buff = new byte[size];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
}
private static string GetSalt(string password)
{
var passwordSplit = password.Split(':');
if (passwordSplit.Length == 2)
{
return passwordSplit[1];
}
return String.Empty;
}
</code></pre>
|
[] |
[
{
"body": "<p>This is a pretty good start: you've got salting done pretty well (<code>RNGCryptoServiceProvider</code> is one of the most common recommended was to generate a salt), and the idea of using multiple iterations is a good one.</p>\n\n<p><strong>However</strong>, doing 38 iterations of HMAC SHA1 yourself is not really going to help you much. The point of iterations is to slow down someone who is trying to brute-force passwords by making it take longer to do so. SHA1 is designed to be fast (it has to be in order to be used for message authentication \"at scale\"), so doing it multiple times doesn't slow you down all that much.</p>\n\n<p>Instead, consider using an algorithm purpose-built for password hashing, like <a href=\"http://en.wikipedia.org/wiki/PBKDF2\" rel=\"nofollow noreferrer\">PBKDF2</a>, <a href=\"http://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">bcrypt</a>, or <a href=\"http://en.wikipedia.org/wiki/Scrypt\" rel=\"nofollow noreferrer\">scrypt</a>. They are built on the same cryptographic hash functions, but are tuned for the specific purpose of password hashing. (They also typically recommend <em>more than 1000 iterations</em>, significantly more than your 38.) The easiest thing to do is to use a library like <a href=\"http://www.zer7.com/software.php?page=cryptsharp\" rel=\"nofollow noreferrer\">CryptSharp</a>, <a href=\"https://github.com/shawnmclean/SimpleCrypto.net\" rel=\"nofollow noreferrer\">SimpleCrypto.net</a>, <a href=\"http://bcrypt.codeplex.com/\" rel=\"nofollow noreferrer\">BCrypt.net</a>, or many others.</p>\n\n<p><strong>UPDATE</strong> PBKDF2 is built in to the .NET Framework using the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx\" rel=\"nofollow noreferrer\"><code>Rfc2898DeriveBytes</code></a> class. Here is how to use it (based on your <code>EncodePassword</code> function:</p>\n\n<pre><code>private string EncodePassword(string password, string salt = \"\")\n{\n int numIterations = 1000;\n\n if (string.IsNullOrEmpty(salt))\n salt = CreateSalt();\n\n using (var pbkdf2 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), numIterations))\n {\n var hash = pbkdf2.GetBytes(64);\n return String.Format(\"{0}:{1}\", Convert.ToBase64String(key), salt);\n }\n}\n</code></pre>\n\n<p>Another thing you could do to \"future-proof\" your hashing is to store the number of iterations and the encryption method along with the password. That way, if you decide to change the number of iterations used (for example, you may wish to do so if/when computing power gets to the point that a few thousand iterations isn't slow enough) you won't have to invalidate all existing passwords all at once. For example, PHP's <code>password_hash</code> function (which uses <code>bcrypt</code>, not <code>PBKDF2</code> - but the principle is the same) stores a code representing the hash function used and the number of iterations along with the salt and the password. (For an easy look at how they do it, see <a href=\"https://github.com/ircmaxell/password_compat/blob/master/lib/password.php\" rel=\"nofollow noreferrer\">this implementation</a>.)</p>\n\n<hr>\n\n<p>(<strong>A general word of advice:</strong> it is very tempting to roll your own password encryption. Resist the urge and <a href=\"https://security.stackexchange.com/questions/18197/why-shouldnt-we-roll-our-own\">Just Don't Do It</a>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T19:41:38.797",
"Id": "64626",
"Score": "0",
"body": "Thanks, I have no intention of making my own cryptographic hash, I know that would end badly. I'm trying to avoid anything outside of the base .NET (but will if it's necessary), would `HMACSHA512` with more iterations be a safer mechanism? Or should I still look at PBKDF2 etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T19:58:08.463",
"Id": "64628",
"Score": "0",
"body": "As an added comment about rolling my own, this will sit behind the standard ASP.NET login system and is a drop in replacement method for `UserManager`. So all of the security before it will be left intact."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T18:48:49.557",
"Id": "38711",
"ParentId": "38608",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38711",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T04:04:15.067",
"Id": "38608",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"security",
"cryptography"
],
"Title": "Is this password hashing acceptable for a custom MembershipProvider?"
}
|
38608
|
<p>I am working on a website, and due to some reasons, they want my code to be as short as possible. I have, from my side, tried everything to shorten this code.</p>
<p>So if possible, can you all also help me in making this code shorter? I know that there are vulnerabilities, and I will solve them later.</p>
<p>For now, just help me make it shorter. There are two files that need to be shortened.</p>
<h3>first.php</h3>
<pre><code><?php
$LocationId = (isset($_GET['l'])) ? $_GET['l'] : null;
if( $LocationId )
{ //Make connection to DB
$DBConn = mysqli_connect("localhost","root","","url") or die("Connection Error");
//Selects the URL which mathces the ID or say shortcode
$Resut = mysqli_query($DBConn, sprintf("SELECT url FROM url WHERE id LIKE '%s' LIMIT 0,1", mysqli_real_escape_string($DBConn, $LocationId))) or die( mysqli_error() );
if( $Resut )
{ $Row = mysqli_fetch_array($Resut);
if( isset($Row['url']) && !empty($Row['url']) ) //checks whether URL exist or not
{ header('HTTP/1.1 301 Moved Permanently');
header(sprintf('Location: %s', $Row['url'])); //Redirects the user to the long URL
exit; }
else
{ echo "Invalid URL"; }}} //If wrong ID given by user then returns this error
?>
</code></pre>
<h3>second.php</h3>
<pre><code><?php
$con=mysqli_connect("localhost","root","","url") or die("Connection Error");
$url = $_POST['url'];
$sql=mysqli_query($con,"INSERT INTO url (url)VALUES('$url')");
$result = mysqli_query($con,"SELECT * FROM url WHERE url='$url'");
while($id = mysqli_fetch_array($result))
{
echo " URL Shortened Successfully! ".'<br>'."Your shortened URL is ";
echo 'http://localhost/redirect/' . $id['id'];
}
mysqli_close($con);
?>
</code></pre>
<p>And one more thing: there are 6-7 lines of whose meaning I can't understand, so please explain this to me this as well. Those 6-7 lines are as follows:</p>
<pre><code> $Resut = mysqli_query($DBConn, sprintf("SELECT url FROM url WHERE id LIKE '%s' LIMIT 0,1", mysqli_real_escape_string($DBConn, $LocationId))) or die( mysqli_error() );
if( $Resut )
{ $Row = mysqli_fetch_array($Resut);
if( isset($Row['url']) && !empty($Row['url']) ) //checks whether URL exist or not
{ header('HTTP/1.1 301 Moved Permanently');
header(sprintf('Location: %s', $Row['url'])); //Redirects the user to the long URL
exit; }
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T14:48:06.847",
"Id": "64578",
"Score": "0",
"body": "If its any help, I open sourced my url shortener http://smfu.in (doesn't work as I'm in the middle of a server move). You can see the code at https://github.com/jsanc623/smfu"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-19T12:27:00.607",
"Id": "212128",
"Score": "1",
"body": "Asking for explanations of other people's code is off topic here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-25T18:04:06.010",
"Id": "213531",
"Score": "0",
"body": "Solve the vulnerabilities before shortening your code. It may impact how you can shorten it, may prevent certain things from being used, may add new avenues -- but most importantly, it's very, very difficult to modify extremely golfed code."
}
] |
[
{
"body": "<p>Brevity of code seems an odd point of focus, so I plan on ignoring that. I do, however, have quite a few suggestions, and, convieniently for you, those will probably shorten the code.</p>\n\n<hr>\n\n<p>Don't assume user provided variables are actually set. For example, don't access <code>$_POST['url']</code> directly. Either cover it in a <code>isset</code> guard like you've done other places, or use <code>filter_input</code>. Also, don't trust that user provided variables will be strings. They can be arrays. Might want to add a <code>is_string</code> check.</p>\n\n<hr>\n\n<p>Your code is wide open to SQL injection. <em>Never</em> put an unescaped string into a query. Always either use prepared statements or properly escape strings. Prepared statements tend to be a bit harder to accidentally forget to do, so they are what I usually go with.</p>\n\n<hr>\n\n<p>Use either <code>$a=val</code> or <code>$a = val</code> consistently. Inconsistent coding style is hard on the brain. I <em>strongly</em> suggest the <code>$a = val</code> style.</p>\n\n<hr>\n\n<p>Your indention and line breaks are rather sporadic and odd. <code>first.php</code> is particularly bad. Don't include things on the same line as a brace like:</p>\n\n<pre><code>if ()\n{ something here\n</code></pre>\n\n<p>Also, make sure you develop a habit for indention at each code block level and stick with it.</p>\n\n<hr>\n\n<p>For such a simple script, <code>or die</code> is fine. In general though, it can be a bit of a problem since it doesn't allow for pretty error handling very easily. It's often better to throw an exception so that higher up code can catch it and gracefully render an error instead of just a plain text string. Like I said though, it doens't really apply here since nothing is being rendered anyway.</p>\n\n<hr>\n\n<p>Queries should never fail in production code. This means that <code>if( $Resut )</code> shouldn't be necessary. If the query is failing, something is majorly wrong as it means either an entity is missing (like a DB or table) or a syntax error happened. An entity missing is problematic since it means the DB is out of sync with the code, and a syntax error is worrying since it means that code either wasn't tested and legitimately has a syntax error or that SQL injection is occuring.</p>\n\n<hr>\n\n<p>Basically all of the comments are meaningless. All they do is describe exactly what the code is doing. As long as someone can read PHP, they can already see what the code is doing. Typically comments should describe <em>why</em> something is being done not <em>how</em>. (In algorithmical code, it's fairly common to comment what is going on, but that's because it's much harder to follow than straight forward code like this.)</p>\n\n<hr>\n\n<p>There's no reason to put the final closing tag in a PHP file. It can end up causing complications with trailing whitespace or non-printed characters, and it isn't syntactically required. For this reason, it's become customary lately to omit the closing tag.</p>\n\n<hr>\n\n<p>This comes down to personal preference and OCD really, but I tend to avoid closing resources that last until the end of script execution. The mysql connection is about to be cleaned up anyway when PHP tears itself down, so the <code>mysqli_close</code> is really just superfluous. Some people like the explicitness of it though and it gives them peace of mind knowing that they closed something they opened. That's a very valid approach. There's just not technically a need for it, and I like to avoid clutter.</p>\n\n<p>Note that this does not apply to resources that are not tied to the life time of the script. In general, resources should be held as briefly as reasonably possible.</p>\n\n<hr>\n\n<p><code>empty($x)</code> is equivalent to <code>isset($x) && $x</code>. This means that <code>isset($x) && !empty($x)</code> is the same as <code>isset($x) && isset($x) && $x</code>. In other words, just use <code>!empty($x)</code> if you want the behavior specified. The <code>isset</code> is redundant.</p>\n\n<hr>\n\n<p>For code this simple and short, it's not really necessary, but if this grows, I would extract common setup in a bootstrapping mechanism of some sort. This would allow you to avoid having to duplicate your mysqli conneciton across every file. That means you won't have to change the DB credentials in <code>n</code> files if you need. Instead, you could just change them in one.</p>\n\n<hr>\n\n<p>If the code grows more complex, I would extract functionality into functions. Two obvious functions that could exist now are <code>getUrlFromId</code> and <code>createUrlShortening</code>.</p>\n\n<p>Functions allow your program flow to focus on program flow and not implementation.</p>\n\n<p>Functions also allow for a central point of change. For example, if this grows into a complex website that has tons of pages and whatnot, you're likely going to need to be able to retrieve URLs from many pieces of code. Now imagine that you've found a bug in your URL retrieving code or you want to change a table name or something. You can either <code>Control+F</code> and fix it in a ton of places and hope you haven't missed anything, or you can have one centralized place to change it.</p>\n\n<hr>\n\n<blockquote>\n <p>And one more thing: there are 6-7 lines of whose meaning I can't understand, so please explain this to me this as well.</p>\n</blockquote>\n\n<p>That block of code queries the database for a record in the table <code>url</code> that has an ID equivalent to the location ID the end user provided (via the <code>l</code> GET parameter -- like <code>blah.php?l=33</code>).</p>\n\n<hr>\n\n<pre><code>WHERE id LIKE `%s` LIMIT 0, 1\n</code></pre>\n\n<p>This is wrong for three reasons.</p>\n\n<ul>\n<li>Simple equality should be used like <code>id = blah</code> since there's no pattern matching needed</li>\n<li>The limit is unnecessary since id is (or should be) a primary key and primary keys are unique</li>\n<li><code>id</code> is (or should be) an integer, not a string and thus should be treated as such. Don't escape it with mysqli_real_escape_string, and don't interpolate it in as a string. Instead, make sure it's an integer format and put it in as an integer. The easiest way to do this is simply casting the variable like <code>\" ... WHERE id = \" . (int) $locationID\"</code></li>\n</ul>\n\n<p>If you want to be able to actually detect an invalid integer, you can use something like ctype_digit or filter_input with the proper validation flags:</p>\n\n<pre><code>$blah = (isset($_GET['blah']) && is_string($_GET['blah'])) ? $_GET['blah'] : null;\nif ($blah === null) {\n echo \"You must provide blah!\";\n} else if (!ctype_digit($blah)) {\n echo \"Blah is invalid!\";\n} else {\n $query = \"SELECT blah FROM bleh WHERE id = \" . (int) $blah;\n //(The int cast is unnecessary since you already know it's an int. It can protect\n //against a change in the code flow later allowing an invalid value through though)\n}\n</code></pre>\n\n<p>Not only do prepared statements simplify this situation a bit, they can also allow it to be a bit briefer since you don't have to worry as much about validation or careful interpolation/concatenation.</p>\n\n<hr>\n\n<p>In <code>second.php</code>: inserting a value only to immediately retrieve it is a bit odd. Just use <code>mysqli_insert_id($conn)</code> instead of fetching back the <code>id</code>.</p>\n\n<p>Also, <code>while($id = mysqli_fetch_array($result))</code> doesn't make sense. Only one row should be returned since the user just created one shortening. Oddly enough, this loop can actually return more than 1 item though since I'm assuming the <code>url</code> column isn't unique. If this is the functionality you desire, ignore the point about not fetching back the row. That is required to bring back all of the duplicates.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:08:09.997",
"Id": "64420",
"Score": "0",
"body": "`while($id = mysqli_fetch_array($result))` Yes @corbin you are right it actually sometimes return more rows, \n\n1) Can you please tell me how can I make it in a way so that only 1 result should come out OR \n\n2) we can either do this: When the user gives the URL then `second.php` should also check that whether this URL exist or not, if it exist then a error but if the URL do not exist then no error. \n\nSo please edit my code as per 1st or 2nd way, cause I am actually a noob and I think i won't be able to do it without any problems!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:14:12.270",
"Id": "64422",
"Score": "0",
"body": "I tried to make some changes myself and now it returns only one ID; I just added `LIMIT 0,1` in this line `$result = mysqli_query($con,\"SELECT * FROM url WHERE url='$url' LIMIT 0,1\");` But now the problem is this that the URL is being added in the database! Can you tell me that how can I do some changes in my code so that it should not accept the URLs that already exist in my database. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:39:26.057",
"Id": "64429",
"Score": "0",
"body": "@user3161945 just perform a select to retrieve the ID of an existing one. If it doesn't exist, create a new one instead. For tracking purposes in the future though, you might to actually keep duplicates. As for the technical specifics, perhaps StackOverflow could help you with that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T08:24:17.177",
"Id": "38612",
"ParentId": "38611",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T07:00:42.903",
"Id": "38611",
"Score": "0",
"Tags": [
"php",
"html",
"mysqli",
"http"
],
"Title": "Shorten my URL shortener"
}
|
38611
|
<p>This JavaScript converts degrees to a compass point, e.g. <code>convert.toCompass(140)</code> gets <code>140° -> SE</code>.</p>
<p>I can't help but think: is there a more concise way to do this?</p>
<pre><code>var convert = {
toCompass: function(degrees)
{
if(degrees >= 0 && degrees <= 11.25)
{
return 'N';
}
else if(degrees > 11.25 && degrees <= 33.75)
{
return 'NNE';
}
else if(degrees > 33.75 && degrees <= 56.25)
{
return 'NE';
}
else if(degrees > 56.25 && degrees <= 78.75)
{
return 'ENE';
}
else if(degrees > 78.75 && degrees <= 101.25)
{
return 'E';
}
else if(degrees > 101.25 && degrees <= 123.75)
{
return 'ESE';
}
else if(degrees > 123.75 && degrees <= 146.25)
{
return 'SE';
}
else if(degrees > 146.25 && degrees <= 168.75)
{
return 'SSE';
}
else if(degrees > 168.75 && degrees <= 191.25)
{
return 'S';
}
else if(degrees > 191.25 && degrees <= 213.75)
{
return 'SSW';
}
else if(degrees > 213.75 && degrees <= 236.25)
{
return 'SW';
}
else if(degrees > 236.25 && degrees <= 258.75)
{
return 'WSW';
}
else if(degrees > 258.75 && degrees <= 281.25)
{
return 'W';
}
else if(degrees > 281.25 && degrees <= 303.75)
{
return 'WNW';
}
else if(degrees > 303.75 && degrees <= 326.25)
{
return 'NW';
}
else if(degrees > 326.25 && degrees <= 348.75)
{
return 'NNW';
}
else if(degrees > 348.75 && degrees <= 360)
{
return 'N';
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:25:18.163",
"Id": "64434",
"Score": "0",
"body": "THis question is very similar to another question here. There is a fair amount of discussion on that other question whihc may be useful to you too: http://codereview.stackexchange.com/questions/36744/find-number-matching-range"
}
] |
[
{
"body": "<p>By looking at values in your series of <code>if</code>'s, you can make an array (<code>[]</code>), then calculate which index to pick:</p>\n\n<pre><code>var convert = {\n toCompass: function(degrees)\n {\n return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'][Math.round(degrees / 11.25 / 2)];\n }\n}\n\nalert(convert.toCompass(140)); // SE\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/dMRL5/4/\">JSFiddle demo</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T09:22:09.073",
"Id": "64416",
"Score": "7",
"body": "I'd throw in a `% 360` to be defensive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T08:52:59.017",
"Id": "38615",
"ParentId": "38613",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38615",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-05T08:34:39.770",
"Id": "38613",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Getting a compass point from 140°"
}
|
38613
|
<p><a href="http://qt-project.org/" rel="nofollow">Qt</a> is a cross-platform application and UI framework for developers using <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a> or QML, a <a href="/questions/tagged/css" class="post-tag" title="show questions tagged 'css'" rel="tag">css</a> and <a href="/questions/tagged/javscript" class="post-tag" title="show questions tagged 'javscript'" rel="tag">javscript</a>-like language.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T09:44:21.010",
"Id": "38617",
"Score": "0",
"Tags": null,
"Title": null
}
|
38617
|
Qt is a cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like-language. (Also use the [c++] tag for C++ code.)
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T09:44:21.010",
"Id": "38618",
"Score": "0",
"Tags": null,
"Title": null
}
|
38618
|
<p>A few years ago I required a lightweight in-app-in-memory cache. Requirements:</p>
<ul>
<li>Time complexity <code>O(1)</code> for individual element read/write access</li>
<li>Space complexity <code>O(n)</code> (for <code>n</code> elements)</li>
<li>Safe for concurrent read/write access </li>
<li>Cache size limited by fixed number of entries or max age of entries</li>
</ul>
<p>Before you ask: The code was written in times of .NET 3 and is still required to work in .NET 3.5, so <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache%28v=vs.110%29.aspx"><code>MemoryCache</code></a> was and is no option.</p>
<p>Anyway the code works fine but now looking back in retrospect the design strikes me as a bit non-optimal.</p>
<p>So I'm looking for some input regarding design/best practices/style.</p>
<p><strong>Base cache class implementation</strong></p>
<p>This is the base cache class. The cache entry holds the value to be cached and also some meta data, mainly time of last access and an index reference. The index reference is a node in a linked list. Whenever a cache element is accessed it is being moved to the front of the list. This allows for an easy LRU eviction strategy for a size based cache. The access time can be used by the age based eviction cache.</p>
<p>My main quarrel with this is that the base class contains knowledge about both strategies although it does not implement any of the eviction strategies itself.</p>
<pre><code>public class Cache<TKey, TValue> : IDisposable
{
protected class CacheValue<TCacheKey, TCacheValue>
{
public CacheValue(TCacheValue value)
{
LastAccess = DateTime.Now;
Value = value;
}
public LinkedListNode<KeyValuePair<TCacheKey, CacheValue<TCacheKey, TCacheValue>>> IndexRef { get; set; }
public DateTime LastAccess { get; set; }
public TCacheValue Value { get; set; }
}
protected readonly LinkedList<KeyValuePair<TKey, CacheValue<TKey, TValue>>> _IndexList = new LinkedList<KeyValuePair<TKey, CacheValue<TKey, TValue>>>();
private readonly Dictionary<TKey, CacheValue<TKey, TValue>> _ValueCache = new Dictionary<TKey, CacheValue<TKey, TValue>>();
protected object SyncRoot = new object();
private DateTime _LastCacheAccess = DateTime.MaxValue;
public virtual int Count
{
get
{
lock (SyncRoot)
{
return _ValueCache.Count;
}
}
}
public virtual bool TryGetValue(TKey key, out TValue value)
{
CacheValue<TKey, TValue> v;
value = default(TValue);
lock (SyncRoot)
{
_LastCacheAccess = DateTime.Now;
v = GetCacheValueUnlocked(key);
if (v != null)
{
value = v.Value;
UpdateElementAccess(key, v);
return true;
}
}
return false;
}
protected virtual void UpdateElementAccess(TKey key, CacheValue<TKey, TValue> cacheValue)
{
// update last access and move it to the head of the list
cacheValue.LastAccess = DateTime.Now;
var idxRef = cacheValue.IndexRef;
if (idxRef != null)
{
_IndexList.Remove(idxRef);
}
else
{
idxRef = new LinkedListNode<KeyValuePair<TKey, CacheValue<TKey, TValue>>>(new KeyValuePair<TKey, CacheValue<TKey, TValue>>(key, cacheValue));
cacheValue.IndexRef = idxRef;
}
_IndexList.AddFirst(idxRef);
}
protected virtual CacheValue<TKey, TValue> GetCacheValueUnlocked(TKey key)
{
CacheValue<TKey, TValue> v;
return _ValueCache.TryGetValue(key, out v) ? v : null;
}
public virtual void SetValue(TKey key, TValue value)
{
lock (SyncRoot)
{
SetValueUnlocked(key, value);
}
}
protected virtual CacheValue<TKey, TValue> SetValueUnlocked(TKey key, TValue value)
{
_LastCacheAccess = DateTime.Now;
CacheValue<TKey, TValue> cacheValue = GetCacheValueUnlocked(key);
if (cacheValue == null)
{
cacheValue = new CacheValue<TKey, TValue>(value);
_ValueCache[key] = cacheValue;
}
else
{
cacheValue.Value = value;
}
UpdateElementAccess(key, cacheValue);
return cacheValue;
}
public virtual void Invalidate(TKey key)
{
lock (SyncRoot)
{
_LastCacheAccess = DateTime.Now;
InvalidateUnlocked(key);
}
}
protected void InvalidateUnlocked(TKey key)
{
var value = GetCacheValueUnlocked(key);
if (value != null)
{
_ValueCache.Remove(key);
_IndexList.Remove(value.IndexRef);
}
}
public virtual void Expire(TimeSpan maxAge)
{
lock (SyncRoot)
{
var toExpire = _ValueCache.Where(x => IsExpired(x.Key, x.Value.Value, x.Value.LastAccess, maxAge)).Select(x => x.Key).ToList();
toExpire.ForEach(InvalidateUnlocked);
}
}
public virtual void Expire(int maxSize)
{
lock (SyncRoot)
{
while (_IndexList.Count > maxSize)
{
InvalidateUnlocked(_IndexList.Last.Value.Key);
}
}
}
public virtual void Flush()
{
lock (SyncRoot)
{
_ValueCache.Clear();
_IndexList.Clear();
}
}
protected virtual bool IsExpired(TKey key, TValue value, DateTime lastValueAccess, TimeSpan maxAge)
{
return lastValueAccess + maxAge < _LastCacheAccess;
}
public List<TKey> GetKeys()
{
lock (SyncRoot)
{
return new List<TKey>(_ValueCache.Keys);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
</code></pre>
<p><strong>Implementation for the size limited cache</strong></p>
<p>On every element access we invalidate the elements at the end of the index list as long as the list is longer than number of max entries. Normally this will only evict one element unless the max size has been changed since the last access.</p>
<pre><code>public class SizeLimitedCache<TKey, TValue> : Cache<TKey, TValue>
{
private int _MaxSize;
public int MaxSize
{
get { return _MaxSize; }
set { _MaxSize = value; }
}
public SizeLimitedCache(int maxSize)
{
_MaxSize = maxSize;
}
protected override void UpdateElementAccess(TKey key, CacheValue<TKey, TValue> cacheValue)
{
base.UpdateElementAccess(key, cacheValue);
while (_IndexList.Count > _MaxSize)
{
InvalidateUnlocked(_IndexList.Last.Value.Key);
}
}
public virtual void Expire()
{
base.Expire(MaxSize);
}
}
</code></pre>
<p><strong>Implementation for the automatic age based eviction cache</strong></p>
<p>A background thread is spawned which evicts all entries older than a certain age in regular intervals.</p>
<pre><code>public class AutoExpiryCache<TKey, TValue> : Cache<TKey, TValue>
{
private Thread _ExpiryThread;
private readonly object _WaitLock;
private volatile bool _Quit;
private volatile bool _RestartWait;
private TimeSpan _MaxEntryAge;
public TimeSpan MaxEntryAge
{
get { return _MaxEntryAge; }
set { _MaxEntryAge = value; }
}
private TimeSpan _ExpiryInterval;
public TimeSpan ExpiryInterval
{
get { return _ExpiryInterval; }
set
{
_ExpiryInterval = value;
RestartWaiting();
}
}
private int _NumberOfExpiryRuns = 0;
public int NumberOfExpiryRuns
{
get { return _NumberOfExpiryRuns; }
}
public bool ExpiryThreadIsRunning
{
get { return _ExpiryThread != null && _ExpiryThread.IsAlive; }
}
private void RestartWaiting()
{
_RestartWait = true;
WakeUpThread();
}
private void WakeUpThread()
{
lock (_WaitLock)
{
Monitor.PulseAll(_WaitLock);
}
}
public AutoExpiryCache(string cacheName)
{
_Quit = false;
_RestartWait = false;
_WaitLock = new object();
_MaxEntryAge = TimeSpan.FromHours(1);
_ExpiryInterval = TimeSpan.FromMinutes(30);
_ExpiryThread = new Thread(ThreadMain);
_ExpiryThread.Name = cacheName + "ExpiryThread";
_ExpiryThread.IsBackground = true;
_ExpiryThread.Start();
}
private void ThreadMain()
{
while (!_Quit)
{
lock (_WaitLock)
{
_RestartWait = false;
Monitor.Wait(_WaitLock, ExpiryInterval);
if (!_Quit && !_RestartWait)
{
Expire(MaxEntryAge);
++_NumberOfExpiryRuns;
}
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_Quit = true;
WakeUpThread();
if (_ExpiryThread != null)
{
if (!_ExpiryThread.Join(100))
{
_ExpiryThread.Abort();
}
_ExpiryThread = null;
}
}
base.Dispose(disposing);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-10T14:54:17.437",
"Id": "251491",
"Score": "0",
"body": "Can you please publish the improved code? The base seems very nice, and if it's better now..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-02T14:26:35.633",
"Id": "296660",
"Score": "0",
"body": "MemoryCache class is thread safe. http://stackoverflow.com/a/6738179/665783"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-05T18:52:03.603",
"Id": "297186",
"Score": "0",
"body": "@Jacob: Sure, I never said it wasn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:46:08.053",
"Id": "438195",
"Score": "0",
"body": "Does this design allow us to use azure redis distributed cache in future?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:18:45.953",
"Id": "438268",
"Score": "0",
"body": "@MuraliMurugesan: Not sure exactly what you're after. The code above is what it says on the box - a simple in-memory cache. Redis is an external caching service which is something different. If you want an easily swapable caching implementation in your application I'd suggest you hide that behind a common interface"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:30:31.210",
"Id": "438366",
"Score": "0",
"body": "@ChrisWue Thank you. We are having almost similar design as of yours and it runs only in one webserver and no issues. However, we want to scale it different zones and going to use Azure. Now thinking how this can be rewritten / redesign to work with Redis with large data. We cache almost 5Million Object in a cache for a performance today. Not sure, how Redis will handle those :("
}
] |
[
{
"body": "<p>Before I get to the main issue, first some smaller notes:</p>\n\n<ol>\n<li><p>A type that is nested in a generic type doesn't need to redeclare the type parameters of the parent, it can use them directly:</p>\n\n<pre><code>public class Cache<TKey, TValue>\n{\n protected class CacheValue\n {\n public CacheValue(TValue value)\n {\n LastAccess = DateTime.Now;\n Value = value;\n }\n\n public LinkedListNode<KeyValuePair<TKey, CacheValue>> IndexRef { get; set; }\n public DateTime LastAccess { get; set; }\n public TValue Value { get; set; }\n }\n}\n</code></pre></li>\n<li><p>Even with your design, you should still put code that's specific only to one implementation to the corresponding derived class. This means that the method <code>UpdateElementAccess()</code> should be <code>abstract</code> and each override should contain only the part specific to that implementation.</p></li>\n<li><p>Why are so many of your methods <code>virtual</code> when you never override them?</p></li>\n<li><p>Why does <code>IsExpired()</code> take <code>key</code> and <code>value</code> when it never uses them? <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\">YAGNI.</a></p></li>\n<li><p>The full disposable pattern (with <code>Dispose(bool)</code>) is used when you expect unmanaged resources and a finalizer. You don't have either of those, so you can just make the normal <code>Dispose()</code> <code>virtual</code>.</p></li>\n</ol>\n\n<p>Now, I can think of two ways to solve the <code>CacheValue</code> issue, but neither of them feels very clean to me:</p>\n\n<p>Solution one would be to add a third type parameter to <code>Cache</code> that represents a type derived from <code>CacheValue</code> that's used in the derived class. Something like:</p>\n\n<pre><code>public abstract class Cache<TKey, TValue, TCacheValue>\n where TCacheValue : CacheValue\n{\n protected abstract class CacheValue\n {\n public CacheValue(TValue value)\n {\n Value = value;\n }\n\n public TValue Value { get; set; }\n }\n\n private readonly Dictionary<TKey, TCacheValue> _ValueCache = new Dictionary<TKey, TCacheValue>();\n}\n\npublic class SizeLimitedCache<TKey, TValue> : Cache<TKey, TValue, SizeLimitedCacheValue>\n{\n private class SizeLimitedCacheValue : CacheValue\n {\n public SizeLimitedCacheValue(TValue value)\n : base(value)\n { }\n\n public LinkedListNode<KeyValuePair<TKey, SizeLimitedCacheValue>> IndexRef { get; set; }\n }\n}\n</code></pre>\n\n<p>This code explains the idea, but it doesn't actually compile (for several reasons). The simplest way to fix them would be to move both <code>CacheValue</code>s into the outer scope, which is not very nice.</p>\n\n<p>The second solution is to add a generic property to <code>CacheValue</code>, which will contain the data the derived class needs:</p>\n\n<pre><code>public abstract class Cache<TKey, TValue, TCacheValueData>\n{\n public abstract class CacheValue\n {\n public CacheValue(TValue value)\n {\n Value = value;\n }\n\n public TValue Value { get; set; }\n public TCacheValueData Data { get; set; }\n }\n\n private readonly Dictionary<TKey, CacheValue> _ValueCache = new Dictionary<TKey, CacheValue>();\n}\n\npublic class AutoExpiryCache<TKey, TValue> : Cache<TKey, TValue, DateTime>\n{\n}\n</code></pre>\n\n<p>But this again isn't very clean. Moreover, I believe it's impossible to use this for <code>SizeLimitedCache</code> as you designed it, because you would have to write something like:</p>\n\n<pre><code>public class SizeLimitedCache<TKey, TValue>\n : Cache<TKey, TValue, LinkedListNode<KeyValuePair<TKey, Cache<TKey, TValue, ???>.CacheValue>>>\n</code></pre>\n\n<p>And there is nothing you could write instead of those <code>???</code> that would make the code work correctly.</p>\n\n<p>With both solutions, <code>Cache</code> now has an additional type parameter that's just an implementation detail. Because of that, I would also add an interface like <code>ICache<TKey, TValue></code> and use that in code that uses the cache.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T09:36:50.367",
"Id": "64844",
"Score": "1",
"body": "1+2 good points which are easy to incorporate. 3 - there is a `XYZCacheWithStats` derived class which overrides most of the methods to collect usage statistics. 4- good point, don't quite remember, been too long ago :), 5 - I have a template for the pattern which I tend to use everywhere except in `sealed classes` and it has served me well. For the other refactoring: your first suggestion is not possible to implement like that but it gave me an idea which I'm going to try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:46:18.897",
"Id": "438196",
"Score": "0",
"body": "Does this design allow us to use azure redis distributed cache in future?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T19:55:17.830",
"Id": "38786",
"ParentId": "38619",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "38786",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:37:51.507",
"Id": "38619",
"Score": "13",
"Tags": [
"c#",
"cache"
],
"Title": "In-memory cache implementation"
}
|
38619
|
<p>I am doing a web app for an event company whereby customer can access the website for a self-help instant quotation. Customer will choose the type of event, fill a form and expect an instant quotation.</p>
<p>Can anyone give me some tips how can I improve my design? Below are my current design thoughts.</p>
<p>Quotation class:</p>
<pre><code>public class Quotation{
// Customer specific details
private String customerName;
private String customerEmail;
private String customerMobile;
// Event specific details
private WeddingEvent weddingEvent;
private RetreatEvent retreatEvent;
// ... another 4 or 5 more event classes
// getters and setters
// ...
}
</code></pre>
<p>Event Classes:</p>
<pre><code>public class BaseEvent{
private int attendance;
private String venue;
}
public class WeddingEvent extends BaseEvent{
private boolean needWeddingPlanner;
// getters and setters
// ...
}
public class RetreatEvent extends BaseEvent{
private boolean needBreakfast;
private boolean needLunch;
private boolean needDinner;
// getters and setters
// ...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:50:41.440",
"Id": "64437",
"Score": "1",
"body": "What is this supposed to accomplish, in what way are you **using** these classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T00:50:02.413",
"Id": "64507",
"Score": "0",
"body": "Hi Simon, these are domain classes."
}
] |
[
{
"body": "<p>I would suggest the following potential improvements.</p>\n\n<p>Change the Quotation class to the following</p>\n\n<pre><code>public class Quotation\n{\n private Customer customer;\n\n private List<BaseEvent> events = new List<BaseEvent>();\n\n\n // Getters and setters to access the two entities above.\n}\n</code></pre>\n\n<p>So now you have divided you elements into specific entities like Quotation, Customer and Events.</p>\n\n<p>Adding more details to a Customer or adding a new Event type, don't require change to the Quotation class, but only changes to the specific entity.</p>\n\n<p>On the side, you might also find it beneficial to look into a simple visitor pattern for the events and provide algorithms to etc. calculate total price, date collisions, number of participants etc. etc.</p>\n\n<p>Enjoy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:06:55.537",
"Id": "64426",
"Score": "0",
"body": "Really appreciate the pointers. May I ask further.. if I do a BaseEvent event = new RetreatEvent(), can I do a event.getNeedBreakfast() method? I tried it but I realised I couldn't call getNeedBreakfast() method. Not sure if I am missing out anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:30:26.490",
"Id": "64427",
"Score": "0",
"body": "Having a collection of BaseEvent's only allow you to call the methods that you expose on the BaseEvent class or an IBaseEvent interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:37:24.117",
"Id": "64428",
"Score": "1",
"body": "So those methods will be pretty generic. You might have a Show() method on the IBaseEvent, that all events will implement. Does that help you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T00:49:24.193",
"Id": "64506",
"Score": "0",
"body": "thanks man. That means i have to do a cast if I need to call methods in the child yea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T08:35:06.363",
"Id": "64535",
"Score": "1",
"body": "Yes, that is a possibility, but I normally try to prevent doing type cast's as it can indicate a problem with the design and the layering of the application. The motor/logic of the code should typically not need to know about specific event types. You might implement different renderes, repositories and logic components to support each event type. It might seem like overkill, but as you application gets larger and the logic more complex, it might not be a bad choice to go this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T05:22:43.917",
"Id": "64675",
"Score": "0",
"body": "Thanks @andershybertz! Just to double confirm.. so you are saying that I could implement different renderers or logic components to access the class-specific methods such as the `WeddingEvent.needWeddingPlanner()` and `RetreatEvent.needBreakfast()` right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T05:52:48.080",
"Id": "64676",
"Score": "0",
"body": "Yip - dedicated logic will know all the event details, properties and methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T03:44:20.153",
"Id": "64820",
"Score": "0",
"body": "Thanks so much for the pointers! Really appreciate it. =)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:59:38.383",
"Id": "38622",
"ParentId": "38620",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38622",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:45:42.377",
"Id": "38620",
"Score": "2",
"Tags": [
"java",
"design-patterns"
],
"Title": "Design To Handle Multiple Similar Model Class"
}
|
38620
|
<blockquote>
<p>Tom Sawyer has many friends who paints his fence. Each friend painted
contiguous part of the fence. Some planks could stay unpainted, some
could be painted several times. Program must output the number of
painted planks.</p>
<p><strong>Input format:</strong></p>
<p>First line: <em>N</em> smaller than 100000 - number of Tom Sawyer's friends.</p>
<p><em>N</em> lines (for each friend): <code>a</code>, <code>b</code> smaller than 10<sup>9</sup> - numbers (from the
beginning of the fence) of the first painted by the person plank and
the last painted by the person plank.</p>
<p><strong>Example:</strong></p>
<p>Input:</p>
<pre><code>3
1 2
4 5
2 4
</code></pre>
<p>Output:</p>
<pre><code>5
</code></pre>
<p>The problem is: program must work no more than 1 second on every test.</p>
</blockquote>
<p>I've written many programs of different work ideas, but all of them are not fast enough. I work with online automatic system that checks my code on inputs that are unknown for me, and the system says on some tests that running the program takes 1.032, 1.036 seconds - more than a second.</p>
<p>Example of a working program (idea is to make all segments non-intersecting):</p>
<pre><code>program sortirovkaI;
var a,b:array[1..100000] of longint;
{a - array of numbers of first planks for each person}
{b - array of numbers of last planks for each person}
n,m,i,j:longint;
procedure peresech(var a1,b1,a2,b2:longint);
{processing two segments [a1,b1], [a2,b2] - making them non-intersecting}
{if two segments intersect, procedure will make one of them bigger}
{ and "kill" another - make it [-1,-1]}
begin
if (a1>b2) or (a2>b1) or (a1=-1) or (a2=-1) then
exit;
if a2<a1 then a1:=a2;
if b2>b1 then b1:=b2;
a2:=-1;
b2:=-1;
end;
begin
readln(n);
for i:=1 to n do
read(a[i],b[i]); {filling the arrays}
for i:=2 to n do {for each segment, except the first}
for j:=1 to i-1 do
peresech(a[i],b[i],a[j],b[j]); {make it non-intersecting with every}
{preceding segment}
m:=0; {summarize the lengths of all "not killed" segments}
for i:=1 to n do
if a[i]<>-1 then m:=m+b[i]-a[i]+1;
writeln(m); {output}
end.
</code></pre>
<p>One more example of working program (idea is to "go" along the fence from the beginning to the end):</p>
<pre><code>program sortirovkaI;
var a,b:array[1..100000] of longint;
{a - array of numbers of first planks for each person}
{b - array of numbers of last planks for each person}
n,m,i,j,v,t:longint;
begin
readln(n);
for i:=1 to n do
read(a[i],b[i]); {filling the arrays}
{sorting the segments - a[1]<a[2]<a[3]<...<a[n]}
{ b[1] b[2] b[3] ... b[n]}
{method of inserts - the fastest known on my level}
for v:=1 to n-1 do
begin
i:=v;
while (i>0) and (a[v+1]<a[i]) do i:=i-1;
if i<v then
begin
t:=a[v+1];
for j:=v+1 downto i+2 do a[j]:=a[j-1];
a[i+1]:=t;
t:=b[v+1];
for j:=v+1 downto i+2 do b[j]:=b[j-1];
b[i+1]:=t;
end;
end;
{now start going along the fence}
t:=b[1]; {t is the number of current plank}
m:=b[1]-a[1]+1; {m is the number of painted planks that we've already seen}
for i:=2 to n do {consider every segment}
begin
if a[i]>t then {we see ahead some non-painted planks}
{ and then current segment}
begin
m:=m+b[i]-a[i]+1; {add length of segment to m}
t:=b[i]; {go to the end of the segment}
end
else {the beginning of the segment is somewhere behind us}
if b[i]>t then {but we can see ahead the ending of the segment}
begin
m:=m+b[i]-t; {add to m the way from "here" to the end of current segment}
t:=b[i]; {go to the end of the segment}
end;
end;
{we need sorting because while going along the fence we can go only forward}
writeln(m); {output}
end.
</code></pre>
<p>One more example of code - the last idea, but without sorting the arrays:</p>
<pre><code>program sortirovkaI;
var a,b:array[1..100000] of longint;
n,m,i,j,t,bmax,r:longint;
f:boolean;
begin
readln(n);
for i:=1 to n do {input}
read(a[i],b[i]);
bmax:=b[1];
for i:=1 to n do {searching for the max element n array B }
if b[i]>bmax then bmax:=b[i]; { - the end of the fence}
j:=1;
for i:=1 to n do
if a[i]<a[j] then j:=i; {searching for the index of min element in array A}
t:=a[j];
a[j]:=a[1]; {making the first segment start with min value}
a[1]:=t; {changing a[1],b[1] and a[j],b[j]}
t:=b[j];
b[j]:=b[1];
b[1]:=t;
{now start going along the fence}
t:=b[1]; {t is the number of current plank}
m:=b[1]-a[1]+1; {m is the number of painted planks that we have already seen}
a[1]:=-1; b[1]:=-1; {kill the segment}
repeat
f:=false;
for i:=2 to n do
begin
if t=bmax then {if it is end of the fence}
begin
writeln(m);
exit;
end;
if a[i]=-1 then continue; {if the segment is killed}
if a[i]<=t+1 then {if ahead us are painted planks of current segmant}
begin
if b[i]>t then
begin
m:=m+b[i]-t; {add to m number of planks from here to the end of current segment}
t:=b[i]; {go to the end of the segment}
end;
a[i]:=-1; b[i]:=-1; {kill the segment}
f:=true;
end;
end;
if not f then {if there are non-painted planks ahead}
begin
i:=1;
while a[i]<t do i:=i+1; {searching for the index of min element in array A}
j:=i; {it is number of the first painted plank we can see}
for i:=i to n do
if (a[i]<a[j]) and (a[i]>t) then j:=i;
r:=a[j];
a[j]:=a[1];
a[1]:=r; {making the first segment start with min value}
r:=b[j];
b[j]:=b[1];
b[1]:=r;
t:=b[1]; {t is the number of current plank}
m:=m+b[1]-a[1]+1; {m is the number of painted planks that we have already seen}
a[1]:=-1; b[1]:=-1; {kill the segment}
end;
until t=bmax; {until we reach the end of the fence}
writeln(m); {output}
end.
</code></pre>
<p>This last one is the fastest, but still takes more than a second on some tests.</p>
|
[] |
[
{
"body": "<p>Because of this, the first algorithm is of the <a href=\"http://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow\">order</a> \\$O(n^2)\\$:</p>\n\n<pre><code> for i:=2 to n do {for each segment, except the first}\n for j:=1 to i-1 do\n</code></pre>\n\n<p>The second algorithm is also of the order \\$O(n^2)\\$, because of the <a href=\"http://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow\">insertion sort</a>. Every insertion involves both a search <em>and</em> shifting elements to make room for the insertion.</p>\n\n<p>The third algorithm appears to be of the order \\$O(n^2)\\$ as well.</p>\n\n<p>You do need to sort, but it should not be an insertion sort. You want a fast in-place sort such as <a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow\">quicksort</a>. Quicksort is, on average, of the order \\$O(n log(n))\\$. Once you have that (use a library sort, if available), then the second algorithm should do much better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:00:46.210",
"Id": "64444",
"Score": "0",
"body": "Thanks a lot, that really works. I feel like the quicksort algorithm is the only sensible solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T11:53:06.257",
"Id": "38623",
"ParentId": "38621",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T10:51:53.183",
"Id": "38621",
"Score": "3",
"Tags": [
"optimization",
"array",
"programming-challenge",
"time-limit-exceeded",
"pascal"
],
"Title": "Painting Tom Sawyer's Fence - programming on Free Pascal"
}
|
38621
|
<p>Is the below code efficient for parsing the file, or do I face performance issues? If the latter, please offer suggestions.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <map>
using namespace std;
ofstream outfile;
void writedata(string data, string file)
{
outfile.open(file.c_str(), ios::app);
outfile << data;
outfile.close();
}
int main()
{
ifstream input("data.txt", ios::in);
ofstream out;
string line;
string tmp;
string data;
string filename;
string name;
size_t found;
map<string, string> MyFileMap;
map<string, string>::iterator it;
while (input >> line)
{
found = line.find_last_of("pmf");
if (found != string::npos)
{
name = line.substr(found + 1, line.length());
filename = line.substr(found + 1, line.length());
cout << "filename without txt " << filename << endl;
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
{
if (name.compare(it->first) == 0)
{
while (input >> tmp && tmp.compare("pme"))
{
data += tmp;
}
cout << "Data push " << data << " to " << it->second << endl;
writedata(data, it->second);
data.clear();
break;
}
}
if (it == MyFileMap.end() || MyFileMap.empty())
{
cout << "No match in map" << endl;
filename = filename + ".txt";
cout << "Filename " << filename << endl;
while (input >> tmp && tmp.compare("pme"))
{
data += tmp;
}
cout << "Data push " << data << " to " << it->second << endl;
out.open(filename.c_str());
MyFileMap[name] = filename;
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
{
if (name.compare(it->first) == 0)
{
writedata(data, it->second);
data.clear();
break;
}
}
}
}
}
system("pause");
}
</code></pre>
<p><strong>sample file : data.txt</strong></p>
<pre><code>pmfwork1
data1
data1
pme
pmfwork2
data2
data2
pme
pmfwork3
data3
data3
pme
pmfwork4
data4
data4
pme
</code></pre>
<p>In the above code, I am trying to parse the sample file with <code>pmf</code> and <code>pme</code> as begin and end flags, <code>work</code> as the file name, and <code>data</code> as file contents. Below is the sample file.</p>
<p>I would like to reduce the use of open call for multiple times. It would be of great help if you provide any suggestions.</p>
<p>Above code is generating four different text files: work1, work2 and so on.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:05:39.710",
"Id": "64456",
"Score": "2",
"body": "The only real way to know if you'll face performance issues is to actually run the code. If it turns out to be slow, _then_ optimise it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T23:39:14.473",
"Id": "64661",
"Score": "0",
"body": "I would not worry about performance yet. Worry about readability of your code."
}
] |
[
{
"body": "<ol>\n<li><pre><code>ofstream outfile;\n</code></pre>\n\n<p>Why is this declared global? The variable is only used in <code>writedata</code>. Declare it in this scope.</p></li>\n<li><pre><code>ofstream out;\n</code></pre>\n\n<p>What is the purpose of this stream? It is opened (multiple times!) in the code but never written to.</p></li>\n<li><pre><code>string tmp;\nstring data;\nstring filename;\nstring name;\nsize_t found;\n</code></pre>\n\n<p>You should declare objects in the narrowest scope that they need to exist, instead of the function head.</p></li>\n<li><pre><code>while (input >> line)\n</code></pre>\n\n<p>The operator <code>>></code> will read one word at a time, not a whole line. If you want to read whole lines, you should use <code>while(std::getline(input, line))</code>.</p></li>\n<li><pre><code>found = line.find_last_of(\"pmf\");\n</code></pre>\n\n<p>I think this doesn't do what you expect it to do. It finds the position of the last character in <code>line</code> which is equal to either of the single characters in <code>\"pmf\"</code>. You probably want to use <code>line.rfind(\"pmf\")</code> instead, which returns the position of the last occurrence of the full string <code>\"pmf\"</code>.</p>\n\n<p>Looking at your example file however I believe you <em>actually</em> want to check whether the beginning of the line is <code>\"pmf\"</code> (consider the work string might include <code>\"pmf\"</code>), so you would use <code>line.find(\"pmf\")</code> and check it against <code>0</code> instead of <code>string::npos</code>. </p></li>\n<li><pre><code>name = line.substr(found + 1, line.length());\nfilename = line.substr(found + 1, line.length());\n</code></pre>\n\n<p>These two strings are the same? Why? In the following code they are used interchangeable, so stick to one and remove the other. Even if they were used differently you could still use <code>filename = name</code>.</p>\n\n<p>Also you are trying to get a substring of the same length as the whole line (the second argument to <code>substr</code> is the length of the substring to be extracted), which obviously doesn't work. However <code>substr</code> truncates in this case such that a substring ending at the end of the input string is returned.</p>\n\n<p>The supposed filename you are extracting should be the part after <code>pmf</code> in <code>pmfwork1</code>. However you start the substring one position after the position of the last occurrence of <code>pmf</code>, which would be result in <code>\"mf\"</code> being part of the string. However with the particular example file you provided and in combination with the semantic error I laid out in 5., you actually get the expected result. Here two errors cancel each other. For different input however you would have very unexpected results.</p></li>\n<li><pre><code>for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)\n if (name.compare(it->first) == 0)\n</code></pre>\n\n<p>The whole purpose of a map is to be able to access the values via a key instead of iterating over them. You should use this functionality:</p>\n\n<pre><code>auto it = MyFileMap.find(name);\nif(it != MyFileMap.end())\n // \"name\" found it is at \"it\"\nelse\n // \"name\" is not in \"MyFileMap\"!\n</code></pre></li>\n<li><pre><code>while (input >> tmp && tmp.compare(\"pme\"))\n</code></pre>\n\n<p>Again the input is one word each instead of lines. Data which includes the word <code>\"pme\"</code> would trigger the end.</p></li>\n<li><pre><code>if (it == MyFileMap.end() || MyFileMap.empty())\n</code></pre>\n\n<p>The second condition is redundant. If <code>MyFileMap.empty()</code> is <code>true</code>, then also <code>it == MyFileMap.begin() == MyFileMap.end()</code> at this point.</p></li>\n<li><pre><code>cout << \"Data push \" << data << \" to \" << it->second << endl;\n</code></pre>\n\n<p>Here you try to dereference <code>it</code>, which you previously checked to be <code>MyFileMap.end()</code>. Dereferencing the <code>end()</code> iterator invokes undefined behaviour. Since I guess these lines are debug output only anyway, just remove that part.</p></li>\n<li><pre><code>MyFileMap[name] = filename;\nfor (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)\n{\n if (name.compare(it->first) == 0)\n {\n writedata(data, it->second);\n data.clear();\n break;\n }\n}\n</code></pre>\n\n<p>What is the purpose of this loop? You just inserted the key <code>name</code> into the map and now you search it again. Why not simply access it directly:</p>\n\n<pre><code>MyFileMap[name] = filename;\nwritedata(data, MyFileMap[name]);\ndata.clear();\n</code></pre>\n\n<p>Note however that this is the same as, but in general slower than:</p>\n\n<pre><code>MyFileMap[name] = filename;\nwritedata(data, filename);\ndata.clear();\n</code></pre></li>\n<li><pre><code>system(\"pause\");\n</code></pre>\n\n<p>In order to use <code>std::system</code> you need to <code>#include<cstdlib></code>.</p></li>\n<li><p>What is the purpose of the <code>MyFileMap</code> at all? It stores the <code>name</code>s as keys and <code>filename</code>s as values. The only difference between the two is that <code>filename</code> has an <code>\".txt\"</code> added. Why do you need to save this? You can append the <code>\".txt\"</code> each time you have a new <code>name</code>. This would be much easier to read and much faster.</p></li>\n<li><p>If you are trying to minimize the number of <code>open</code> calls you might want to store all the opened <code>ofstream</code>s in the map and access them as you need them, closing all at the end of the function. Notice however that <code>ofstream</code> is not copyable, so you need to store references to them in the map, instead of the objects themself.</p>\n\n<p>If the input files are not that big, you might also consider saving all the parsed data in memory first and then writing it to the output files in one go. While parsing you can use a string-string map to save the data for each file.</p></li>\n<li><p>You are lacking any check of syntax errors in the input file. You probably should add code that reports back if the syntax is not as expected instead.</p></li>\n</ol>\n\n<p>In summary:</p>\n\n<p>Your code will likely not do what you expect it to do in many cases. You should generate more diverse test cases. (try <code>pmfworkm</code> instead of <code>pmfwork1</code> in your example file and report what happens).</p>\n\n<p>Several parts of the code are redundant (all the map-iterating loops) and at the same time they might be very time costly for large input files (since the map might grow rapidly).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T17:01:27.090",
"Id": "64603",
"Score": "0",
"body": "Thank you for giving me the detailed analysis and i made the changes accordingly and performed different tests after making the suggested changes and that was working as expected."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:41:16.917",
"Id": "38645",
"ParentId": "38626",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Is the below code efficient for parsing the file, or do I face performance issues?</p>\n</blockquote>\n\n<p>If you approach performance problems like this you will be unable to implement any effective optimizations.</p>\n\n<p>There are two ways to tackle optimizing code:</p>\n\n<ul>\n<li><p>the first one is to make sure you avoid efficiency worst cases and pitfalls (prefer integers (or enums) as keys in maps instead of strings for example). This applies to all code you write.</p></li>\n<li><p>the second one is to do these steps, in this order:</p>\n\n<ol>\n<li><p>establish speed requirement for module.</p></li>\n<li><p>measure current performance (i.e. measure what your biggest processor hogs are in the affected code)</p></li>\n<li><p>optimize code focusing on the problem areas</p></li>\n<li><p>go to step 2 and repeat until speed requirement is met.</p></li>\n</ol></li>\n</ul>\n\n<p>Regarding the first way (generic optimizations in written code), your code could use the following improvements:</p>\n\n<ul>\n<li><p>only declare variables right before you use them; this way, in the case of an early return from the function (or in the case the local scope is avoided because of an alternate code path) the constructor code will not be executed at all. The most optimal code possible is the one that isn't executed at all.</p></li>\n<li><p>do not declare global variables.</p></li>\n<li><p>remove unused and redundant variables</p></li>\n</ul>\n\n<p>Regarding the second way of optimizing (what your question seems to be actually about) you have the following steps yet do to:</p>\n\n<ol>\n<li><p>establish speed requirement for the code (i.e. \"how optimized do you need it to be\")</p></li>\n<li><p>measure the current efficiency of the code.</p></li>\n</ol>\n\n<p>Until you do this, it may be that optimization is unnecessary and a waste of time.</p>\n\n<p>As a side note (and not related to your question - just a pet-peeve): please stop putting <code>using namespace std</code> in the global scope. At the very least (if you do use it) use it in function scope, not in file scope - it's bad practice). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T16:59:52.453",
"Id": "64602",
"Score": "0",
"body": "Thank you very much for explanation. This would be really helpful for me in future too :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:48:45.673",
"Id": "38679",
"ParentId": "38626",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:42:18.300",
"Id": "38626",
"Score": "1",
"Tags": [
"c++",
"parsing",
"c++11"
],
"Title": "Is this code efficient for file parsing?"
}
|
38626
|
<p>I am still a beginner in C++ and I am always curious about good/best coding methods.</p>
<p>Let's say I have a program which allows a users to edit the salary of a employee.</p>
<ol>
<li><p>The system will prompt the user which to key in a employee's name first.</p></li>
<li><p>The system will then check whether or not the username exist.</p></li>
<li><p>If the username existed, the system will then allow the user to change the employee's
salary.</p></li>
</ol>
<p>The salary and the name of the person is stored in a text file.</p>
<p><strong>employeeInfo.txt</strong> (formatted by name and salary)</p>
<pre><code>john 1000
mary 2000
bob 3000
</code></pre>
<p><strong>user.h</strong></p>
<pre><code>#ifndef user_user_h
#define user_user_h
#include <iostream>
class user {
public:
user(std::string userName,std::string salary);
std::string getUserName();
std::string getSalary();
void setUserName(std::string userName);
void setSalary(std::string salary);
private:
std::string userName,salary;
};
#endif
</code></pre>
<p><strong>user.cpp</strong></p>
<pre><code>#include "user.h"
#include <iostream>
#include <string>
using namespace std;
user::user(string userName,string salary) {
setUserName(userName);
setSalary(salary);
};
string user::getUserName() {
return userName;
}
string user::getSalary() {
return salary;
}
void user::setUserName(std::string userName) {
this->userName = userName;
}
void user::setSalary(std::string salary) {
this->salary = salary;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "user.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
vector<user> userDetails;
string line;
string userName;
string salary;
ifstream readFile("employeeInfo.txt");
while(getline(readFile,line)) {
stringstream iss(line);
iss >> userName >> salary;
//consturctor
user employeeDetails(userName,
salary
);
userDetails.push_back(employeeDetails);
}
readFile.close();
string name;
cout << "Please enter a user name\n";
cin >> name;
for (int i =0; i<userDetails.size(); i++) {
//search if there's a match
if (userDetails[i].getUserName() == name) {
string newSalary;
cout << "Please enter a new salary" << endl;
cin >> newSalary;
userDetails[i].setSalary(newSalary);
}
}
//display to see if the salary gets updated
for (int i=0; i<userDetails.size(); i++) {
cout << userDetails[i].getSalary << "\n";
}
}
</code></pre>
<p>I am not really sure if my code (shown below) is the worst method to search for a record in a vector and match it against the input of the user. I would like to know is there any way to improve my code. I'd also like to gather some tips and ideas from you all to determine if this is the worst method to search for a record in a vector.</p>
<pre><code>//search for existing username
for (int i =0; i<userDetails.size(); i++) {
if (userDetails[i].getUserName() == name) {
//do stuff
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your question is surprisingly hard to answer, largely because you ask one question in your words, but a different question in your code. Your written question is whether looking up a value by sequentially scanning a vector is the best or worst way to do it. And the answer to that question is nuanced. I'll talk more about this in a bit.</p>\n\n<p>However your code shows a full scenario in which you read a file, look up and edit your single user, and display the full vector's contents. In this fuller context, the performance questions of the sequential scan almost definitely do not matter, as reading and displaying the whole vector will cost more time than you could save by having a smarter look-up. A more typical program might let you perform multiple edits, and then the time it took to look up each person might be more important. So that's another improvement to consider.</p>\n\n<h2>Scanning a Vector</h2>\n\n<p>Scanning a vector with a hand-rolled for loop is not generally considered the best way to do things. It's often much better to find an <a href=\"http://www.cplusplus.com/reference/algorithm/\" rel=\"nofollow noreferrer\">algorithm</a> that does what you want, and use it. In this case we don't know anything particularly useful about the contents of your vector, so the best bet is going to be <a href=\"http://www.cplusplus.com/reference/algorithm/find/\" rel=\"nofollow noreferrer\"><code>find</code></a> or <a href=\"http://www.cplusplus.com/reference/algorithm/find_if/\" rel=\"nofollow noreferrer\"><code>find_if</code></a>. To use <code>find</code>, you'll have to overload <code>operator==</code> in something, and pass it around; to use <code>find_if</code> you can instead create a helper function or overload <code>operator()</code>, or in C++11 you can pass a lambda function. Let's examine the middle option:</p>\n\n<pre><code>struct user_by_name {\n user_by_name(string name) : name(name) {}\n bool operator()(user& user) { return user.getUserName() == name; }\n string name;\n};\n\n: : :\n\nvector<user>::iterator iterFound = std::find_if(userDetails.begin(), userDetails.end(), user_by_name(name));\nif (iterFound != userDetails.end())\n{\n : : :\n}\n</code></pre>\n\n<p>The nice thing about this approach is you can create ways to find users by other criteria, such as a <code>user_by_salary</code>, and substitute it in with almost no code change. The downside is that without making other changes, you'll never get better than \"linear\" performance - on average you'll always have to look through half of the items in your vector to find the one you need.</p>\n\n<h2>Scanning faster</h2>\n\n<p>If there's a natural ordering for the items in your vector, you have two main options. Both of them require implementing an <code>operator<</code>, and thus do change your <code>user</code> struct's usage paterns. And both of them scan faster by being able to skip past some items while finding the one you want.</p>\n\n<ul>\n<li>You can keep the items in the vector, but sort them by this ordering. This allows you to use an algorithm such as <a href=\"http://www.cplusplus.com/reference/algorithm/lower_bound/\" rel=\"nofollow noreferrer\"><code>lower_bound</code></a> to find them in a fraction of the time.</li>\n<li>You can store the items in a different data structure such as a <code>std::map</code> which makes similar use of the ordering to give you the same performance assistance that <code>lower_bound</code> does on the sorted vector.</li>\n</ul>\n\n<p>Choosing between these cases depends on how the data will be used. Again, with just a single edit in your main program, this is all overkill. But if you are going to have a long-running multi-edit scenario, especially one with thousands of employees being looked up by name and updated, it might be worth examining these options.</p>\n\n<h2>Other options</h2>\n\n<p>If you were storing a realistic amount of data about each employee, had a realistic number of employees, and had a lot of tasks you wanted to perform on them, chances are you'd find storing their information in a database would make a lot more sense. Databases solve a lot of problems for you; not only do they support fast look-ups, they handle persistence of the data (loading and saving it as necessary) and, for the right scenarios, save you a lot of time and effort. Obviously for learning how to do some of the C++ programming that you show here, using a database may help you less (although learning how to use a database isn't a bad skill either).</p>\n\n<h2>Other comments</h2>\n\n<p>Finally I wanted to end this review with a list of more generic comments about your actual code. A lot of these things are details you don't need to care about yet, or that may have occurred just in trying to post your code here, but they may help you form better habits as you advance your C++ programming skills.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a> is frowned upon. It's utter anathema in a header file (which you didn't do), but it's also a risk in your cpp file. You're better off either adding the <code>std::</code> prefixes, or adding <code>using std::string;</code> <code>using std::vector;</code> etc. However it's unlikely to matter in code like you show here.</li>\n<li>Your use of whitespace is inconsistent. You don't always put spaces after commas, and sometimes use newlines instead. In some places you use more blank lines that I would consider helpful. Also not going to really matter in code this short.</li>\n<li>Your property accessors (getUserName, getSalary) should be <code>const</code> as they should not visibly modify the object, and probably should return a <code>const string&</code> instead of a mutable copy.</li>\n<li>Your header should include <code><string></code> instead of <code><iostream></code>, and <code>user.cpp</code> can similarly drop its incldue of <code><iostream></code>; you don't appear to use anything from iostream in there. Your <code>main.cpp</code> similarly has a lot of unused includes, but I would expect it's more of a testing file so won't harp on it.</li>\n<li>Your search loop will find multiple matches. If you have multiple employees named <code>bruce</code>, your code will stop at each of them and ask for a new salary. If this is not intentional, you can use <code>break;</code> to avoid this. Note that most of my commentary above assumes you will want to only update a single employee at a time.</li>\n<li>If there's no match, the program directly displays the output without any explanatory messages. That seems a little surprising to me, but perhaps it's intentional.</li>\n</ul>\n\n<p>There's not a lot of self-documentation in your code. You'll note the last two bullets I talk about what's intentional, and in particular that I'm uncertain what you meant for your code to do. Finding the right balance between variable names, function names, and comments will help resolve that in the future. This can start as simply as adding the description you gave in your post as a comment in your <code>main.cpp</code>.</p>\n\n<p>But all that said, I think you're starting off on the right foot. You show some solid understanding, and you also show interest in refining your skills. Congratulations on a good first post here!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T14:46:43.123",
"Id": "64577",
"Score": "0",
"body": "Thanks for your compliment as well as your detailed explanations!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:05:46.057",
"Id": "38634",
"ParentId": "38629",
"Score": "4"
}
},
{
"body": "<p>I just have a little to add to @MichaelUrman's review.</p>\n\n<p>Keep as much code out of <code>main()</code> as practical. It will force you to write better structured code.</p>\n\n<pre><code>int main() {\n std::vector<user> userDatabase = loadEmployees(\"employeeInfo.txt\");\n\n std::string name;\n std::cout << \"Please enter a user name\" << std::endl;\n std::cin >> name;\n\n changeSalary(name);\n display(userDatabase);\n}\n</code></pre>\n\n<p>Storing the salary as a string is probably a bad idea. A <code>long</code> would be more appropriate. (If you need more precision, don't use a <code>float</code> or <code>double</code>, but store the number of cents as a <code>long</code> instead.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T18:26:21.790",
"Id": "38648",
"ParentId": "38629",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38634",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T13:36:34.677",
"Id": "38629",
"Score": "3",
"Tags": [
"c++",
"beginner",
"search"
],
"Title": "Searching and comparing a record"
}
|
38629
|
<p>I have written a Tic-Tac-Toe game. I have a class called <code>GameEndAnalyzer</code> that will check if the game has already ended or not.</p>
<p>Would it violate the Single Responsibility Principle if I will add more responsibilities to this class to not only decide if someone has won the game, but who has won (X or O)? What is the best way to add responsibility to this?</p>
<pre><code>public interface IGameEndAnalyzer
{
bool IsGameEnd(IBoard board);
}
public class GameEndAnalyzer : IGameEndAnalyzer
{
public bool IsGameEnd(IBoard board)
{
return IsAnyRowHasAllSameValue(board) ||
IsAnyColumnHasAllSameValue(board) ||
IsLeftDiagonalHasAllSameValue(board) ||
IsRightDiagonalHasAllSameValue(board);
}
private bool IsAnyRowHasAllSameValue(IBoard board)
{
for (int rowIndex = Board.Row.Top; rowIndex <= Board.Row.Bottom; rowIndex++)
{
var isSameValue = board
.Cells
.WhereInRow(rowIndex)
.AllCellIs_O_Or_X();
if (isSameValue)
{
return true;
}
}
return false;
}
private bool IsAnyColumnHasAllSameValue(IBoard board)
{
for (int columnIndex = Board.Column.Left; columnIndex <= Board.Column.Right; columnIndex++)
{
var isSameValue = board
.Cells
.WhereInRow(columnIndex)
.AllCellIs_O_Or_X();
if (isSameValue)
{
return true;
}
}
return false;
}
private bool IsLeftDiagonalHasAllSameValue(IBoard board)
{
var isSameValue = board
.Cells
.WhereInDiagonalLeft()
.AllCellIs_O_Or_X();
return isSameValue;
}
private bool IsRightDiagonalHasAllSameValue(IBoard board)
{
var isSameValue = board
.Cells
.WhereInDiagonalRight()
.AllCellIs_O_Or_X();
return isSameValue;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T18:43:29.173",
"Id": "64464",
"Score": "0",
"body": "I rewrote my earlier Tic Tac Toe implementation to address your question and amended my answer; [check it out](http://codereview.stackexchange.com/a/38639/2634)."
}
] |
[
{
"body": "<p>You're using extension methods for cells; why do use <code>for</code> loops for rows? It strikes me as weird. Also, there's plenty of repetition in your analyzer; you can do better by abstracting some things away (more on that below).</p>\n\n<p>To answer your main question, <strong>instead of returning <code>bool</code> for whether somebody won, you can return <code>Nullable<Player></code></strong> where <code>Player</code> is an enum with <code>X</code> and <code>O</code> values. This would not in any way violate single responsibility principle because your class' responsibility is to <strong>analyze the game</strong>, and determine the winner. There is no point in finding out if <em>somebody</em> has won, if you don't know who that <em>somebody</em> is.</p>\n\n<p>That being said, I think you could still do better with the implementation. Your <code>GameEndAnalyzer</code> <strong>analyzes each outcome manually, whereas you could've made it more generic</strong> by introducing a concept of “lines” and a few extension methods (somewhat less than you seem to have). </p>\n\n<p><strong>I <a href=\"https://github.com/gaearon/tictactoe/commit/7fe1668afac3fb37adcd4d1bcb67dd1b7ae60f9c\" rel=\"nofollow\">re-wrote</a> my earlier toy <a href=\"https://github.com/gaearon/tictactoe\" rel=\"nofollow\">Tic Tac Toe implementation</a> specifically to address your question</strong>, with the following separation:</p>\n\n<ul>\n<li><p><code>Player</code> is a simple enum:</p>\n\n<pre><code>enum Player {\n X,\n O\n}\n</code></pre></li>\n<li><p><code>IBoard</code> represents a board with an indexer by <code>row</code> and <code>column</code> and <code>Size</code>.</p>\n\n<pre><code>interface IBoard\n{\n int Size { get; }\n Player? this [int row, int column] { get; set; }\n}\n</code></pre>\n\n<p>(really, you don't need anything else in <code>IBoard</code>)</p></li>\n<li><p>The implementation is trivial:</p>\n\n<pre><code>class Board : IBoard\n{\n Player? [,] _cells;\n\n public int Size {\n get { return _cells.GetLength (0); }\n }\n\n public Board (int size)\n {\n _cells = new Player? [size, size];\n }\n\n public Player? this [int row, int column] {\n get {\n return _cells [row, column];\n } set {\n if (_cells [row, column].HasValue)\n throw new InvalidOperationException (\"The cell is already claimed.\");\n\n _cells [row, column] = value;\n }\n }\n}\n</code></pre></li>\n<li><p><code>IBoardAnalyzer</code> has a single method that scans the board to find the winner, similarly to yours:</p>\n\n<pre><code>interface IBoardAnalyzer\n{\n Player? DetermineWinner (IBoard board);\n}\n</code></pre></li>\n<li><p>All the <em>actual</em> heavy-lifting for scanning the board lives in <code>BoardExtensions</code> that can <strong>enumerate board rows, columns and diagonals</strong>. There is also an über-method called <code>SelectAllLines</code> that returns a sequence of all “lines” (rows, columns and diagonals) on the board. Note that <code>BoardExtensions</code> <strong>does no analysis</strong>; it only provides convenience methods for <em>extracting</em> data out of <code>Board</code>.</p>\n\n<pre><code>static class BoardExtensions\n{\n public enum DiagonalKind {\n Primary,\n Secondary\n }\n\n public static IEnumerable<IEnumerable<Player?>> SelectAllLines (this IBoard board)\n {\n return board.SelectAllDiagonals ()\n .Concat (board.SelectAllRows ())\n .Concat (board.SelectAllColumns ());\n }\n\n public static IEnumerable<IEnumerable<Player?>> SelectAllRows (this IBoard board)\n {\n return from row in board.SelectIndices ()\n select board.SelectRow (row);\n }\n\n public static IEnumerable<IEnumerable<Player?>> SelectAllColumns (this IBoard board)\n {\n return from column in board.SelectIndices ()\n select board.SelectColumn (column);\n }\n\n public static IEnumerable<IEnumerable<Player?>> SelectAllDiagonals (this IBoard board)\n {\n return from kind in new [] { DiagonalKind.Primary, DiagonalKind.Secondary }\n select board.SelectDiagonal (kind);\n }\n\n public static IEnumerable<Player?> SelectRow (this IBoard board, int row)\n {\n return from column in board.SelectIndices ()\n select board [row, column];\n }\n\n public static IEnumerable<Player?> SelectColumn (this IBoard board, int column)\n {\n return from row in board.SelectIndices ()\n select board [row, column];\n }\n\n public static IEnumerable<Player?> SelectDiagonal (this IBoard board, DiagonalKind kind)\n {\n return from index in board.SelectIndices ()\n let row = index\n let column = (kind == DiagonalKind.Primary)\n ? index\n : board.Size - 1 - index\n select board [row, column];\n }\n\n public static IEnumerable<int> SelectIndices (this IBoard board)\n {\n return Enumerable.Range (0, board.Size);\n }\n}\n</code></pre></li>\n<li><p>The implementation for <code>BoardAnalyzer</code> <em>uses</em> <code>BoardExtensions</code> to find the winner, but in itself is trivial:</p>\n\n<pre><code>class BoardAnalyzer : IBoardAnalyzer\n{\n public Player? DetermineWinner (IBoard board)\n {\n return (\n from line in board.SelectAllLines ()\n let winner = DetermineLineWinner (line)\n where winner.HasValue\n select winner\n ).FirstOrDefault ();\n }\n\n static Player? DetermineLineWinner (IEnumerable<Player?> line)\n {\n try {\n return line.Distinct ().Single ();\n } catch (InvalidOperationException) {\n return null;\n }\n }\n}\n</code></pre></li>\n<li><p>Finally, I implemented an IO which has a simple interface:</p>\n\n<pre><code>interface IGameIO\n{\n Tuple<int, int> AskNextMove (Player player, IBoard board);\n void DisplayError (GameError error);\n void DisplayWinner (Player player);\n}\n</code></pre></li>\n<li><p>And just as simple implementation:</p>\n\n<pre><code>class ConsoleGameIO : IGameIO\n{\n public Tuple<int, int> AskNextMove (Player player, IBoard board)\n {\n Console.WriteLine (\"\\n\\n\");\n Console.WriteLine (\"{0}, what is your move?\\n\", FormatPlayer (player));\n Console.WriteLine (FormatBoard (board));\n Console.Write (\"\\nType A1 to C3: \", FormatPlayer (player));\n\n return ParseMove (Console.ReadLine ().Trim ().ToUpperInvariant ());\n }\n\n public void DisplayError (GameError error)\n {\n switch (error) {\n case GameError.CellAlreadyOccupied:\n Console.WriteLine (\"Bad move: cell is already occupied.\");\n break;\n case GameError.CouldNotParseMove:\n Console.WriteLine (\"Bad move. Valid moves are A1 to C3.\");\n break;\n default:\n Console.WriteLine (\"Something went wrong.\");\n break;\n }\n }\n\n public void DisplayWinner (Player player)\n {\n Console.WriteLine (\"Congatulations, {0}! You won.\", FormatPlayer (player));\n }\n\n static string FormatBoard (IBoard board)\n {\n return string.Join (\"\\n\", from row in board.SelectAllRows () select FormatRow (row));\n }\n\n static string FormatRow (IEnumerable<Player?> row)\n {\n return string.Join (\"|\", from cell in row select FormatCell (cell));\n }\n\n static string FormatPlayer (Player player)\n {\n return FormatCell (player);\n }\n\n static string FormatCell (Player? cell)\n {\n return cell.HasValue ? cell.Value.ToString () : \"_\";\n }\n\n static Tuple<int, int> ParseMove (string input)\n {\n return Tuple.Create (\n input [0] - 'A',\n input [1] - '1'\n );\n }\n}\n</code></pre></li>\n<li><p>Finally, there goes the <code>Game</code> class with the run loop and <code>Main</code> method:</p>\n\n<pre><code>class Game\n{\n IBoard board;\n IBoardAnalyzer analyzer;\n IGameIO io;\n\n public Game (IBoard board, IBoardAnalyzer analyzer, IGameIO io)\n {\n this.board = board;\n this.analyzer = analyzer;\n this.io = io;\n }\n\n public void Run ()\n {\n Player player = Player.X;\n Player? winner = null;\n\n do {\n Tuple<int, int> move;\n try {\n move = io.AskNextMove (player, board);\n } catch {\n io.DisplayError (GameError.CouldNotParseMove);\n continue;\n }\n\n if (!ValidateMove (move)) {\n io.DisplayError (GameError.CouldNotParseMove);\n continue;\n }\n\n try {\n board [move.Item1, move.Item2] = player;\n } catch (InvalidOperationException) {\n io.DisplayError (GameError.CellAlreadyOccupied);\n continue;\n }\n\n player = GetNextPlayer (player);\n winner = analyzer.DetermineWinner (board);\n\n } while (!winner.HasValue);\n\n io.DisplayWinner (winner.Value);\n }\n\n bool ValidateMove (Tuple<int, int> move)\n {\n return (move.Item1 >= 0 && move.Item1 < board.Size)\n && (move.Item2 >= 0 && move.Item2 < board.Size);\n }\n\n static Player GetNextPlayer (Player player)\n {\n switch (player) {\n case Player.X:\n return Player.O;\n case Player.O:\n return Player.X;\n default:\n throw new NotImplementedException ();\n }\n }\n\n public static void Main (string[] args)\n {\n var game = new Game (new Board (3), new BoardAnalyzer (), new ConsoleGameIO ());\n game.Run ();\n }\n}\n</code></pre></li>\n</ul>\n\n<p><a href=\"https://github.com/gaearon/tictactoe\" rel=\"nofollow\">Check it out on Github</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:48:05.903",
"Id": "38639",
"ParentId": "38632",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "38639",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T14:22:26.063",
"Id": "38632",
"Score": "5",
"Tags": [
"c#",
"game",
"tic-tac-toe"
],
"Title": "Adding more responsibility to this endgame-analyzer class"
}
|
38632
|
<p>Some time ago I wrote a little property class for a then abandoned project. I just stumbled over it again and I would like to know if the design is using good, efficient C++.</p>
<pre><code>#pragma once
#ifndef NO_THREAD_SAFETY
#include <atomic>
#endif
template<typename T1>
class Property {
public:
#ifndef NO_THREAD_SAFETY
typedef std::atomic<long> PropertyID;
typedef std::atomic<T1> PropertyValue;
#else
typedef long PropertyID;
typedef T1 PropertyValue;
#endif
Property(T1 value): value(value), id(id_count++) {
}
Property(): value(), id(id_count++) {
}
Property(const Property &rhs): id(id_count++) {
value = static_cast<T1>(rhs.value);
}
Property(Property &&rhs): value(std::move(rhs.value)), id(id_count++) {
}
const Property &operator=(const Property &rhs) {
value = std::move(static_cast<T1>(rhs.value));
return *this;
}
const Property &operator=(const T1 &rhs) {
value = rhs;
return *this;
}
const Property &operator=(T1 &&rhs) {
value = std::move(rhs);
return *this;
}
bool operator==(const Property &rhs) const {
return value == rhs.value;
}
bool operator==(const T1 &rhs) const {
return value == rhs;
}
bool operator< (const Property &rhs) const {
return value < rhs.value;
}
bool operator< (const T1 &rhs) const {
return value < rhs;
}
void set(const T1 &value) {
this->value = value;
}
T1 get() const {
return value;
}
operator T1() const {
return value;
}
PropertyID getID() const {
return id;
}
private:
PropertyValue value;
PropertyID id;
static PropertyID id_count;
};
template<typename T1>
typename Property<T1>::PropertyID Property<T1>::id_count (0);
</code></pre>
|
[] |
[
{
"body": "<p>These are the things that stuck out to me:</p>\n\n<ol>\n<li>Your copy constructor and move constructor don't result in an identical <code>Property<T1></code> as they increment the <code>id</code>. Why is that? (There is no documentation anywhere in this that helps the consumer of your Property class.)</li>\n<li>Your value constructor <code>Property(T1 value)</code> should probably initialize <code>value</code> with <code>std::move(value)</code>. It has already received a copy (perhaps moved), so it is safe to move from <code>value</code>.</li>\n<li>Your copy constructor uses what appears to be a superfluous <code>static_cast<T1></code> and uses the constructor body instead of an initialization list. I would suggest this be more like the move constructor just without the call to <code>std::move</code>.</li>\n<li><p>As nothing appears to change the value of <code>id</code> after it has been constructed, I don't see the benefit of <code>id</code> being <code>atomic</code>. I do understand the value of <code>id_count</code> being atomic, but making them both atomic seems to be asking for unnecessary overhead. Related, perhaps the usage of <code>id_count</code> should be moved to a static function so that it cannot be subverted.</p>\n\n<pre><code>static PropertyID getNextId() { // assumes PropertyID is non-atomic\n static AtomicPropertyID id = 0; // and AtomicPropertyID is conditionally atomic\n return id++;\n}\n</code></pre></li>\n<li><p>I don't quite understand how <code>Property<T1></code> is expected to be used. Does it go in a collection of properties? Is it used to declare as members of another type? If the former, the implementation of <code>operator<</code> doesn't seem to provide any useful characteristics for finding the right property. If the latter, the encapsulation seems to be a very long winded way of conditionally making a member <code>atomic</code> - since there is no business logic in the setter or getter methods, and no way to provide that other than inheriting, I'm unclear what the benefit is of using this class.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T20:30:20.490",
"Id": "64630",
"Score": "0",
"body": "Thanks! Very helpful answer. I'll just comment on a few things: `1)` Copying should result in a new ID because the copied property can be altered independently. Moving of course shouldn't. `3)` I can't remember why I did this in the first place! `4)` `id` being atomic was indeed unnecessary. `5)` I don't know why I wrote it in the old project, but such class can be useful when adding serialization specializations, or adding callbacks for when values are changed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T16:53:58.120",
"Id": "38641",
"ParentId": "38635",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:18:27.830",
"Id": "38635",
"Score": "3",
"Tags": [
"c++",
"c++11",
"properties"
],
"Title": "Generic Property class"
}
|
38635
|
<p>I'm trying to learning JS good practices. With jQuery, everything was easier and organized. With JS, I really don't know if I doing this right.</p>
<p>I must repeat the element I am manipulating all the time? For example:</p>
<pre><code>elementHere.className = "";
elementHere.classList.add(test);
elementHere.addEventListener(etc, function() {
}, true);
</code></pre>
<p>Is it a a good code, for example? Is it DRY? I really need to repeat the element name all the time? How to improve?</p>
<p>I would like tips to improve and make it DRY! I did not find any tutorial on the internet.</p>
<p>I think it is also not good for maintenance.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:19:10.190",
"Id": "64449",
"Score": "0",
"body": "why not: `elementHere.className = test;` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:22:44.867",
"Id": "64450",
"Score": "0",
"body": "The empty value removes the current class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:25:26.803",
"Id": "64451",
"Score": "1",
"body": "But you don't need it if you are setting class using className directly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:51:19.430",
"Id": "64452",
"Score": "5",
"body": "This code doesn't really need to be DRY'd up. If you were doing the same thing to multiple elements then you would be repeating yourself, but not in this case."
}
] |
[
{
"body": "<p>This code is perfectly fine (aside from the fact that it's weird to clean up <code>className</code> and then add one item to <code>classList</code>—might as well set <code>className</code> directly).</p>\n\n<p>DRY is about repetition of logic (which is dangerous because you may forget to change it in one place when you change it in the other place). Repetition of variable name is totally fine. </p>\n\n<p>In fact, sometimes some verbosity is preferred to excessive succinctness.</p>\n\n<pre><code>// Bad\n\nsb.className = \"\";\nsb.classList.add(test);\nsb.dataset.kind = 'web';\nsb.addEventListener('click', function() {\n}, true);\n\n\n// Good\n\nsearchWebButton.className = \"\";\nsearchWebButton.classList.add('search');\nsearchWebButton.dataset.kind = 'web';\nsearchWebButton.addEventListener('click', function() {\n}, true);\n</code></pre>\n\n<p>You're not repeating yourself—these are several distinct actions, and they are obvious.<br>\nThere is nothing to simplify here.</p>\n\n<p>As noted by Greg, if you did this sequence of calls for <strong>several</strong> elements, you could have extracted them into a function:</p>\n\n<pre><code>// Hm-kay\n\nsearchWebButton.className = \"\";\nsearchWebButton.dataset.kind = 'web';\nsearchWebButton.classList.add('search');\nsearchWebButton.addEventListener('click', function() {\n}, true);\n\nsearchHistoryButton.className = \"\";\nsearchHistoryButton.dataset.kind = 'history';\nsearchHistoryButton.classList.add('search');\nsearchHistoryButton.addEventListener('click', function() {\n}, true);\n\n\n// Good\n\nfunction setupSearchButton(btn, kind) {\n btn.className = \"\";\n btn.classList.add('search');\n btn.dataset.kind = kind;\n btn.addEventListener('click', function() {\n }, true);\n}\n\nsetupSearchButton(searchWebButton, 'web');\nsetupSearchButton(searchHistoryButton, 'history');\n</code></pre>\n\n<p>Note that <code>btn</code> by itself is short but not descriptive, and it would make a bad name in outer scope, but as a parameter to <code>setupSearchButton</code> it's obvious so we can keep it short.</p>\n\n<p>It also might be a good idea to extract initialisation code if the initialization is long and you have several other elements to initialize (and maybe something else) in one function:</p>\n\n<pre><code>// Hm-kay\n\nfunction initialize() {\n searchField.className = \"\";\n searchField.classList.add('search');\n searchField.addEventListener('change', function() {\n search();\n }, true);\n searchField.addEventListener('focus blur', function() {\n refreshSearchPlaceholder();\n }, true);\n\n searchWebButton.className = \"\";\n searchWebButton.dataset.kind = 'web';\n searchWebButton.classList.add('search');\n searchWebButton.addEventListener('click', function() {\n }, true);\n\n doSomethingElseForInitialization();\n}\n\n\n// Good\n\nfunction initialize() {\n initializeSearchField(searchField);\n initializeSearchButton(searchWebButton);\n doSomethingElseForInitialization();\n}\n\nfunction initializeSearchField(field) {\n field.className = \"\";\n field.classList.add('search');\n field.addEventListener('change', function() {\n search();\n }, true);\n field.addEventListener('focus blur', function() {\n refreshSearchPlaceholder();\n }, true);\n}\n\nfunction initializeSearchButton(btn) {\n btn.className = \"\";\n btn.classList.add('button');\n btn.dataset.kind = 'web';\n btn.addEventListener('click', function (e) {\n e.preventDefault();\n search();\n }, true);\n}\n</code></pre>\n\n<p>For some ideas about easy-to-maintain JS code, read <a href=\"https://github.com/airbnb/javascript\" rel=\"nofollow\">Airbnb Javascript Guide</a> (or <a href=\"https://github.com/airbnb/javascript#resources\" rel=\"nofollow\">any other popular guide</a>, for that matter).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T15:06:09.770",
"Id": "65325",
"Score": "0",
"body": "Honestly? Thank you! Epic answer! Happy new year, Dan."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T21:02:54.060",
"Id": "38654",
"ParentId": "38637",
"Score": "4"
}
},
{
"body": "<p>You can use with statement:</p>\n\n<pre><code>with(elementHere){\n className = \"\";\n classList.add(test);\n addEventListener(etc, function() {\n }, true);\n}\n</code></pre>\n\n<p>But Google Chrome's JavaScript engine will not optimize this code if the parser encounters with statement and with statement is not popular among JavaScript developers. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:38:42.060",
"Id": "64649",
"Score": "1",
"body": "While technically it answers OP's question, I doubt this is the kind of advice we want to give on CodeReview. [`with` in code written by humans is bad, period.](http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/) (Nothing wrong with using `with` in generated code though if you know what you're doing—I'm thinking Underscore templates.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T22:02:45.330",
"Id": "38722",
"ParentId": "38637",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38654",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T15:07:34.963",
"Id": "38637",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to improve my JS code? Avoid repeated element"
}
|
38637
|
<p>I've built a small library that I use to boot or start a web application. The library code has been posted below, as well an example of application code. I'm looking for ways to make the code more concise or "tighter".</p>
<p>If there's anything I can do to make the comments better, let me know.</p>
<p><strong>Library Code</strong></p>
<pre><code>/*******************************************************************************
**BOOTER
** manageGlobal - manages the single global variable that BOOT uses
** validateBrowser - validates the browser and version type
** configureFrame - passes a user defined function to config_boot which will
** configure the booter
** setResources - appends a user defined object to config_boot*
** bootResources - boots or starts the application, checks validation and
** calls the user defined function, then calls checkStorageAndBoot
** checkStorageAndBoot - checks storage and loops through the tokens loading
** as needed.
** parseResourceToken - parses the resource object, calls ajax, and adds
** elements as needed
** addElement - adds a resource element based on type ( htm, css, js, txt,
** etc. )
** addElementText - adds a txt file which may contain any kind of
** static text
*******************************************************************************/
(function () {
"use strict";
var $A,
$P = {},
$R = {};
// holds boot configuration info -> encapsulate this some where else.
$R.config_boot = {};
// requires utility, comms, and dom
// resources are loaded to the dom and their status is
// communicated to other packages
(function manageGlobal() {
if (window.$A && window.$A.pack && window.$A.pack.utility &&
window.$A.pack.comms && window.$A.pack.dom) {
$A = window.$A;
$A.pack.booter = true;
} else {
throw "booter requires utility, dom, and comms module";
}
}());
// only working with modern browsers
$P.validateBrowser = function (obj) {
var name = 'unknown',
browser_version = 'unknown',
element,
temp;
$A.Reg.set('browser_type', null);
$A.Reg.set('browser_validated', null);
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
$A.Reg.set('browser_type', 'ie');
name = 'Internet Explorer';
browser_version = parseFloat(RegExp.$1);
if (browser_version >= obj.In) {
$A.Reg.set('browser_validated', true);
return;
}
} else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
$A.Reg.set('browser_type', 'ch');
name = 'Chrome';
browser_version = parseFloat(RegExp.$1);
if (browser_version >= obj.Ch) {
$A.Reg.set('browser_validated', true);
return;
}
} else if (/Safari/.test(navigator.userAgent)) {
$A.Reg.set('browser_type', 'sa');
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
name = 'Safari';
browser_version = parseFloat(RegExp.$1);
if (browser_version >= obj.Sa) {
$A.Reg.set('browser_validated', true);
return;
}
} else if (navigator.userAgent.match(/Firefox[\/\s](\d+\.\d+)/)) {
$A.Reg.set('browser_type', 'ff');
temp = navigator.userAgent.match(/Firefox[\/\s](\d+\.\d+)/);
name = 'Firefox';
browser_version = parseFloat(temp[1]);
if (browser_version >= obj.Fi) {
$A.Reg.set('browser_validated', true);
return;
}
}
if (!name) {
name = 'X';
}
if (!browser_version) {
browser_version = 'y';
}
element = document.getElementById('browser_validation');
element.innerHTML += " You are running " + name +
" " + browser_version + ".";
element.style.display = 'block';
$A.Reg.set('browser_validated', false);
$A.Reg.set('browser_element', element);
};
// things the framework needs to get ( server paths, server variables, etc. )
// and to set ( events, client variables, etc )
$P.configureFrame = function (func) {
$R.config_boot.func = func;
};
// sets version and resoures to load
$P.setResources = function (obj) {
$R.config_boot = $A.extend($R.config_boot, obj);
};
$P.bootResources = function (skip_validation) {
var validated = $A.Reg.get('browser_validated'),
element;
if (!skip_validation && !validated) {
return;
}
if (!validated) {
// we are skipping validation, remove the validation message
element = $A.Reg.get('browser_element');
element.style.display = 'none';
}
// run the configuration function
if ($R.config_boot.func) {
$R.config_boot.func();
}
// checkStorage for previous resources saved in storage and then boot
$R.checkStorageAndBoot();
};
$R.checkStorageAndBoot = function () {
var kindex,
length;
if (localStorage.file_version && localStorage.file_version >=
$R.config_boot.file_version) {
$R.config_boot.cached = true;
} else {
localStorage.file_version = $R.config_boot.file_version;
$R.config_boot.cached = false;
}
for (kindex = 0, length = $R.config_boot.resources.length;
kindex < length; kindex += 1) {
$R.parseResourceToken($R.config_boot.resources[kindex], null);
}
};
$R.parseResourceToken = function (source, callback) {
var matches,
prefix,
file_token;
// START (/ or //) () / () (.) () END
matches = source.match(/^(\/\/|\/)?([\w\/\.]*)\/([\w\.]+)(\.)([\w]+)$/);
if (matches) {
prefix = matches[1];
file_token = 'file_' + matches[3] + '_' + matches[5];
source = source + '?_time=' + new Date().getTime();
}
if ($R.config_boot.cached) {
$R.addElement(file_token, callback, localStorage[file_token]);
return;
}
// relative to directory || relative to root
if (prefix === undefined || prefix === '/') {
$A.serialAjax(source, function (response_text) {
$R.addElement(file_token, callback, response_text);
localStorage[file_token] = response_text;
});
return;
}
// not implemented yet
if (prefix === '//') {
return;
}
};
$R.addElement = function (file_token, callback, response_text, source) {
var file_type = file_token.match(/file_[\x20-\x7E]+_([\x20-x7E]+)$/)[1],
element;
if (file_type === 'txt') {
$R.addElementText(callback, response_text);
return;
}
if (file_type === 'htm') {
element = document.createElement("div");
element.id = file_token;
if (!source) {
element.innerHTML = response_text;
document.body.appendChild(element);
if (callback) {
callback();
}
$A.Event.trigger(file_token);
}
return;
}
if (file_type === 'js') {
element = document.createElement('script');
element.id = file_token;
if (!source) {
element.innerHTML = response_text;
document.head.appendChild(element);
if (callback) {
callback();
}
} else {
element.onload = callback;
element.async = true;
element.src = source;
document.head.appendChild(element);
}
$A.Event.trigger(file_token);
return;
}
if (file_type === 'css') {
if (!source) {
element = document.createElement('style');
element.id = file_token;
element.innerHTML = response_text;
document.head.appendChild(element);
if (callback) {
callback();
}
} else {
element = document.createElement("link");
element.onload = callback;
element.id = file_token;
element.rel = "stylesheet";
element.type = "text/css";
element.href = source;
document.head.appendChild(element);
}
$A.Event.trigger(file_token);
return;
}
if (file_type === 'ico') {
element = document.createElement("link");
element.onload = callback;
element.id = file_token;
element.rel = "icon";
if (!source) {
element.href = response_text;
} else {
element.href = source;
}
document.head.appendChild(element);
$A.Event.trigger(file_token);
return;
}
if (file_type === 'png') {
element = document.getElementById(file_token);
element.onload = callback;
element.id = file_token;
element.src = response_text;
$A.Event.trigger(file_token);
return;
}
};
$R.addElementText = function (callback, response_text) {
var regex,
token_content,
subtoken,
subtoken_text,
name,
name_is_variable,
index,
length;
regex = /\/\*<\|([\x20-\x7E]+)(_[\x20-\x7E]+)\|>\*\//g;
token_content = response_text.split(regex);
length = token_content.length;
for (index = 1; index < length; index += 3) {
subtoken = 'file_' + token_content[index] +
token_content[index + 1];
subtoken_text = token_content[index + 2];
name = token_content[index];
// handles variable based statics
name_is_variable = name.match(/\{([\x20-\x7E]*)\}/);
if (name_is_variable) {
if (name_is_variable[1] === $A.Reg.get('browser_type')) {
$R.addElement(subtoken, callback, subtoken_text);
}
// straight statics
} else {
$R.addElement(subtoken, callback, subtoken_text);
}
}
};
window.$A = $A.extendSafe($A, $P);
}());
</code></pre>
<p><strong>Application Code</strong></p>
<pre><code>/*******************************************************************************
**BOOT
*******************************************************************************/
/*jslint
browser: true,
forin: true,
plusplus: true,
eqeq: true,
*/
/*global
$A,
$
*/
(function () {
"use strict";
var debug = true;
function libHasLoaded() {
// ( 1 ) Validate browser by type and version number ( filter out older browsers )
$A.validateBrowser({
In: 10,
Fi: 14,
Sa: 5,
Ch: 18
});
// ( 2 ) Configure the framework
$A.configureFrame(function () {
// add FRAME events
$A.Event.add('file_arcmarks_js', function () {
$A.getDomElements('E');
$A.initByProperty('init');
});
$A.Event.add('file_jqueryui_js', function () {
$A.getLibElements('J', $);
$A.initByProperty('initJ');
});
// add FRAME variables
$A.Reg.setMany($A.getData('universals'));
$A.Reg.setMany({
path_ajax: 'arcmarks/source/class.CMachine.php',
path_pictures: 'arcmarks/pictures/',
path_images: 'arcmarks/images/'
});
});
if (debug) {
$A.setResources({
file_version: Date.now(),
resources:
[
'arcmarks/source/arcmarks.txt',
'arcmarks/source/arcmarks.htm',
'arcmarks/source/arcmarks.js',
'arcmarks/source/arc_large.txt'
]
});
} else {
$A.setResources({
file_version: 5,
resources:
[
'arcmarks/source/arcmarks.txt',
'arcmarks/source/arcmarks.htm',
'arcmarks/source/arcmarks.js',
'arcmarks/source/arc_large.txt'
]
});
}
// ( 3 ) Boot or start the application
$A.bootResources();
}
var script_el = document.createElement('script');
script_el.src = 'arcmarks/source/arc.js';
document.head.appendChild(script_el);
script_el.onload = function () {
libHasLoaded();
};
}());
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<p>This</p>\n\n<pre><code> if (!name) {\n name = 'X';\n }\n</code></pre>\n\n<p>can be changed by using a fairly common logic trick:</p>\n\n<pre><code>name = name || 'X';\n</code></pre>\n\n<p>This could be simplified, mostly using some sugar:</p>\n\n<pre><code>$R.checkStorageAndBoot = function () {\n var kindex,\n length;\n if (localStorage.file_version && localStorage.file_version >=\n $R.config_boot.file_version) {\n $R.config_boot.cached = true;\n\n } else {\n localStorage.file_version = $R.config_boot.file_version;\n $R.config_boot.cached = false;\n\n }\n for (kindex = 0, length = $R.config_boot.resources.length;\n kindex < length; kindex += 1) {\n $R.parseResourceToken($R.config_boot.resources[kindex], null);\n }\n};\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>$R.checkStorageAndBoot = function () {\n var i, //Going Spartan for a simple for loop is more readable\n length,\n fs = localStorage, //localStorage is so wordy\n config = $R.config_boot; //So is $R.config_boot\n //No need to first check for fs.file_version \n config.cached = (fs.file_version >= config.file_version);\n fs.file_version = config.file_version;\n\n for (i = 0, length = config.resources.length; i < length; i++) {\n $R.parseResourceToken($R.config_boot.resources[kindex], null);\n }\n};\n</code></pre>\n\n<ul>\n<li><p><code>$R.addElement</code> should be split into smaller functions, this would probably prevent the multiple <code>$A.Event.trigger(file_token);</code> statements.</p></li>\n<li><p>The use of underscores is still not right, I understand this is your naming standard, that does not make it less wrong.</p></li>\n<li><p>Still, the code looks solid and should be a good base to build apps with.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T14:30:01.900",
"Id": "38696",
"ParentId": "38643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:19:46.883",
"Id": "38643",
"Score": "2",
"Tags": [
"javascript",
"library"
],
"Title": "A package for application booting"
}
|
38643
|
<p>I have written my first jQuery plugin for a website. It is, essentially, a Fancybox style popup that uses AJAX to load content from other pages. It's kind of a frankenstein build from multiple tutorials and best guess uses of the jQuery API. It works, but I am looking to refine it further.</p>
<p>As this is my first major step into writing jQuery or js, I am not sure how I can compact the code. Things seem a bit bloated, and I am sure bits could be trimmed down. The rules of reusing variables or functions are where I get tied up.</p>
<p>If anyone has any advice, input, criticism, etc., it would be great to hear and learn from.</p>
<p>Code:</p>
<pre><code>$(document).ready(function(){
var $ = jQuery,
$bodyCall = $('body'),
homePage = window.location.pathname;
// Initialize framebox
//-------------------------------------------------------------------/
$('.framebox-trigger').click(function(e){
// Prevent default linking
e.preventDefault();
var $toLoad = $(this).attr('href')+' #single-project-wrapper',
thisURL = $(this).attr('href'),
singleContent = '<div id="framebox-overlay">' +
'<div id="framebox-close-panel-left"></div>' +
'<div id="framebox-close-panel-left"></div>' +
'<div id="framebox-wrapper">' +
'<div id="framebox-nav-wrapper">' +
'<p><a href="#prev" id="framebox-prev" class="framebox-nav"><i class="fa fa-long-arrow-left"></i>Previous</a>' +
'||' +
'<a href="#" id="framebox-next" class="framebox-nav">Next<i class="fa fa-long-arrow-right"></i></a></p>' +
'</div>' +
'<section id="framebox-content">' +
//AJAX to insert #single-project-wrapper content here
'</section>' +
'<div id="framebox-close">' +
'<p>Click to close</p>' +
'</div>' +
'<ul class="ajax-list"></ul>' +
'</div>' +
'</div>';
// Fix body & Append Content
$bodyCall.removeClass('framebox-freeze');
$bodyCall.addClass('framebox-freeze').append(singleContent).fadeIn('fast', loadContent);
// Add loading beacon
$('.framebox-freeze').append('<span id="framebox-loading">+ Loading +</span>');
$('#framebox-loading, #framebox-overlay').fadeIn('fast');
// Load AJAX content
function loadContent(){
$('#framebox-content').load($toLoad , showNewContent);
}
// Show loaded AJAX content and hide loading bar
function showNewContent(){
$('#single-project-wrapper').show('normal', hideLoader);
}
// Hide loading bar
function hideLoader(){
$('#framebox-loading').fadeOut('fast');
}
// Match height to viewport height
$('#framebox-content').css('min-height', $(window).height());
// Add class of Current
$(this).parent('li').addClass('current-link');
// Push URL
history.pushState(null, null, thisURL);
});
// Next
//-------------------------------------------------------------------/
$bodyCall.on('click', 'a#framebox-next', function(e) {
e.preventDefault();
var next = $('#portfolio-wrapper li.current-link').next('li'),
first = $('#portfolio-wrapper li:first-child');
// Remove current class and conditionally move it to the next
if ($('.current-link').is(':last-child')) {
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(first).addClass('current-link');
}
else {
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(next).addClass('current-link');
}
// Load next content
var $nexthref = $('#portfolio-wrapper li.current-link > a').attr('href')+' #single-project-wrapper',
nextURL = $('#portfolio-wrapper li.current-link > a').attr('href');
// First remove existing content
$('#single-project-wrapper').fadeOut('fast', function(){
$(this).remove();
});
// Add loading beacon
$('.framebox-freeze').append('<span id="framebox-loading">+ Loading +</span>');
$('#framebox-loading').fadeIn('fast', loadNextContent);
function loadNextContent(){
$('#framebox-content').load($nexthref , showNextContent);
};
// Show loaded AJAX content and hide loading bar
function showNextContent(){
$('#single-project-wrapper').show('normal', hideLoader);
};
// Hide loading bar
function hideLoader(){
$('#framebox-loading').fadeOut('fast')
};
// Push URL
history.pushState(null, null, nextURL);
return false;
});
// Prev
//-------------------------------------------------------------------/
$bodyCall.on('click', 'a#framebox-prev', function(e) {
e.preventDefault();
//remove and add selected class
var prev = $('#portfolio-wrapper li.current-link').prev('li');
last = $('#portfolio-wrapper li:last-child');
// Remove current class and conditionally move it to the prev
if ($('.current-link').is(':first-child')) {
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(last).addClass('current-link');
} else {
$('#portfolio-wrapper li.current-link').removeClass('current-link');
$(prev).addClass('current-link');
}
// Load prev content
var $prevhref = $('#portfolio-wrapper li.current-link > a').attr('href')+' #single-project-wrapper',
prevURL = $('#portfolio-wrapper li.current-link > a').attr('href');
// First remove existing content
$('#single-project-wrapper').fadeOut('fast', function(){
$(this).remove();
});
// Add loading beacon
$('.framebox-freeze').append('<span id="framebox-loading">+ Loading +</span>');
$('#framebox-loading').fadeIn('fast', loadNextContent);
function loadNextContent(){
$('#framebox-content').load($prevhref , showNextContent)
};
// Show loaded AJAX content and hide loading bar
function showNextContent(){
$('#single-project-wrapper').show('normal', hideLoader);
};
// Hide loading bar
function hideLoader(){
$('#framebox-loading').fadeOut('fast')
};
// Push URL
history.pushState(null, null, nextURL);
return false;
});
// Set min-height to Window Height
//-------------------------------------------------------------------/
function setHeight(){
$('#framebox-content').css('min-height', $(window).height());
};
$(window).resize(function(){
setHeight;
});
// Close out Framebox
var findme;
jQuery(document).on('click', '#framebox-close, #framebox-close-panel-left, #framebox-close-panel-right', function(){
$bodyCall.removeClass('framebox-freeze');
$('#framebox-overlay').fadeOut();
$('#framebox-overlay, #framebox-loading').remove();
$('.project-tile').removeClass('current-link');
history.pushState(null, null, homePage);
});
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over review </p>\n\n<ul>\n<li>Code is well commented</li>\n<li>You have 2 variables that you did not declare with a <code>var</code> : <code>last</code> and <code>nextURL</code></li>\n<li>Your resize listener will not work, use <code>setHeight();</code> instead of <code>setHeight;</code></li>\n<li><code>setHeight</code> is a one liner, which is called once, you should inline it into your <code>resize</code> listener</li>\n<li>You declare some functions twice ( with the same code! ) like <code>hideLoader</code> or <code>showNextContent</code>, take those functions out of the listeners, right before <code>Initialize framebox</code>, this should cut down the size of your code.</li>\n<li>The HTML string looks terrible, since it is a plug in, you cannot have the markup in the HTML so I would least indent the HTML strings so that it is grokkable. Something like this:</li>\n</ul>\n\n<blockquote>\n<pre><code>singleContent = '<div id=\"framebox-overlay\">' +\n '<div id=\"framebox-close-panel-left\"></div>' +\n '<div id=\"framebox-close-panel-left\"></div>' +\n '<div id=\"framebox-wrapper\">' +\n '<div id=\"framebox-nav-wrapper\">' +\n '<p>' +\n '<a href=\"#prev\" id=\"framebox-prev\" class=\"framebox-nav\">' +\n '<i class=\"fa fa-long-arrow-left\"></i>' +\n 'Previous' + \n '</a>' +\n '||' +\n '<a href=\"#\" id=\"framebox-next\" class=\"framebox-nav\">' +\n 'Next' + \n '<i class=\"fa fa-long-arrow-right\"></i>' + \n '</a>' + \n '</p>' +\n '</div>' +\n '<section id=\"framebox-content\">' +\n //AJAX to insert #single-project-wrapper content here\n '</section>' +\n '<div id=\"framebox-close\">' +\n '<p>Click to close</p>' +\n '</div>' +\n '<ul class=\"ajax-list\"></ul>' +\n '</div>' +\n '</div>';\n</code></pre>\n</blockquote>\n\n<ul>\n<li>I now see that <code>$bodyCall.on('click', 'a#framebox-prev'</code> and <code>$bodyCall.on('click', 'a#framebox-next'</code> are pretty much the same. You must identify the parts that are the same, extract that code in to a function ( which you place prior to <code>Initialize framebox</code> ).</li>\n</ul>\n\n<p>If you are truly unable to merge those 2 listeners, I would suggest you gain some rep and put a bounty out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:31:30.357",
"Id": "39294",
"ParentId": "38644",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39294",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:31:59.527",
"Id": "38644",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"ajax"
],
"Title": "Compacting jQuery Code for Framebox Plugin"
}
|
38644
|
<p>I have some data in a .csv file, which looks roughly like this:</p>
<pre><code>[fragment1, peptide1, gene1, replicate1, replicate2, replicate3]
[fragment1, peptide2, gene1, replicate1, replicate2, replicate3]
[fragment2, peptide1, gene2, replicate1, replicate2, replicate3]
[fragment2, peptide2, gene2, replicate1, replicate2, replicate3]
[fragment3, peptide1, gene2, replicate1, replicate2, replicate3]
</code></pre>
<p>And the problem is this - I need to use this data (the three replicates) in several different manners:</p>
<ol>
<li>Over each row (i.e. just <code>replicate1</code>-3 for each row)</li>
<li>Over each replicate column for each fragment (i.e. <code>replicate1</code> from <code>peptides1</code> and 2 from <code>fragment1</code>, and the same for <code>replicate2</code> and 3)</li>
<li>Over each replicate column for each gene (i.e. same as (2), but using genes instead of fragments</li>
</ol>
<p>The data files all have the same columns, but the rows (i.e. number of fragments/peptides/genes) vary, so I have to read the data without specifying row numbers. What I need, essentially, is statistics (coefficients of variation) across each row, across each fragment and across each gene. </p>
<p>The variant across rows just uses the three replicates (always three values from one row), and is of course very simple to get to. Both the variants across fragments and across genes first calculates statistics for using first statistics from every applicable <code>replicate1</code>, then every <code>replicate2</code>, then <code>replicate3</code>, (i.e. unknown number of values from unknown number of rows) and after that do the same statistics using the values previously calculated (i.e. always three values). </p>
<p>I have a script that does this, almost, but it's very long and (I think) overly complicated. I basically read the file three times, each time gathering the data in the different manners described, mostly in lists and sometimes <code>numpy.array</code>s. </p>
<pre><code>with open('Data/MS - PrEST + Sample/' + data_file,'rU') as in_file:
reader = csv.reader(in_file,delimiter=';')
x = -1
data = numpy.array(['PrEST ID','Genes','Ratio H/L ' + cell_line + '_1','Ratio H/L ' + cell_line + '_2',\
'Ratio H/L ' + cell_line + '_3'])
current_PrEST = ''
max_CN = []
for row in reader:
# First (headers) row
if x == -1:
for n in range(len(row)):
if row[n] == 'PrEST ID':
PrEST_column = n
continue
if row[n] == 'Gene names':
Gene_column = n
continue
if row[n] == 'Ratio H/L ' + cell_line + '_1':
Ratio_R1_column = n
continue
if row[n] == 'Ratio H/L ' + cell_line + '_2':
Ratio_R2_column = n
continue
if row[n] == 'Ratio H/L ' + cell_line + '_3':
Ratio_R3_column = n
continue
if row[n] == 'Sequence':
Sequence_column = n
continue
x += 1
continue
# Skips combined / non-unique PrESTs
if row[PrEST_column].count(';') == 1:
continue
# Collects and writes data for first (non-calculated) data set
MC_count = row[Sequence_column].count('R') + row[Sequence_column].count('K') - 1
write = (row[PrEST_column],row[Gene_column],row[Ratio_R1_column],row[Ratio_R2_column],\
row[Ratio_R3_column],row[Sequence_column],MC_count)
writer_1.writerow(write)
# Plots to figure 1 (copy numbers for peptides), but only if there is some data to plot
if current_PrEST != row[PrEST_column]:
colour = cycle(['k','#A9F5A9','#6699FF','#A9F5F2','#9370DB','#FF3333'])
current_PrEST = row[PrEST_column]
x += 1
# Checks if data for at least one replicate exists
if row[Ratio_R1_column] != 'NaN' or row[Ratio_R2_column] != 'NaN' or row[Ratio_R3_column] != 'NaN':
ccolour = next(colour)
plt.figure(1)
CN1 = (spike[row[PrEST_column]] / float(row[Ratio_R1_column]) * (10**-12) * (6.022*10**23) / (1*10**6))
CN2 = (spike[row[PrEST_column]] / float(row[Ratio_R2_column]) * (10**-12) * (6.022*10**23) / (1*10**6))
CN3 = (spike[row[PrEST_column]] / float(row[Ratio_R3_column]) * (10**-12) * (6.022*10**23) / (1*10**6))
plt.plot(x,CN1,marker='o',color=ccolour)
plt.plot(x,CN2,marker='o',color=ccolour)
plt.plot(x,CN3,marker='o',color=ccolour)
if CN1 > Copy_Number_Cutoff or CN2 > Copy_Number_Cutoff or CN3 > Copy_Number_Cutoff:
plt.plot(x,Copy_Number_Cutoff*0.97,marker='^',color='red')
max_CN.append(max(CN1,CN2,CN3))
# Collects data for downstream calculations
row_data = numpy.array([row[PrEST_column],row[Gene_column],row[Ratio_R1_column],row[Ratio_R2_column],row[Ratio_R3_column]])
data = numpy.vstack((data,row_data))
# Prints largest copy number above CN cutoff (if applicable)
if max_CN != []:
print('Largest copy number: ' + str(round(max(max_CN))))
# Gathers PrEST/Gene names
PrEST_list = []
Gene_list = []
for n in range(len(data) - 1):
PrEST = data[n+1][0]
if PrEST not in PrEST_list:
PrEST_list.append(PrEST)
Gene_list.append(data[n+1][1])
# Analyses data and writes to file
collected_PrESTs = []
collected_Genes = []
collected_CNs = []
collected_CVs = []
collected_counts = []
collected_medians = []
while len(PrEST_list) != 0:
PrEST = PrEST_list[0]
PrEST_list.remove(PrEST)
Gene = Gene_list[0]
Gene_list.remove(Gene)
Peptide_count = 0
# Collects H/L ratios and calculate copy numbers / statistics
R1 = []
R2 = []
R3 = []
for n in range(len(data) - 1):
if data[n+1][0] == PrEST:
if data[n+1][2] != 'NaN':
R1.append((spike[PrEST] / float(data[n+1][2])) * (10**-12) * (6.022*10**23) / (1*10**6))
Peptide_count += 1
if data[n+1][3] != 'NaN':
R2.append((spike[PrEST] / float(data[n+1][3])) * (10**-12) * (6.022*10**23) / (1*10**6))
Peptide_count += 1
if data[n+1][4] != 'NaN':
R3.append((spike[PrEST] / float(data[n+1][4])) * (10**-12) * (6.022*10**23) / (1*10**6))
Peptide_count += 1
# Checks if lacking data
if R1 == [] and R2 == [] and R3 == []:
write = (PrEST,Gene,'No data')
writer_2.writerow(write)
continue
# Calculate statistics
curated_medians = []
if R1 != []:
curated_medians.append(numpy.median(R1))
if R2 != []:
curated_medians.append(numpy.median(R2))
if R3 != []:
curated_medians.append(numpy.median(R3))
End_Copy_Number = int(round(numpy.median(curated_medians),0))
if len(curated_medians) > 1:
CV = round((numpy.std(curated_medians,ddof=1) / numpy.mean(curated_medians)) * 100,1)
else:
CV = -1
# Writes data to file
write = (PrEST,Gene,End_Copy_Number,CV)
writer_2.writerow(write)
# Checks if the current PrEST maps to a gene that has more than one PrEST and calculates statistics for that gene
if Gene in collected_Genes and Gene not in Gene_list:
CNs = []
for n in range(len(collected_Genes)):
if Gene == collected_Genes[n]:
CNs.append(collected_medians[n])
CNs.append(curated_medians)
Gene_CN = int(round(numpy.median(CNs),0))
Gene_CV = round((numpy.std(CNs,ddof=1) / numpy.mean(CNs)) * 100,1)
write = ('',Gene,Gene_CN,Gene_CV)
writer_2.writerow(write)
</code></pre>
<p>How can I best read data in different ways effectively, both speed-wise and "less code"-wise? I tried to find similar questions, but to no avail.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:09:12.050",
"Id": "64586",
"Score": "2",
"body": "FWIW I think your code would be much simpler if rewritten using [`pandas`](http://pandas.pydata.org), and I think its `groupby` facilities would come in very handy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T13:44:01.007",
"Id": "103210",
"Score": "0",
"body": "It would be very helpful if you could post some sample data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-16T12:23:08.530",
"Id": "140753",
"Score": "0",
"body": "A year later: `pandas` is awesome! Thank you so much DSM, that helped me a lot."
}
] |
[
{
"body": "<p>First off, if you want re-usability, you should probably encapsulate this into a function with it's specific arguments.</p>\n\n<p>Also, the general style for naming is <code>snake_case</code> for functions and variables, and <code>PascalCase</code> for classes. You also have some other style issues. For example, <code>(PrEST,Gene,End_Copy_Number,CV)</code> should be changed to <code>(PrEST, Gene, End_Copy_Number, CV)</code>. You also have various other style violations as well. To correct these, see <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>, Python's official style guide.</p>\n\n<p>You have an <code>if</code>/<code>elif</code>/<code>else</code> block with many <code>continue</code>s. </p>\n\n<pre><code>for n in range(len(row)):\n if row[n] == 'PrEST ID':\n PrEST_column = n\n continue\n ...\n</code></pre>\n\n<p>These <code>continue</code>s can be removed.</p>\n\n<p>Finally, as mentioned by @DSM, you can use <a href=\"http://pandas.pydata.org/\" rel=\"nofollow\"><code>pandas</code></a> to re-write this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-07T03:24:20.247",
"Id": "96040",
"ParentId": "38646",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "96040",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:51:07.460",
"Id": "38646",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"csv",
"numpy"
],
"Title": "Reading columns and rows in a .csv file"
}
|
38646
|
<p>Is my below merge sort implementation in O(n log n)? I am trying to implement a solution to find k-th largest element in a given integer list with duplicates with O(N*log(N)) average time complexity in Big-O notation, where N is the number of elements in the list.</p>
<pre><code> public class FindLargest {
public static void nthLargeNumber(int[] arr, String nthElement) {
mergeSort_srt(arr, 0, arr.length - 1);
// remove duplicate elements logic
int b = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[b] != arr[i]) {
b++;
arr[b] = arr[i];
}
}
int bbb = Integer.parseInt(nthElement) - 1;
// printing second highest number among given list
System.out.println("Second highest number is::" + arr[b - bbb]);
}
public static void mergeSort_srt(int array[], int lo, int n) {
int low = lo;
int high = n;
if (low >= high) {
return;
}
int middle = (low + high) / 2;
mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high)) {
if (array[low] < array[start_high]) {
low++;
} else {
int Temp = array[start_high];
for (int k = start_high - 1; k >= low; k--) {
array[k + 1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
public static void main(String... str) {
String nthElement = "2";
int[] intArray = { 1, 9, 5, 7, 2, 5 };
FindLargest.nthLargeNumber(intArray, nthElement);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:24:18.170",
"Id": "64469",
"Score": "0",
"body": "Any reason why are you passing `nthElement` as `String`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:26:07.537",
"Id": "64470",
"Score": "0",
"body": "actually it is to to find the k-th largest element in a given integer list"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:38:47.710",
"Id": "64471",
"Score": "2",
"body": "Then why not pass it as `int`?"
}
] |
[
{
"body": "<blockquote>\n <p>Is my below merge sort implementation in O(n log n)?</p>\n</blockquote>\n\n<p>No, while your merge sort appears to be a good implementation of the <a href=\"http://en.wikipedia.org/wiki/In-place_merge_sort#Variants\" rel=\"nofollow\">in-place merge sort</a>, that sort has a complexity of <em>O(n log<sup>2</sup>n )</em>. While the complexity may look reasonably scalable, the actual surt is quite slow compared to others. Specifically, it is a much slower sort than the <a href=\"http://en.wikipedia.org/wiki/Timsort\" rel=\"nofollow\">native TimSort</a> used by the Collections API in Java7 and above.</p>\n\n<p>@tintinmj is right to challenge the use of a String input parameter for <code>nthElement</code>. It should be a simple <code>int</code> input parameter.</p>\n\n<p>You should note that you could get to the <code>nthElement</code> faster by moving backwards from the end of the sorted data. If you move forwards you have to scan the entire array. If you move backwards, you only have to go as far as the matching value.</p>\n\n<p>OK, so the input parameters are of the wrong type, the sort is more expensive than anticipated, and the final scan could be faster ... but, the real question I have is why not just scan the data once and be done with it....</p>\n\n<pre><code>private static final int nthLagest(int[] data, int nth) {\n int[] result = new int[nth];\n int rescnt = 0;\n for (int d : data) {\n // read the documentation for binarySearch, and why I do ` - xxx - 1`\n int ip = - Arrays.binarySearch(result, 0, rescnt, d) - 1;\n if (ip >= 0) {\n\n // this value is not recorded... which may be because it is good,\n // or because it is not better than the nth.\n if (rescnt < result.length) {\n // we don't have nth large numbers yet.\n System.arraycopy(result, ip, result, ip + 1, rescnt - ip);\n rescnt++;\n result[ip] = d;\n } else if (ip > 0) {\n // this value is larger than one of the nth values we already have.\n ip = ip - 1;\n System.arraycopy(result, 1, result, 0, ip);\n result[ip] = d;\n }\n }\n }\n if (rescnt < result.length) {\n throw new IllegalStateException(\"There is no \" + nth + \" largest value in \" + Arrays.toString(data));\n }\n return result[0];\n}\n</code></pre>\n\n<p>The above function takes the data, and scans through it just once. As it goes, it keeps track of the highest 'n' numbers, where 'n' is the n<sup>th</sup> largest number you want to get.</p>\n\n<p>The overall complexity for this function is something like <em>O(n log m)</em> where <code>n</code> is the number of elements in the input data, and <code>m</code> is the input value <em>n<sup>th</sup></em> (if you want to get the third-largest value, then <code>m = 3</code>). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T05:07:57.067",
"Id": "39782",
"ParentId": "38649",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39782",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T18:59:22.663",
"Id": "38649",
"Score": "5",
"Tags": [
"java",
"sorting",
"mergesort",
"complexity"
],
"Title": "Is this an efficient merge sort implementation with regards to average time complexity in Big-O notation?"
}
|
38649
|
<p>Both <code>Cities</code> and <code>Positions</code> are associated to <code>Jobs</code> through a has_many :through relationship.</p>
<p>On the <code>Jobs#Index</code> page, I have a form, which when submitted allows a user to filter jobs based on a combination of city and positions.</p>
<p>I got this to work, but know the code can be a lot better.</p>
<p>This is my <code>Jobs#Index</code> controller:</p>
<pre><code> def index
@cities = City.all
@positions = Position.all
@city = City.find(params[:city_id]) if params[:city_id] && params[:city_id] != "0"
@position = Position.find(params[:position_id]) if (params[:position_id] && params[:position_id] != "0")
@jobs = Job.all
@jobs = @jobs.includes(:cities).where(cities: { id: @city }) if @city
@jobs = @jobs.includes(:positions).where(positions: { id: @position }) if @position
@jobs = @jobs.paginate(page: params[:page], per_page: 5)
end
</code></pre>
<p>This is my <code>Jobs#Index</code> View:</p>
<pre><code>- provide(:title, 'All Jobs')
.thinstripe_career
.darken
.container
.row
.span10.offset1
.jobs_header
.row
.span7
h2 All #{@city.name if @city} #{@position.name if @position} Jobs
.span3
== link_to "Sign up for Job Alerts!", "#", :class => "button"
- if current_user && current_user.admin?
== render 'shared/dashboard_header'
.container
.row
.span10.offset1
.job_search
== form_tag jobs_path, :method => 'get', :id => "jobs_filter" do
h2 I'd like jobs in
.filter_sect
== select_tag :city_id, content_tag(:option,'all cities...', :value=>"0") + options_from_collection_for_select(@cities, "id", "name", params[:city_id].to_i ), :class => "basic"
.filter_sect
== select_tag :position_id, content_tag(:option,'all roles...',:value=>"0") + options_from_collection_for_select(@positions, "id", "name", params[:position_id].to_i ), :class => "basic"
.filter_sect.filter_search
== submit_tag "Search", :class => "button search_button button_black", :name => nil
ul.jobs
- if @jobs.any?
== render @jobs
- else
li.non_founds
h2 No jobs founds.
p There are currently no jobs founds for these combinations. Sign up to requests
== will_paginate
</code></pre>
|
[] |
[
{
"body": "<p>In <code>models/job.rb</code>, you can add scopes and use them chained on the controller:</p>\n\n<pre><code>class Job < ActiveRecord::Model\n scope :with_cities, ->(city) { includes(:cities).where(cities: { id: @city }) if city }\n scope :with_positions, ->(position) { includes(:positions).where(positions: { id: @position }) if position }\n\n # rest of the code ...\nend\n</code></pre>\n\n<hr>\n\n<p>For <code>JobsController</code>, you can:</p>\n\n<ul>\n<li><p>Add a <code>before_filter</code> to load all the data, and if you need to use that data on other actions, you just need to append the name of that action too.</p></li>\n<li><p>Use <a href=\"http://railscasts.com/episodes/1-caching-with-instance-variables?view=asciicast\" rel=\"nofollow\">memoization</a> to load the city and the position. </p></li>\n</ul>\n\n<p>In <code>controllers/jobs_controller.rb</code>:</p>\n\n<pre><code>class JobsController < ApplicationController\n before_filter :load_data, only: [:index]\n\n def index\n @jobs = Job.with_cities(city).with_positions(position).paginate(page: params[:page], per_page: 5)\n end\n\n # ...\n\n protected:\n\n def load_data\n @cities = City.all\n @positions = Position.all\n end\n\n def city\n @city ||= City.find(params[:city_id]) unless params[:city_id].empty?\n end\n\n def position\n @position ||= Position.find(params[:position_id]) unless params[:position_id].empty?\n end\n</code></pre>\n\n<hr>\n\n<p>On the view:</p>\n\n<p>Use <code>try</code>, so instead of:</p>\n\n<pre><code> - if current_user && current_user.admin? \n == render 'shared/dashboard_header' \n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code> == render 'shared/dashboard_header' if current_user.try(:admin?)\n</code></pre>\n\n<p>Use <code>include_blank</code> and <code>prompt</code> options in <code>select_tag</code>. \nThis not only simplifies the views, but also allows to use <code>params[city_id].empty?</code> on the controller.</p>\n\n<pre><code>select_tag :city_id, \n options_from_collection_for_select(@cities, :id, :name, params[:city_id].to_i), \n include_blank: true, prompt: \"all cities...\", class: \"basic\" \n</code></pre>\n\n<p>Finally, you could extract <code>ul.jobs</code> into a partial:</p>\n\n<pre><code>= render partial: 'jobs', locals: { jobs: @jobs }\n</code></pre>\n\n<p>Or even the <code>.job_search</code> div, especially if you'll be needing this somewhere else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T22:40:47.173",
"Id": "42820",
"ParentId": "38650",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T19:22:24.987",
"Id": "38650",
"Score": "5",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Filtering index using has_many through relationships"
}
|
38650
|
<p>I'm trying to learn basic algorithms which are typically taught in an introduction to CS course, which is usually taught in a compiled language like Java. However, I want to focus on JavaScript, so I wrote the algorithms in JavaScript and encapsulated them into a library.</p>
<p>I'm looking for feedback on the efficiency of my implementations (<code>bubbleSort, selectionSort, insertionSort</code>):</p>
<pre><code>/***************************************************************************************************
**ALGORITHMS
***************************************************************************************************/
(function () {
"use strict";
var $A,
$P = {};
(function manageGlobal() {
if (window.$A && window.$A.pack) {
$A = window.$A;
$A.pack.algo = true;
}
}());
$P.swap = function (arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
// checks to see if sorted
$P.isSorted = function (arr) {
var index_outer,
length = arr.length;
for (index_outer = 1; index_outer < length; index_outer++) {
if (arr[index_outer - 1] > arr[index_outer]) {
return false;
}
}
return true;
};
// repeatedly orders two items ( a bubble ) at a time
$P.bubbleSort = function (arr) {
var index_outer,
index_inner,
swapped = false,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
swapped = false;
for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
if (arr[index_inner] > arr[index_inner + 1]) {
$P.swap(arr, index_inner, index_inner + 1);
swapped = true;
}
}
if (swapped === false) {
break;
}
}
return arr;
};
// repeatedly finds minimum and places it the next index
$P.selectionSort = function (arr) {
var index_outer,
index_inner,
index_min,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
index_min = index_outer;
for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
if (arr[index_inner] < arr[index_min]) {
index_min = index_inner;
}
}
if (index_outer !== index_min) {
$P.swap(arr, index_outer, index_min);
}
}
return arr;
};
// repeatedly places next item in correct spot using a "shift"
$P.insertionSort = function (arr) {
var index_outer,
index_inner,
value,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
value = arr[index_outer];
for (index_inner = index_outer - 1; (index_inner >= 0 && (arr[index_inner] > value));
index_inner--) {
arr[index_inner + 1] = arr[index_inner];
}
arr[index_inner + 1] = value;
}
return arr;
};
// module complete, release to outer scope
$A = $A.extendSafe($A, $P);
}());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T23:51:42.367",
"Id": "66456",
"Score": "0",
"body": "new version here - http://codereview.stackexchange.com/questions/39619/a-package-for-sort-algorithms-v2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T00:07:10.287",
"Id": "66458",
"Score": "2",
"body": "This one comment linking to the new version is sufficient. Adding the same comment to *every* answer is a bit spammy IMHO."
}
] |
[
{
"body": "<p>Note that <code>isSorted</code> has a bit of an off-by-one error. It will check outside the bounds of its argument. This actually works OK, because it compares the last element of the array to <code>undefined</code> which always results in <code>false</code>. However, you should really only check up to <code>index_outer < length - 1</code>.</p>\n\n<p>I haven't looked too closely at your implementations of the basic sorting algorithms, but assuming they are correct, then there isn't much that could be said about their efficiency that hasn't already. It's all well defined.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:39:47.090",
"Id": "64472",
"Score": "0",
"body": "Well, but when `index_outer` is `0` make sure you're not checking `arr[0] > arr[-1]`. Either way, you need to adjust the bounds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:24:29.903",
"Id": "64592",
"Score": "0",
"body": "I'm confused? Are you suggesting that subtracting one from `length` a single time is going to hurt performance? I hope you're not suggesting that. Even taking that into consideration, it's better to be *correct* than anything else. (Although, by the way, I like your update.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:02:03.693",
"Id": "38652",
"ParentId": "38651",
"Score": "3"
}
},
{
"body": "<p>Your implementations look mostly correct besides a couple things.</p>\n\n<p>As mentioned by @Iwburk, your <code>isSorted</code> function will always return false because <code>arr[index_outer + 1]</code> will always be <code>undefined</code> for the last element. You should either iterate <code>arr</code> backwards starting at the last (I'd recommend this way) element or end the loop at <code>index_outer === length -1</code></p>\n\n<pre><code>$P.isSorted = function (arr) {\n for (var index_outer = arr.length; index_outer >= 1; index_outer--) {\n if (arr[index_outer - 1] > arr[index_outer]) {\n return false;\n }\n }\n return true;\n};\n</code></pre>\n\n<p>In your insertion sort algorithm you can get away without checking <code>index_inner >= 0</code> which will reduce your total comparisons; one of your goals when designing sorting algorithms.</p>\n\n<pre><code>$P.insertionSort = function (arr) {\n var index_outer,\n index_inner,\n value,\n length = arr.length;\n for (index_outer = 0; index_outer < length; index_outer++) {\n value = arr[index_outer];\n for (index_inner = index_outer - 1; arr[index_inner] > value; index_inner--) {\n arr[index_inner + 1] = arr[index_inner];\n }\n arr[index_inner + 1] = value;\n }\n return arr;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T04:47:56.453",
"Id": "64530",
"Score": "0",
"body": "Note that his original implementation of `isSorted` *actually works* because the final comparison does not invalidate the check that determines if the items are out of order. I still think it needs to be fixed. Right now it's just working accidentally because of a quirk in the language."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T21:11:40.500",
"Id": "38655",
"ParentId": "38651",
"Score": "2"
}
},
{
"body": "<p>From a style perspective:</p>\n\n<ul>\n<li>Naming variables with $ is discouraged unless those variables are jQuery search results</li>\n<li>$A and $P are too crypticically named</li>\n<li>lowerCamelCase is encouraged for variables ( index_outer -> indexOuter which frankly should probably be called outerIndex )</li>\n<li>Your 2nd for loop in <code>insertionSort</code> is too convoluted, you are doing too much</li>\n<li><code>if( swapped === false )</code> is more readable as <code>if(!swapped)</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T13:59:11.047",
"Id": "64573",
"Score": "0",
"body": "Depends on the browser, http://jsperf.com/falsey, on FF 28 `(!swapped)` would be fastest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T13:38:44.153",
"Id": "38694",
"ParentId": "38651",
"Score": "3"
}
},
{
"body": "<p>I would like to add some points, however those already mentioned are all valid. You get +1 for encapsulating your code in a function and using <code>'use strict';</code>. However you should rather return your 'library' than populate it into the global namespace. This way you can later use dependency injection, which is especially important and common in the JavaScript world.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T19:57:32.553",
"Id": "39604",
"ParentId": "38651",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T19:39:24.530",
"Id": "38651",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"algorithm",
"sorting",
"modules"
],
"Title": "A package for sort algorithms"
}
|
38651
|
<p>Another try at this problem in LISP. This time rather than generating every possible row combination for the melody I tried to calculate the best combination directly. Unfortunately there's a problem - the output is a messy list full of vectors and single values. Is there a good way to concatenate vectors together with value between them?</p>
<pre><code>(proclaim '(type (vector (vector symbol 4) 3) *rows*))
(defparameter *rows* #( #(:c :ds :fs :a) #(:cs :e :g :as) #(:d :f :gs :b)))
(defun row-for-note (note)
(declare (symbol note))
"Returns the lower row on which a note is played."
(position-if (lambda (row) (find note row)) *rows*))
(defun equivalent-row (row)
(declare (fixnum row))
"Returns the equivalent upper row to a given lower row."
(case row (1 -2) (2 -1) (0 0)))
(defun rows-for-notelist (notelist)
(declare ((vector symbol) notelist))
"Returns the sequence of lower rows on which a sequence of notes are played."
(map 'vector #'row-for-note notelist))
(defun flip-sequence (rowlist)
(declare ((vector fixnum) notelist))
"Returns the sequence of upper rows equivalent to a sequence of lower rows."
(map 'vector #'equivalent-row rowlist))
(defun vector-last (thevec)
(declare (vector thevec))
"Returns the last element of a vector."
(elt thevec (- (length thevec) 1)))
(defun vector-first (thevec)
(declare (vector thevec))
"Returns the first element of a vector."
(elt thevec 0))
(defun should-flip-block (rowlist)
(declare ((vector fixnum) rowlist))
"Determines if a sequence of rows starts and ends on row 2 or not."
"These sequences are more easily played on upper rows because they will then start and end on row -1."
(if (= (length rowlist) 0) nil
(let* ((exithigh (= (vector-last rowlist) 2))
(enterhigh (= (vector-first rowlist) 2)))
(and exithigh enterhigh))))
(defun flip-block-if-should (rowlist)
(declare ((vector number) rowlist))
(if (should-flip-block rowlist) (flip-sequence rowlist) (eval rowlist)))
(defun optimal-sequence (notelist)
(declare ((vector symbol) notelist))
(let* ((baserows (rows-for-notelist notelist))
(blocks (split-sequence '(0) baserows))
(flipped (mapcar #'flip-block-if-should blocks)))
(loop for x in flipped collect x collect 0)))
</code></pre>
|
[] |
[
{
"body": "<p>To concatenate vectors, you can do this:</p>\n\n<pre><code>(apply #'concatenate 'vector \n (mapcar (lambda (x) \n (typecase x \n (vector x) \n (t (vector x))))\n list-of-vectors-or-numbers))\n</code></pre>\n\n<p>PS. Since this is CR, here are some notes on your code:</p>\n\n<ol>\n<li><p>Doc string (no more than one, but it can be multi-line!) <em>usually</em> comes <em>before</em> the declarations. Please see <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/03_dk.htm\" rel=\"nofollow\">Syntactic Interaction of Documentation Strings and Declarations</a>: <code>(defun foo (...) (declare ...) \"doc\")</code> will define a function <code>foo</code> which has no docstring and return <code>\"doc\"</code>, while <code>(defun foo (...) \"doc\" (declare ...))</code> will declare a function with a docstring, returning <code>nil</code>.</p></li>\n<li><p><code>(declare ((vector number) rowlist))</code> <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/04_bc.htm\" rel=\"nofollow\">should be</a> <code>(declare (type (vector number) rowlist))</code>.</p></li>\n<li><p><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_elt.htm\" rel=\"nofollow\"><code>elt</code></a> should not be used if you know that the object is a <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/t_vector.htm\" rel=\"nofollow\"><code>vector</code></a>; use <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_aref.htm\" rel=\"nofollow\"><code>aref</code></a> instead.</p></li>\n<li><p>There is no need to bind <code>exithigh</code> and <code>enterhigh</code> in <code>should-flip-block</code> since they are used just once.</p></li>\n<li><p><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_declai.htm\" rel=\"nofollow\"><code>declaim</code></a> is, I think, more \"idiomatic\" than <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_procla.htm\" rel=\"nofollow\"><code>proclaim</code></a> in your case.</p></li>\n<li><p>It is clearer to use <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_1pl_1_.htm\" rel=\"nofollow\"><code>1-</code></a> in <code>vector-last</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T01:12:30.030",
"Id": "38660",
"ParentId": "38657",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T22:47:39.707",
"Id": "38657",
"Score": "2",
"Tags": [
"beginner",
"common-lisp"
],
"Title": "Finding optimal row sequence for a melody on 5-row Bayan Accordion, v2.0"
}
|
38657
|
<p>I'm writing a small library to do some image-processing on GPU for WinRT, however, I'm not sure if such design breaks SRP.</p>
<p>One class loads and saves image, renders and maintains filters - isn't it too much?</p>
<p><a href="http://pastebin.com/h8iYCmzw" rel="nofollow">Code</a></p>
<pre><code>public class FilteredImageProvider : IDisposable
{
public event Action ImageSourceChangedEvent;
GPUImage currentImage;
SharpDXRenderer renderer;
FilterContainer filterContainer;
ImageGPULoaderFactory loaderFactory;
public FilteredImageProvider()
{
this.renderer = new SharpDXRenderer();
this.filterContainer = new FilterContainer();
this.loaderFactory = new ImageGPULoaderFactory();
}
public ImageSource Image
{
get { return renderer.GetRendererSource(); }
}
public async Task LoadFromFile(IStorageFile sourceFile)
{
var imageLoader = loaderFactory.GetImageLoader(sourceFile);
if (currentImage != null)
currentImage.Dispose();
currentImage = await imageLoader.LoadImage();
renderer.Load(currentImage);
ImageSourceChangedEvent();
}
public async Task SaveToFile(IStorageFile destinyFile)
{
var imageSaver = loaderFactory.GetImageLoader(destinyFile);
var deviceManager = renderer.GetDeviceManager();
await imageSaver.SaveImage(currentImage, deviceManager);
}
public void Render()
{
var filterCompilator = new FilterCompilator();
var renderedImage = currentImage.GetImageAsEffect();
var compiledEffect = filterCompilator.CompileFiltersToEffect(renderedImage, filterContainer);
renderer.Render(compiledEffect);
}
public void AddFilter(IFilter filter)
{
filterContainer.AddFilter(filter);
}
public void RemoveFilter(IFilter filter)
{
filterContainer.RemoveFilter(filter);
}
public void Undo()
{
filterContainer.Undo();
}
public void Redo()
{
filterContainer.Redo();
}
public void Dispose()
{
if (currentImage != null)
currentImage.Dispose();
renderer.Dispose();
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Private Fields</strong></p>\n\n<p>I prefer to prefix my private fields with an underscore, and as <code>readonly</code> as possible. If you don't like the underscore, fine - but then be consistent with <code>this</code>, and don't use it only in your constructor - use <code>this</code> whenever you're referring to a private field. It greatly helps telling private fields from parameters.</p>\n\n<p>Personally I don't like sprinkling <code>this</code> everywhere in my code, so I prefer the underscore; I also like my access modifiers explicit:</p>\n\n<pre><code>public class FilteredImageProvider : IDisposable\n{\n private readonly SharpDXRenderer _renderer;\n private readonly FilterContainer _filterContainer;\n private readonly ImageGPULoaderFactory _loaderFactory;\n\n private GPUImage _currentImage;\n\n //...\n</code></pre>\n\n<p><strong>Constructor</strong></p>\n\n<p>The <code>readonly</code> fields are still assigned in the constructor:</p>\n\n<blockquote>\n<pre><code>public FilteredImageProvider()\n{\n _renderer = new SharpDXRenderer();\n _filterContainer = new FilterContainer();\n _loaderFactory = new ImageGPULoaderFactory();\n}\n</code></pre>\n</blockquote>\n\n<p>These three should be injected as constructor arguments - creating these instances within the constructor breaks SRP, at least if you're applying DI principles. SRP is only the <kbd>S</kbd> of SOLID. By taking these instances in as constructor arguments, you greatly facilitate the rest of SOLID.</p>\n\n<hr>\n\n<p>You're mostly exposing cherry-picked encapsulated methods, that works for me. However I find that you shouldn't be <code>new</code>ing up the <code>FilterCompilator</code> like you're doing. It should be constructor-injected, and perhaps made a dependency of <code>FilterContainer</code>, or of another type that would deal with everything that can be done with a <code>Filter</code>.</p>\n\n<hr>\n\n<p>Note: If <code>_renderer</code> is injected in the constructor, then you shouldn't call <code>_renderer.Dispose()</code> since you've put that burden onto the caller (ideally your favorite IoC container).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:18:43.790",
"Id": "64542",
"Score": "1",
"body": "The problem with SharpDXRenderer, ImageGPULoaderFactory and FilterCompilator is that it's pretty \"low-level\" code messing with DirectX and I dont think this should be constructed by client. It is also not possible to write good unit tests for such code because of too big coupling with Windows Runtime library (can't use any mocking framework) so DI wouldn't give me any benefits. Don't you think UI code/Low level code should be treated a bit diffrent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:52:11.627",
"Id": "64544",
"Score": "0",
"body": "I don't think you need to unit test DX stuff. But by treating them as the dependencies they are, you allow *your own code* to be testable independently of DX; by keeping the tight coupling you inevitably call code that you don't own when you test this class. DI cannot be applied \"halfway\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:56:28.567",
"Id": "64546",
"Score": "0",
"body": "I wouldn't want `.SaveToFile` to hit the file system in my unit tests; hence I'd want to inject a factory that I have control over, even if it means wrapping the DX stuff with an interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:58:23.690",
"Id": "64548",
"Score": "0",
"body": "Ok. So I should create some common interface like IRenderable, IFilterRepository, ILoaderFactory (or maybe abstract class) and inject them in constructor? How to deal with .GetDeviceManager line - cause I don't think IRenderable interface should contains such a method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T14:19:20.603",
"Id": "64575",
"Score": "0",
"body": "Whatever works with your mocking framework. `GetDeviceManager` sounds like an implementation detail, maybe `loaderFactory` can supply the `imageSaver` with its own `deviceManager`?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T03:43:18.880",
"Id": "38669",
"ParentId": "38658",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T23:14:21.130",
"Id": "38658",
"Score": "5",
"Tags": [
"c#",
"image",
"library"
],
"Title": "Does this image-processing library break the Single Responsibility Principle?"
}
|
38658
|
<p>I develop a small game using C# and need A* in it. For that, I need a PriorityQueue, which .NET does not have. I wanted to make my own one for practice. Here is it, please comment on performance and usability:</p>
<pre><code>public class PriorityQueue<T> : IEnumerable
{
List<T> items;
List<int> priorities;
public PriorityQueue()
{
items = new List<T>();
priorities = new List<int>();
}
public IEnumerator GetEnumerator() { return items.GetEnumerator(); }
public int Count { get { return items.Count; } }
/// <returns>Index of new element</returns>
public int Enqueue(T item, int priority)
{
for (int i = 0; i < priorities.Count; i++) //go through all elements...
{
if (priorities[i] > priority) //...as long as they have a lower priority. low priority = low index
{
items.Insert(i, item);
priorities.Insert(i, priority);
return i;
}
}
items.Add(item);
priorities.Add(priority);
return items.Count - 1;
}
public T Dequeue()
{
T item = items[0];
priorities.RemoveAt(0);
items.RemoveAt(0);
return item;
}
public T Peek()
{
return items[0];
}
public int PeekPriority()
{
return priorities[0];
}
}
</code></pre>
<p>I tested it with...</p>
<pre><code> PriorityQueue<String> pQ = new PriorityQueue<string>();
for (int i = 0; i < 100; i++)
{
int prio = Provider.Rnd.Next(0, 1000);
pQ.Enqueue(prio.ToString(), prio);
if (pQ.Count > 0 && Provider.Rnd.Next(0, 2) == 0) pQ.Dequeue();
}
while (pQ.Count > 0)
{
Console.WriteLine(pQ.Dequeue());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-11T07:00:47.017",
"Id": "86975",
"Score": "0",
"body": "I am just asking: what is the `IEnumerable` in your code?"
}
] |
[
{
"body": "<ol>\n<li><p>According to my understanding <a href=\"http://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow\">and wikipedia</a> a priority queue serves items with a higher priority first. Your implementation serves items with a lower priority first by inserting them at the front. I guess it depends on your definition of \"higher priority\" but your comment indicates that you consider lower values as lower priority. So you implementation is a bit counter intuitive.</p></li>\n<li><p>Using an array means you have to copy the entries around when inserting/removing an element at a specific index which means that <code>Enqueue</code> and <code>Dequeue</code> both are <code>O(n)</code> operations.</p></li>\n<li><p>You keep two lists, one for the items and one for the priorities, which are linked by the index in both lists referring to the same element. This requires you to keep both data structures in exact sync which seems a bit of a code smell to me.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T13:12:47.717",
"Id": "64567",
"Score": "0",
"body": "I made it this way because of a* where I need to get the node with the lowest cost"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:33:55.817",
"Id": "38677",
"ParentId": "38659",
"Score": "2"
}
},
{
"body": "<p>There are other data structures for priority queues. You might consider implementing the queue as a <a href=\"http://en.wikipedia.org/wiki/Binary_heap\" rel=\"noreferrer\">binary heap</a> instead, which gives you a run-time complexity of O(1) for accessing the \"largest\" (or \"smallest\", depending on the comparison) element, and O(log n) for insertion and removal (of the largest).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:45:11.967",
"Id": "38683",
"ParentId": "38659",
"Score": "5"
}
},
{
"body": "<p>You should check some algorithms and implement your priority queue as binary heap. You'll get <code>O(logn)</code> to <code>Dequeue</code> max/min item from queue and <code>Enqueue</code> in <code>O(logn)</code>. Here you have sample implementation (note that code is ugly and bad - it's just sample, please don't judge me because I've written it year ago;-) )\n<a href=\"http://pastebin.com/FFqj53DW\" rel=\"nofollow\">http://pastebin.com/FFqj53DW</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T16:25:20.693",
"Id": "64600",
"Score": "2",
"body": "Thanks for the link! Eventually I used a SortedDictionary without having to implement a binary heap by myself. It was in Eric Lippert's blog [link](http://blogs.msdn.com/b/ericlippert/archive/2007/10/08/path-finding-using-a-in-c-3-0-part-three.aspx)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:46:26.367",
"Id": "38684",
"ParentId": "38659",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38683",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T00:47:48.457",
"Id": "38659",
"Score": "3",
"Tags": [
"c#",
"queue"
],
"Title": "Priority Queue in C#"
}
|
38659
|
<p>As a learning exercise I wrote a short C program that changes the instructions of a function at runtime in order to execute a shell. It's obviously dependent on x86_64 architecture and Linux (for the syscall number). Indeed, it does start a shell when I run it. I was told to post it here by someone on StackOverflow so what I'm wondering is if there is anything that I'm overlooking in the overall concept or if anything can be improved?</p>
<p>For the sake of brevity, below is only the final product. I wrote up a much longer <a href="https://shanetully.com/2013/12/29/writing-a-self-mutating-x86_64-c-program/" rel="nofollow">explanation of the whole process on my blog</a>, but I'm only concerned about the code below, not my long explanation of it.</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
void foo(void);
int change_page_permissions_of_address(void *addr);
int main(void) {
void *foo_addr = (void*)foo;
// Change the permissions of the page that contains foo() to read, write, and execute
// This assumes that foo() is fully contained by a single page
if(change_page_permissions_of_address(foo_addr) == -1) {
fprintf(stderr, "Error while changing page permissions of foo(): %s\n", strerror(errno));
return 1;
}
puts("Calling foo");
foo();
char shellcode[] =
"\x48\x31\xd2" // xor %rdx, %rdx
"\x48\x31\xc0" // xor %rax, %rax
"\x48\xbb\x2f\x62\x69\x6e\x2f\x73\x68\x00" // mov $0x68732f6e69622f2f, %rbx
"\x53" // push %rbx
"\x48\x89\xe7" // mov %rsp, %rdi
"\x50" // push %rax
"\x57" // push %rdi
"\x48\x89\xe6" // mov %rsp, %rsi
"\xb0\x3b" // mov $0x3b, %al
"\x0f\x05"; // syscall
// Careful with the length of the shellcode here depending on what is after foo
memcpy(foo_addr, shellcode, sizeof(shellcode));
puts("Calling foo");
foo();
return 0;
}
void foo(void) {
int i=0;
i++;
printf("i: %d\n", i);
}
int change_page_permissions_of_address(void *addr) {
// Move the pointer to the page boundary
int page_size = getpagesize();
addr -= (unsigned long)addr % page_size;
if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
return -1;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks pretty good to me. I can see that a lot of research has gone into this. There are a few things I would fix though.</p>\n\n<ul>\n<li><p>You print \"Calling foo\" right before you call it, which I don't really see a need for since you are printing something that looks like a counter within <code>foo()</code>. I would remove them.</p></li>\n<li><p>For your <code>shellcode[]</code> you comment what all the hex does in Assembly, which is good. But I would take it a step farther, and comment on what the Assembly actually does, since it can be hard to follow sometimes.</p></li>\n<li><p>Some of your names are a bit long, such as <code>change_page_permissions_of_address()</code>. That can be a task to type without an IDE, and annoying if you misspell it. Perhaps you should make the name shorter.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:52:13.600",
"Id": "67622",
"Score": "1",
"body": "Thanks for looking over it! Printing \"Calling foo\" was just more to illustrate that `foo()` was changed, but, yes, it can be removed. To address points 2 and 3, I have a very detailed explanation of the shellcode in a blog post since it would be very lengthy to make a comment in the program. I'm a fan of long function names that describe what the function does without a need for a comment when calling it. Plus, I use an editor with auto-complete so it's no big deal to type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:54:50.767",
"Id": "67624",
"Score": "1",
"body": "@shanet Overall your code was very good, and what I had was just nitpicks. Hopefully you can ask some more questions here in the future!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:40:37.583",
"Id": "40223",
"ParentId": "38662",
"Score": "6"
}
},
{
"body": "<p>There's one small bug in your code here:</p>\n\n<pre><code>memcpy(foo_addr, shellcode, sizeof(shellcode));\n</code></pre>\n\n<p>This copies the contents of <code>shellcode</code>, but being a string literal, <code>shellcode</code> includes a null terminator and <code>sizeof(shellcode)</code> is equal to 30, not 29. You should replace this line with:</p>\n\n<pre><code>memcpy(foo_addr, shellcode, sizeof(shellcode) - 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T01:26:10.087",
"Id": "67625",
"Score": "1",
"body": "Good catch, thanks. Darn off-by-one errors!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T01:04:48.150",
"Id": "40225",
"ParentId": "38662",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "40223",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T02:20:55.800",
"Id": "38662",
"Score": "8",
"Tags": [
"c",
"linux"
],
"Title": "Self-mutating C (x86_64)"
}
|
38662
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.