body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm learning F# and I've decided to solve <a href="http://projecteuler.net/problem=81" rel="nofollow">Project Euler's Problem #81</a> with Dijkstra's algorithm.</p>
<blockquote>
<p>In the 5 by 5 matrix below, the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is indicated
in bold red and is equal to 2427.</p>
<pre><code>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
</code></pre>
<p>Find the minimal path sum, in matrix.txt (right click and 'Save
Link/Target As...'), a 31K text file containing a 80 by 80 matrix,
from the top left to the bottom right by only moving right and down.</p>
</blockquote>
<p>Are there any obvious mistakes, inefficiency, any obvious possible improvements, any non-idiomatic use of the F# language?</p>
<pre><code>open System
open System.IO
open Microsoft.FSharp.Collections
// Solving Project Euler #81 with Dijkstra's algorithm
// http://projecteuler.net/problem=81
// Explanation of the algorithm can be found here (Dijkstra is A* with H = 0)
// http://www.policyalmanac.org/games/aStarTutorial.htm
// The costs are provided in a text file and are comma-separated
// We read them into a jagged array of ints
let costs = File.ReadAllLines("matrix.txt")
|> Array.map(fun line -> line.Split(',') |> Array.map int32)
let height = costs.Length;
let width = costs.[0].Length;
// A node has fixed coords, but both its parent and cost can be changed
type Node = {
Coords: int*int
mutable Parent: Node
mutable Cost: int
}
// The total cost of moving to a node is the cost of moving to its parent
// plus the inherent cost of the node as given by the file
let cost srcNode (x, y) =
srcNode.Cost + costs.[y].[x]
// This function returns the next nodes to explore
// In this particular problem, we can only move down or right (no diagonals either)
let neighbours node =
let coords = function
| x, y when (x < width - 1 && y < height - 1) -> [(x + 1, y); (x, y + 1)]
| x, y when (x < width - 1) -> [(x + 1, y)]
| x, y when (y < height - 1) -> [(x, y + 1)]
| _ -> []
coords(node.Coords) |> List.map (fun coord -> { node with Coords = coord;
Parent = node;
Cost = cost node coord })
// Start is top-left; end is bottom-right
let rec startNode = { Coords = 0, 0; Parent = startNode; Cost = costs.[0].[0] }
let rec endNode = { Coords = width - 1, height - 1; Parent = endNode; Cost = Int32.MaxValue }
let currentNode = startNode
let openSet = new ResizeArray<Node>()
let closedSet = new ResizeArray<Node>()
// returns whether node exists in set
let existsIn set node =
set |> Seq.exists(fun n -> n.Coords = node.Coords)
// This is the main function. It returns the path as a list of nodes.
let findPath() =
// 1) Add the starting square (or node) to the open list.
openSet.Add(startNode)
// 2) Repeat the following:
while not(endNode |> existsIn closedSet) do
// a) Look for the lowest cost node on the open list.
// We refer to this as the current node.
let currentNode = openSet |> Seq.minBy (fun node -> node.Cost)
// b) Switch it to the closed list.
// Note that using "Remove" would cause Stackoverflow with the starting node
// since it is defined recursively
openSet.RemoveAll(fun node -> node.Coords = currentNode.Coords) |> ignore
closedSet.Add(currentNode)
// c) For each of the nodes adjacent to this current node …
// If it is not walkable or if it is on the closed list, ignore it.
let neighbourNodes = neighbours currentNode |> List.filter ((existsIn closedSet) >> not)
for node in neighbourNodes do
// If it isn’t on the open list, add it to the open list.
// Make the current node the parent of this node.
// Record the cost of the node.
match openSet |> Seq.tryFind (fun n -> n.Coords = node.Coords) with
| None -> (openSet.Add(node)
node.Parent <- currentNode
node.Cost <- cost currentNode node.Coords)
// If it is on the open list already, check to see if this path to that node is better.
// A lower G cost means that this is a better path.
// If so, change the parent of the square to the current square,
// and recalculate the G and F scores of the square.
| Some(n) -> (let newCost = cost currentNode n.Coords
if newCost < n.Cost then
n.Parent <- currentNode
n.Cost <- newCost)
// 3) Save the path. Working backwards from the target square,
// go from each square to its parent square until you reach the starting square.
// That is your path.
let rec walkBack node =
seq {
if node.Coords <> startNode.Coords then
yield! walkBack node.Parent
yield node
}
walkBack (closedSet.Find(fun n -> n.Coords = endNode.Coords))
// Execute and print!
do
let path = findPath()
for n in path do
let x, y = n.Coords
printfn "%A %A" n.Coords costs.[y].[x]
printfn "Total cost : %A" (Seq.last path).Cost
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T04:13:07.293",
"Id": "20476",
"Score": "0",
"body": "\"Code Review - Stack Exchange is for sharing code from projects you are working on\" -> This is not a project I'm working on. It's a short piece of code I wrote in an hour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T04:21:57.073",
"Id": "20477",
"Score": "0",
"body": "Given that you state that you are looking for a code review, arguably, codereview seems a better fit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T04:22:54.433",
"Id": "20478",
"Score": "0",
"body": "Ok I don't state it anymore. Happy? My question would be off-topic on codereview by their own rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T04:35:12.410",
"Id": "20479",
"Score": "0",
"body": "How exactly do you think your rewording is any more fit for SO? \"*This question is ambiguous, vague, incomplete, overly broad, or rhetorical*\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T04:48:01.193",
"Id": "20480",
"Score": "0",
"body": "... \"and cannot be reasonably answered?\" There's an \"and\" there, not an \"or\". Are you actually saying this question cannot be reasonably answered? Come on, I'm just asking for a few comments on a short piece of code. If you don't feel like reading it, that's fine, just let it live and someone else will come along."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T05:09:29.857",
"Id": "20481",
"Score": "3",
"body": "@Dr_Asik - there isn't really any good answer - there are many possible performance improvements that would make the code less idiomatic and also more idiomatic methods which are slower. As a result, any answer is subjective, which is not the sort of question for SO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T05:48:40.407",
"Id": "20482",
"Score": "0",
"body": "\"A few comments\" is what CodeReview.SE is for. Why are you taking offense to suggesting it should be migrated? Did someone hurt your feelings?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T14:23:40.850",
"Id": "20483",
"Score": "0",
"body": "If the consensus is that the question should be migrated to codereview.SE, why is the question closed rather than migrated to codereview.SE?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T19:01:03.527",
"Id": "20484",
"Score": "0",
"body": "@Dr_Asik : Because CodeReview.SE is not one of the migration options for 'off topic'. If you want it migrated, you need to either flag it for moderation attention or delete it and post it there yourself."
}
] |
[
{
"body": "<p>Apparently there is a strong opinion that this is not a good question for SO, hence no good answer may be given. Nevertheless, I'll try to approach it from efficiency side.</p>\n\n<p>Regardless of quality of given implementation of Dijkstra's algorithm it may be not a good approach for solving <a href=\"http://projecteuler.net/problem=81\">Project Euler Problem 81</a>. The latter has specifics allowing for much shorter and significantly more effective imperative <a href=\"http://en.wikibooks.org/wiki/Algorithms/Greedy_Algorithms\">greedy</a> solution. Assuming function <code>getData(\"matrix.txt, costs)</code> can populate <code>Array2D</code> of costs, the rest of the solution is just:</p>\n\n<pre><code>let problemEuler81() =\n let side = 80\n let costs = Array2D.zeroCreate side side\n getData(\"matrix.txt\", costs)\n for i = side - 2 downto 0 do\n costs.[side-1,i] <- costs.[side-1,i] + costs.[side-1,i+1]\n costs.[i,side-1] <- costs.[i,side-1] + costs.[i+1,side-1]\n\n for i = side - 2 downto 0 do\n for j = side - 2 downto 0 do\n costs.[i,j] <- costs.[i,j] + (min costs.[i+1,j] costs.[i,j+1])\n\n printfn \"%A\" costs.[0, 0]\n</code></pre>\n\n<p>It should not be surprising that more appropriate algorithm choice yields an overwhelming performance gain:</p>\n\n<pre><code>Real: 00:00:00.014, CPU: 00:00:00.015, GC gen0: 1, gen1: 1, gen2: 0\n</code></pre>\n\n<p>versus your solution yielding</p>\n\n<pre><code>Real: 00:00:01.797, CPU: 00:00:01.778, GC gen0: 1, gen1: 0, gen2: 0\n</code></pre>\n\n<p>In the light of this finding the further considerations about your solution may not matter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T15:44:17.270",
"Id": "20485",
"Score": "0",
"body": "Thanks for answering. I'm not sure why your solution works, could you explain it shortly? \n\nI tried to code for clarity and conciseness rather than performance; I didn't use a priority queue as is customary for instance, so the performance is probably not representative of Dijkstra's algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:22:42.007",
"Id": "20507",
"Score": "1",
"body": "You can find the algorithm's detailed description [here](http://infsharpmajor.wordpress.com/2012/03/28/project-euler-problem-81/)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T07:00:04.117",
"Id": "12688",
"ParentId": "12687",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T03:26:03.603",
"Id": "12687",
"Score": "5",
"Tags": [
"algorithm",
"f#",
"matrix",
"programming-challenge",
"pathfinding"
],
"Title": "Path sum - Dijkstra's algorithm in F#"
}
|
12687
|
<p>This is a lock-free <code>Container</code> class. By <code>Container</code> I mean it will hold objects for iteration at a later time. To achieve \$O(1)\$ it returns a token from the <code>put</code> method which you can then use to remove the object. The token is actually the node in which the object has been placed.</p>
<p>It is instantiated with a fixed size and throws an exception if capacity is exhausted. Internally it uses a ring buffer.</p>
<p>It is not intended as a candidate for the <code>Collections</code> toolbox.</p>
<p>Please try to find a way to break it if you can, or point out any areas where you think it might fail under certain situations.</p>
<pre><code>/**
* Container
* ---------
*
* A lock-free container that offers a close-to O(1) add/remove performance.
*
*/
public class Container<T> implements Iterable<T> {
// The capacity of the container.
final int capacity;
// The list.
AtomicReference<Node<T>> head = new AtomicReference<Node<T>>();
// Constructor
public Container(int capacity) {
this.capacity = capacity;
// Construct the list.
Node<T> h = new Node<T>();
Node<T> it = h;
// One created, now add (capacity - 1) more
for (int i = 0; i < capacity - 1; i++) {
// Add it.
it.next = new Node<T>();
// Step on to it.
it = it.next;
}
// Make it a ring.
it.next = h;
// Install it.
head.set(h);
}
// Empty ... NOT thread safe.
public void clear() {
Node<T> it = head.get();
for (int i = 0; i < capacity; i++) {
// Trash the element
it.element = null;
// Mark it free.
it.free.set(true);
it = it.next;
}
}
// Add a new one.
public Node<T> add(T element) {
// Get a free node and attach the element.
return getFree().attach(element);
}
// Find the next free element and mark it not free.
private Node<T> getFree() {
Node<T> freeNode = head.get();
int skipped = 0;
// Stop when we hit the end of the list
// ... or we successfully transit a node from free to not-free.
while (skipped < capacity && !freeNode.free.compareAndSet(true, false)) {
skipped += 1;
freeNode = freeNode.next;
}
if (skipped < capacity) {
// Put the head as next.
// Doesn't matter if it fails. That would just mean someone else was doing the same.
head.set(freeNode.next);
} else {
// We hit the end! No more free nodes.
throw new IllegalStateException("Capacity exhausted.");
}
return freeNode;
}
// Mark it free.
public void remove(Node<T> it, T element) {
// Remove the element first.
it.detach(element);
// Mark it as free.
if (!it.free.compareAndSet(false, true)) {
throw new IllegalStateException("Freeing a freed node.");
}
}
// The Node class. It is static so needs the <T> repeated.
public static class Node<T> {
// The element in the node.
private T element;
// Are we free?
private AtomicBoolean free = new AtomicBoolean(true);
// The next reference in whatever list I am in.
private Node<T> next;
// Construct a node of the list
private Node() {
// Start empty.
element = null;
}
// Attach the element.
public Node<T> attach(T element) {
// Sanity check.
if (this.element == null) {
this.element = element;
} else {
throw new IllegalArgumentException("There is already an element attached.");
}
// Useful for chaining.
return this;
}
// Detach the element.
public Node<T> detach(T element) {
// Sanity check.
if (this.element == element) {
this.element = null;
} else {
throw new IllegalArgumentException("Removal of wrong element.");
}
// Useful for chaining.
return this;
}
public T get () {
return element;
}
@Override
public String toString() {
return element != null ? element.toString() : "null";
}
}
// Provides an iterator across all items in the container.
@Override
public Iterator<T> iterator() {
return new UsedNodesIterator<T>(this);
}
// Iterates across used nodes.
private static class UsedNodesIterator<T> implements Iterator<T> {
// Where next to look for the next used node.
Node<T> it;
int limit = 0;
T next = null;
public UsedNodesIterator(Container<T> c) {
// Snapshot the head node at this time.
it = c.head.get();
limit = c.capacity;
}
@Override
public boolean hasNext() {
// Made into a `while` loop to fix issue reported by @Nim
while (next == null && limit > 0) {
// Scan to the next non-free node.
while (limit > 0 && it.free.get() == true) {
it = it.next;
// Step down 1.
limit -= 1;
}
if (limit != 0) {
next = it.element;
}
}
return next != null;
}
@Override
public T next() {
T n = null;
if ( hasNext () ) {
// Give it to them.
n = next;
next = null;
// Step forward.
it = it.next;
limit -= 1;
} else {
// Not there!!
throw new NoSuchElementException ();
}
return n;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
}
</code></pre>
<p>Having posted this request I now find myself searching aggressively for areas of doubt in the code. Some of those follow but I plan to edit the code and remove these as and when you point me in the right direction.</p>
<ol>
<li>Should <code>Node<T>.element</code> be <code>volatile</code>? I think perhaps.</li>
<li>Should <code>Node<T>.next</code> be <code>volatile</code>? I think not but I am not sure why.</li>
<li>Have I chosen a good method for the iterator? I picked a counter rather than seeing the head for the second time to ensure I am resilient to an increase/decrease in size of the ring. This has the small downside of having slightly less predictability but it guarantees termination and is only a bit strange under high parallelism.</li>
</ol>
<p>NB: <code>Container</code> is not intended to be used between a producer and a consumer. It is designed more for keeping a note of which objects have a particular feature in an iterable way. I use it to keep track of threads in the process of calling <code>put</code> on a <code>BlockingQueue</code> (which may of course block) so I can interrupt them if the queue needs to close.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T13:38:42.760",
"Id": "20486",
"Score": "0",
"body": "The original post is [here](http://stackoverflow.com/a/11080869/823393)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T16:26:41.240",
"Id": "20786",
"Score": "0",
"body": "The declaration of `stop` variable seems to be missing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:13:56.983",
"Id": "20790",
"Score": "0",
"body": "@blufox - my apologies - it should have read `limit`"
}
] |
[
{
"body": "<p>I thought about a comment, but too long, several things I can think of:</p>\n\n<ol>\n<li><p>This does not guarantee order, i.e. an item is entered into the next free slot, and if there is a fast producer, the order the consumer sees is not guaranteed. Is this intentional?</p></li>\n<li><p>There is no atomic combined detach/attach operation, this means that for example:\nThread A: Attach starts, calls <code>getFree()</code>, which marks the node as not free (and is switched out before the element reference is set)\nThread B: is iterating, and hits this node, sees it's not free, so valid node, and returns this, if access to element is done (without a null pointer check), will result in an exception - I guess this is okay(?) Or should you test in your iterator and throw a ConcurrentModification?</p></li>\n</ol>\n\n<p>I think it's simpler if you maintain an <code>AtomicReference</code> in the node to the element and test that rather than a separate boolean and the reference.</p>\n\n<p><strong>Edit 1:</strong></p>\n\n<p>Looking at this:</p>\n\n<pre><code> // Doesn't matter if it fails. That would just mean someone else was doing the same.\n head.set(freeNode.next);\n</code></pre>\n\n<p>Is this necessarily correct? If Thread A sets <span class=\"math-container\">\\$n+1\\$</span> as head at the same time as Thread B setting n as head, and B succeeds - is the ring in a consistent state? I guess the no ordering guarantee means that this doesn't matter too much, but it would violate the <span class=\"math-container\">\\$O(1)\\$</span> claim! ;) In fact, I would question the whole <span class=\"math-container\">\\$O(1)\\$</span> claim, this is at best <span class=\"math-container\">\\$O(1)\\$</span> and at worst <span class=\"math-container\">\\$O(n)\\$</span>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:06:21.790",
"Id": "20763",
"Score": "0",
"body": "1. You are correct - no statement has been made about ordering and there are no guarantees in that respect. All that is guaranteed is that anything that is in the `Container` throughout iteration time will be offered to the `Iterator` user. Anything that is added/removed to/from the `Container` during iteration may or may not be presented to the user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:07:44.267",
"Id": "20764",
"Score": "1",
"body": "2. I see your concern. Very good catch. This scenario could then return false from `hasNext` and thus halt the iteration prematurely. I will fix that. A combined attach/detach would be an interesting detail. Note that the `Node` class is `public` and exposes its `attach` and `detach` methods so it is possible (encouraged) to replace the object without freeing the slot it occupies if that is desired."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:11:21.720",
"Id": "20765",
"Score": "0",
"body": "I hold the `AtomicBoolean free` in the `Node` to allow for the above activity (instant `detach/attach`). I will investigate your idea to see how it affects the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:18:41.493",
"Id": "20767",
"Score": "0",
"body": "2. (revisited) On further thought, your scenario may result in `null` being returned by the `next` method but will not result in a breach of contract as the iteration will continue because `next` is a `Node` not an element. My mistake. BTW - there is an even wider window for this issue because the element can be removed any time between `hasNext` and `next`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:35:44.157",
"Id": "20768",
"Score": "0",
"body": "2. (yet again) ... but `next` calls `hasNext` again and thus could end up throwing a `NoSuchElement`. :( I'd better fix that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:37:53.320",
"Id": "20769",
"Score": "3",
"body": "btw - I think the standard practice with Iterator is that you would call `hasNext()` and if this is true, call `next()` to get the element, you should not invoke `hasNext()` within the call to `next()`, `next()` should just return the element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T15:03:30.907",
"Id": "20770",
"Score": "0",
"body": "Fixed `hasNext` to loop until it finds a valid non-null element or runs out of steam. On `hasNext/next` ... have a look at the documentation on `Iterator` ... there is no guarantee that `hasNext` has been called when `next` is called. It is perfectly reasonable (although unusual) for a user to just keep calling `next` until exception is thrown."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T15:32:10.357",
"Id": "20779",
"Score": "0",
"body": "On your Edit1: This line is a small attempt at optimisation that merely moves `head` to follow the most recent `add` which is often also a free element. In my tests it improved the efficiency significantly. It certainly will not cause the algorithm to fail if the head move fails due to parallel contention. ... I agree that O(1..n) would be more accurate but it would take a huge effort to achieve a test case that is O(n). I have found that even under maximum stress I cannot get it above O(1.1)ish."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-06-21T13:03:35.763",
"Id": "12885",
"ParentId": "12691",
"Score": "6"
}
},
{
"body": "<p>If thread A does <code>Container.remove()</code> and then gets interrupted by thread B after the <code>.detach()</code> but before the <code>//Mark it free</code>, and thread B then iterates, it's going to get a ref to an item that's <code>null</code>, which is probably Not What You Want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T08:15:07.983",
"Id": "20840",
"Score": "0",
"body": "Thanks for the feedback - That was the case in the original code but a recent change triggered by a similar scenario pointed out by @Nim means that the iterator will never return a `null` value. In your case the null value will be skipped."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T02:48:26.587",
"Id": "12918",
"ParentId": "12691",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12885",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T13:36:53.167",
"Id": "12691",
"Score": "17",
"Tags": [
"java",
"collections",
"circular-list",
"lock-free",
"atomic"
],
"Title": "O(1) lock free container"
}
|
12691
|
<p>I recently started learning jQuery and JavaScript and put this together for the site I work on <a href="http://wncba.co.uk/results" rel="nofollow">here</a>.</p>
<pre><code>/*
* Manages the error report popups
*
* written by Tom Jenkinson
*/
jQuery(document).ready(function($) {
var bottomTableReport = {
timer: null,
init: function() {
this.mouseover();
this.mouseout();
},
mouseover: function() {
var self = this;
$(".report-error").mouseover(function() {
if(typeof(this.timer) != 'undefined')
{
clearTimeout(this.timer);
}
$(this).find('.text').css('display','inherit');
});
},
mouseout: function() {
var self = this;
$(".report-error").mouseout(function() {
var self2 = this;
this.timer=setTimeout(function() {
$(self2).find('.text').css('display','none');
},300);
});
}
};
bottomTableReport.init();
function initialiseProblemQtips()
{
var htmlBottomTable= new Array();
htmlBottomTable[0] ='<div class="error-report-popup-1">';
htmlBottomTable[0]+='<div class="main-content">';
htmlBottomTable[0]+='<span class="text-1">Please click on the <img src="images/icons/error.png" /> next to the information in the table that is incorrect.</span>';
htmlBottomTable[0]+='<span class="text-2">If the error doesn\'t have the symbol next to it please <a class="link">click here</a>.</span>';
htmlBottomTable[0]+='</div>';
htmlBottomTable[0]+='</div>';
htmlBottomTable[1] ='<div class="error-report-popup-1">';
htmlBottomTable[1]+='<div class="main-content-2">';
htmlBottomTable[1]+='<span class="title">Report An Error</span>';
htmlBottomTable[1]+='<span class="text-1">To report an error with this table please click on the e-mail address below to send a message to the manager.</span>';
htmlBottomTable[1]+='<span class="email">&rarr; <a class="link" href="mailto:'+errorReportEmail+'?subject=Website Table Error">'+errorReportEmail+'</a> &larr;</span>';
htmlBottomTable[1]+='</div>';
htmlBottomTable[1]+='</div>';
var htmlTable='<div class="error-report-popup-2">';
htmlTable+='<div class="main-content">';
htmlTable+='<span class="title">Report An Error</span>';
htmlTable+='<div class="error-id">';
htmlTable+='<span class="text">Error id: </span><span class="code"><img src="images/icons/code_loading.gif" alt="Loading"></span>';
htmlTable+='</div>';
htmlTable+='<span class="text-1">To report an error with this part of the table please click on the e-mail address below to send a message to the manager.</span>';
htmlTable+='<span class="text-2">Please make sure that the error id above is quoted in your message.</span>';
htmlTable+='<span class="email">&rarr; <a class="link" onclick="alert(\'Please wait for the error id to be retrieved first.\');return false;" href="">'+errorReportEmail+'</a> &larr;</span>';
htmlTable+='</div>';
htmlTable+='</div>';
$(".report-error-container").css('display', 'block');
var popupVisible = new Object();
$(".report-error, .report-error-table").qtip(
{
content: '', //set later in api
position:
{
target: false, //it is changed in the 'beforeRender' part in api section
corner:
{
target: 'bottomMiddle',
tooltip: 'topRight'
}
},
show:
{
when:
{
event: 'click'
},
delay: 0
},
style:
{
name: 'cream',
tip:
{
corner: 'topRight'
},
padding: 0,
width: 400,
border:
{
radius: 5,
width: 0
}
},
hide:
{
when:
{
event: 'unfocus'
}
},
api:
{
beforeRender: function() {
this.targetThis = $(this.elements.target);
this.options.position.target = $(this.targetThis).find('.icon');
this.elements.target = this.options.position.target; //update this as well. I don't actually know what it's use is
var tableNo= $(this.targetThis).attr('data-tableNo');
if($(this.targetThis).hasClass('report-error'))
{
this.options.position.adjust.screen = false;
}
else if($(this.targetThis).hasClass('report-error-table'))
{
this.options.position.adjust.screen = true;
}
},
onRender: function () {
this.qtipThis=$("div[qtip='"+this.id+"']");
},
beforeShow: function () {
var tableNo= $(this.targetThis).attr('data-tableNo');
if($(this.targetThis).hasClass('report-error'))
{
this.updateContent(htmlBottomTable[0],true);
}
else if($(this.targetThis).hasClass('report-error-table'))
{
this.updateContent(htmlTable,true);
}
},
onShow: function() {
var tableNo= $(this.targetThis).attr('data-tableNo');
popupVisible[this.id] = true; //creates item in array or updates it
showHideIcons(tableNo);
this.updatePosition(false,false);
if($(this.targetThis).hasClass('report-error'))
{
var self=this;
$(this.qtipThis).find(".link").click(function () {
self.updateContent(htmlBottomTable[1],true);
})
}
else if($(this.targetThis).hasClass('report-error-table'))
{
var self = this;
$.post("ajax_requests.php?action=get_error_code", {data:$(this.targetThis).attr('data-errorData')}, function(data) {
$(self.qtipThis).find('.code').html(data);
$(self.qtipThis).find('.email .link').attr('onclick', '');
$(self.qtipThis).find('.email .link').attr('href', 'mailto:'+errorReportEmail+'?subject=Website Table Error (Error id: '+data+')');
});
}
},
onHide: function() {
var tableNo= $(this.targetThis).attr('data-tableNo');
popupVisible[this.id] = false;
showHideIcons(tableNo);
}
}
});
var iconTimer = new Object();
function showHideIcons(tableNo)
{
action = 'h';
for (x in popupVisible)
{
if (popupVisible[x]===true)
{
action = 's';
break;
}
}
if(action=='s')
{
if(typeof(iconTimer[tableNo]) != 'undefined')
{
clearTimeout(iconTimer[tableNo]);
}
$('.report-error-table-icon[data-tableNo='+tableNo+']').css('display','inline-block');
$('.report-error-table-icon-inline[data-tableNo='+tableNo+']').css('display','inline');
}
else if(action=='h')
{
iconTimer[tableNo]=setTimeout(function() {
$('.report-error-table-icon[data-tableNo='+tableNo+']').css('display','none');
$('.report-error-table-icon-inline[data-tableNo='+tableNo+']').css('display','none');
}, 2500);
}
}
}
initialiseProblemQtips();
});
</code></pre>
<p>The script location is <a href="http://www.wncba.co.uk/results/javascript/error-reportingv2.js" rel="nofollow">here</a>. You can see it working by clicking on an exclamation mark under a table.</p>
<p>Is there a better way of doing this or are there any improvements that could be made to it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:00:49.973",
"Id": "20488",
"Score": "1",
"body": "`[]` instead of `new Array()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:37:48.877",
"Id": "20498",
"Score": "0",
"body": "@ThiefMaster I've seen that the current best-practice is to avoid `= new array()`, but can you provide some detail as to why `[]` is preferable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:44:25.840",
"Id": "20499",
"Score": "0",
"body": "Looks better and when creating a single-element array `[5]` works while `new Array(5)` would create an array containing 5 `undefined` elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:55:16.237",
"Id": "20503",
"Score": "0",
"body": "also in that bit where I put the html into the variable is there a way of wrapping it across lines (like in php) so I don't have to append to the variable for each line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:56:02.767",
"Id": "20504",
"Score": "1",
"body": "@ThiefMaster Indeed! Are there any other improvements? I admit that it's also cleaner when creating arrays through loops (which a great many are) since you don't need to allocate an empty array just to fill it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:36:50.837",
"Id": "20510",
"Score": "0",
"body": "@TomJenkinson use a backslash \\ in the end of the line, and it wraps to the next. (ES5 feature, see http://stackoverflow.com/a/8090192/148412 )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:15:09.683",
"Id": "20601",
"Score": "2",
"body": "@ANeves That is recommended against [by Google](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Multiline_string_literals#Multiline_string_literals). Besides, then you're mixing your code indentation into the data it's dealing with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T08:04:00.090",
"Id": "20610",
"Score": "0",
"body": "the string concatenation example on that page is pretty much what I was looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T12:02:43.257",
"Id": "20618",
"Score": "1",
"body": "@st-boost thank you, I misunderstood what he meant. To continue a statement in the next line one can leave a hanging operand at the end of the sentence, like a +. To have linebreaks inside strings one can use `line 1\\nline 2` or a backslash at the end of the line and continue on the next."
}
] |
[
{
"body": "<h2><code>[]</code> instead of <code>new Array()</code></h2>\n\n<p>Initialize arrays with <code>[]</code> instead of <code>new Array()</code> - it looks better, and when creating a single-element array [5] works while new Array(5) would create an array containing 5 undefined elements;</p>\n\n<h2>Long strings in multiple lines, rather than concat</h2>\n\n<p>Do </p>\n\n<pre><code>var str = \"The quick brown fox\" +\n \" jumped over the lazy dog.\";\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>var str = \"The quick brown fox\";\nstr += \" jumped over the lazy dog.\"\n</code></pre>\n\n<h2><code>===</code> instead of <code>==</code></h2>\n\n<p>Use <code>===</code> instead of <code>==</code>, and <code>!==</code> instead of <code>!=</code>. <code>==</code> <strong>is not transitive</strong>:</p>\n\n<pre><code>'' == 0; // true\n0 == \"0\"; // true\n'' == \"0\"; // false!\n</code></pre>\n\n<h2>Avoid using inline styles</h2>\n\n<p>Ideally JS would be used to add or remove classes, and those classes styled through CSS.</p>\n\n<p>Separate responsibilities.</p>\n\n<h2>Pick names carefully</h2>\n\n<pre><code>var htmlBottomTable= [];\n</code></pre>\n\n<p>Its name should be pluralized, since it holds a <em>set</em> of things.</p>\n\n<pre><code>bottomTableReport.mouseover\n</code></pre>\n\n<p>I would use a more suggesting name: <code>bottomTableReport.setMouseover</code>.</p>\n\n<h2>Reuse <code>$('foo')</code> when possible</h2>\n\n<p>Instead of repeatingly getting <code>$(\".report-error\")</code>, you can store it once and reuse it:</p>\n\n<pre><code>var bottomTableReport = {\n timer: null,\n target: $(\".report-error\"),\n // ...\n mouseover: function() {\n // ...\n this.target.mouseover(function() { // Reusing.\n // ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-28T16:37:13.757",
"Id": "21299",
"Score": "0",
"body": "+1 all a very valid points that should be considered. The inline styles would have to be my favorite, separating the logic from the design."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T12:41:30.937",
"Id": "12727",
"ParentId": "12693",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "12727",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T13:45:51.033",
"Id": "12693",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"html5"
],
"Title": "Managing error report popups"
}
|
12693
|
<p>Yet another interview question:</p>
<blockquote>
<p>Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.</p>
</blockquote>
<p>First off, did I understand the question correctly? In other words, we are looking for a subtree in a tree (or rotation of it) that looks like:</p>
<blockquote>
<pre><code> root
/ \
leaf_1 leaf_2
/
leaf1_1
</code></pre>
</blockquote>
<p>My initial idea was to count the depth of the tree and check if <code>maxDepth</code> - <code>minDepth</code> < 2 (which requires 2 traversal) . But I think I found a more efficient solution. The trade-off is that we should keep the ref to the root. I assume n-ary tree.</p>
<p>Is this correct?</p>
<pre><code>import java.util.LinkedList;
public class Trees {
Node threeRoot;
private boolean isBalanced = true;
Trees(Node threeRoot){
this.threeRoot = threeRoot;
}
static class Node{
public Node root;
public LinkedList<Node> children = new LinkedList<>();
}
boolean isBalanced(Node node){
if (threeRoot == null) {
isBalanced = true;
}
if (threeRoot.children == null || threeRoot.children.isEmpty()) {
isBalanced = true;
}
isBalancedRed(node);
return isBalanced;
}
void isBalancedRed(Node node) {
if (node.children.isEmpty()) {
if (node.root != null && node.root.children.size() == 1) {
isBalanced = false;
}
}
for(Node nodeEl : node.children)
{
isBalancedRed(nodeEl);
}
}
public static void main(String[] args){
Trees tree = new Trees(new Node());
Node root = tree.threeRoot;
Node leaf1 = new Node();
Node leaf2 = new Node();
Node leaf11 = new Node();
root.children.add(leaf1);
leaf1.root = root;
root.children.add(leaf2);
leaf2.root = root;
leaf2.children.add(leaf11);
leaf11.root = leaf2;
System.out.println(tree.isBalanced(root));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, I would use something other than a LinkedList to hold the children of an n-ary tree. A LinkedList requires you to enumerate the list in order to get the reference to any child other than the leftmost, which is going to slow you down.</p>\n\n<p>Second, your code is basically returning false in any situation where the Node's parent has one child that itself doesn't have any children. In your example tree, that's the exact case (you have two children of the root, one of which has another child) but the tree is balanced according to the rules, so I would expect this algorithm to return a lot of false positives (and negatives).</p>\n\n<p>Finding the depth of an n-ary tree is a linear-bound operation; you traverse each branch of the tree recursively, finding the depth at each leaf node. You can find both the maximum and minimum depth in one traversal; at each level, ask each branch for its maximum and minimum depth, passing the depth of the current node. The base case is that of a leaf node (no children); the min and max is the depth of that leaf. You can store this result in a Tuple or in a more specialized MinMax struct, as you please. With those results returned to the calling level, scan them to find the lowest Min and the greatest Max, and return that to the caller. </p>\n\n<p>Here's a basic implementation:</p>\n\n<pre><code>public class MinMax<T>\n{\n private T minVal;\n private T maxVal;\n\n public MinMax(T min, T max)\n {\n minVal = min;\n maxVal = max;\n }\n\n public T min() {return minVal;}\n public T max() {return maxVal;}\n}\n\nprivate MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)\n{\n //base case; no children. Max and min depth at this leaf is currDepth.\n if(node.children == null || node.children.size() == 0)\n return new MinMax<Integer>(currDepth, currDepth);\n\n //determine the maximum and minimum depth of all child branches,\n //and track the absolute max and min across all of them.\n int min = Integer.MAX_VALUE, max = -1;\n for(Node nextNode : node.children)\n {\n MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);\n if(childDepth.min() < min) min = childDepth.min();\n if(childDepth.max() > max) max = childDepth.max();\n } \n\n return new MinMax<Integer>(min, max);\n}\n\nboolean isBalanced()\n{\n //easy cases; a tree with 0 or 1 elements.\n if(treeRoot == null || treeRoot.children == null || treeRoot.children.size() == 0)\n return true;\n //traverse the tree and find the minimum and maximum depth.\n MinMax<Integer> minMaxDepth = GetMinMaxDepth(treeRoot, 0);\n\n return minMaxDepth.max() - minMaxDepth.min() > 1;\n}\n</code></pre>\n\n<p>This could probably be optimized in our case to return early if we discover that any node's child depths differ by more than 1. We could hack it by throwing an Exception, but the proper strategy is almost as easy to implement:</p>\n\n<pre><code>private MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)\n{\n //base case; no children. max and min depth at this leaf is currDepth.\n if(node.children == null || node.children.size() == 0)\n return new MinMax<Integer>(currDepth, currDepth);\n\n //determine the maximum and minimum depth of all child branches,\n //and track the absolute max and absolute minimum.\n int min = Integer.MIN_VALUE, max = -1;\n for(Node nextNode : node.children)\n {\n MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);\n //Exit now if child is unbalanced\n if(childDepth.max() - childDepth.min() > 1) return childDepth;\n if(childDepth.min() < min) min = childDepth.min();\n if(childDepth.max() > max) max = childDepth.max();\n //Exit now if current node is unbalanced\n if(max-min > 1) break;\n } \n\n return new MinMax<Integer>(min, max);\n}\n</code></pre>\n\n<p>The upside is that we quit as soon as we know the answer to the question (is the tree unbalanced?), which will increase the average performance (but not the worst-case performance on a tree that is balanced or is unbalanced at its furthest extremities). The downside is that we no longer know <em>how</em> unbalanced the tree is; the MaxMin returned to the top level will always have a Max and Min that differ by the first detected difference greater than the threshold (probably 2), not the absolute difference in depth of leaf nodes in the tree.</p>\n\n<p>The one case that is difficult to determine in an n-ary tree is that of a tree that never forks. This algorithm will find a depth difference between any two or more branches, but when there is only one branch, the maximum and minimum depths of the tree are the same and there's nothing to use for comparison. Technically, it would have only one \"leaf\" node (usually defined as a node with no children) and so by the given definition all (one) of the leaves are the same distance from the root, however if you looked at the map of an N-ary tree that was more like a linked list (or even a V or Y shape) and went deeper than two levels, you wouldn't call it balanced.</p>\n\n<p>Perhaps a change in definition may be required; a node is a \"leaf\" node if it does not have N child nodes (where N is the order of the N-ary tree). So, in a quaternary tree (4 children per node), if any node has fewer than 4 children, then the depth of the current node is considered as a \"minimum\" depth and will almost certainly be the minimum depth at that level. That's another easy change:</p>\n\n<pre><code>private MinMax<Integer> GetMinMaxDepth(Node node, int currDepth)\n{\n //base case; no children. max and min depth at this leaf is currDepth.\n if(node.children == null || node.children.size() == 0)\n return new MinMax<Integer>(currDepth, currDepth);\n\n //determine the maximum and minimum depth of all child branches,\n //and track the absolute max and absolute minimum.\n //Exit as soon as we know that this or any child node is unbalanced.\n int min = Integer.MIN_VALUE, max = -1;\n\n //If this node isn't \"full\", its depth is the minimum depth for this branch\n if(node.children.size < max_children) min = currDepth; \n\n for(Node nextNode : node.children)\n {\n MinMax<Integer> childDepth = GetMinMaxDepth(nextNode, currDepth+1);\n //check if child is already unbalanced\n if(childDepth.max() - childDepth.min() > 1) return childDepth;\n if(childDepth.min() < min) min = childDepth.min();\n if(childDepth.max() > max) max = childDepth.max();\n //check if current node is unbalanced\n if(max-min > 1) break;\n } \n\n return new MinMax<Integer>(min, max);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:14:45.463",
"Id": "20550",
"Score": "0",
"body": "thx for the input. 1. LinkedList - sure. If I optimize for performance I'd use ArrayList. Not only for fast random access, but also CPU cache usage. The odds that next element of an array will be in cache is very high comparing to odds that next element of a linked list will be in cache(close to 0). 2. LindkeList is implemented as a double linked list do getFirst() and getLast() should be O(1) and the rest O(n) ofc. 3. you prolly mean public class MinMax<T> not struct and return minValue. 4. Seems I didn't understand the problem correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T18:50:29.057",
"Id": "20560",
"Score": "0",
"body": "Yes, I probably mean public class MinMax<T>; I'm a C# developer by trade, and in that language generic structs are allowed. In this simple example you could just make all Ts ints and remove the generic parameter, but of course a struct like MinMax could have value elsewhere so I tried to make it more useful. Edits coming."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T17:50:24.587",
"Id": "12710",
"ParentId": "12694",
"Score": "5"
}
},
{
"body": "<p>The return statement in <code>isBalanced()</code> should be:</p>\n\n<pre><code>return !( minMaxDepth.max() - minMaxDepth.min() > 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T07:58:13.437",
"Id": "88352",
"Score": "1",
"body": "Would you mind explaining **why?** Also this answer isn't much of a *review* but a rather radical change to the code-behavior. While it may be helpful to criticize and improve the implementation / algorithms of a question, it should not happen without an explanation, why your algorithm is better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T07:13:42.823",
"Id": "51189",
"ParentId": "12694",
"Score": "-2"
}
},
{
"body": "<p>To check if a binary tree is balanced or not we need to check if both its\n left and right children are balance and difference between their heights is \n atmost 1. Here instead of computing the height for each node multiple times\n we can store the height in a hashmap i.e for each node its corresponding height. We can even store the height of a node as a property in the node itself.\nrest of the code is straight forward.</p>\n\n<pre><code>/**\n * Definition for a binary tree node.\n */\nclass TreeNode {\n int val;\n TreeNode left;\n TreeNode right;\n\n TreeNode(int x) {\n val = x;\n }\n}\n\n// first we will get the left height and right height of the node\n// and compute the height difference.if it is > 1 we will return false\n// hashtable to maintain height of each node to reduce the no of redundant\n// height computations\nstatic Hashtable<TreeNode, Integer> haTab = new Hashtable<>();\npublic static boolean isBalanced(TreeNode root) {\n if (root == null) {\n return true;\n }\n int leftHeight, rightHeight;\n leftHeight = height(root.left);\n rightHeight = height(root.right);\n // if left child and right child are balanced and the difference in\n // their heights is < 2\n // then it is balanced\n if (isBalanced(root.left) && isBalanced(root.right)\n && Math.abs(leftHeight - rightHeight) < 2) {\n return true;\n }\n return false;\n }\n\npublic static void main(String[] args) {\n TreeNode root = new TreeNode(1);\n root.left = new TreeNode(-2);\n root.right = new TreeNode(-3);\n root.left.left = new TreeNode(1);\n root.left.right = new TreeNode(3);\n root.right.right = new TreeNode(-1);\n System.out.println(isBalanced(root));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T14:47:20.297",
"Id": "233241",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T14:27:40.077",
"Id": "125066",
"ParentId": "12694",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "12710",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T13:46:55.283",
"Id": "12694",
"Score": "1",
"Tags": [
"java",
"interview-questions",
"tree"
],
"Title": "Implement a function to check if a tree is balanced"
}
|
12694
|
<p>All models are in the model namespace and follow a naming convention. This makes it easy to consolidate control into <code>cType()</code> as shown below.</p>
<p>All control passes through <code>cTYpe()</code> which calls the correct model. It does this by way of the type parameter which is set by the call back function for the specified event.</p>
<p><strong>Calls to Model</strong></p>
<pre><code>model[type].pre()
model[type].post()
</code></pre>
<p><strong>Controller and Model</strong></p>
<pre><code>var model = {};
model.user_try =
{
pre : function()
{
},
post : function( text )
{
}
};
function cType( type, param )
{
var m_response = model[type].pre();
if( m_response )
{
cServer( param, function( text, type ){ model[type].post( text ); }, type );
return true;
}
else
{
return m_response;
}
}
</code></pre>
<p><strong>PostScript</strong></p>
<p>Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, advanced abstractions / design patterns, defensive coding against programmer error / malicious users. Will add these later if the project matures.</p>
|
[] |
[
{
"body": "<p><strong>Disclaimer:</strong> I'm here at behest of the OP. I'm not all that proficient at JS, just enough to do some basic things, but I am fairly well versed in PHP. That being said, the knowledge should be fairly universal and I said I'd lend my point of view on the subject. Please feel free to point out my mistakes. I'd love to know more myself.</p>\n\n<p><strong>Edit:</strong> You can't have structure without syntax, so I ignored that bit. But I did edit my answer per your request for no comments on your naming scheme. I do still think its relevant so I left it, however I hid it so you may skip over it if you wish.</p>\n\n<p><strong>Descriptive Code (Naming Scheme)</strong></p>\n\n<blockquote class=\"spoiler\">\n <p>I'll be honest, I'm not sure what exactly is going on here. Mostly because your function names are not very descriptive. More descriptive function names would be nice, or at the very least, more documentation. Especially documentation about where some of these other functions are coming from. Because JS is so loose with its scope control these could be coming from anywhere and it would be nice to know where they SHOULD be coming from and what they SHOULD be doing/returning.</p>\n</blockquote>\n\n<p><strong>Nesting Functions</strong></p>\n\n<p>There are a couple of problems with nesting functions. The first is that those \"inner\" functions are only available within the scope of the \"outer\" function and are recreated every time that outter function is called. Second is that it is generally considered <a href=\"http://net.tutsplus.com/tutorials/javascript-ajax/stop-nesting-functions-but-not-all-of-them/\" rel=\"nofollow\">bad practice</a>. Not all nested functions, just most. But that is because most are not created properly. I've already said I'm not an expert on this, that's why I gave you the link so you can make your own opinions. I will mention that I don't think what you have here is a good example of nested functions. Mostly because I can't figure out how <code>cIO()</code> is supposed to work if it never calls <code>in()</code>.</p>\n\n<p><strong>Switch Statements</strong></p>\n\n<p>You are defining your switch statements wrong. The colon \":\" should come after the case argument, not before.</p>\n\n<pre><code>case 'user_try':\n</code></pre>\n\n<p>This is one of those <strong>rare</strong> instances where I would say you should look at case dropping. Not sure if that's the right term, but it sounds cool. What I mean by that is instead of retyping the same statements for similar cases, you can write it once, and prepend all the cases that use it above that statement, excluding any breaks so that they \"drop\" down to the next.</p>\n\n<pre><code>case 'user_new':\ncase 'user_exist':\n//etc...\ncase 'tweet_add':\n out( cPreHold( 'model=' + type, cPost( type, text ) ) );\n break;\n</code></pre>\n\n<p><strong>Magic Numbers</strong></p>\n\n<p>You have some magic numbers going on here. Not really sure how you should fix them, but I think there has to be some way. If someone could recommend an example as an edit, I will accept it.</p>\n\n<pre><code>array_pair[0].appendChild( array_pair[1] ) \n</code></pre>\n\n<p><strong>Miscellaneous</strong></p>\n\n<p>I'm confused as to what <code>cPreHold()</code> is supposed to be doing. You have it set up a response variable, check if it has a \"true\" value, which if it does, you do nothing with it, but then if it doesn't it returns the response variable, which is false... Why not just return false? Why use response variable at all?</p>\n\n<pre><code>if( mPre( type ) ) {}\n</code></pre>\n\n<p>I do not think that switch statements are necessary in <code>cPre()</code> and <code>cPost()</code> unless you are planning on extending their functionality. It would be better written as an if/else statement.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I can't really say much about your structure. As I mentioned, I only use JS for very basic applications. More or less, your structure looks the same as how I'd write mine, except for all those lamda functions and nested functions. I can catch some syntax errors, and provide some logic suggestions, but I'm not the best one to turn to for advanced topics such as structure.</p>\n\n<p>BTW: Here's a function I find I use a lot. Seems like you could use it too.</p>\n\n<pre><code>function eID( id ) { return document.getElementById( id ); }\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T21:53:51.000",
"Id": "20582",
"Score": "0",
"body": "Sorry that mPre() was suppose to be cPre()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T21:55:18.450",
"Id": "20584",
"Score": "0",
"body": "cIO(), cPre(), and cPost() are all switch statements because they might expand + with a switch ( as opposed to if/else chainingg ) you don't have to check each block you go right to the correct block"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T21:56:34.120",
"Id": "20585",
"Score": "0",
"body": "I could pass an object instead of the array and then access by name array_pair.childElement and array_pair.parentElement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:05:27.567",
"Id": "20590",
"Score": "0",
"body": "- removed pseudo-code and replaced w/ working, passes jshint.com code..used object literal for subsetting functions...take a look now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:06:33.027",
"Id": "20591",
"Score": "0",
"body": "- One purpose of MVC is to provide single entry point for entering / exiting code - in this case CIO.iN and CIO.out (in is a reserved key word)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:25:14.640",
"Id": "20593",
"Score": "0",
"body": "how is the structure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:03:00.520",
"Id": "20598",
"Score": "0",
"body": "@showerhead On a very, very picky note, those array indexes are not magic numbers. In particular, what would your suggestion for meaningful names for those constants be? They don't have a meaningful replacement because there is no meaningful replacement. The ambiguity there is the entire `out` function, not the array indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:12:16.190",
"Id": "20623",
"Score": "0",
"body": "@Corbin: \"0\" could easily be called parent, and \"1\" either child or append. But the fact that I don't know what this program does limits my understanding of how to name them. Normally I would say they do not need a name, they need to be abstracted through some built-in function that specifically caters to such and explains what they are at the same time. Such as `shift()` and `pop()`."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:27:30.340",
"Id": "12714",
"ParentId": "12695",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:29:34.427",
"Id": "12695",
"Score": "7",
"Tags": [
"javascript",
"mvc"
],
"Title": "MVC - Control Module - Version 2"
}
|
12695
|
<p>This is an function that downloads a single file from an FTP server and saves it to disk
This is my first time doing anything with FTP, please let me know if i have missed anything.</p>
<pre><code>public void DownloadFile(string fileloc, string saveLoc)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fileloc);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(Username, Password);
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var fileStream = File.Create(saveLoc))
{
response.GetResponseStream().CopyTo(fileStream);
}
}
}
catch (Exception EX)
{
throw EX;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>When you rethrow an exception using <code>throw ex;</code> you refresh its stacktrace. (Frame?) This means the exception will seem to have been initially raised at your <code>throw ex;</code> line, and loses its previous stacktrace.</p>\n\n<p>You want to simply <code>throw;</code> - like this:</p>\n\n<pre><code>try {\n new Profiterole(); // BOOM!\n} catch (Exception ex) {\n throw; // Preserves the stacktrace, showing that the Exception was raised in InitGlacing();\n}\n</code></pre>\n\n<hr>\n\n<p>As suggested by @svick: better yet, don't have a <code>try</code>/<code>catch</code> at all; it serves no purpose here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:55:31.937",
"Id": "20516",
"Score": "1",
"body": "Better yet, don't have a `try`/`catch` at all. It serves mo purpose here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:46:48.000",
"Id": "12702",
"ParentId": "12697",
"Score": "1"
}
},
{
"body": "<p>First, like ANeves said, the only thing your <code>catch</code> does is that it resets the exception's stack trace, which is not what you want to do. Just remove the <code>try</code>/<code>catch</code> completely, it serves no purpose here.</p>\n\n<p>Second, I don't see any reason to use <code>WebRequest</code> here, using <code>WebClient</code> is <em>much</em> simpler.</p>\n\n<p>Also, you might want to have better parameter names: <code>fileloc</code> doesn't say what exactly it is, and doesn't use the usual capitalization. And <code>loc</code> is unnecessarily abbreviated (you're not trying to write a Twitter post where every character counts, readability is more important) and too ambiguous.</p>\n\n<pre><code>public void DownloadFile(string url, string savePath)\n{\n var client = new WebClient();\n client.Credentials = new NetworkCredential(Username, Password);\n client.DownloadFile(url, savePath);\n}\n</code></pre>\n\n<p>This method could be rewritten as one expression, but I probably wouldn't do that:</p>\n\n<pre><code>public void DownloadFile(string url, string savePath)\n{\n new WebClient { Credentials = new NetworkCredential(Username, Password) }\n .DownloadFile(url, savePath);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:31:33.307",
"Id": "20594",
"Score": "0",
"body": "Almost everything I have to say."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:02:16.030",
"Id": "12703",
"ParentId": "12697",
"Score": "6"
}
},
{
"body": "<p>It is always good to have a buffer parameter or at least overload the function to provide one. I think this justifies using the FtpWebRequest vs the WebClient as increasing your buffer can <strong>greatly</strong> increase your transfer speed and saturate all available network bandwidth. You will not see any improvement on small files but if you are downloading anything over 100mb is when you will start seeing a noticiceable difference. </p>\n\n<p>Just overfload the CopyTo as</p>\n\n<pre><code>responseStream.CopyTo(fileStream, buffer)\n</code></pre>\n\n<p>And it will do all the work for you. Default is 4096 bytes (4kb). It will take some testing to find just the right buffer but I have found 32kb works well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T07:04:28.267",
"Id": "12766",
"ParentId": "12697",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T14:36:02.300",
"Id": "12697",
"Score": "3",
"Tags": [
"c#",
".net",
"networking",
"ftp"
],
"Title": "FTP Download Function"
}
|
12697
|
<p>I have some code in Go that is attempting to compare two images and determine how different they are. The method is fairly crude, but it is fast enough. Basically it just compares both images pixel by pixel and for each pixel it determines how different they are by comparing the RGBA values separately and using the absolute value of the difference (summed across the 4 channels) as the difference value for the current pixel. It sums together all these difference values and uses that number as the final result (that is then printed).</p>
<p>Does anyone have any comment on how this can be improved? Specifically for accuracy, as I mentioned, performance is "good enough" for now, though I'm not opposed to comments on efficiency as well.</p>
<pre><code>package main
import (
"os"
"log"
"image"
"image/color"
"math"
"fmt"
_ "image/png"
)
func main () {
// open the target file
target_file, err := os.Open("/home/gregg/workspace/Fueled/imagefilters/www/test_images/nashville.png")
if (err != nil) {
log.Fatal(err)
}
defer target_file.Close()
// open the source file
source_file, err := os.Open("/home/gregg/workspace/Fueled/imagefilters/www/test_images/out.png")
if (err != nil) {
log.Fatal(err)
}
defer source_file.Close()
// decode the target file
target, _, err := image.Decode(target_file)
if (err != nil) {
log.Fatal(err)
}
// decode the source file
source, _, err := image.Decode(source_file)
if (err != nil) {
log.Fatal(err)
}
// check to make sure Bounds match
target_bounds := target.Bounds()
source_bounds := source.Bounds()
if (!boundsMatch(target_bounds, source_bounds)) {
log.Fatal("Image sizes don't match!")
}
var diff int64
for y := target_bounds.Min.Y; y < target_bounds.Max.Y; y++ {
for x := target_bounds.Min.X; x < target_bounds.Max.X; x++ {
diff += compareColor(target.At(x, y), source.At(x, y))
}
}
fmt.Printf("%d\n", diff)
}
func compareColor(a, b color.Color) (diff int64) {
r1, g1, b1, a1 := a.RGBA()
r2, g2, b2, a2 := b.RGBA()
diff += int64(math.Abs(float64(r1-r2)))
diff += int64(math.Abs(float64(g1-g2)))
diff += int64(math.Abs(float64(b1-b2)))
diff += int64(math.Abs(float64(a1-a2)))
return diff
}
func boundsMatch(a, b image.Rectangle) bool {
return a.Min.X == b.Min.X && a.Min.Y == b.Min.Y && a.Max.X == b.Max.X && a.Max.Y == b.Max.Y
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:30:34.550",
"Id": "20508",
"Score": "1",
"body": "I wouldn't use rgba for this kind of difference but a color model more natural, like HSL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:46:50.293",
"Id": "20512",
"Score": "0",
"body": "I'm going to give that a try and see how it works, but int he mean time, do you have any specific justification?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:51:58.870",
"Id": "20514",
"Score": "2",
"body": "Look for \"Use in image analysis\" in [this page](http://en.wikipedia.org/wiki/HSL_and_HSV). It's also my experience that HSL gives good results especially when looking for contrast, distance, and color merging (and probably other domains but my personal experience in image analysis is limited)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:05:32.143",
"Id": "20518",
"Score": "0",
"body": "That page also says: \"While HSL, HSV, and related spaces serve well enough to, for instance, choose a single color, they ignore much of the complexity of color appearance.\" How might that affect comparing two pixels? will that be irrelevant in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:09:04.660",
"Id": "20519",
"Score": "0",
"body": "It depends on your goal. Why a pixel by pixel comparison ? What kind of similarity are you looking for ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T16:16:59.180",
"Id": "20520",
"Score": "0",
"body": "\"What kind of similarity are you looking for ?\" ideally they will be identical, but the fewer differences in pixels the better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-24T14:43:54.427",
"Id": "295732",
"Score": "0",
"body": "I believe this can be used for comparing bounds: https://golang.org/pkg/image/#Rectangle.Eq"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T00:46:53.390",
"Id": "470468",
"Score": "0",
"body": "https://www.devdungeon.com/content/working-images-go may get some ideas from this article"
}
] |
[
{
"body": "<p>Though I didn't check the whole program and, according to you, performance is good enough, I do have one performance related suggestion:</p>\n\n<p>avoid <code>int64(math.Abs(float64(</code><strong>var1</strong><code>-</code><strong>var2</strong><code>)))</code>. Casting between int and float types is not free. Just read about <a href=\"http://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow\">Two's complement</a> for ints and how floats are represented in the <a href=\"http://en.wikipedia.org/wiki/IEEE_754\" rel=\"nofollow\">IEEE 754</a> standard. That conversion is not trivial!</p>\n\n<p>As Go (as far as I know) doesn't have an abs method for int-like types, this may provide inspiration on how to <a href=\"http://bits.stephan-brumme.com/absInteger.html\" rel=\"nofollow\">calculate the abs for signed ints</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T14:58:07.923",
"Id": "15033",
"ParentId": "12700",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T15:08:17.050",
"Id": "12700",
"Score": "2",
"Tags": [
"image",
"go"
],
"Title": "Comparing two images"
}
|
12700
|
<p>I am new to Java, and I would like some tips from the 'pros'. I know of the Pascal naming system, and things like that, but how can I improve this code?</p>
<p><strong>Menu.java</strong></p>
<pre><code>package com.x12.addsubtract;
import java.util.Random;
import java.util.Scanner;
public class Subtract {
Game game = new Game();
String[] question = new String[game.numberOfQuestions];
int[] questionAnswer = new int[game.numberOfQuestions];
String[] userQuestionAnswerString = new String[game.numberOfQuestions];
int[] userQuestionAnswerInt = new int[game.numberOfQuestions];
Random rGen = new Random();
int firstNumber;
int secondNumber;
int score;
String tempQuestion;
Scanner input = new Scanner(System.in);
// Sum generation function
public String makeSum(int id) {
// Generate numbers in sum
firstNumber = rGen.nextInt(9);
secondNumber = rGen.nextInt(9);
// Create question
tempQuestion = firstNumber + " - " + secondNumber + " = ";
// Work out question answer
questionAnswer[id - 1] = firstNumber - secondNumber;
// Return question answer
return tempQuestion;
}
// Creation method
Subtract() {
// Print game mode and status information
System.out.println("\nAdding game started!");
System.out.println("Generating questions...");
System.out.println("1 question = 100 points");
System.out.println("Your time is subtracted from your score");
// Print number generation [debug] information
System.out.print("[ ");
for (int qid = 1; qid <= game.numberOfQuestions; qid++) {
question[qid - 1] = makeSum(qid);
System.out.print(qid + " ");
}
System.out.println("]");
// Start timer
long start = System.currentTimeMillis();
// Ask the user the questions
for (int qnum = 0; qnum < question.length; qnum++) {
System.out.print(question[qnum]);
userQuestionAnswerString[qnum] = input.nextLine();
}
long finish = System.currentTimeMillis();
// Convert to number
for (int cQAS = 0; cQAS < userQuestionAnswerString.length; cQAS++) {
try {
userQuestionAnswerInt[cQAS] = Integer.parseInt(userQuestionAnswerString[cQAS]);
} catch (Exception e) {
System.out.println("Error: Your answer for question " + (cQAS + 1) + " is not a number!");
}
}
// Check if user was correct
for (int uQAI = 0; uQAI < userQuestionAnswerInt.length; uQAI++) {
if (userQuestionAnswerInt[uQAI] == questionAnswer[uQAI]) {
score += 1;
}
}
int scoreMass = (int) ((score * 100) - ((finish-start)/1000));
System.out.println("\nYou got " + score + " questions correct out of " + game.numberOfQuestions + ".\nYour score was " + scoreMass + ".");
double totaltime = (finish-start) / 1000D;
System.out.println("It took you " + totaltime + " seconds to do " + game.numberOfQuestions + " additions.");
float spq = (float)totaltime/game.numberOfQuestions;
System.out.println("That is an average of " + spq + " calculation(s) per second!");
}
}
</code></pre>
<p><strong>Add.java</strong></p>
<pre><code>package com.x12.addsubtract;
import java.util.Random;
import java.util.Scanner;
public class Add {
Game game = new Game();
String[] question = new String[game.numberOfQuestions];
int[] questionAnswer = new int[game.numberOfQuestions];
String[] userQuestionAnswerString = new String[game.numberOfQuestions];
int[] userQuestionAnswerInt = new int[game.numberOfQuestions];
Random rGen = new Random();
int firstNumber;
int secondNumber;
int score;
String tempQuestion;
Scanner input = new Scanner(System.in);
// Sum generation function
public String makeSum(int id) {
// Generate numbers in sum
firstNumber = rGen.nextInt(9);
secondNumber = rGen.nextInt(9);
// Create question
tempQuestion = firstNumber + " + " + secondNumber + " = ";
// Work out question answer
questionAnswer[id - 1] = firstNumber + secondNumber;
// Return question answer
return tempQuestion;
}
// Creation method
Add() {
// Print game mode and status information
System.out.println("\nAdding game started!");
System.out.println("Generating questions...");
System.out.println("1 question = 100 points");
System.out.println("Your time is subtracted from your score");
// Print number generation [debug] information
System.out.print("[ ");
for (int qid = 1; qid <= game.numberOfQuestions; qid++) {
question[qid - 1] = makeSum(qid);
System.out.print(qid + " ");
}
System.out.println("]");
// Start timer
long start = System.currentTimeMillis();
// Ask the user the questions
for (int qnum = 0; qnum < question.length; qnum++) {
System.out.print(question[qnum]);
userQuestionAnswerString[qnum] = input.nextLine();
}
long finish = System.currentTimeMillis();
// Convert to number
for (int cQAS = 0; cQAS < userQuestionAnswerString.length; cQAS++) {
try {
userQuestionAnswerInt[cQAS] = Integer.parseInt(userQuestionAnswerString[cQAS]);
} catch (Exception e) {
System.out.println("Error: Your answer for question " + (cQAS + 1) + " is not a number!");
}
}
// Check if user was correct
for (int uQAI = 0; uQAI < userQuestionAnswerInt.length; uQAI++) {
if (userQuestionAnswerInt[uQAI] == questionAnswer[uQAI]) {
score += 1;
}
}
int scoreMass = (int) ((score * 100) - ((finish-start)/1000));
System.out.println("\nYou got " + score + " questions correct out of " + game.numberOfQuestions + ".\nYour score was " + scoreMass + ".");
double totaltime = (finish-start) / 1000D;
System.out.println("It took you " + totaltime + " seconds to do " + game.numberOfQuestions + " additions.");
float spq = (float)totaltime/game.numberOfQuestions;
System.out.println("That is an average of " + spq + " calculation(s) per second!");
}
}
</code></pre>
<p><strong>Subtract.java</strong></p>
<pre><code>package com.x12.addsubtract;
import java.util.Random;
import java.util.Scanner;
public class Subtract {
Game game = new Game();
String[] question = new String[game.numberOfQuestions];
int[] questionAnswer = new int[game.numberOfQuestions];
String[] userQuestionAnswerString = new String[game.numberOfQuestions];
int[] userQuestionAnswerInt = new int[game.numberOfQuestions];
Random rGen = new Random();
int firstNumber;
int secondNumber;
int score;
String tempQuestion;
Scanner input = new Scanner(System.in);
// Sum generation function
public String makeSum(int id) {
// Generate numbers in sum
firstNumber = rGen.nextInt(9);
secondNumber = rGen.nextInt(9);
// Create question
tempQuestion = firstNumber + " - " + secondNumber + " = ";
// Work out question answer
questionAnswer[id - 1] = firstNumber - secondNumber;
// Return question answer
return tempQuestion;
}
// Creation method
Subtract() {
// Print game mode and status information
System.out.println("\nAdding game started!");
System.out.println("Generating questions...");
System.out.println("1 question = 100 points");
System.out.println("Your time is subtracted from your score");
// Print number generation [debug] information
System.out.print("[ ");
for (int qid = 1; qid <= game.numberOfQuestions; qid++) {
question[qid - 1] = makeSum(qid);
System.out.print(qid + " ");
}
System.out.println("]");
// Start timer
long start = System.currentTimeMillis();
// Ask the user the questions
for (int qnum = 0; qnum < question.length; qnum++) {
System.out.print(question[qnum]);
userQuestionAnswerString[qnum] = input.nextLine();
}
long finish = System.currentTimeMillis();
// Convert to number
for (int cQAS = 0; cQAS < userQuestionAnswerString.length; cQAS++) {
try {
userQuestionAnswerInt[cQAS] = Integer.parseInt(userQuestionAnswerString[cQAS]);
} catch (Exception e) {
System.out.println("Error: Your answer for question " + (cQAS + 1) + " is not a number!");
}
}
// Check if user was correct
for (int uQAI = 0; uQAI < userQuestionAnswerInt.length; uQAI++) {
if (userQuestionAnswerInt[uQAI] == questionAnswer[uQAI]) {
score += 1;
}
}
int scoreMass = (int) ((score * 100) - ((finish-start)/1000));
System.out.println("\nYou got " + score + " questions correct out of " + game.numberOfQuestions + ".\nYour score was " + scoreMass + ".");
double totaltime = (finish-start) / 1000D;
System.out.println("It took you " + totaltime + " seconds to do " + game.numberOfQuestions + " additions.");
float spq = (float)totaltime/game.numberOfQuestions;
System.out.println("That is an average of " + spq + " calculation(s) per second!");
}
}
</code></pre>
<p><strong>Game.java</strong></p>
<pre><code>package com.x12.addsubtract;
public class Game {
public int numberOfQuestions = 15;
public void startGameAdd() {
new Add();
}
public void startGameSubtract() {
new Subtract();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:26:58.343",
"Id": "20572",
"Score": "0",
"body": "It appears you added subtract class twice instead of menu"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T21:16:05.183",
"Id": "20581",
"Score": "0",
"body": "An initial thought is that the display logic is mixed with core game logic i.e. System.out.println mixed in with the actual game. First idea I would potentially look at is abstracting these two concepts out perhaps?"
}
] |
[
{
"body": "<p>Welcome to java :), it is not hard to get into the OO mindset. But you might have to unlearn the procedural way of thinking.</p>\n\n<p>A few thoughts to help you along ,</p>\n\n<p>(The Menu.java is missing. So I couldn't look at it)</p>\n\n<ul>\n<li>You seem to be using Game.numberOfQuestions as a static final constant. Why not name it so? This would also make sure that you dont have to instantiate it to access the member.</li>\n<li><p>There does not seem to be any difference between Add.java and Subtract.java except for a single character. (Diff below)</p>\n\n<pre><code>+ Add.java: tempQuestion = firstNumber + \" + \" + secondNumber + \" = \";\n- Subtract.java: tempQuestion = firstNumber + \" - \" + secondNumber + \" = \";\n31c31\n+ Add.java:questionAnswer[id - 1] = firstNumber + secondNumber;\n- Subtract.java:questionAnswer[id - 1] = firstNumber - secondNumber;\n</code></pre></li>\n</ul>\n\n<p>I think you should abstract both Add.java and Subtract.java into a parent class. (use the Game class itself) and make it define a protected method op() that takes two numbers, and does an operation on them. Override them in Add.java with addition and in Subtract.java with subtraction.</p>\n\n<p>This should allow the duplication to go away.</p>\n\n<pre><code>class Subtract extends Game {\n public String name() { return \"Subtract\"; }\n public String opStr() { return \"-\"; }\n public int op(int a, int b) { return a - b; }\n}\n\nclass Add extends Game {\n public String name() { return \"Add\"; }\n public int opStr() { return \"+\"; }\n public int op(int a, int b) { return a + b; }\n}\n</code></pre>\n\n<ul>\n<li>An advice, it is better to take out the println statements from the middle of your logic. They only serve to obscure it. If possible, isolate them to separate methods.</li>\n</ul>\n\n<pre>\n package com.x12.addsubtract;\n import java.util.Random;\n import java.util.Scanner;\n public abstract class Game {\n\n static final int numberOfQuestions = 15;\n\n public abstract String name();\n public abstract String opStr();\n public abstract int op(int a, int b);\n\n\n String[] question = new String[numberOfQuestions];\n int[] questionAnswer = new int[numberOfQuestions];\n</pre>\n\n<p>Avoid excessively long variable names. I know that various books advocate longer variable names, but often they take away from your screen real-estate, </p>\n\n<p>Also, try to restrict the width of your statements to about 100 characters. It is a little more easier on the eye of the reader.</p>\n\n<pre>\n String[] userQAString = new String[numberOfQuestions];\n int[] userQAInt = new int[numberOfQuestions];\n Random rGen = new Random();\n</pre>\n\n<p>Declare the variables at the place you want to use them. Here, firstNumber, secondNumber etc are to be moved to makeSum method.</p>\n\n<pre>\n Scanner input = new Scanner(System.in);\n</pre>\n\n<p>Avoid excessive comments. Especially if the comment only describes the algorithm. Instead, focus on why a function does what it does. A general thumb rule is to focus on the outside rather than the inside. That is, the comment should describe how the function fits into the larger scheme of things.</p>\n\n<p>Also avoid extra variables if possible. They only serve to clutter you code.</p>\n\n<pre><code> public String makeSum(int id) {\n int firstNumber = rGen.nextInt(9);\n int secondNumber = rGen.nextInt(9);\n\n questionAnswer[id - 1] = op(firstNumber, secondNumber);\n return firstNumber + opName() + secondNumber + \" = \";\n }\n\n void banner() {\n System.out.println(name () + \"game started!\");\n System.out.println(\"Generating questions...\");\n System.out.println(\"1 question = 100 points\");\n System.out.println(\"Your time is subtracted from your score\");\n System.out.print(\"[ \");\n for (int qid = 1; qid <= numberOfQuestions; qid++) {\n question[qid - 1] = makeSum(qid);\n System.out.print(qid + \" \");\n }\n System.out.println(\"]\");\n }\n\n void getUserInput() {\n // Ask the user the questions\n for (int qnum = 0; qnum < question.length; qnum++) {\n System.out.print(question[qnum]);\n userQAString[qnum] = input.nextLine();\n }\n</code></pre>\n\n<p>I am unsure if it was intended to be this way (allow user to input all answers before validating) otherwise, combine the below loop with above.</p>\n\n<pre><code> for (int cQAS = 0; cQAS < userQAString.length; cQAS++) {\n try {\n userQAInt[cQAS] = Integer.parseInt(userQAString[cQAS]);\n } catch (Exception e) {\n System.out.println(\"Error: Your answer for question \" \n + (cQAS + 1) + \" is not a number!\");\n }\n }\n }\n\n Game() {\n banner();\n long start = System.currentTimeMillis();\n getUserInput();\n long time = System.currentTimeMillis() - start;\n int score = 0;\n // Check if user was correct\n for (int uQAI = 0; uQAI < userQAInt.length; uQAI++) {\n if (userQAInt[uQAI] == questionAnswer[uQAI]) score++;\n }\n result(score, time);\n }\n</code></pre>\n\n<p>Separate out these from your main logic.</p>\n\n<pre><code> void result(int score, long time) {\n double totaltime = time / 1000D;\n int scoreMass = (int) ((score * 100) - totalTime));\n System.out.println(\"\\nYou got \" + score + \" questions correct out of \" \n + numberOfQuestions + \".\\nYour score was \" + scoreMass + \".\");\n System.out.println(\"It took you \" + totaltime + \" seconds to do \" \n + numberOfQuestions + \" additions.\");\n float spq = (float)totaltime/numberOfQuestions;\n System.out.println(\"That is an average of \" + spq + \" calculation(s) per second!\");\n }\n}\n</code></pre>\n\n<hr>\n\n<p>There is something seriously wrong with the markdown, I cann't get the code quotes to work right anymore. It was working until yesterday.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:11:19.427",
"Id": "20592",
"Score": "0",
"body": "umm, where is that last code segment going? It looks the same as the original code i.e. still has println' in it etc ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:33:21.807",
"Id": "20595",
"Score": "0",
"body": "@dreza you might have seen a partial answer :) check if it answers your question now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:11:34.847",
"Id": "20599",
"Score": "0",
"body": "yep does now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:28:19.650",
"Id": "20661",
"Score": "0",
"body": "I think `op` and `opStr` are taking *\"saving screen real estate\"* too far. If `Game` were called `Operator` (as it should be if `Add` and `Subtract` inherit from it), one could use `calculate` and `getSymbol` as method names instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:33:20.200",
"Id": "20663",
"Score": "0",
"body": "Hmm I agree :). And the Game should be called Operator or Operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:49:47.070",
"Id": "20666",
"Score": "0",
"body": "it's a good answer, by the way."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T22:43:12.280",
"Id": "12718",
"ParentId": "12713",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12718",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:12:56.537",
"Id": "12713",
"Score": "1",
"Tags": [
"java",
"optimization",
"beginner",
"game"
],
"Title": "Add/subtract questions game"
}
|
12713
|
<p>I have been trying to make this code go faster by trying to write it more efficiently and I don't know what else to do. I got it to 30 seconds but I have seen 23 and 24 and I have no idea on how to do it. </p>
<pre class="lang-java prettyprint-override"><code>public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
for(long n = 1; n <= 100000000; n+=2){
long value = cycleLength(n);
if(value > (n*n)){
System.out.println(n + " " + value);
}
}
long endTime = System.currentTimeMillis();
System.out.println("Runtime = " + (endTime - startTime) + " milliseconds");
}//main
public static long cycleLength(long n) {
long hi = n;
while (n > 1) {
if((n&1)==0) // bitwise AND
n = n >> 1; // n even
else {
n = 3*n+1; // n odd
if(hi < n)
hi = n;
n = n >> 1;
}
}
return hi;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:17:48.130",
"Id": "20577",
"Score": "2",
"body": "Where have you seen the other timings? On your computer? You just might want to buy a faster computer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:36:22.610",
"Id": "20578",
"Score": "2",
"body": "Reducing the number of method calls to `System.out.println` will probably help... maybe use a `StringBuilder` to create the output and then print the entire thing at the very end? (idk, I've never done it before)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:47:57.143",
"Id": "20579",
"Score": "0",
"body": "Most of the optimizations are through caching values in an array/hashmap. You can search SO to find similar questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T20:49:09.077",
"Id": "20580",
"Score": "0",
"body": "Is cycleLength supposed to return the cycle length, or the maximum value within in the resulting sequence?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:23:17.590",
"Id": "20630",
"Score": "0",
"body": "Are we talking about [UVA The 3n + 1 problem](http://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=36)?"
}
] |
[
{
"body": "<p>A little bit of loop unrolling plus a time memory tradeoff yields this, which on my machine runs in just over 6s. Your original code took about 32s, so that's a speedup of over 500%. You will need to launch it manually, eclipse cannot run it at the default settings, it takes too much RAM (over 800MB)</p>\n\n<p>It's also worth noting that it will take a fraction of a second longer if you move the <code>long[] solutionarray = new long[max];</code> declaration inside the timing zone.</p>\n\n<p>Apologies for the ugly indentation, eclipse sort of mixed yours and mine.</p>\n\n<pre><code>public class Main {\n\npublic static void main(String[] args) {\n int max = 100000000;\n long[] solutionarray = new long[max];\n solutionarray[1] = 1;\n long startTime = System.currentTimeMillis();\n long n = 1;\n long value = 0;\n while (n < max)\n {\n value = cycleLength(n, solutionarray);\n fillArray(n, value, solutionarray);\n if(value > (n*n))\n System.out.println(n + \" \" + value);\n n += 2;\n }\n\n long endTime = System.currentTimeMillis();\n\n System.out.println(\"Runtime = \" + (endTime - startTime) + \" milliseconds\");\n\n}//main\n\npublic static long cycleLength(long n, long[] array) {\n long orig = n;\n long hi = n;\n while (n > 64) {\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n }\n while (n > 1) {\n if (n < array.length)\n {\n long m = array[(int)n];\n if (m != 0)\n {\n hi = (m < hi) ? hi : m;\n return hi;\n }\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n\n if(hi < n)\n hi = n;\n n >>= 1;\n }\n }\n return hi;\n }\n\n static void fillArray(long n, long hi, long[] array)\n {\n while (true)\n {\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n }\n if (n < array.length)\n {\n if (array[(int) n] != 0) break;\n array[(int) n] = hi;\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n }\n if (n < array.length)\n {\n if (array[(int) n] != 0) break;\n array[(int) n] = hi;\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n }\n if (n < array.length)\n {\n if (array[(int) n] != 0) break;\n array[(int) n] = hi;\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n }\n if (n < array.length)\n {\n if (array[(int) n] != 0) break;\n array[(int) n] = hi;\n }\n if((n&1)==0) // bitwise AND\n n >>= 1; // n even\n else{\n n = n+n+n+1; // n odd\n }\n if (n < array.length)\n {\n if (array[(int) n] != 0) break;\n array[(int) n] = hi;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:55:24.227",
"Id": "20597",
"Score": "0",
"body": "This response is not correct, as it return 61 and 81, which don't show in the original code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:53:36.410",
"Id": "20628",
"Score": "0",
"body": "So it does. Fixing it makes it run much longer unfortunately (the fix simply limits fillArray to filling only until max is reached)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T21:18:36.360",
"Id": "12717",
"ParentId": "12715",
"Score": "0"
}
},
{
"body": "<p>This code runs in 2 secs vs the original 24 secs in my box, with no additional memory needed, or 0.5 secs if you don't mind using more than 1 CPU.</p>\n\n<p>Going to explain how it works with an example:</p>\n\n<p>Let say that \"n\" is 97. \nAt this point maxSoFar is 9232 (which is the value of cycleLength for 27, 31, 41, ...), which is the maximun value of cycleLength found for all \"n\" < 97.\n97 * 97 is 9409 which is bigger than 9232, which means that if inside the loop of the cycleLength, \"j\" becomes smaller than 97, then cycleLength will be at most 9232, which is smaller than 9409 so it is not necessary to continue doing any calculations as cycleLenght will be never bigger than n * n.</p>\n\n<p>So with \"n\" 97, n_square is 9409. We do the first loop, which means that \"j\" is 292. As \"j\" > \"n\", we still have hope that it can become bigger than 9409. Two cycles latter, \"j\" becomes 73 (292 / 2 / 2). Now we know that 73 is never going to be bigger than 9232, which means that there is no point of searching anymore and we can exit cycleLength.</p>\n\n<p>Note that with this implementation cycleLength for 97 actually return 73 (instead of 9232 of your implementation) but the results are still correct.</p>\n\n<p>The code is basically the same as yours but adding a condition in the cycleLength loop.</p>\n\n<pre><code>public class Main {\n\nprivate static long maxSoFar = -1;\n\npublic static void main(String[] args) {\n long startTime = System.currentTimeMillis();\n\nfor (long n = 1; n <= 100000000; n += 2) {\n long value = cycleLength(n);\n if (value > (n * n)) {\n System.out.println(n + \" \" + value);\n maxSoFar = Math.max(value, maxSoFar);\n }\n}\n\nlong endTime = System.currentTimeMillis();\n\nSystem.out.println(\"Runtime = \" + (endTime - startTime) + \" milliseconds\");\n}//main\n\npublic static long cycleLength(long j) {\nlong hi = j;\nlong original = j;\nlong n_square = j * j;\nwhile (j > 1) {\n if (j < original && maxSoFar < n_square) {\n return hi;\n }\n if ((j & 1) == 0) // bitwise AND\n {\n j = j >> 1; // n even\n } else {\n j = 3 * j + 1; // n odd\n if (hi < j) {\n hi = j;\n }\n j = j >> 1;\n }\n}\n\nreturn hi;\n}\n\n}\n</code></pre>\n\n<p>The multithreaded version creates a bunch of threads each one calculating a different serie of n. So for 2 threads:\nThread 1 will do 1, 5, 9, 13 ...\nThread 2 will do 3, 7, 11, 15 ...</p>\n\n<p>In my box (4 cores) the optimal value for n = 10^8 is 32 threads.</p>\n\n<pre><code>import java.util.concurrent.ConcurrentHashMap;\n\npublic class Main implements Runnable {\n\nprivate long maxSoFar = -1;\nprivate int start;\nprivate int step;\nstatic ConcurrentHashMap results = new ConcurrentHashMap();\n\npublic Main(final int start, final int step) {\n this.start = start;\n this.step = step;\n}\n\npublic static void main(String[] args) throws InterruptedException {\nlong startTime = System.currentTimeMillis();\n\nThread[] threads = new Thread[32];\n\nfor (int i = 0; i < threads.length; i++) {\n threads[i] = new Thread(new Main((i * 2) + 1, threads.length * 2));\n}\n\nfor (Thread thread : threads) {\n thread.start();\n}\n\nfor (Thread thread : threads) {\n thread.join();\n}\n\nSystem.out.println(\"results = \" + results);\n\nlong endTime = System.currentTimeMillis();\n\nSystem.out.println(\"Runtime = \" + (endTime - startTime) + \" milliseconds\");\n\n}\n\npublic void run() {\nlong startTime = System.currentTimeMillis();\n\nfor (long n = start; n <= 100000000; n += step) {\n long value = cycleLength(n);\n if (value > (n * n)) {\n System.out.println(Thread.currentThread().getName() + \" \" + n + \" \" + value);\n results.put(n, value);\n maxSoFar = Math.max(value, maxSoFar);\n }\n}\n\nlong endTime = System.currentTimeMillis();\n\nSystem.out.println(\"Runtime = \" + Thread.currentThread().getName() + \" \" + (endTime - startTime) + \" milliseconds\");\n}//main\n\npublic long cycleLength(long j) {\nlong hi = j;\nlong original = j;\nlong n_square = j * j;\nwhile (j > 1) {\n if (j < original && maxSoFar < n_square) {\n return hi;\n }\n if ((j & 1) == 0) // bitwise AND\n {\n j = j >> 1; // n even\n } else {\n j = 3 * j + 1; // n odd\n if (hi < j) {\n hi = j;\n }\n j = j >> 1;\n }\n}\n\nreturn hi;\n}\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:33:02.823",
"Id": "12720",
"ParentId": "12715",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T19:56:55.417",
"Id": "12715",
"Score": "5",
"Tags": [
"java",
"performance"
],
"Title": "Speeding up 3n+1 challenge"
}
|
12715
|
<p>The client side version in JavaScript is <a href="https://codereview.stackexchange.com/questions/12695/mvc-control-module-architecture-design-structure-review-js">here</a></p>
<p>This is the server side version of my control module. How does the structure look. </p>
<p><strong>PostScript</strong></p>
<p>Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, advanced abstractions / design patterns, defensive coding against programmer error / malicious users. Auto-Loading, optimization Will add these later if the project matures. </p>
<pre><code><?php
function __autoload( $class_name ) { include 'class.' . $class_name . '.php'; }
$object_c = new CMachine();
$object_c->invoke();
class CMachine
{
public function invoke()
{
$pipe = $this->getPipe();
switch( $pipe['model'] )
{
case 'MUserNew': case 'MUserExist':
$model_object = new $pipe['model']( new SDB(), new SUniversals() , new SText( $pipe['page'] ), new SMessage() );
$this->send( $model_object->invoke( $pipe['args'] ) );
break;
case 'MUserTry':
$model_object = new $pipe['model']( new SDB(), new SText( $pipe['page'] ) );
$test = $model_object->invoke( $pipe['args'] );
$this->send( $test );
break;
case 'MUserAny': case 'MOrb':
$model_object = new $pipe['model']( new SDB() );
$this->send( $model_object->invoke( $pipe['args'] ) );
break;
default:
echo " -> Undefined Module Requested";
}
}
private function send( $string_send )
{
echo "|A|" . $string_send;
}
private function getPipe()
{
return json_decode( $_POST['pipe'], true );
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T00:18:05.823",
"Id": "20603",
"Score": "0",
"body": "Too lazy to write a full answer, but the first thing that jumps out at me is that it looks like your controller is actually a dispatcher and your models are actually controllers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T16:26:54.533",
"Id": "20653",
"Score": "0",
"body": "...the models hold all my logic...once they are complete they all output a string with the results...the Controller calls the model ( a controller is suppose to call either the view or the model, but I have no views on my server )...and sends the result to the Browser..."
}
] |
[
{
"body": "<p>Would separate those includes a bit differently. I'd use a newline after each include then use a double new line when I wanted to section them off. All one line as you are doing, and not even spaces between them, could make someone think that you have only three includes. Speaking of includes. You are loading all of these classes that you aren't going to use. Take a look a <a href=\"http://en.wikipedia.org/wiki/Lazy_initialization\" rel=\"nofollow\">lazy initialization</a>. Assuiming you only need to use those classes once in this class, and that is in that switch statement, then you can just include the correct one via case and avoid the overhead of those other unneeded classes.</p>\n\n<p>Would have to agree with Corbin about this looking more like a dispatcher/router. These are okay, just letting you know that what you have isn't a controller.</p>\n\n<p>Would suggest moving the <code>send()</code> method out of the switch. It doesn't really appear to change much and is just causing you to rewrite code. Assign whatever paramters you need to in the switch and just call the method outside of it. To prevent the default case from doing this, since you mentioned wanting to use try/catch, I would throw an error there instead of using echo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T16:23:19.873",
"Id": "20652",
"Score": "0",
"body": "I called it router() at one point...how is a router different from a controller? The send() function provides error checking as all output must go through send() it is concatenated with an |A|, if this is not found on the client an alert is raised..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T16:59:30.727",
"Id": "20655",
"Score": "0",
"body": "A router's or dispatcher's only job is to choose which model or controller to load and, in my opinion, which session information to pass to it. Such as GET, POST, etc... Think of it as an old fashioned switch board operator. She collects information she needs to forward your call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T19:30:51.900",
"Id": "20669",
"Score": "0",
"body": "http://www.codeforest.net/cakephp-from-scratch-basic-principles"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T19:32:22.233",
"Id": "20670",
"Score": "0",
"body": "All the models I've seen show the controller doing this( see link...it shows the dispatcher handling only incoming requests w/ no ties to the model)...perhaps they are combined here...I actually need to remove the switch / case and load dynamically...I will update soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:11:02.850",
"Id": "20672",
"Score": "0",
"body": "The good and the bad thing about all design patterns is that everyone adapts them to their own purposes. So the fact that you call a controller, what I call a router, and apparently what Corbin calls a dispatcher, only proves that these are loose terms used to describe an idea and not a strict standard. If you had never heard of a router or dispatcher before and I started explaining my switch board operator analogy, you'd immediately be able to identify it, but as what you think of as a controller. I may not agree on your definition of a controller, but its just a difference in opinions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:15:07.277",
"Id": "20673",
"Score": "0",
"body": "In other words, what you have is perfectly fine. We just disagree on terminology. Maybe it is a unique aspect of cakephp..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:20:18.877",
"Id": "20675",
"Score": "0",
"body": "perhaps...what i like about my model is that you can go to one place to review the input stream and the output stream...and once I remove that switch case it will be very efficient...I am about do dynamically load my classes which I just learned I can do in PHP...already doing similar in my .js Contoller"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T20:36:09.793",
"Id": "20676",
"Score": "0",
"body": "I just made the loading dynamic...the new version is almost 1/2 as long...I need to find a way to autoload or do the lazy initialization as you mentioned next."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T22:29:20.890",
"Id": "20682",
"Score": "0",
"body": "Router is actually the proper name for it. I couldn't remember the name, and dispatcher is the first thing that came to mind. Dispatching is something that the router would handle (as dispatching essentially = routing), but it's typically called a router. I strongly disagree with the link that controllers do routing, but as showerhead said, perhaps it's just opinion. As long as there's a clearly defined separation of responsibilities and loose or no coupling, names aren't important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T22:38:12.080",
"Id": "20683",
"Score": "0",
"body": "@stack.user.0 I do suspect though that if model is acting as a controller, there is no actual models. Models are meant to model data. Nothing less, nothing more. (Well, business rules are often in models.) If you ever have $_GET/$_POST/etc in a model, it's not a model by a strict interpretation of MVC."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-30T23:27:09.413",
"Id": "21392",
"Score": "0",
"body": "Yep, I don't have any GET or POST in my models...they simply take a request...\"model it\" and send back the data.....I'm using autoloading now which implements lazy inits...Let me update....just a sec."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-30T23:30:06.120",
"Id": "21393",
"Score": "0",
"body": "I added the new code above..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-30T23:30:54.447",
"Id": "21394",
"Score": "0",
"body": "This is cool b.c. now I use an object pipe to choose the model to instantiate and pass it args."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:58:02.093",
"Id": "12733",
"ParentId": "12719",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12733",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-18T23:15:19.757",
"Id": "12719",
"Score": "0",
"Tags": [
"php"
],
"Title": "MVC - Control Class - Architecture / Design - Structure Review - PHP"
}
|
12719
|
<p>I'm in the alpha stages of development for my console RPG, and I need some input.</p>
<p>My main question is how should I handle attacks? (You'll see what I mean if you look through my world, item, and enemy classes code.)</p>
<p>Here are some code snippets and a link to my full code. Please note that my latest revision has some unfinished code.</p>
<p>Full code: <a href="http://code.google.com/p/escape-text-rpg/source/browse/Escape/" rel="nofollow">http://code.google.com/p/escape-text-rpg/source/browse/Escape/</a></p>
<p>Main Class:</p>
<pre><code>using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;
using System.Reflection;
namespace Escape
{
class Program
{
#region Declarations
private const int Width = 73;
private const int Height = 30;
private const string saveFile = "save.dat";
public enum GameStates { Start, Playing, Battle, Quit, GameOver };
public static GameStates GameState = GameStates.Start;
private static bool run = true;
private static bool isError = false;
private static List<string> errors = new List<string>();
private static bool isNotification = false;
private static List<string> notifications = new List<string>();
public static Random Rand = new Random();
#endregion
#region Main
public static void Main(string[] args)
{
Console.WindowWidth = Width;
Console.WindowHeight = Height;
Console.BufferWidth = Width;
Console.BufferHeight = Height;
World.Initialize();
while(run)
{
if (!isError)
{
if (Player.Health <= 0)
{
GameState = GameStates.GameOver;
}
switch (GameState)
{
case GameStates.Start:
StartState();
break;
case GameStates.Playing:
PlayingState();
break;
case GameStates.Battle:
BattleState();
break;
case GameStates.Quit:
QuitState();
break;
case GameStates.GameOver:
GameOverState();
break;
}
}
else
{
DisplayError();
}
}
}
#endregion
#region GameState Methods
private static void StartState()
{
Text.WriteLine("Hello adventurer! What is your name?");
Player.Name = Text.SetPrompt("> ");
Text.Clear();
GameState = GameStates.Playing;
}
private static void PlayingState()
{
if (isNotification)
{
DisplayNotification();
}
World.LocationHUD();
string temp = Text.SetPrompt("[" + World.Map[Player.Location].Name + "] > ");
Text.Clear();
Player.Do(temp);
}
private static void BattleState()
{
if (isNotification)
{
DisplayNotification();
}
BattleCore.BattleHUD();
}
private static void QuitState()
{
Console.Clear();
Text.WriteColor("`r`/-----------------------------------------------------------------------\\", false);
Text.WriteColor("|`w` Are you sure you want to quit? (y/n) `r`|", false);
Text.WriteColor("\\-----------------------------------------------------------------------/`w`", false);
ConsoleKeyInfo quitKey = Console.ReadKey();
if (quitKey.KeyChar == 'y')
{
run = false;
}
else
{
Text.Clear();
GameState = GameStates.Playing;
}
}
private static void GameOverState()
{
Console.Clear();
Text.WriteColor("`r`/-----------------------------------------------------------------------\\", false);
Text.WriteColor("|`w` Game Over! `r`|", false);
Text.WriteColor("|`w` Try again? (y/n) `r`|", false);
Text.WriteColor("\\-----------------------------------------------------------------------/`w`", false);
ConsoleKeyInfo quitKey = Console.ReadKey();
if (quitKey.KeyChar == 'y')
{
Process.Start(Assembly.GetExecutingAssembly().Location);
run = false;
}
else
{
run = false;
}
}
#endregion
#region Notification Handling
private static void DisplayNotification()
{
Console.CursorTop = Console.WindowHeight - 1;
Text.WriteColor("`g`/-----------------------------------------------------------------------\\", false);
foreach (string notification in notifications)
{
List<string> notificationLines = Text.Limit(string.Format("`g`Alert: `w`" + notification), Console.WindowWidth - 4);
foreach (string line in notificationLines)
{
Text.WriteColor("| `w`" + line + Text.BlankSpaces(Console.WindowWidth - Regex.Replace(line, @"`.`", "").Length - 4, true) + "`g` |", false);
}
}
Text.Write("\\-----------------------------------------------------------------------/");
Console.SetCursorPosition(0, 0);
UnsetNotification();
}
public static void SetNotification(string message)
{
notifications.Add(message);
isNotification = true;
}
private static void UnsetNotification()
{
notifications.Clear();
isNotification = false;
}
#endregion
#region Error Handling
private static void DisplayError()
{
Console.CursorTop = Console.WindowHeight - 1;
Text.WriteColor("`r`/-----------------------------------------------------------------------\\", false);
foreach (string error in errors)
{
List<string> errorLines = Text.Limit(string.Format("`r`Error: `w`" + error), Console.WindowWidth - 4);
foreach (string line in errorLines)
{
Text.WriteColor("| `w`" + line + Text.BlankSpaces(Console.WindowWidth - Regex.Replace(line, @"`.`", "").Length - 4, true) + "`r` |", false);
}
}
Text.Write("\\-----------------------------------------------------------------------/");
Console.SetCursorPosition(0, 0);
UnsetError();
}
public static void SetError(string message)
{
errors.Add(message);
isError = true;
}
private static void UnsetError()
{
errors.Clear();
isError = false;
}
#endregion
#region Save and Load
public static void Save()
{
SaveGame saveGame = new SaveGame();
try
{
using (Stream stream = File.Open(saveFile, FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, saveGame);
}
Program.SetNotification("Save Successful!");
}
catch (AccessViolationException)
{
Program.SetError("Save Failed! File access denied.");
}
catch (Exception)
{
Program.SetError("Save Failed! An unspecified error occurred.");
}
}
public static void Load()
{
try
{
using (Stream stream = File.Open(saveFile, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
SaveGame saveGame = (SaveGame)bin.Deserialize(stream);
saveGame.Load();
}
Program.SetNotification("Load Successful!");
}
catch (FileNotFoundException)
{
Program.SetError("No savegame exists!");
}
catch (AccessViolationException)
{
Program.SetError("Load failed! File access denied.");
}
catch (Exception)
{
Program.SetError("Load failed! An unspecified error occurred.");
}
}
#endregion
}
}
</code></pre>
<p>Player Class:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Escape
{
static class Player
{
#region Declarations
public static string Name;
public static int Location = 0;
public static int MaxHealth = 100;
public static int Health = MaxHealth;
public static int MaxMagic = 100;
public static int Magic = MaxMagic;
public static List<int> Inventory = new List<int>();
#endregion
#region Public Methods
public static void Do(string aString)
{
if(aString == "")
return;
string verb = "";
string noun = "";
if (aString.IndexOf(" ") > 0)
{
string[] temp = aString.Split(new char[] {' '}, 2);
verb = temp[0].ToLower();
noun = temp[1].ToLower();
}
else
{
verb = aString.ToLower();
}
switch(Program.GameState)
{
case Program.GameStates.Playing:
switch(verb)
{
case "help":
case "?":
WriteCommands();
break;
case "exit":
case "quit":
Program.GameState = Program.GameStates.Quit;
break;
case "move":
case "go":
MoveTo(noun);
break;
case "examine":
Examine(noun);
break;
case "take":
case "pickup":
Pickup(noun);
break;
case "drop":
case "place":
Place(noun);
break;
case "use":
Use(noun);
break;
case "items":
case "inventory":
case "inv":
DisplayInventory();
break;
case "attack":
//attack command
break;
case "hurt":
Player.Health -= Convert.ToInt32(noun);
break;
case "save":
Program.Save();
break;
case "load":
Program.Load();
break;
default:
InputNotValid();
break;
}
break;
case Program.GameStates.Battle:
switch(verb)
{
case "attack":
//attack command
break;
case "flee":
case "escape":
//flee command
break;
case "use":
//use command
break;
case "items":
case "inventory":
case "inv":
//items command
break;
default:
InputNotValid();
break;
}
break;
}
}
public static void RemoveItemFromInventory(int itemId)
{
if (ItemIsInInventory(itemId))
{
Inventory.Remove(itemId);
}
}
#endregion
#region Command Methods
private static void WriteCommands()
{
Text.WriteColor("`g`Available Commands:`w`");
Text.WriteColor("help/? - Display this list.");
Text.WriteColor("exit/quit - Exit the game.");
Text.WriteColor("move/go <`c`location`w`> - Move to the specified location.");
Text.WriteColor("examine <`c`item`w`> - Show info about the specified item.");
Text.WriteColor("take/pickuip <`c`item`w`> - Put the specified item in your inventory.");
Text.WriteColor("drop/place <`c`item`w`> - Drop the specified item from your inventory and place it in the world.");
Text.WriteColor("items/inventory/inv - Display your current inventory.");
Text.WriteColor("use <`c`item`w`> - Use the specified item.");
Text.WriteColor("save/load - saves/loads the game respectively.");
Text.BlankLines();
}
private static void MoveTo(string locationName)
{
if (World.IsLocation(locationName))
{
int locationId = World.GetLocationIdByName(locationName);
if (World.Map[Location].ContainsExit(locationId))
{
Location = locationId;
World.Map[Location].CalculateRandomBattle();
}
else if (Player.Location == locationId)
{
Program.SetError("You are already there!");
}
else
{
Program.SetError("You can't get there from here!");
}
}
else
{
Program.SetError("That isn't a valid location!");
}
}
private static void Examine(string itemName)
{
int itemId = World.GetItemIdByName(itemName);
if (World.IsItem(itemName))
{
if (World.Map[Location].ContainsItem(itemId) || ItemIsInInventory(itemId))
{
World.ItemDescription(itemId);
}
else
{
Program.SetError("That item isn't here!");
}
}
else
{
Program.SetError("That isn't a valid item!");
}
}
private static void Pickup(string itemName)
{
if (World.IsItem(itemName))
{
int itemId = World.GetItemIdByName(itemName);
if (World.Map[Location].ContainsItem(itemId))
{
World.Map[Location].Items.Remove(itemId);
Inventory.Add(itemId);
Program.SetNotification("You put the " + World.Items[itemId].Name + " in your bag!");
}
else
{
Program.SetError("That item isn't here!");
}
}
else
{
Program.SetError("That isn't a valid item!");
}
}
private static void Place(string itemName)
{
if (World.IsItem(itemName))
{
int itemId = World.GetItemIdByName(itemName);
if (ItemIsInInventory(itemId))
{
Inventory.Remove(itemId);
World.Map[Location].Items.Add(itemId);
Program.SetNotification("You placed the " + World.Items[itemId].Name + " in the room!");
}
else
{
Program.SetError("You aren't holding that item!");
}
}
else
{
Program.SetError("That isn't a valid item!");
}
}
private static void Use(string itemName)
{
if (World.IsItem(itemName))
{
int itemId = World.GetItemIdByName(itemName);
if (ItemIsInInventory(itemId))
{
World.Items[itemId].Use();
}
else
{
Program.SetError("You aren't holding that item!");
}
}
else
{
Program.SetError("That isn't a valid item!");
}
}
private static void DisplayInventory()
{
if (Inventory.Count <= 0)
{
Program.SetNotification("You aren't carrying anything!");
return;
}
Text.WriteColor("`m`/-----------------\\");
Text.WriteColor("|`w` Inventory `m`|");
Text.WriteLine(">-----------------<");
for (int i = 0; i < Inventory.Count; i++)
{
string name = World.Items[Inventory[i]].Name;
Text.WriteColor("|`w` " + name + Text.BlankSpaces(16 - name.Length, true) + "`m`|");
}
Text.WriteColor("\\-----------------/`w`");
Text.BlankLines();
}
#endregion
#region Helper Methods
private static void InputNotValid()
{
Program.SetError("That isn't a valid command!");
}
private static bool ItemIsInInventory(int itemId)
{
if (Inventory.Contains(itemId))
return true;
else
return false;
}
#endregion
}
}
</code></pre>
<p>World Class:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Escape
{
static class World
{
#region Declarations
public static List<Location> Map = new List<Location>();
public static List<Item> Items = new List<Item>();
public static List<Enemy> Enemies = new List<Enemy>();
#endregion
#region Initialization
public static void Initialize()
{
GenerateWorld();
GenerateItems();
GenerateEnemies();
}
#endregion
#region World Generation Methods
private static void GenerateWorld()
{
Map.Add(new Location(
"Room 1",
"This is a room.",
new List<int>() {1},
new List<int>() {0, 2}));
Map.Add(new Location(
"Room 2",
"This is another room.",
new List<int>() {0, 2},
new List<int>() {1},
new List<int>() {0},
50));
Map.Add(new Location(
"Room 3",
"This is yet another room.",
new List<int>() {1},
new List<int>(),
new List<int>() {0, 1},
75));
Map.Add(new Location(
"Secret Room",
"This is a very awesome secret room.",
new List<int>() {2}));
}
private static void GenerateItems()
{
Items.Add(new Key(
"Brass Key",
"Just your generic key thats in almost every game.",
2, 3,
true));
Items.Add(new ShinyStone(
"Shiny Stone",
"Its a stone, and its shiny, what more could you ask for?"));
Items.Add(new Rock(
"Rock",
"It doesn't do anything, however, it is said that the mystical game designer used this for testing."));
}
private static void GenerateEnemies()
{
Enemies.Add(new Rat(
"Rat",
"Its just a pwesious wittle wat that will KILL YOU!",
new List<int>() {10, 3, 5},
new List<int>() {0, 1}));
Enemies.Add(new Hawk(
"Hawk",
"It flies around looking for prey to feed on.",
new List<int>() {15, 5, 0},
new List<int>() {2, 3}));
}
#endregion
#region Public Location Methods
public static bool IsLocation(string locationName)
{
for (int i = 0; i < Map.Count; i++)
{
if (Map[i].Name.ToLower() == locationName.ToLower())
return true;
}
return false;
}
public static int GetLocationIdByName(string locationName)
{
for (int i = 0; i < Map.Count; i++)
{
if (Map[i].Name.ToLower() == locationName.ToLower())
return i;
}
return -1;
}
public static void LocationHUD()
{
Text.WriteColor("`c`/-----------------------------------------------------------------------\\", false);
List<string> locationDesctiption = Text.Limit(Map[Player.Location].Description, Console.WindowWidth - 4);
foreach (string line in locationDesctiption)
{
Text.WriteColor("| `w`" + line + Text.BlankSpaces((Console.WindowWidth - line.Length - 4), true) + "`c` |", false);
}
Text.WriteColor(">-----------------v-----------------v-----------------v-----------------<", false);
Text.WriteColor("| `w`Exits`c` | `w`Items`c` | `w`People`c` | `w`Stats`c` |", false);
Text.WriteColor(">-----------------#-----------------#-----------------#-----------------<`w`", false);
int currentY = Console.CursorTop;
int i;
int longestList = 0;
for (i = 0; i < Map[Player.Location].Exits.Count; i++)
{
string name = Map[Map[Player.Location].Exits[i]].Name;
Text.WriteColor(" " + name);
}
longestList = (i > longestList) ? i : longestList;
Console.SetCursorPosition(18, currentY);
for (i = 0; i < Map[Player.Location].Items.Count; i++)
{
string name = Items[Map[Player.Location].Items[i]].Name;
Text.WriteColor(" " + name);
}
longestList = (i > longestList) ? i : longestList;
Console.SetCursorPosition(36, currentY);
for (i = 0; i < Map[Player.Location].Enemies.Count; i++)
{
string name = Enemies[Map[Player.Location].Enemies[i]].Name;
Text.WriteColor(" " + name);
}
longestList = (i > longestList) ? i : longestList;
Console.SetCursorPosition(54, currentY);
Text.WriteColor(" HP [`r`" + Text.ToBar(Player.Health, Player.MaxHealth, 10) + "`w`]");
Text.WriteColor(" MP [`g`" + Text.ToBar(Player.Magic, Player.MaxMagic, 10) + "`w`]");
longestList = (2 > longestList) ? 2 : longestList;
Console.SetCursorPosition(0, currentY);
for (i = 0; i < longestList; i++)
{
for (int j = 0; j < 4; j++)
{
Text.WriteColor("`c`|", false);
Console.CursorLeft += 17;
}
Text.Write("|");
Console.CursorLeft = 0;
}
Text.WriteColor("\\-----------------^-----------------^-----------------^-----------------/`w`");
}
#endregion
#region Public Item Methods
public static bool IsItem(string itemName)
{
for (int i = 0; i < Items.Count; i++)
{
if (Items[i].Name.ToLower() == itemName.ToLower())
return true;
}
return false;
}
public static int GetItemIdByName(string itemName)
{
for (int i = 0; i < Items.Count; i++)
{
if (Items[i].Name.ToLower() == itemName.ToLower())
return i;
}
return -1;
}
public static void ItemDescription(int itemId)
{
Text.WriteLine(Items[itemId].Description);
Text.BlankLines();
}
#endregion
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Well I have a few comments on the code, specifically dealing with the <code>Player</code> class.</p>\n\n<ol>\n<li>I would break up the Do method into a few methods. You could add a static method to parse the action/verb string.</li>\n<li>You could consider changing the verb data into an enum and then user Enum.TryParse to convert the string to the Enum values. That would make the switch statement a little more readable (IMHO).</li>\n<li>Currently the MaxHealth and MaxMagic are public static ints, which means they could be changed later. Now if the player can level up that would be okay, except that these values are static and so if they change for one player, they change for all. They seem more like instance values.</li>\n<li>Player class has a static location, this means when one player moves, all players move to that location. This should be instance data.</li>\n<li>Speaking of player, you may want to make a base character class that can be shared between players and enemies. Containing HP/MP and Inventory/weapons/etc. This will allow more code reuse. Enemies will have location/HP/MP, Players have them, if you have other characters that will interact they will have some of that information (maybe not HP/MP but they will have location).</li>\n</ol>\n\n<p>Edit - Code sample added. Note. I think it would be better to store a list of Items for the player in their inventory as opposed to just an ID. If you want to go the ID route then you should really create an enum for the items and then in the world class or some other more global class maintain a Dictionary that maps the Enum to the Item object (to make easy retrieval of item information). I also added a ParseCommand method that you can call from the Do method. I am sorry that I don't have more time to work on this.:</p>\n\n<pre><code>[DataContract]\n[KnownType(typeof(Player))]\n[KnownType(typeof(Enemy))]\nabstract class Entity\n{\n #region Declarations\n\n [DataMember]\n public string Name { get; protected set; }\n\n [DataMember]\n public string Description { get; protected set; }\n\n [DataMember]\n public int Health { get; protected set; }\n\n [DataMember]\n public int Magic { get; protected set; }\n\n #endregion\n\n #region Constructor\n public Entity(string name, string description, int health, int magic)\n {\n Name = name;\n Description = description;\n Health = health;\n Magic = magic;\n } \n #endregion\n}\n\n[DataContract]\npublic class Player : Entity\n{\n #region Constants\n\n private const DefaultMaxHealth = 100;\n private const DefatulMaxMagic = 100;\n\n #endregion\n\n #region Declarations\n [DataMember]\n public int Location {get; protected set;}\n\n [DataMember]\n public int MaxHealth {get; protected set; }\n\n [DataMember]\n public int MaxMagic {get; protected set; }\n\n [DataMember]\n public List<Item> Inventory = new List<Item>();\n\n #endregion\n\n #region Constructor\n public Player(string name) :\n base(name, \"This is the player\", DefaultMaxHealth, DefaultMaxMagic)\n {\n MaxHealth = DefaultMaxHealth;\n MaxMagic = DefaultMaxMagic;\n } \n #endregion\n\n private static Tuple<string, string> ParseCommand(string command)\n {\n var commands = command.Split(new char[] {' '}, 2, StringSplitOptions.RemoveEmptyEntries);\n var verb = commands[0].ToLower();\n var noun = string.Empty;\n if (commands.Length > 1)\n {\n noun = commands[1].ToLower();\n }\n\n return new Tuple<string, string>(verb, noun);\n }\n</code></pre>\n\n<p>Edit 2 - Some comments on the Location class/code in general\nThere are lots of <a href=\"http://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">Magic Numbers</a> (see also <a href=\"https://stackoverflow.com/q/47882/416574\">this SO</a> post. Instead of a <code>Location</code> maintaining a <code>List<int></code> for the possible exits, consider maintaining a <code>List<Location></code> for possible exits. Instead of a <code>List<int></code> of items, consider a <code>List<Item></code> for the items. This will make the code easier to maintain in the long run. When debugging you won't be going back and forth trying to match up the <code>int</code> with the <code>Item</code> it corresponds to.</p>\n\n<p>The locations all have a name and it appears in the <code>World</code> class that you lookup valid locations via a string match. You should consider storing all the valid locations in a <code>Dictionary</code> that uses a string as the key. You could even define a case insensitive string comparison for the key and then all you need to do to validate a location would be to check if the dictionary contains the key. This will be more efficient than walking a List each time. You can also validate not only that it is an actual location, but you could then change the Location class to store a HashSet of Locations and then pass that into the validation method and use the TryGet method of the dictionary class to not only get the location, but then check if the HashSet contains it thus returning true if the location exists and is reachable from the current location.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T21:14:41.783",
"Id": "20905",
"Score": "0",
"body": "All these are great points. In terms of the player class' static fields, there will never be more than one player in the game, so it doesn't matter. And yes, the player's max's can be leveled up. I will probably add the location/HP/MP stats to the entity class, and make them optional parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T21:15:16.713",
"Id": "20906",
"Score": "0",
"body": "Oh also, I'll most likely accept your answer, but I don't want to mark this question as answered yet so I can get more feedback. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T21:17:45.213",
"Id": "20907",
"Score": "2",
"body": "@ryansworld10 no worries. I would definitely leave it open for a little while to get more feedback. If I have some time over the weekend I will try to add some more suggestions with code samples."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T21:00:10.640",
"Id": "12957",
"ParentId": "12721",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "12957",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T01:12:46.160",
"Id": "12721",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Can I get some constructive criticism on my C# console RPG?"
}
|
12721
|
<p>I feel like I write this a lot in PHP:</p>
<pre><code> $val = isset($var['foo']) ? $var['foo'] : '';
</code></pre>
<p>Is there a shorter way to write this? I can't use the ternary operator because the conditional is an <code>isset</code> check, not the value of the function itself.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:42:58.697",
"Id": "20626",
"Score": "0",
"body": "I toyed around with using `filter_var()` but that isn't any shorter really. Never got around to doing speed test on it. Benjamin's answer is your best bet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-27T20:52:14.077",
"Id": "179994",
"Score": "0",
"body": "The most simple way is merely `$val = @$var['foo'];`. You may look at my [previous answer at a similar question](http://codereview.stackexchange.com/a/85969/69690) for detailed explanation."
}
] |
[
{
"body": "<p>You could wrap it in a function (check the syntax, I don't actually know PHP):</p>\n\n<pre><code>function getDefault($array, $key, $default) {\n return isset($array[$key]) ? $array[$key] : $default;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T06:11:21.017",
"Id": "20607",
"Score": "2",
"body": "Was just about to post that! :) (And your syntax is correct, though I would probably do `function getDefault(array $array, $key, $default)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T06:10:53.977",
"Id": "12723",
"ParentId": "12722",
"Score": "7"
}
},
{
"body": "<p>Another approach is </p>\n\n<pre><code>$foo = ''; // default value\nextract($var); // extracts all array items to corresponding variables\n</code></pre>\n\n<p>This is not appropriate in all cases, eg. when:</p>\n\n<ul>\n<li>You don't want to extract all array elements, just one</li>\n<li>You want to extract the variable to a different name (it's possible to specify a prefix though, so the item will extract to $prefix_foo)</li>\n<li>You don't want to pollute your name space</li>\n</ul>\n\n<p>But in other cases it's quite neat and clean.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-12T18:02:20.743",
"Id": "19543",
"ParentId": "12722",
"Score": "2"
}
},
{
"body": "<p>Building off of what Benjamin Kloster has</p>\n\n<p>If you pass the parameter by reference instead of value it will not choke trying to pass in an invalid index.</p>\n\n<pre><code>function getDefault(&$isset, $default) {\n return isset($isset) ? $isset : $default;\n}\n</code></pre>\n\n<p>Or if you want a dynamic amount of parameters to default to</p>\n\n<p>Just don't pass in any unknown indexes for them because I'm not sure how to do dynamic parameters as reference if that's even possible</p>\n\n<p>ie: getDefault(\"default\", $notSet, $stillNotSet, \"isSet\");</p>\n\n<pre><code>function getDefault($default, &$isset)\n{\n $argCount = func_num_args();\n if ($argCount < 3)\n return isset($isset) ? $isset : $default;\n else\n {\n for($i = 0; $i < $argCount; $i++)\n {\n $arg = func_get_arg($i);\n if (isset($arg))\n return $arg;\n }\n return $default;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T10:12:06.057",
"Id": "184778",
"Score": "0",
"body": "Return is missing in else statement. Why do you start loop from 2nd argument?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T20:53:27.253",
"Id": "184846",
"Score": "0",
"body": "@Andy that's a good point I'm sure my updated code would include that so I will update this answer to include that; good catch : ) It's been a while since I wrote this so I'm not sure if I had a reason but that's also a good catch I will update ; )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T20:55:53.913",
"Id": "184847",
"Score": "0",
"body": "Too bad this won't work for multiple arguments. it throws a notice when calling getDefault with bunch of non-existing variables, apparently because only the first argument is passed by ref."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T20:57:37.350",
"Id": "184849",
"Score": "0",
"body": "@Andy unfortunately there's no way to pass any given amount of parameters all as reference from what my last research concluded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T20:59:05.813",
"Id": "184850",
"Score": "0",
"body": "You can drop else statement completely and just leave isset($isset) ? $isset : $default;. PHP 7 solves that disaster with ?? operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T21:04:04.230",
"Id": "184851",
"Score": "0",
"body": "I just switched the parameters around so that default is the first parameter, thus if nothing is set with any amount of parameters it will always grab the first parameter as the default.\n\nYeah I've heard talk about PHP 7 being out and was just wondering if it introduced something to help with this issue ;)\n\nI'm not sure if the if($argCount < 3) short circuit is a shortcut that will save time, you could always strip it out and just have the for loop in the function.\n\nLast I remember the passing by reference was important for arrays and invalid indexes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T21:04:32.380",
"Id": "184852",
"Score": "0",
"body": "Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/27028/discussion-between-cts-ae-and-andy)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T03:07:33.900",
"Id": "40323",
"ParentId": "12722",
"Score": "6"
}
},
{
"body": "<p>If you want something fancier that supports nested structures, like such:</p>\n\n<pre><code>$foo = json_decode('{\"bar\":[42]}');\necho getDefault( $foo, '-default-', 'bar', 0 );\n# 42\necho getDefault( $foo, '-default-', 'bar', 1 );\n# -default-\necho getDefault( $foo, '-default-', 'missing' );\n# -default-\n</code></pre>\n\n<p>... consider:</p>\n\n<pre><code>function getDefault( $container, $default /*, key1, key2 */ ) {\n // get all remaining arguments\n $keys = array_slice( func_get_args(), 2 );\n\n while( $keys ) {\n $key = array_shift( $keys );\n if( is_array( $container ) && isset( $container[ $key ] ) ) {\n $container = $container[ $key ];\n } else if( is_object( $container ) && isset( $container->$key ) ) {\n $container = $container->$key;\n } else {\n return $default;\n }\n }\n\n return $container;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T05:12:20.290",
"Id": "55189",
"ParentId": "12722",
"Score": "1"
}
},
{
"body": "<p>Now three years later we have the <a href=\"https://wiki.php.net/rfc/isset_ternary\" rel=\"noreferrer\">Null Coalesce Operator</a> in PHP7:</p>\n\n<pre><code> $val = $var['foo'] ?? '';\n</code></pre>\n\n<p><a href=\"http://3v4l.org/Kcb2A\" rel=\"noreferrer\">http://3v4l.org/Kcb2A</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-16T21:07:50.000",
"Id": "184854",
"Score": "0",
"body": "That's awesome! About time ;) I wonder how long it's going to take for most servers to get updated to PHP7 and have it be the main standard at least people on shared hosts. Time for me to look into updating my system."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-17T07:13:32.927",
"Id": "184909",
"Score": "1",
"body": "Note that it is still in beta phase (currently beta 3)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-27T20:08:24.427",
"Id": "98251",
"ParentId": "12722",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "12723",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T05:22:42.480",
"Id": "12722",
"Score": "11",
"Tags": [
"php"
],
"Title": "Shorthand for isset($var['foo']) ? $var['foo'] : ''"
}
|
12722
|
<p>I have a class that has 5 similar methods, they just relay input parameters and return a result - best practice would be to skip the class, but that's not what I'm asking about :) This is a method from the class:</p>
<pre><code>public String deleteItem(Integer itemId,String username, String kpNumber) {
try {
return getItemServiceFacade().deleteItem(itemId, username, kpNumber);
} catch (RemoteException re) {
String message = "5:unexpected error:" + re.toString();
logger.error(message);
return message;
} catch (CoreException ce) {
String message = "5:unexpected error:" + ce.toString();
logger.error(message);
return message;
}
}
</code></pre>
<p>Now, since all the methods are similar, each has the same catch block, each does the same things... so I'd like to rewrite this but I'm unsure how far should I go in "atomizing" the methods. One way is what I consider the "pure" way, so the new code looks like this:</p>
<pre><code>public String deleteItem(Integer itemId,String username, String kpNumber) {
try {
return getItemServiceFacade().deleteItem(itemId, username, kpNumber);
} catch (RemoteException re) {
logException(re);
return getMessage(re);
} catch (CoreException ce) {
logException(ce);
return getMessage(re);
}
}
private String getMessage(Exception exception){
return "5:unexpected error:" + exception.toString();
}
private void logException(Exception exception){
logger.error(getMessage(exception));
}
</code></pre>
<p>but I'm also left wondering if I should combine these two methods into one method, like this</p>
<pre><code>public String handleException (Exception e){
String message = "5:unexpected error:" + exception.toString();
logger.error(message);
return message;
}
</code></pre>
<p>so what I guess I'm trying to ask is how far should you go in separation of concerns when you have clear and simple cases like this one.</p>
<p>Edit: It seems I have not managed to make myself clear, so I'll try again :) In this case simple case, is it considered better to write one method:</p>
<pre><code>public String handleException (Exception e){
String message = "5:unexpected error:" + exception.toString();
logger.error(message);
return message;
}
</code></pre>
<p>or should I have two:</p>
<pre><code>private String getMessage(Exception exception){
return "5:unexpected error:" + exception.toString();
}
private void logException(Exception exception){
logger.error(getMessage(exception));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:07:25.313",
"Id": "20622",
"Score": "0",
"body": "In what way are those methods different?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:28:59.860",
"Id": "20624",
"Score": "0",
"body": "In this two lines `public String deleteItem(Integer itemId,String username, String kpNumber)` and `return getItemServiceFacade().deleteItem(itemId, username, kpNumber);`"
}
] |
[
{
"body": "<p>One alternative, although I don't know if you think it's too complex, would be to apply a visitor pattern:</p>\n\n<pre><code>private interface Command {\n String apply(ItemServiceFacade facade) throws RemoteException, CoreException;\n}\n\npublic String deleteItem(final Integer itemId, final String username, final String kpNumber) {\n return execute(new Command() {\n @Override\n public String apply(ItemServiceFacade facade) throws RemoteException, CoreException {\n return facade.deleteItem(itemId, username, kpNumber);\n }\n });\n}\n\n // other methods...\n\nprivate String execute(Command command) {\n try {\n return command.apply(getItemServiceFacade());\n } catch (RemoteException re) {\n String message = \"5:unexpected error:\" + re.toString();\n logger.error(message);\n return message;\n } catch (CoreException ce) {\n String message = \"5:unexpected error:\" + ce.toString();\n logger.error(message);\n return message;\n }\n}\n</code></pre>\n\n<p>I used this pattern when faced with a similar though slightly more complicated situation (implementing optimistic locking for a few different operations).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:53:29.837",
"Id": "20627",
"Score": "0",
"body": "This is a bit too complex, but the thing is, I was asking about optimizing the part in the Catch block, not making the method call generic :) Plus, I'm working on Java 1.4 :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:36:43.423",
"Id": "12732",
"ParentId": "12728",
"Score": "3"
}
},
{
"body": "<p>There are several things you might want to think about.</p>\n\n<p>The method returns a string. I'm not sure what the facade might return, but to me a boolean or the id (-1 if the method invocation fails) would make more sense. Return the string created by the exceptions requires you not only to implement the try {} catch {} finally block for the checked exceptions, but also forces you to check for an error when the method has been invoked. Since that is what you are returning to the system.</p>\n\n<p>I guess i would think of something like</p>\n\n<pre><code>public boolean deleteItem(Integer itemId,String username, String kpNumber) {\n try {\n getItemServiceFacade().deleteItem(itemId, username, kpNumber);\n } catch (Exception e) {\n // log it away in a descriptive way, you just pass the Exception instance to the method.\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>in contrast to what kyck-ling did, which is a nice way as well. But in the end, as far as i can see, it can be simpler for those cases. But that's always the problem - we don't have any inside regarding the rest of the application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:23:59.473",
"Id": "20631",
"Score": "0",
"body": "The facade also returns a string, in the form of \"1:11:2012\" where the \"1\" means success and the rest is calculated data. Example of unsuccessful message would be \"3:id does not exist!\". But again, I'm not so much interested specifically how to optimize this method, but more generally, what's better practice, making a method do two things at once since it's really simple, or making a full separation of concerns while keeping in mind that the use case is simple and we assume nothing will change in the way the methods behave - more methods could be added but the method logic won't change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:43:15.277",
"Id": "20636",
"Score": "0",
"body": "Well, best practice is concise and clean code. You gain nothing by explicitly adding new try {} catch blocks because you handle the errors independently from Java offers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:09:00.637",
"Id": "12734",
"ParentId": "12728",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T12:51:47.573",
"Id": "12728",
"Score": "5",
"Tags": [
"java"
],
"Title": "What is the \"proper\" way to write this in Java?"
}
|
12728
|
<p>I have following code for a library management system.</p>
<ol>
<li><p>Is the following code a proper implementation of the Repository Pattern?</p></li>
<li><p>How can I adapt this code to use generics?</p></li>
<li><p>Should I let <code>MyOracleReservationRepository</code> and <code>MyOracleBookRepository</code> be <code>DataContracts</code> if I am consuming this code as a WCF service (business Layer will be called by service layer)? </p></li>
</ol>
<h2>Business Layer</h2>
<pre><code>namespace LibraryBL
{
public class ReservationManager
{
//LibraryDAL.ReservationDAL resDAL = new LibraryDAL.ReservationDAL();
//LibraryDAL.BookDAL bookDAL = new LibraryDAL.BookDAL();
LibraryRepository.IReservationRepository reservationRepository;
LibraryRepository.IBookRepository bookRepository;
public ReservationManager(LibraryRepository.IReservationRepository resRepositroy, LibraryRepository.IBookRepository bookRepositroy)
{
reservationRepository = resRepositroy;
bookRepository = bookRepositroy;
}
public List<LibraryDTO.Reservation> GetAllReservations()
{
List<LibraryDTO.Reservation> allReservations = reservationRepository.GetAllReservations();
//Book object inside allReservations has two values as NULL (author and BookTitile).
//These values need to be set using foreach loop
foreach (LibraryDTO.Reservation reservation in allReservations)
{
int bookID =reservation.ReservedBook.BookID;
LibraryDTO.Book book = bookRepository.GetBookByID(bookID);
reservation.ReservedBook = book;
}
return allReservations;
}
}
}
</code></pre>
<h2>Repository</h2>
<pre><code>namespace LibraryRepository
{
public interface IReservationRepository
{
List<LibraryDTO.Reservation> GetAllReservations();
}
public interface IBookRepository
{
LibraryDTO.Book GetBookByID(int bookID);
}
public class MyOracleReservationRepository : IReservationRepository
{
public List<LibraryDTO.Reservation> GetAllReservations()
{
int databaseValueResID1 = 1;
DateTime databaseValueResDate1 = System.Convert.ToDateTime("1/1/2001");
int databaseValueResBookID1 = 101;
List<LibraryDTO.Reservation> reservations = new List<LibraryDTO.Reservation>();
LibraryDTO.Reservation res = new LibraryDTO.Reservation();
res.ReservationID = databaseValueResID1;
res.ReservedDate = databaseValueResDate1;
res.ReservedBook = new LibraryDTO.Book();
res.ReservedBook.BookID = databaseValueResBookID1;
res.ReservedBook.Author = null; //Set as null as we don't have values in Reservation DAL
res.ReservedBook.BookTitle = null; //Set as null as we don't have values in Reservation DAL
reservations.Add(res);
return reservations;
}
}
public class MyOracleBookRepository : IBookRepository
{
public LibraryDTO.Book GetBookByID(int bookID)
{
LibraryDTO.Book book = null;
if (bookID == 101)
{
book = new LibraryDTO.Book();
book.BookID = 101;
book.Author = "First Author";
book.BookTitle = "Book 1";
}
return book;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:31:23.623",
"Id": "20792",
"Score": "1",
"body": "This is more of an aside, not warranting a full answer, but it is good practice to have your public APIs expose as low-level objects as you can. For example, depending upon intended usage, your GetAllReservations function could return IList<T>, ICollection<T>, or (most likely) IEnumerable<T>. Similarly, if you had lower-level representations of your Book and Reservation objects, you would want to use those. Though, if they are simple data structure types, they are fine as-is."
}
] |
[
{
"body": "<p>That is a very good start. However, look into moving the loop to get all the books into the GetAllReservations() method in the concrete class that implements IReservationRepository. When I see the method name \"GetAllReservations\" in the interface IReservationRepository I would expect it would return all the reservation DTOs fully populated. You can still keep the logic separate in the repository, it would just have a call to GetByBookId method. This means the constructor on MyOracleReservationRepository would have to change, but you can hide that in a factory. </p>\n\n<pre><code>namespace LibraryRepository\n{\n public interface IReservationRepository\n {\n List<LibraryDTO.Reservation> GetAllReservations();\n }\n\n public interface IBookRepository\n {\n LibraryDTO.Book GetBookByID(int bookID);\n }\n\n public class LibraryRepositoryFactory\n {\n public virtual IReservationRepository GetReservationRepository()\n {\n IBookRepository bookRepo = GetBookRepository();\n\n return new MyOracleReservationRepository(bookRepo);\n }\n\n public virtual IBookRepository GetBookRepository()\n {\n return new MyOracleBookRepository();\n }\n }\n\n public class MyOracleReservationRepository : IReservationRepository\n {\n private IBookRepository m_BookRepo;\n\n public MyOracleReservationRepository(IBookRepository bookRepo)\n {\n m_BookRepo = bookRepo;\n }\n\n public List<LibraryDTO.Reservation> GetAllReservations()\n {\n List<LibraryDTO.Reservation> reservations = GetReservationsFromDatabase();\n\n foreach (LibraryDTO.Reservation reservation in allReservations)\n {\n int bookID =reservation.ReservedBook.BookID;\n LibraryDTO.Book book = bookRepository.GetBookByID(bookID);\n reservation.ReservedBook = book;\n }\n return allReservations;\n }\n\n private List<LibraryDTO.Reservation> GetReservationsFromDatabase()\n {\n int databaseValueResID1 = 1;\n DateTime databaseValueResDate1 = System.Convert.ToDateTime(\"1/1/2001\");\n int databaseValueResBookID1 = 101;\n\n List<LibraryDTO.Reservation> reservations = new List<LibraryDTO.Reservation>();\n\n LibraryDTO.Reservation res = new LibraryDTO.Reservation();\n res.ReservationID = databaseValueResID1;\n res.ReservedDate = databaseValueResDate1;\n res.ReservedBook = new LibraryDTO.Book();\n res.ReservedBook.BookID = databaseValueResBookID1;\n res.ReservedBook.Author = null; //Set as null as we don't have values in Reservation DAL\n res.ReservedBook.BookTitle = null; //Set as null as we don't have values in Reservation DAL\n\n reservations.Add(res);\n return reservations;\n }\n }\n\n public class MyOracleBookRepository : IBookRepository\n {\n public LibraryDTO.Book GetBookByID(int bookID)\n {\n LibraryDTO.Book book = null;\n if (bookID == 101)\n {\n book = new LibraryDTO.Book();\n book.BookID = 101;\n book.Author = \"First Author\";\n book.BookTitle = \"Book 1\";\n }\n return book;\n }\n }\n}\n</code></pre>\n\n<p>Now your ReservationManager would look something like this:</p>\n\n<pre><code>namespace LibraryBL\n{\n public class LibraryBLFactory\n {\n public ReservationManager GetReservationManager()\n {\n var repoFactory = new LibraryRepository.LibraryRepositoryFactory();\n LibraryRepository.IReservationRepository reservationRepo = repoFactory.GetReservationRepository();\n\n return new ReservationManager(reservationRepo);\n }\n }\n\n public class ReservationManager\n {\n LibraryRepository.IReservationRepository reservationRepository;\n\n\n public ReservationManager(LibraryRepository.IReservationRepository resRepositroy)\n {\n reservationRepository = resRepositroy; \n }\n\n public List<LibraryDTO.Reservation> GetAllReservations()\n {\n return reservationRepository.GetAllReservations();\n }\n\n }\n\n}\n</code></pre>\n\n<p>I am sure there is a bit of refactoring that can be done but hopefully you get the idea. </p>\n\n<p>The idea of the repository is to hide how the data is stored and retrieved from other components. In this particular example ReservationManager. How would the ReservationManager know that after it got all the reservations it would need to go back to the repository and load all the books? What if there was another consumer of the repository? How would it know to do that? The fact you added a comment to indicate why a for loop is needed should be an indication the loop was not in the right place.</p>\n\n<p>As for your other questions. I am not sure what your intention is for Generics, I cannot see a good place where it could be used. As for using data contracts, I would not be in favor of that. The LibraryBL namespace should exist in it's own set of class libraries another service library should invoke through interfaces. The service library should be the one consumed directly by the WCF service. And it would map your DTOs to the Data Contracts. This will keep your code decoupled, because if you ever had to change your logic in LibraryBL you wouldn't really have to worry about how it affects the WCF service, unless you alter a property in the DTOs, but then you would only have to worry about the mapping.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T13:23:19.847",
"Id": "12832",
"ParentId": "12730",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12832",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T13:22:09.013",
"Id": "12730",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"object-oriented",
"generics",
".net-2.0"
],
"Title": "Repository Pattern Review"
}
|
12730
|
<p>I'm verifying South African IDs with jQuery, the code below works but Id like to know if it could be simplified in anyway or if there is a better way of doing things here?</p>
<p>South African IDs are verified as follows:</p>
<blockquote>
<pre><code>Using ID Number 8001015009087 as an example:
Add all the digits in the odd positions (excluding last digit).
8 + 0 + 0 + 5 + 0 + 0 = 13 .............................[1]
Move the even positions into a field and multiply the number by 2.
011098 x 2 = 22196 .....................................[2]
Add the digits of the result in [2].
2 + 2 + 1 + 9 + 6 = 20 .................................[3]
Add the answer in [3] to the answer in [1].
13 + 20 = 33 ...........................................[4]
Subtract the second digit of [4](i.e. 3) from 10. The number must tally with
the last number in the ID Number. If the result is 2 digits, the last digit is
used to compare against the last number in the ID Number. If the answer differs,
the ID number is invalid.
</code></pre>
</blockquote>
<p>And the code:</p>
<pre><code>var me = $("#id");
var odd = new Number();
var even_string = new String();
var even_result = new Number();
var even = new Number();
var result = new Number();
// Check length
if( me.val().length == 13 )
{
$.each(me.val(), function(p,v){
if (p%2 == 0 & p != 12)
{
odd += Number(v); // --> 1. Add all odd positions except the last one.
}
else
{
if(p != 12)
{
even_string += String(v); // --> 2.1 Join all even positions.
}
}
});
// 2.2 Multiply even string by two.
even_result = (even_string * 2);
// 3. Add the digits of the new even result in two point two.
$.each(String(even_result), function(p,v){
even += Number(v);
});
// 4. Add answer in three to the answer in one.
result = odd+even;
// 5. Subtract the second digit from step 4. from ten.
result = 10 - Number(String(result).substr(1,1));
// 6. Make sure we use the very last digit on the result.
if( (String(result)).length > 1 )
{
result = Number( (String(result)).charAt( (String(result)).length-1 ) );
}
// 6. The final check
if( Number(result) != me.val().substr(12,1) )
{
// Not a valid South African ID
alert("Your South African ID is not valid.");
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:13:22.860",
"Id": "20629",
"Score": "0",
"body": "You can [beautify](http://jsbeautifier.org/) (better indenting and spacing) or uglify (compress) it, I don't see why make changes to a fully working code which is as simple as that though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:24:52.763",
"Id": "20632",
"Score": "0",
"body": "First, read on the differences between `==` and `===`. Second, remove all of the `==` and `!=` you are using that needs no type conversion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:27:14.897",
"Id": "20633",
"Score": "0",
"body": "You also can avoid your dependance to jQuery by using `document.getElementById` `element.value` and `for`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:29:32.803",
"Id": "20634",
"Score": "0",
"body": "Are all ID numbers's the same length?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:33:47.183",
"Id": "20635",
"Score": "1",
"body": "Also when you say sum the digits in odd positions for step 1, the index goes from the right to the left correct? So the second digit from the right would be index 0? Which is why the third digit from the right \"0\" is index 1 and is included as part of component 1? Correct?"
}
] |
[
{
"body": "<p>I don't know if it's simpler or more readable, it's kind of in the eye of the beholder. the immediate algorithm is more succinct. However it's still a little convoluted.</p>\n\n<p>You can decide for yourself, but here is a different way of writing it.</p>\n\n<p><a href=\"http://jsfiddle.net/BJhSp/1/\" rel=\"nofollow\">http://jsfiddle.net/BJhSp/1/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:04:49.857",
"Id": "12739",
"ParentId": "12735",
"Score": "0"
}
},
{
"body": "<ul>\n<li><p>Instead of using <code>Number(v)</code>, use <code>+v</code>. This <a href=\"https://stackoverflow.com/a/2243631/148412\">coerces a number</a> out of v. Similarly, to get a string I would .toString() instead of <code>new String(v)</code>;</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/5385372/using-new-in-constructors-john-resigs-35\">Calling constructors without <code>new</code> is not good</a>;</p></li>\n<li><p>I would also choose initialize numbers to <code>0</code>, and strings to <code>\"\"</code> - or not initialize at all.</p></li>\n</ul>\n\n<p>I like that you keep your algorithm simple, rather than condensing it.<br>\nHere is how I would refactor it:</p>\n\n<pre><code>// Wrapped in a self-executing function, not to polute the global scope.\n(function (isNan, $, console) {\n \"use strict\";\n function validateId(id) {\n var odd_checksum = 0,\n even_digits = \"\",\n even_intermediate,\n even_checksum = 0,\n result = 0,\n lastDigit;\n\n // Check length\n if (id.length !== 13) {\n return false;\n }\n\n lastDigit = +id.charAt(12);\n if (isNan(lastDigit)) {\n return false;\n }\n\n $.each(id, function (i, digit) {\n if (i === 12) {\n return false; // end\n }\n if (i % 2 === 0) {\n odd_checksum += +digit; // --> 1. Add all odd positions except the last one.\n } else {\n even_digits += digit.toString(); // --> 2.1 Join all even positions.\n }\n });\n\n // 2.2 Multiply even string by two.\n even_intermediate = 2 * +even_digits;\n\n // 3. Add the digits of the new even result in two point two.\n $.each(even_intermediate.toString(), function (i, digit) {\n even_checksum += +digit;\n });\n\n // 4. Add answer in three to the answer in one.\n result = odd_checksum + even_checksum;\n // If there was any char not a digit, we have NaN here. ( i + NaN === NaN)\n if (isNaN(result)) {\n return false;\n }\n\n // 5. Subtract the second digit from step 4. from ten.\n result = result.toString();\n if (result.length > 1) {\n result = +result.charAt(1);\n } else {\n result = 0;\n }\n result = 10 - result;\n\n // 6. Make sure we use the very last digit on the result.\n if (result === 10) {\n result = 0;\n }\n\n // 6. The final check\n if (result !== lastDigit) {\n return false;\n }\n\n return true; // success!\n }\n\n // Testing.\n var test_ids = [\n \"8001015009087\",\n \"8001015009080\"\n ],\n test;\n // Seems to work.\n for (test in test_ids) {\n test = test_ids[test];\n if (validateId(test)) {\n console.log(\"Your South African ID is valid:\" + test);\n } else {\n console.log(\"Your South African ID is NOT valid:\" + test);\n }\n }\n} (isNaN, $, window.console || { log: function (msg) { alert(msg); } }));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:15:40.260",
"Id": "12750",
"ParentId": "12735",
"Score": "0"
}
},
{
"body": "<ul>\n<li>jQuery is entirely unnecessary and will just make your solution slower</li>\n<li>Don't initialize to <code>new Class()</code> - this is not Java. Instead, initialize to the initial value, or <code>undefined</code> (<code>var x;</code>).</li>\n<li>use a function to encapsulate your verification logic, and to separate it from the DOM interface.</li>\n<li>don't call <code>me.val()</code> more than once; cache the result</li>\n<li>instead of the slow <code>$.each</code>, use a simpler loop</li>\n<li>You already know the length of the id string, so you can get rid of the <code>p%2</code> check and simply operate twice on each loop, once on the current position and once on p + 1, and increment by 2 each time (this also results in half as many iterations, speeding up the loop even further).</li>\n<li>Cast using <code>+string</code> (resulting in a number) and <code>'' + number</code> (resulting in a string)</li>\n<li>split the string into the first 12 and the last 1 at the beginning, so you don't have to keep excluding the last character and re-extracting it.</li>\n<li><code>'string'.slice(-1)</code> is a more concise way to access the last character in a string</li>\n<li>check to make sure that not only is the string 13 characters long, but also that every character is a numeral</li>\n</ul>\n\n<p>With all that and a few stylistic preferences, here's my take on your problem:</p>\n\n<pre><code>function isValidSAID(id) {\n var i, c,\n even = '',\n sum = 0,\n check = id.slice(-1);\n\n if (id.length != 13 || id.match(/\\D/)) {\n return false;\n }\n id = id.substr(0, id.length - 1);\n for (i = 0; c = id.charAt(i); i += 2) {\n sum += +c;\n even += id.charAt(i + 1);\n }\n even = '' + even * 2;\n for (i = 0; c = even.charAt(i); i++) {\n sum += +c;\n }\n sum = 10 - ('' + sum).charAt(1);\n return ('' + sum).slice(-1) == check;\n}\n\nif (!isValidSAID(document.getElementById('id').innerHTML)) {\n alert('Your South African ID is not valid.');\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T11:48:08.233",
"Id": "25092",
"Score": "0",
"body": "IE bug, use: check = id.slice(-1);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T02:46:56.377",
"Id": "25203",
"Score": "0",
"body": "@Derrick thanks. You'd think I would know to always check IE by now. Answer fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T05:24:54.993",
"Id": "12762",
"ParentId": "12735",
"Score": "3"
}
},
{
"body": "<p>Keep in mind that the first 6 digits of a South African ID are the birthdate of the person, so it might be helpful if you check that these are a valid date as well. In your example here, the birthdate would be 1 January 1980 (YYMMDD).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-21T05:19:19.797",
"Id": "190095",
"ParentId": "12735",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12762",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T14:10:39.863",
"Id": "12735",
"Score": "7",
"Tags": [
"javascript",
"jquery"
],
"Title": "Verifying a South African ID"
}
|
12735
|
<p>I'm trying to "sanitize" a textarea input by disallowing repeated characters like "!!!", "???", etc. add spaces after commas, and I would like to optimize the code because I'm not a pro at this.</p>
<p><a href="http://jsfiddle.net/XbZrS/6/" rel="nofollow noreferrer">jsFiddle</a></p>
<pre><code>$("#post_input").keypress(function() {
var obj = this;
setTimeout(function() {
var text = obj.value;
var selStart = obj.selectionStart;
var newText = text.replace(/,{2,}|\.{4,}|\!{4,}|\¡{4,}|\?{4,}|\¿{4,}/, function(match, index) {
if (index < selStart) {
selStart -= (match.length - 4); // correct the selection location
}
return(match.substr(0,1));
});
if (newText != text) {
obj.value = newText;
obj.selectionStart = obj.selectionEnd = selStart;
}
}, 1);
});
$("#post_input").blur(function(){
this.value = this.value.replace( /,\s*/g, ', ' );
});
</code></pre>
<p>I would like to merge all in only one regex and function.</p>
<p>Basically, I want to:</p>
<ul>
<li>Prevent repeated characters (all kind of characters) to 3. No "aaaaa" or "!!!!!"</li>
<li>Add space after commas (,) or any kind of punctuation (!) (?) (.)</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:28:12.977",
"Id": "20642",
"Score": "0",
"body": "Why do you want to turn it all into one big ugly regex?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:29:17.173",
"Id": "20643",
"Score": "0",
"body": "@DavidB is there any better solution? I just want to make a clean code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:34:15.610",
"Id": "20644",
"Score": "0",
"body": "No one will ever complain about the number of carriage returns in your code. Morphing validation into one gigantic, ugly regex will just make it harder to maintain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:35:04.473",
"Id": "20645",
"Score": "0",
"body": "In \"prevent repetead characters to 3\", define \"prevent\" and \"repetead characters to\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:37:35.110",
"Id": "20646",
"Score": "0",
"body": "Thanks David, I see your point. @Qtax I don't want to allow repetead any characters to avoid things like \"helloooooo\" or \"WTF!!!!!!!!\". Just limit the repetition to 3 max..."
}
] |
[
{
"body": "<blockquote>\n <p>Prevent repetead characters (all kind of characters) to 3.</p>\n</blockquote>\n\n<p>If you mean replace 4 or more repeated characters with single character:</p>\n\n<pre><code>str.replace(/(.)\\1{3,}/g, '$1');\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Add space after commas (,) or any kind of punctuation (!) (?) (.)</p>\n</blockquote>\n\n<pre><code>str.replace(/[,.!?:;](?=\\S)/g, '$& ');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:39:22.127",
"Id": "20647",
"Score": "0",
"body": "Great! With the second regex the problem is that it adds spaces if there are 3 of the same punctuation, like \"...\" it converts it to \". . .\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:40:34.687",
"Id": "20648",
"Score": "1",
"body": "@Santiago, add a `+`, like `[,.!?:;]+(?=\\S)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-07T13:55:43.290",
"Id": "399702",
"Score": "0",
"body": "The 1st regex would work for **same consecutive characters** (eg. @@, .. etc), but what about **different consecutive characters from a set** (eg. @.) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-07T23:46:14.957",
"Id": "399801",
"Score": "0",
"body": "@NikhilNanjappa consecutive characters from a set could be matched with `/[@.]{2,}/`. If you want replace it with the first matching character use `/([@.])[@.]+/g` in the first statement."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:37:14.440",
"Id": "12741",
"ParentId": "12740",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12741",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T15:21:32.433",
"Id": "12740",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"regex"
],
"Title": "Disallowing repeated characters and space after punctuation"
}
|
12740
|
<p>I post the following code writen all by hand. Why I have the feeling that it is a western spaghetti on its own. Second, could that be written better?</p>
<pre><code> <div id="form-board" class="notice" style="height: 200px; min-height: 109px; width: auto;display: none;">
<script type="text/javascript">
jQuery(document).ready(function(){
$(".form-button-slide").click(function(){
$( "#form-board" ).dialog();
return false;
});
});
</script>
<?php
echo $this->Form->create('mysubmit');
echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));
echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));
echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));
echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));
echo $this->Form->end("Submit");
?>
</div>
<div style="width:100%"></div>
<div class="form-button-slide" style="float:left;display:block;">
<?php echo $this->Html->link("Error Results", "#"); ?>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#mysubmitIndexForm").submit(function() {
// we want to store the values from the form input box, then send via ajax below
jQuery.post("Staffs/view", { data1: $("#inputs").attr('value'), data2:$("#inputs2").attr('value'),data3:$("#fields").attr('value'), data4:$("#fields2").attr('value') } );
//Close the dialog
$( "#form-board" ).dialog('close')
return false;
});
$("#inputs").change(function() {
// we want to store the values from the form input box, then send via ajax below
var input_id = $('#inputs').attr('value');
$.ajax({
type: "POST",
//The controller who listens to our request
url: "Inputs/getFieldsFromOneInput/"+input_id,
data: "input_id="+ input_id, //+"&amp; lname="+ lname,
success: function(data){//function on success with returned data
$('form#mysubmit').hide(function(){});
data = $.parseJSON(data);
var sel = $("#fields");
sel.empty();
for (var i=0; i<data.length; i++) {
sel.append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
});
return false;
});
$("#inputs2").change(function() {
// we want to store the values from the form input box, then send via ajax below
var input_id = $('#inputs2').attr('value');
$.ajax({
type: "POST",
//The controller who listens to our request
url: "Inputs/getFieldsFromOneInput/"+input_id,
data: "input_id="+ input_id, //+"&amp; lname="+ lname,
success: function(data){//function on success with returned data
$('form#mysubmit').hide(function(){});
data = $.parseJSON(data);
var sel = $("#fields2");
sel.empty();
for (var i=0; i<data.length; i++) {
sel.append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
});
return false;
});
});
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T21:55:24.180",
"Id": "20679",
"Score": "0",
"body": "Yannis did a good job with his review +1 to him. This is just an addition. I think there should be better form names and ID's than inputs, inputs2, etc... These are meaningless. If you can define their purpose then should be able to attribute a better name for them. Such as username or something more descriptive. This helps you identify it later and helps other programmers who might take over your work in the future. With that being said, a better way than incrementing an integer onto the end of your fields is to use array syntax (`inputs[]`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T22:13:03.080",
"Id": "20680",
"Score": "0",
"body": "off course, you are right about the indices. I build up this, by looking some tutorial in order to somehow build a responsive ui with combo boxes in parent-child relationship.so simple!I only needed fast to see results. One side.The other is that because I don't know Jq/ajax, really took me quite a lot and really I am disappointed on one side, and on the other, I didn't know. really. I mean to find how to pass 4 variables from jquery to php back to the controller, I could never imagine that I had to 'post' when in php keyword 'return' is sufficient&clear.after 3 hours I was really..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:17:29.727",
"Id": "20688",
"Score": "0",
"body": "@showerhead I was going to mention the naming, however I took a quick look at my IDE (open at my 2nd monitor at the time), was reminded of how bad I am at naming things and decided to not say a thing ;) To get an idea, I have a function called `voodoo()`..."
}
] |
[
{
"body": "<p>Yes it can. Here are few things:</p>\n\n<ul>\n<li>CSS should be in a separate file</li>\n<li>JavaScript should be in a separate file</li>\n<li>JS file should be included at the bottom, before <code></body></code>. At that point all the content of file would already be \"inside\" an <code>onDomReady</code> \"event\".</li>\n</ul>\n\n<p>Also prominence of <code>$this</code> in the code makes me think, that this is inside some class definition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-29T07:44:18.177",
"Id": "21332",
"Score": "0",
"body": "Note on `$this` - looks like a cakephp view template, the `$this` is used to invoke helpers to create html."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T17:58:40.143",
"Id": "12748",
"ParentId": "12747",
"Score": "2"
}
},
{
"body": "<p><strong>Move all your Javascript out of the way.</strong></p>\n<p>From <a href=\"http://developer.yahoo.com/performance/rules.html\" rel=\"noreferrer\">Yahoo's Best Practices for Speeding Up Your Web Site</a>:</p>\n<blockquote>\n<p><strong>Make JavaScript and CSS External</strong></p>\n<p>Many of these performance rules deal with how external components are managed. However, before these considerations arise you should ask a more basic question: Should JavaScript and CSS be contained in external files, or inlined in the page itself?</p>\n<p>Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.</p>\n</blockquote>\n<p>Obviously, what's more important right now is to minimize that glorious readability mess, hopefully the (small) performance gain might be just the incentive you needed.</p>\n<p><strong>Cache your jQuery objects</strong></p>\n<p>You are using <code>$('#inputs')</code> in <code>$("#mysubmitIndexForm").submit( ... );</code> and twice in <code>$("#inputs").change( ... );</code>. That's three times jQuery traverses the DOM to find <code>#inputs</code>, what you need to do is:</p>\n<pre><code>var inputs = $("#inputs");\n</code></pre>\n<p>at the top of your (external) script, and then use <code>$(inputs)</code> instead. Do it for all your objects, even if you're using them once, it will stay with you as a (good) habit.</p>\n<p><strong>Avoid inline CSS</strong></p>\n<p>Consider moving all your style declarations into an external CSS file. Other than a slight performance gain (similar to external JavaScript), you'll have all your style declarations in one, easy to find, place.</p>\n<hr />\n<p>If you do all of the above, your code would look like:</p>\n<pre><code><head>\n <script type="text/javascript" src="myFunkyScript.js"></script> \n <link rel="stylesheet" type="text/css" href="myFunkyStyles.css" />\n</head>\n\n ...\n \n <div id="form-board" class="notice>\n <?php\n echo $this->Form->create('mysubmit');\n echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));\n echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));\n\n echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));\n echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));\n\n echo $this->Form->end("Submit");\n ?>\n </div>\n <div></div>\n <div class="form-button-slide">\n <?php echo $this->Html->link("Error Results", "#"); ?>\n </div>\n</code></pre>\n<p>and what's up with that empty <code><div></div></code>? If you just want to add some <code>margin-bottom</code>, why not do that on <code>.notice</code> instead?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:54:13.953",
"Id": "20667",
"Score": "0",
"body": "Yannis, thank you a lot for your time and effort to provide me all this explanation. Quite awesome. If I mention that this code you saw, was originally started from some tutorial on the net [and while I do not know JQuery or Ajax fundamentally] it took me perhaps 4 hours maximum, including searching tutorials, screens, help etc etc. [One side effect I had was that I could not understand how to send from JQuery to php back, plain data. And some efforts I tried were useless, like .serialize() totally zero!], how would you comment then? Lost time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:15:25.080",
"Id": "20687",
"Score": "1",
"body": "@hephestos Lost time? Not at all. It works, and that's what's important, that's what you should go for at first. After you get it to work as expected, phase two is to make it look good. In time, both phases will blend, and writing readable code will become instinctual. Now, teresko has a [great point](http://codereview.stackexchange.com/a/12748/4673) about the prominence of `$this`, rewrite your code to move JS and CSS out of the way, and then post a new question here with your full PHP code, there seems to be room for improvement there as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T09:38:24.003",
"Id": "20700",
"Score": "0",
"body": "actually , if you would follow Yahoo guidelines , the JavaScript would be included at the bottom"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:18:10.327",
"Id": "20731",
"Score": "0",
"body": "@teresko Depends on the script, really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:21:40.857",
"Id": "20732",
"Score": "0",
"body": "@YannisRizos , true , there are exceptions. But that's only in very specific cases. But even then they are **not used** inside `<head>` tag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-29T07:42:01.113",
"Id": "21331",
"Score": "0",
"body": "Is there a notable difference when declaring `var inputs = $(\"#inputs\");` from later using `$(inputs).someJqueryFunction()` to `inputs.someJqueryFunction()`?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:00:28.143",
"Id": "12749",
"ParentId": "12747",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "12749",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T17:32:50.913",
"Id": "12747",
"Score": "2",
"Tags": [
"php",
"javascript",
"jquery",
"ajax"
],
"Title": "Is this spaghetti code already?"
}
|
12747
|
<p>The code below is slow. Any thoughts on speeding up? </p>
<pre><code>dict1 = {}
dict2 = {}
list_needed = []
for val in dict1.itervalues():
for k,v in d1ct2.iteritems():
if val == k:
list_needed.append([val,v])
</code></pre>
|
[] |
[
{
"body": "<p>Perhaps,</p>\n\n<pre><code>for val in dict1.itervalues():\n if val in dict2:\n list_needed.append([val,dict2[val]])\n</code></pre>\n\n<p>This is similar to </p>\n\n<pre><code>list_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]\n</code></pre>\n\n<p>My preference would be to make <code>[val,v]</code> a tuple - i.e <code>(val,v)</code> which is an immutable D.S and hence would be faster than a list. But it may not count for much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T19:14:08.573",
"Id": "20668",
"Score": "0",
"body": "like the list comprehension. But need dict2[val] for additional parse-ing"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:57:30.227",
"Id": "12752",
"ParentId": "12751",
"Score": "4"
}
},
{
"body": "<p>Depending on the size of the intersection expected, it might be valuable to let someone else handle the loop & test:</p>\n\n<pre><code>vals = set(dict1.values())\nd2keys = set(dict2.keys())\nlist_needed = [ [val, dict2[val]) for val in vals & d2keys ]\n</code></pre>\n\n<p>Or, is dict2 disposable? If so, you could do:</p>\n\n<pre><code>for k in set(dict2.keys() - set(dict1.values()):\n del dict2[k]\nlist_needed = dict2.items()\n</code></pre>\n\n<p>I just came up with those off the top of my head and have no idea how performant they really are. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T13:45:26.377",
"Id": "20719",
"Score": "0",
"body": "list_needed = [ [val, dict2[val]) for val in vals & d2keys ] is much slower than \nlist_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T02:38:58.353",
"Id": "12760",
"ParentId": "12751",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12752",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T18:45:25.203",
"Id": "12751",
"Score": "2",
"Tags": [
"python"
],
"Title": "Speed up two for-loops?"
}
|
12751
|
<p>I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt </p>
<blockquote>
<p>Write a procedure that takes a list of numbers, nums, and a limit,
limit, and returns a list which is the shortest prefix of nums the sum
of whose values is greater than limit. Use for. Try to avoid using
explicit indexing into the list.</p>
</blockquote>
<p>I wrote the following simple procedure</p>
<pre><code>def numberlist(nums,limit):
sum=0
i=0
for i in nums:
sum=sum+i
if sum>limit:
return i
else:
print i
</code></pre>
<p>It gets the job done, but the division of labor between <em>if</em> and <em>else</em> seems inelegant, as does the use of both <em>return</em> and <em>print</em>. Is there a better way to structure this basic loop? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T07:24:39.357",
"Id": "20836",
"Score": "0",
"body": "I see now that this version was cobbling together a numberlist from the output of print and return, which would be problematic if I tried to pass the result into another function. Thanks to the commenters pointing this out!"
}
] |
[
{
"body": "<p>Welcome to programming :) I did not understand your question first, then I realized that python might be your first language. In that case congratulations on picking a very nice language as your first language. </p>\n\n<p>Your question seems to ask for the list which is the shortest prefix of nums the sum of which is greater than the limit. Here, you might notice that it does not care about the intermediate values. Alls that the function asks is that the return value be greater than the limit. That is, this should be the output</p>\n\n<pre><code>>>> numberlist([1,2,3,4,5], 5)\n[1,2,3]\n</code></pre>\n\n<p>No output in between. So for that goal, you need to remove the print statement in your code, and without the print, there is no need for the else. In languages like python, it is not required that there be an <code>else</code> section to an if-else conditional. Hence you can omit it. We can also use enumerate to iterate on both index and the value at index. Using all these we have,</p>\n\n<pre><code>def numberlist(nums,limit): \n sum=0 \n for index,i in enumerate(nums): \n sum += i\n if sum>limit: \n return nums[:index+1]\n</code></pre>\n\n<p>Note that if you are unsatisfied with omitting the else part, you can turn it back by using <code>pass</code>. i.e</p>\n\n<pre><code> if sum>limit: \n return nums[:index+1]\n else:\n pass\n</code></pre>\n\n<p>Note also that I used an array slice notation <code>nums[:index+1]</code> that means all the values from <code>0 to index+1</code> in the array <code>nums</code>\nThis is a rather nice for loop. If you are feeling more adventurous, you might want to look at list comprehensions. That is another way to write these things without using loops.</p>\n\n<p>edit: corrected for enumeration</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T23:20:35.213",
"Id": "12755",
"ParentId": "12753",
"Score": "2"
}
},
{
"body": "<p>So, a couple things:</p>\n\n<ol>\n<li><p>The problem statement says nothing about printing data, so you can omit the <code>print</code> statement, and thus the entire <code>else:</code> clause, entirely.</p></li>\n<li><p>The problem statement says to return a list, and you're just returning the last item in that list, not the entire list.</p></li>\n</ol>\n\n<p>Here's a short but inefficient way to do it:</p>\n\n<pre><code>def numberlist(nums, limit):\n i = 0\n while sum(nums[:i]) < limit:\n i += 1\n return nums[:i]\n</code></pre>\n\n<p>or a more efficient but longer way:</p>\n\n<pre><code>def numberlist(nums, limit):\n prefix = []\n sum = 0\n for num in nums:\n sum += num\n prefix.append(num)\n if sum > limit:\n return prefix\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T02:48:33.037",
"Id": "20692",
"Score": "0",
"body": "I didn't realize that the question was asking for the subset. Have an upvote :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:26:18.953",
"Id": "20712",
"Score": "0",
"body": "This, like blufox’ solution, uses indexing which we’ve been told to avoid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:46:07.787",
"Id": "20725",
"Score": "0",
"body": "Konrad: the inefficient way does, the other way doesn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T07:27:14.237",
"Id": "20837",
"Score": "0",
"body": "pjz: what makes the second method more efficient, in your estimation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T14:07:46.593",
"Id": "20876",
"Score": "0",
"body": "K. Olivia: the first one runs a sum on the whole slice every time through the loop. The second only adds the newest number to the sum, which is much faster."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T02:19:28.593",
"Id": "12759",
"ParentId": "12753",
"Score": "9"
}
},
{
"body": "<p>The others have discussed how you aren't quite doing what the problem asks, I'll just look at your code:</p>\n\n<pre><code>def numberlist(nums,limit): \n</code></pre>\n\n<p>When the name of a function has two words it in, we recommend separate it with an _, in this case use <code>number_list</code>. Its easier to understand the name</p>\n\n<pre><code> sum=0 \n</code></pre>\n\n<p><code>sum</code> is the name of a built-in function, you should probably avoid using it</p>\n\n<pre><code> i=0 \n</code></pre>\n\n<p>This does nothing. You don't need to pre-store something in i, just use the for loop</p>\n\n<pre><code> for i in nums: \n</code></pre>\n\n<p>I really recommend against single letter variable names, it makes code hard to read</p>\n\n<pre><code> sum=sum+i \n</code></pre>\n\n<p>I'd write this as <code>sum += i</code></p>\n\n<pre><code> if sum>limit: \n</code></pre>\n\n<p>I'd put space around the <code>></code> </p>\n\n<pre><code> return i \n else: \n print i\n</code></pre>\n\n<p>Your instinct is right, using both <code>return</code> and <code>print</code> is odd. As the others have noted, you shouldn't be printing at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:33:58.633",
"Id": "20715",
"Score": "0",
"body": "I generally agree about the one-letter variable names but there’s a broad consensus that they’re OK as simple loop variables (among others) – even though `i` is conventionally reserved for indices …"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:16:24.517",
"Id": "20722",
"Score": "0",
"body": "@KonradRudolph, I disagree with the consensus. But yes, there is one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T04:08:16.980",
"Id": "12761",
"ParentId": "12753",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Try to avoid using explicit indexing into the list.</p>\n</blockquote>\n\n<p>This part in the question was ignored in the other (good) answers. Just to fix this small shortcoming, you can write a <a href=\"http://www.python.org/dev/peps/pep-0255/\" rel=\"nofollow\">generator</a> which avoids indexing completely:</p>\n\n<pre><code>def numberlist(nums, limit):\n sum = 0\n for x in nums:\n sum += x\n yield x\n if sum > limit:\n return\n</code></pre>\n\n<p>This will return an iterator that, when iterated over, will consecutively yield the desired output:</p>\n\n<pre><code>>>> for x in numberlist([2, 4, 3, 5, 6, 2], 10):\n... print x,\n... \n2 4 3 5\n</code></pre>\n\n<p>However, strictly speaking this violates another requirement, “returns a list” – so we need to wrap this code into another method:</p>\n\n<pre><code>def numberlist(nums, limit):\n def f(nums, limit):\n sum = 0\n for x in nums:\n sum += x\n yield x\n if sum > limit:\n return\n\n return list(f(nums, limit))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:32:46.653",
"Id": "12828",
"ParentId": "12753",
"Score": "6"
}
},
{
"body": "<p><strong>I just started programming in Python (well in general) a week ago</strong></p>\n\n<p>This is the analogy I used to make sense of the problem. </p>\n\n<blockquote>\n <p>You have a word like Monday. Each character in the word has a value:\n 'M' = 1, 'o' = 2, n = '3', d = '4', a = '5', y = '6'. If you added the value of each character in the word 'Monday' it would be:\n 1 + 2 + 3 + 4 + 5 + 6 = 21\n So the 'numerical value' of Monday would be 21</p>\n</blockquote>\n\n<p>Now you have a limit like 9</p>\n\n<blockquote>\n <p>The question is asking you to create a program that takes a list of numbers like [1, 2, 3, 4, 5, 6]\n And find out how many of these numbers (starting from the left because prefix means the beginning of word or in this case the list – which starts from the left i.e. 1) can be added together before their sum is greater than the limit.\n The answer would be the sum of the numbers 1, 2, 3 and 4 which is 10.\n Your prefix is the list [1, 2, 3, 4]</p>\n</blockquote>\n\n<pre><code>num = [1,2,3,4,5,6]\n\nlimit = 9\n\ndef prefixLimit(limit, num):\n sumOfPrefix = 0\n prefix = [] \n for i in num:\n if sumOfPrefix < limit:\n sumOfPrefix = sumOfPrefix + i\n prefix.append(i)\n if sumOfPrefix > limit:\n return prefix\n\nprint(prefixLimit(limit, num))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-01T12:47:06.010",
"Id": "262502",
"Score": "0",
"body": "This is not a review of the provided code. At Code Review, we expect all answers to be reviews."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T11:16:54.647",
"Id": "262877",
"Score": "0",
"body": "I would appreciate clarity as to what I did wrong. *I'm new to this - forum, programming - any help will be greatly beneficial to my progress*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T16:06:47.270",
"Id": "262913",
"Score": "0",
"body": "Sure, take a look at the [help/how-to-answer](http://codereview.stackexchange.com/help/how-to-answer)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-01T10:29:18.493",
"Id": "140196",
"ParentId": "12753",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "12759",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T21:54:02.620",
"Id": "12753",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Taking the first few items of a list until a target sum is exceeded"
}
|
12753
|
<p>My first attempt at a user registration code.</p>
<p><code>Login.php</code> defines database log in variables (e.g. Database name, Table name, etc)
<code>Header.php</code> connects to the database.</p>
<p>I used <code>ctype_alum</code> for security of inputs. I also know that I shouldn't use <code>mysql_error()</code> for security issues but I've used the function as a placeholder.</p>
<p>Would love some feedback on possible improvements:</p>
<pre><code><?php
require_once 'login.php';
include 'header.php';
echo <<<_REGFORM
<form action="registration.php" method ="post"><pre>
Register an account:
Usernames and passwords must be at least 6 letters in length comprising of only alphanumeric characters.
Username <input type="text" name="regusername"/>
Password <input type="password" name="regpassword"/>
Retype Password <input type="password" name ="checkregpassword"/>
<input type="submit" value="Register"/>
<input type="hidden" name="clicked" value=yes/>
</pre></form>
_REGFORM;
if ($_POST['clicked']){
if ($_POST['regusername'] && $_POST['regpassword']){
if (ctype_alnum($_POST['regpassword']) && ctype_alnum($_POST['regusername']) && (strlen($_POST['regusername']) > 5) && (strlen($_POST['regpassword']) > 5)){
if ($_POST['regpassword'] === $_POST['checkregpassword']) {
// Insert code to check if the username exists
// Insert code to finally create the account!
$username = $_POST['regusername'];
$password = md5($_POST['regpassword']);
mysql_select_db($db_database) or die("Unable to select database: ".mysql_error());
$query = "SELECT * FROM userlogin WHERE username='$username'";
$result = mysql_query($query) or die("Database access failed: ".mysql_error);
if (!mysql_num_rows($result)) {
$query = "INSERT INTO userlogin VALUES('','$username','$password')";
$result = mysql_query($query) or die("Unable to create account: ".mysql_error());
echo "Thanks ".$username.", your account has been created!";
}
else echo"Username Unavailable, please try another username";
}
else echo "Your passwords do not match";
}
else echo "Username and password must be atleast 6 letters in length and letters a-z, A-Z and numbers 0-9 are accepted <br />";
}
else echo "Please fill in a valid username and password";
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T04:25:05.693",
"Id": "20695",
"Score": "0",
"body": "I'll write a proper response later if no one else beats me to it, but: You're missing the `()` after one of the mysql_error calls. Also, `pre` should typically be avoided for styling. Also, everything other than the first section of this applies to your question: http://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649"
}
] |
[
{
"body": "<p>I think this is better than about 99% of first tries I've ever seen!</p>\n\n<p>Anyway, I've tried my best to address as many things as I saw, whether major or extremely minor. If you have any questions on any points or want to clarify or defend any claims, let me know and I will expand the answer.</p>\n\n<p><strong>Assuming array indexes exist</strong></p>\n\n<p>Any array that comes from user input should never be directly accessed. <code>$_POST['key']</code> is not safe since you can't know for sure whether or not the user supplied the <code>$_POST['key']</code>.</p>\n\n<p>With arrays that can contain <code>null</code> values, you must use <code>array_key_exists</code>, but since input arrays like <code>$_POST</code> and <code>$_GET</code> will always have either strings or arrays, you can safely use <code>isset</code>.</p>\n\n<p>The following is how I tend to access request driven arrays:</p>\n\n<pre><code>$username = (isset($_POST['username']) && is_string($_POST['username'])) ? $_POST['username'] : null;\nif (strlen($username) < 5) {\n //username's must be >= 5 charactes\n} else if (strlen($username > 32)) {\n //username's must be < 32 characters\n}\n\n//If you wanted to check if the user even provided a username:\nif ($username === null) {\n //A username element of the form was not provided. Depending on specific context, this may imply form tampering.\n}\n</code></pre>\n\n<p>Note that the <code>is_string</code> check is necessary so that the user cannot maliciously pass an array to the script. If that were to happen, then the <code>strlen</code> call would complain about not expecting an array. Unfortunately you have to be rather paranoid about anything coming from users.</p>\n\n<p>There's a longer discussion of this <a href=\"https://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649\">here</a> in the last section.</p>\n\n<p>It's also worth noting that some people prefer a <a href=\"http://ie2.php.net/filter_input\" rel=\"nofollow noreferrer\">filter_input</a> approach.</p>\n\n<p><strong>SQL injection</strong></p>\n\n<p>There is no SQL injection possible in your code, but that may be by accident. When putting strings into queries, it's good practice to always run them through <code>mysql_real_escape_string</code>. That way if you change your business rules in a way that does make SQL injection possible, you don't have to worry about the change cascading down to your queries and opening a security hole.</p>\n\n<p>More information about SQL injection can be found in a post I wrote the other day, <a href=\"https://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649\">here</a>.</p>\n\n<p>(Sorry if I'm assuming that you don't know about SQL injection and you do.)</p>\n\n<p><strong>MySQL Extension</strong></p>\n\n<p>The <code>mysql_*</code> extension is quite dated, and PDO offers many advantages. </p>\n\n<ul>\n<li>Offers a cleaner <a href=\"http://is.php.net/manual/en/class.pdo.php\" rel=\"nofollow noreferrer\">API</a></li>\n<li>Offers better error handling (the ability to have failed queries throw exceptions is wonderful)</li>\n<li>Handles <a href=\"http://is.php.net/manual/en/pdo.begintransaction.php\" rel=\"nofollow noreferrer\">transactions</a> SQL-dialect agnostically (for the most part)</li>\n<li><a href=\"http://is.php.net/manual/en/pdo.drivers.php\" rel=\"nofollow noreferrer\">Different RDBMS</a> can be changed out relatively easily (switching from <code>mysql_*</code> to PostreSQL is extremely painful. Switching from PDO with MySQL to PDO with PostreSQL isn't pleasant, but is care is taken to stay as dialect-agnostic as possible, it's reasonably easy)</li>\n<li><a href=\"http://php.net/manual/en/pdo.prepare.php\" rel=\"nofollow noreferrer\">Prepared statements</a></li>\n</ul>\n\n<p>You can find more information here under the <a href=\"https://codereview.stackexchange.com/questions/12647/php-dynamic-insert-mysql-is-there-a-better-way-than-this/12649#12649\">PDO</a> section.</p>\n\n<p><strong><code><pre></code></strong></p>\n\n<p><code>pre</code> can be used to arrange spacing, however you should be aware that it typically uses a fixed width font, and there's a few other quirks with it (you can probably style it to use a different font though). I suppose there's technically nothing wrong with it, but <code>pre</code> doesn't strike me as a good long term method for arranging elements.</p>\n\n<p><strong>ctype_alnum for a password</strong></p>\n\n<p>Why restrict users to a <code>a-zA-Z0-9</code> password? I'm a firm believe that passwords should be allowed to be just about anything. Some restrictions may be in order, such as ASCII only or something of that nature, but if a user wants his password to be <code>this is my password</code>, then why not? You're hashing it anyway, so the length doesn't matter. By the same logic, why not allow non alpha numeric characters? It's not like HTTP or PHP will have any issues handling things like <code>!@#$%^&*()|_+=-</code> and so on.</p>\n\n<p><strong>list column fields in inserts</strong></p>\n\n<pre><code>$query = \"INSERT INTO userlogin VALUES('','$username','$password')\";\n</code></pre>\n\n<p>Listing columns explicitly allows for better maintainability and clarity. What if in the future you add a birthday column after the username column? Suddenly you're trying to insert passwords into the birthday column. Also, if you're going to put an auto incrementing column in a query, it should be null.</p>\n\n<p>I would write the query like this:</p>\n\n<pre><code>$query = \"INSERT INTO userlogin (username, password) VALUES ('$username','$password')\";\n</code></pre>\n\n<p><strong>userlogin</strong></p>\n\n<p>This sounds like a logging table to me. This sounds like it contains records of users logging in, not of actual user records. I would consider renaming this table to something like <code>users</code> or <code>user_accounts</code>.</p>\n\n<p><strong>escape html where necessary</strong></p>\n\n<pre><code>echo \"Thanks \".$username.\", your account has been created!\";\n</code></pre>\n\n<p>Once again, since it's limited to alphanumeric, this is definitely harmless, however, preparing for the future never hurts. If at some point you allow users to create names that contain <code>&</code>, this could output invalid html.</p>\n\n<p>(Once again, sorry if I'm telling you something you already know.)</p>\n\n<p><strong>always use brackets</strong></p>\n\n<p>It's hard to see on a short script with fairly simple logic, but I'm a firm believer that braces should always be used.</p>\n\n<pre><code>if {} else { statement }\n</code></pre>\n\n<p>Looks clearer and is less error prone than:</p>\n\n<pre><code>if {} else statement\n</code></pre>\n\n<p><strong>html element's attributes should always be in quotes</strong></p>\n\n<p><code>value=yes</code> should be <code>value=\"yes\"</code></p>\n\n<p><strong>MD5</strong></p>\n\n<p>Hashing algorithms should be computationally expensive enough that a brute force attack is infeasbile. Due to rainbow tables and other factors, a single MD5 run of an alphanumeric password is not considered secure.</p>\n\n<p>Consider using something like bcrypt that is a bit heavier algorithm, or at least use something like 512 bit SHA repeated a thousand (or more!) times.</p>\n\n<p>Let <code>f</code> be your hashing function. Let <code>S</code> = the set of all possible passwords. The absolute worst case time to brute force a password, <code>p</code>, such that <code>p</code> is in <code>S</code> is <code>size of S * time for f(x)</code></p>\n\n<p>If <code>f = MD5</code> then the time is very small. MD5 and even SHA are considered fairly fast hashes. If you use a an algorithm such as one of those, you should at least repeat it. This way <code>f</code> becomes a much longer operation.</p>\n\n<p>There's a few really good posts on StackOverflow about this, so I'll try to find some and link them.</p>\n\n<p><a href=\"https://stackoverflow.com/a/401684/32775\">This</a> is a pretty good explanation (thanks to luiscubal for finding the link).</p>\n\n<p><strong>More graceful error handling</strong></p>\n\n<p>For the errors, I would probably handle them a bit better than the old <code>or die</code> construct that tends to go along with the <code>mysql_</code> functions.</p>\n\n<p>The idiom I would follow (though I would use PDO with exceptions), would be something like:</p>\n\n<pre><code>$query = \"...\";\n$resource = mysql_query($query);\nif (!$resource) {\n //log the error including all necessary details\n //output a fairly vague error the user\n}\n</code></pre>\n\n<p><code>trigger_error</code> can be useful for this.</p>\n\n<p><strong>Error handling suggestion</strong></p>\n\n<p>I like to validate everything separately and independently such that all errors can be output at once. For example, if my username is only 4 characters and my passwords don't match, it would be nice to see both errors at once instead of having to fix one error, resubmit the form, fix the second error then resubmit the form.</p>\n\n<p>This is by no means perfect, but the structure I typically use for error handling is:</p>\n\n<pre><code>$errors = array();\n$username = $password = null;\n\nif ($_SERVER['REQUEST_METHOD'] === \"POST\") {\n $username = ...;\n $password = ...;\n if (strlen($username) < 5) {\n $errors['username'][] = \"Usernames must be 5 or more characters\";\n }\n if (strlen($username) && !ctype_alnum($username)) {\n $errors['username'][] = \"Usernames must be alphanumeric\";\n }\n if (strlen($password) < 5) {\n $errors['password'][] = \"Passwords must be 5 or more characters\";\n }\n //More validations\n if (!count($errors)) {\n //No errors, so $username and $password are valid\n $insertionQuery = sprintf(\"INSERT INTO users (username, password) VALUES ('%s', '%s')\", mysql_real_escape_string($username), mysql_real_escape_string($password));\n $insertionResult = mysql_query($insertionQuery);\n if (!$insertionResult) {\n trigger_error(\"MySQL query failed. Query: [{$insertionQuery}]. Error: [\" . mysql_error() . \"]\", E_USER_WARNING);\n $errors['db'][] = \"There was an unexpected error. Please try again.\";\n }\n }\n}\n</code></pre>\n\n<p>Then, to render the errors, I typically just create a <code><ul></code> with each error as a <code><li></code>:</p>\n\n<pre><code>if (count($errors)) {\n echo '<ul>';\n foreach ($errors as $element => $errs) {\n foreach ($errs as $err) {\n echo '<li>' . htmlspecialchars($err) . '</li>'\n }\n }\n echo '</ul>';\n}\n</code></pre>\n\n<p>The element name being the array key is useful because it means you can do things like style elements a certain way if they had an error:</p>\n\n<pre><code><input type=\"text\" name=\"username\" value=\"<?php echo htmlspecialchars($username);\"<?php if (array_key_exists('username', $errors)) { echo ' class=\"error\"'; } ?>>\n</code></pre>\n\n<p>You could even take the idea farther and render errors around elements.</p>\n\n<p>In general, it's a lot more flexible to aggregate the errors instead of immediately outputting them. </p>\n\n<p>This philosophy touches into the area of MVC and separation of concerns. MVC isn't particularly important for now, but the general idea of it (and in part SoC) is that each area of code should be concerned with one specific thing and nothing else. </p>\n\n<p>A slight extension of this is the idea that logic and presentation should be separate. Doing this allows many more degrees of freedom, and typically better code. Consider for example if you wanted to have an AJAX interface for submitting the form, but still have an HTML fallback for users with JavaScript disabled. If you were storing errors, you could do something simple like:</p>\n\n<pre><code>if (!empty($_POST['ajax'])) {\n echo json_encode(array('result' => 'errors', 'errors' => $errors));\n //set some kind of flag so that html output will not happen\n //(or, if it's a small script, I might just use `exit;`)\n}\n\n//Then later, if it's not AJAX\n//render the errors as HTML inline in the form\n</code></pre>\n\n<p>If you intermix your logic and presentation code, the code is forever stuck rendering in exactly one way. There's no way to reuse the same logic with a different presentation. If they are separated, however, then the same logic can be used with infinite presentations.</p>\n\n<p><strong>Variable reuse</strong></p>\n\n<p>I'm definitely in the minority on this one, but I don't like to reuse variable names. I would call the repeated query and result variables something like <code>$existsQuery</code> and <code>$insertionQuery</code>. Nothing wrong at all with reusing the same name, just a personal preference (though the more descriptive a name, the better [within reasonable limits]).</p>\n\n<p><strong>header.php</strong></p>\n\n<p>This is not a very descriptive name. I would consider calling it something like <code>database.php</code> or <code>connect.php</code> or something. When I think of headers, I think content, not code.</p>\n\n<p>Also, since the database connection is required for the page to function, <code>require</code> should be used instead of <code>include</code>. A failed include will allow execution to continue, whereas a failed require will kill execution.</p>\n\n<p><strong>mysql_select_db</strong></p>\n\n<p>This should be with your database connection code.</p>\n\n<p><strong>login.php</strong></p>\n\n<p>No idea what \"Login.php defines database log in numbers\" means? I'm a bit confused though about what this could be doing. Also not sure why <code>require_once</code> instead of <code>require</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T17:51:35.500",
"Id": "20730",
"Score": "0",
"body": "As for hashing, bcrypt seems to be a very popular method to handle passwords. See http://stackoverflow.com/a/401684/32775 Also, md5 without salt is a big NO (even if it's obviously better than plain text)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T01:09:35.600",
"Id": "20737",
"Score": "0",
"body": "@luiscubal Ah! Good link! Have edited it into the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T01:10:15.053",
"Id": "20738",
"Score": "0",
"body": "And @palacsint thanks for fixing my lazy formatting :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T17:28:28.810",
"Id": "20789",
"Score": "1",
"body": "Haven't had time to read this in detail yet, but THANK YOU! Great response. The encouragement is very motivating as well. With regards to the SQL injection, I knew a little about it, that's why I made the inputs only alphanumeric (as a temporary solutions until I learn more). I didn't want to think about security yet, that's a lesson for another day... probably. Amount of feedback is amazing...will review all feedback in detail once I get time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:06:10.800",
"Id": "20804",
"Score": "0",
"body": "@JY No problem. Am glad to help :). And I figured you knew about SQL injection since it's pretty hard to accidentally make safe statements, but wasn't sure :p."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:09:43.600",
"Id": "12769",
"ParentId": "12757",
"Score": "14"
}
},
{
"body": "<p>Agree entirely with Corbin's post, these are just additions.</p>\n\n<p>A point on preference rather than efficiency, but I find it odd to have plain, unaltered HTML echoed in PHP. I personally would escape it, but again, preference. At least you are using heredoc :)</p>\n\n<p>I'm assuming <code>$_POST['clicked']</code> is the same concept as checking for a submit button press. This is not very reliable due to the fact that most users do not click those buttons and instead press enter. A form submitted in this manor will not register the \"submit\" because it was not pressed. If this is what you are doing, I'd be wary of it. There are two better ways to do this. The first is the \"right\" way, while the second is a hack that works just as well.</p>\n\n<pre><code>if( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) { }\n//OR\nif( $_POST ) { }\n</code></pre>\n\n<p>Checking for the boolean value of <code>$_POST['regusername']</code> and <code>$_POST['regpassword']</code> is not the same as ensuring that they are set. This method will return errors in your code if those keys are not set. It might still work, but any error is a bad error and should be fixed. Better to use <code>isset()</code> and verify they exist before trying to do anything with them.</p>\n\n<p>Long statements can become difficult to read, especially when combined with numerous operations. To lessen the length and make code more legible you can start by removing some of the functions from the statement.</p>\n\n<pre><code>$passwordAlphaNum = ctype_alnum($_POST['regpassword']);\n$usernameAlphaNum = ctype_alnum($_POST['regusername']);\n$usernameLength = strlen($_POST['regusername']);\n$passwordLength = strlen($_POST['regpassword']);\nif ($passwordAlphaNum && $usernameAlphaNum && ($usernameLength > 5) && ($passwordLength > 5)){}\n</code></pre>\n\n<p>You can reduce line length even more by breaking up statements logically. Currently the above statement does two things. First it confirms that a username and password contains only alpha-numeric characters and that their lengths are greater than five. So...</p>\n\n<pre><code>if ($passwordAlphaNum && $usernameAlphaNum){\n if(($usernameLength > 5) && ($passwordLength > 5)) {}\n}\n</code></pre>\n\n<p>This is much easier to read. Of course you can break this down ever further, as Corbin has done in his demonstration for error reporting. I actually prefer this method as it allows for the custom error messages. But it all depends upon your implementation.</p>\n\n<p>Now, in my opinion you have set the username and password to variables a tad too late. You've performed all these validation checks on them alreday, having to rewrite the post array and key for each element. Better to set it after ensuring that it is set then do all the validation on it. Another way you can go about this is to use PHP's <code>filter_input()</code> method. Corbin mentioned this but did not go into detail. This removes the necessity for checking if a value is set because that function will return FALSE in this instance. This also automatically sanitizes input based on the defined flag. So you can remove a number of those if statements and those <code>ctype_alnum()</code> functions and at the same time reduce the amoutn of times you need to use that post array. (All for one down payment of $19.95!) So before even the first if statement you can do this.</p>\n\n<pre><code>$username = filter_input( INPUT_POST, 'regusername', FILTER_SANITIZE_STRING );\n$password = filter_input( INPUT_POST, 'regusername', FILTER_SANITIZE_STRING );\nif( $username && $password ) {\n $usernameLength = strlen( $username );\n $passwordLength = strlen( $password );\n if( ( $usernameLength > 5 ) && ( $passwordLength > 5 ) ) { }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T01:07:30.567",
"Id": "20735",
"Score": "1",
"body": "(I know I've mentioned this before, and I hate to keep bringing this up, but I'm quite curious about this...) *A form submitted in this manor will not register the \"submit\" because it was not pressed.* As far as I'm aware, an input of type submit does not have to be pressed to be considered \"successful\" (the term used to describe which elements are to be sent as form data). There is a clause that states that only the activated submit button should be considered successful for a form with more than 1, but no such clause about a form with 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T01:09:09.160",
"Id": "20736",
"Score": "0",
"body": "In short, I'd be curious if you can provide an example of a recent browser that exhibits your mentioned behavior. Also, it's worth noting that checking if the request method is post, and checking a button was pressed (or if a hidden input is present) are not the same logical thing (though practically equivalent unless a page is handling multiple forms) (Potentially relevant: http://www.w3.org/TR/html401/interact/forms.html#successful-controls) (Also, for what it's worth, +1 :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T02:45:06.200",
"Id": "20740",
"Score": "0",
"body": "@Corbin: This is something I came upon recently, so I can't provide an example. But I have read enough posts where its claimed that this is a poor choice, even go so far as to claim bad programming, and gave that reason for it. I see that you are stressing \"recent\", however you can still find people using old browsers. While not common, it is still a possibility, and one that some people like to be aware of and include support for. I phrased that the way I did for this reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T02:45:49.273",
"Id": "20741",
"Score": "0",
"body": "No these aren't the same logically. But, as you stated, they do practically the same thing. And multiple forms on the same page IS bad. Better to separate that logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T03:10:17.043",
"Id": "20742",
"Score": "1",
"body": "To be blunt, I'm not sure I believe that claim that there are any even remotely recent browsers that display this behavior. Hitting enter should result in the submit button being sent along. Though, for the simple fact that I can't seem to find any reference that that is required behavior, I suppose it may be better to avoid it. And if you meant that one section of PHP code handling multiple forms is bad, I would agree with that. \"multiple forms on the same page IS bad\", I however do not agree with. (And on that note, I promise I'll stop being an annoying pedant now :p)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:00:01.107",
"Id": "12836",
"ParentId": "12757",
"Score": "11"
}
},
{
"body": "<p>+1 to @showerhead and @Corbin, and:</p>\n\n<ol>\n<li><p><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening arrow code</a> would improve readability a lot.</p></li>\n<li><p>Create local variables for <code>$_POST['regusername']</code> and <code>$_POST['regpassword']</code>. These two statements are repeating too much.</p></li>\n<li><p>I'd create an <code>isValidPassword()</code> and an <code>isValidUsername()</code> instead of the long condition.</p>\n\n<pre><code>function isValidUsername($username) {\n if (!ctype_alnum($username)) {\n return false;\n }\n if (strlen($username]) <= 5)) {\n return false;\n }\n return true;\n}\n\nfunction isValidPassword($password) {\n if (!ctype_alnum($password])) {\n return false;\n }\n if (strlen($password]) <= 5)) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>It's easier to follow and read.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T18:59:01.853",
"Id": "12842",
"ParentId": "12757",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "12769",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:50:20.583",
"Id": "12757",
"Score": "14",
"Tags": [
"php",
"beginner",
"mysql",
"security"
],
"Title": "Basic user registration code"
}
|
12757
|
<p>Following is a working solution for a single xml ajax to retrieve category list, then individual ajax calls for each category. This was developed in response to a question on SO.</p>
<p>Solution creates one deffered for the category ajax call, and array of deffereds for the items ajax calls. Bottom of code nests <code>$when(itemsCallsArray)</code> inside <code>$.when( catgoryCall)</code></p>
<p><strong><a href="http://jsfiddle.net/Dt75U/" rel="nofollow">Working demo</a></strong></p>
<p>Categories should stay in order of xml but looking for any improvements that could be used to keep the items calls in order. </p>
<pre><code>/* store all ajax content in object*/
var content = {};
function parseContent(content) {
$.each(content, function() {
$('body').append('<br><br>' + this.a + '<br>' + this.b.join('<br>'));
})
}
/* array to store nested ajax promises */
var deferreds_b = [];
/* A promise and ajax*/
var xml_A = $.post("/echo/xml/", {
xml: a
}, function(returnedXML) {
var $el_A = $(returnedXML).find("ElementA");
var total_A = $el_A.length;
$el_A.each(function(counter) {
var countA = counter;
var name_of_Attribute_of_Element_A = $(this).attr("name");
/* create EL A object , store EL A content, create array to push B content to */
content[countA] = {
a: countA + ". " + name_of_Attribute_of_Element_A,
b: []
}
var xml_B = $.post("/echo/xml/", {
xml: b
}, function(returnedXML) {
var $el_B = $(returnedXML).find("ElementB");
var total_B = $el_B.length;
$el_B.each(function(idx) {
var name_of_Attribute_of_Element_B = $(this).attr("name");
content[countA].b.push(countA + ". " + name_of_Attribute_of_Element_B);
});
});
/* push B promise to array*/
deferreds_b.push(xml_B);
});
});
$.when(xml_A).done(function() {
/* when A is done , wait for B to be done*/
$.when.apply(null, deferreds_b).done(function() {
parseContent(content);
$("body").append("<p>All done!</p>");
});
})
</code></pre>
|
[] |
[
{
"body": "<p>I'm not sure what do you exactly need? \n<a href=\"http://jsfiddle.net/tomalec/GeRkG/1/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/GeRkG/1/</a></p>\n\n<ul>\n<li>Use promise returned by <code>$.post</code>. we don't need <code>var xml_A</code> and <code>$.when(xml_A)</code></li>\n<li>Remove deffereds_b from global scope, and use it as resolved value.</li>\n</ul>\n\n<p>And now improvements depends on what you are trying to achive:</p>\n\n<ol>\n<li>Just get all responses together in right order, after all is done</li>\n<li>Do above, but performe partial operations as soon as posible, if so do you really need countA while handling B response?</li>\n</ol>\n\n<hr>\n\n<p>1: \n<a href=\"http://jsfiddle.net/tomalec/GeRkG/3/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/GeRkG/3/</a>\n - Move B response handling outside \n - Move content to local scopes\n or even: <a href=\"http://jsfiddle.net/tomalec/GeRkG/4/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/GeRkG/4/</a>\n - one callback, and object creation less</p>\n\n<hr>\n\n<p>2:\n<a href=\"http://jsfiddle.net/tomalec/rwq2d/2/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/rwq2d/2/</a>\n - Move AB response handling outside, we can move A separately if you want to perform it sooner, than later (before B response).\n - Move content to local scopes\n - Removed closure for <code>$.when.apply( null, requests)</code></p>\n\n<pre><code>function parseContent(content) {\n console.log('content',content);\n $.each(content, function() {\n $('body').append('<br><br>' + this.a + '<br>' + this.b.join('<br>'));\n })\n}\nfunction handleABResponse(returnedXML, $el_A, countA) {\n var name_of_Attribute_of_Element_A = $el_A.attr(\"name\"),\n $el_Bs = $(returnedXML).find(\"ElementB\"),\n results_b = [];\n $el_Bs.each(function(index, el) {\n var name_of_Attribute_of_Element_B = $(el).attr(\"name\");\n results_b.push (countA + \". \" + name_of_Attribute_of_Element_B);\n });\n\n return {\n a: countA + \". \" + name_of_Attribute_of_Element_A,\n b: results_b\n }\n}\n/* Request As */ \n$.post(\"/echo/xml/\", {\n xml: a\n}).pipe(function(returnedXML) {\n /* process As */\n /* array to store nested ajax promises */\n var requests = [];\n\n var $el_As = $(returnedXML).find(\"ElementA\");\n $el_As.each(function(countA) {\n var $el_A = $(this);\n /* push B promise to array*/\n requests.push(\n $.post(\"/echo/xml/\", {\n xml: b\n })\n .pipe(function bSuccess (response){\n /* process A and Bs */\n return handleABResponse(response, $el_A, countA);\n })\n );\n });\n /* return promise for all requests */\n return $.when.apply( null, requests );\n}).done(function() { //content[0], content[1],..\n /* collect processed responses */\n console.warn(this,arguments);\n parseContent(arguments);\n $(\"body\").append(\"<p>All done!</p>\");\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T18:24:42.493",
"Id": "24724",
"ParentId": "12758",
"Score": "2"
}
},
{
"body": "<p>If you just want to simplify the javascript without really changing anything, then it will boil down from about 38 active lines to 21 as follows :</p>\n\n<pre><code>$.post(\"/echo/xml/\", { xml: a }).done(function(returnedXML) {\n var content = [], promises = [];\n $(returnedXML).find(\"ElementA\").each(function(counter) {\n var obj = {\n a: counter + \". \" + $(this).attr('name'),\n b: []\n };\n content.push(obj);\n promises.push($.post(\"/echo/xml/\", { xml: b }).done(function(returnedXML) {\n $(returnedXML).find(\"ElementB\").each(function() {\n obj.b.push(counter + \". \" + $(this).attr('name'));\n });\n }));\n });\n $.when.apply(null, promises).done(function() {\n $.each(content, function() {\n $('body').append('<br><br>' + this.a + '<br>' + this.b.join('<br>'));\n });\n $(\"body\").append(\"<p>All done!</p>\");\n });\n});\n</code></pre>\n\n<p><strong><a href=\"http://jsfiddle.net/M2tsf/2/\" rel=\"nofollow\">DEMO</a></strong></p>\n\n<p>If you only ever want to display text, and don't need to keep the jqXHR promises for any other purpose, then you can put the text straight into the DOM as the responses arrive rather than using javascript objects/arrays for intermediate storage :</p>\n\n<pre><code>$.post(\"/echo/xml/\", { xml: a }).done(function(returnedXML) {\n $(returnedXML).find(\"ElementA\").each(function(i) {\n var $div = $(\"<div/>\").addClass('A_wrapper').appendTo(\"body\").append($(\"<div/>\").addClass('A_text').text(i + '. ' + $(this).attr('name')));\n $.post(\"/echo/xml/\", { xml: b }).done(function(returnedXML) {\n $(returnedXML).find(\"ElementB\").each(function() {\n $div.append($(\"<div/>\").addClass('B_text').text(i + '. ' + $(this).attr('name')));\n });\n });\n });\n});\n</code></pre>\n\n<p><em>Just 10 lines</em></p>\n\n<p>The key here is to exploit the closure formed by the outer <code>.each()</code> callback, to keep the reference <code>$div</code>, which remains available to the inner <code>.each()</code> callback, thus putting the B-elements under their corresponding A-element.</p>\n\n<p>This second approach offers the (possible) advantage of not waiting for all the responses to arrive before starting to display the text. You would deny yourself the opportunity of knowing when everything is \"all done\" though, if required, this feature could be added back in with another few lines of code.</p>\n\n<p><strong><a href=\"http://jsfiddle.net/M2tsf/\" rel=\"nofollow\">DEMO</a></strong> (with a little CSS for additional styling)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-29T21:33:46.180",
"Id": "26773",
"ParentId": "12758",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T01:52:07.877",
"Id": "12758",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"ajax",
"promise"
],
"Title": "jQuery nested ajax deffereds- looking for improvements"
}
|
12758
|
<p>We were given two countries, namely Brazil and Argentina. Both had one inventory each with 100 iPods in them. The cost of an iPod in Brazil was 100/unit and in Argentina it was 50/unit. But to get iPods form Argentina, you also had to pay 400/10units. Now they give us some number and we had to find out which purchase would be cheaper.</p>
<pre><code>#include<iostream.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
class country
{
public:
int name;
int items,unit;
float cost,price;
public:
country();
void purchase(std::string,int);
void setData(int,int,float,float, int);
};
country::country()
{
}
void country::setData(int name,int items,float cost,float price,int unit)
{
name=name;
items=items;
cost=cost;
price=price;
unit=unit;
}
void country::purchase(std::string a, int b)
{
float custCost=0;
std::cout<<a;
cout<<"item"<<name;
if(b<=items)
{
items=items-b;
custCost=cost*b;
cout<<name<<":"<<items<<":"<< custCost;
}
}
int main()
{
country t[2];
t[0].setData(0,100,100,0,0);
t[1].setData(1,100,50,400,20);
std::string a;
int b,con;
cout<<"enter the country";
std::cin>>a;
cout<<"enter the items needed";
cin>>b;
if(a=="brazil")
con=0;
else con=1;
t[con].purchase(a,b);
getch();
return 0;
}
</code></pre>
<p>It works but I am not totally satisfied with my design as I feel it's too cumbersome. Specifically, if I change the price etc., code changes have to be made.</p>
|
[] |
[
{
"body": "<p>Before looking at your design, a few trivial points that you can correct,</p>\n\n<pre><code>#include<iostream>\n#include<string>\n#include<cstdlib>\n</code></pre>\n\n<ul>\n<li>Avoid c style header usage. Instead use the c++ header style, and namespaces.</li>\n<li><p>Instead of <code>conio.h/getch()</code> is not really portable. Avoid it.</p></li>\n<li><p>Your <code>setData</code> method should really be the constructor. Using setData to populate the structure is a <code>c</code> habit. Also be sure to use the member initializers for construction.</p></li>\n</ul>\n\n<p>You really want to keep the members private</p>\n\n<pre><code>class country {\n private:\n int name;\n int items,unit;\n float cost,price;\n\n bool try_purchase(std::string,int);\n\n public:\n country(int,int,float,float, int);\n void do_purchace(std::string a);\n};\ncountry::country(int name,int items,float cost,float price,int unit)\n :name(name),items(items),cost(cost),price(price){}\n\n// false indicates that the purchase failed.\nbool country::try_purchase(std::string a, int b) {\n if(b > items) return false;\n items = items - b;\n return true;\n}\nvoid country::do_purchace(std::string a) {\n int b;\n std::cout<<\"enter the items needed: \";\n std::cin>>b;\n if (try_purchase(a,b)) \n std::cout<<name<<\":\"<<items<<\":\"<<cost * b<<std::endl;\n}\nint main()\n{\n country t[] = {country(0,100,100,0,0), country(1,100,50,400,20)};\n std::string a;\n std::cout<<\"enter the country: \";\n std::cin>>a;\n int con = (a==\"brazil\") ? 0 : 1;\n t[con].do_purchace(a);\n}\n</code></pre>\n\n<p>Avoid incorporating io statements with your logic. Refactor <code>purchase</code> so that logic is separated to another method.</p>\n\n<p>Regarding your assertion that code changes have to be made if you change price, I do not see why. You can read the information to construct a country from a file and thus avoid hard coding it in the main file. However, this does not change the design as a whole.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:22:52.843",
"Id": "20711",
"Score": "0",
"body": "+1 but I don’t find `purchase` and `do_purchase` clear. `purchase` should be something along the lines of `try_purchase` to indicate the possibility of error (and explain the return value). And I probably wouldn’t make `do_purchase` a member function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:32:39.960",
"Id": "20714",
"Score": "0",
"body": "@KonradRudolph agree on the naming. I thought about the second point while implementing. I added do_purchase as a member function as it requires access to intimate details of country. The other option would be to make it a friend, but that would have the same level of coupling. Did you mean to write accessors for item and name, and make do_purchase a normal function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:35:27.587",
"Id": "20716",
"Score": "0",
"body": "No, I didn’t mean writing accessors (I prefer to avoid them), I overlooked that it used private data (stupid, I know)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T06:37:01.770",
"Id": "12764",
"ParentId": "12763",
"Score": "4"
}
},
{
"body": "<p>You code doesn't seem to meet your specifications, but since you claim it works we'll ignore that.</p>\n\n<p>blufox's suggestions are good. Here are a few more:</p>\n\n<ul>\n<li>Don't store currency as floats. Wrap it in a money class.</li>\n<li><p>You don't seem to use the price or unit fields in your country class, so I'd chuck 'em. If you want to keep them, you have to do something about you parameters list for setData. Try <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow\">fluent interface</a>:</p>\n\n<pre><code>brazil.setName(0).setItems(100).setCost(100.00).setPrice(0.00).setUnits(0);\n</code></pre></li>\n<li><p>SLVNAHTR (Single Letter Variable Names Are Hard To Read)</p></li>\n<li><code>const int NUMBER_OF_WAYS_MAGIC_NUMBERS_SUCK = 800;</code><br>\n<code>const std::string CONSTANTS(\"are better\");</code></li>\n<li><p>There really should be some error checking for your input. <code>boost::lexical_cast</code> is good, or if Boost is not an option, try:</p>\n\n<pre><code>template <typename InputType>\nInputType getValidatedInput(const std::string& prompt=std::string())\n{\n std::cout << prompt;\n\n while (true)\n {\n std::string input;\n std::getline(std::cin, input);\n\n std::istringstream converter(input);\n InputType result;\n converter >> result;\n\n if (converter.fail())\n {\n std::cout << \"Invalid input. Try again: \";\n continue;\n }\n\n char junk;\n converter >> junk;\n\n if (converter.fail())\n {\n return result;\n }\n\n std::cout << \"Extra character found: \" << junk \". Try again: \";\n }\n}\n</code></pre>\n\n<p>Also add extra validation to ensure that the country entered is either Brazil or Argentina (and not Alaska). You might want to make a menu, so the user knows their options.</p></li>\n<li>Declaring your instance variables <code>public</code> might have been a typo. You want them to be <code>private</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-03T09:00:32.707",
"Id": "13265",
"ParentId": "12763",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T05:41:34.097",
"Id": "12763",
"Score": "4",
"Tags": [
"c++",
"homework"
],
"Title": "Inventories of iPods for different countries"
}
|
12763
|
<p>How can this be improved?</p>
<pre><code>def quick_sort(temp_list):
#Check if the array is having one element or not
if len(temp_list) == 1:
return temp_list
elif len(temp_list) >= 2:
l_list = list()
g_list = list()
#Choose a pivot
if len(temp_list) % 2 == 0:
pivot = temp_list[len(temp_list)/2 - 1]
else:
pivot = temp_list[len(temp_list)/2]
#Make two list greater and lesser than the pivot
for e in temp_list:
if e < pivot:
l_list.append(e)
elif e > pivot:
g_list.append(e)
#Merge the two list with the pivot
return merge(quick_sort(l_list),pivot,quick_sort(g_list))
def merge(list1,mid,list2):
newlist = list()
if not list1 and list2:
newlist.append(mid)
newlist.extend(list2)
if not list2 and list1:
newlist.extend(list1)
newlist.append(mid)
if list1 and list2 :
newlist.extend(list1)
newlist.append(mid)
newlist.extend(list2)
return newlist
</code></pre>
|
[] |
[
{
"body": "<p>Some changes to your code, First, your code didn't handle the case of empty list very well. This was why you need a complicated merge. (Also, the operation is not really a merge. A merge kind of means interleaving.)</p>\n\n<pre><code>def quick_sort(temp_list):\n if len(temp_list) <= 1: return temp_list\n pivot = temp_list[len(temp_list)/2 - (1 if len(temp_list) % 2 == 0 else 0) ]\n l_list = list()\n g_list = list()\n</code></pre>\n\n<p>by keeping a list of values equal to pivot, you can ensure that your sort works even if there are non unique values.</p>\n\n<pre><code> m_list = list()\n for e in temp_list:\n if e < pivot:\n l_list.append(e)\n elif e > pivot:\n g_list.append(e)\n else:\n m_list.append(e)\n return concat([quick_sort(l_list),m_list,quick_sort(g_list)])\n\ndef concat(ll):\n res = list()\n for l in ll: res.extend(l)\n return res\n\n\nprint quick_sort([8,4,5,2,1,7,9,10,4,4,4])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:45:40.080",
"Id": "20703",
"Score": "0",
"body": "Quicksort isn’t necessarily in-place, and it *never* has constant space requirement. – http://stackoverflow.com/a/4105155/1968"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:12:39.673",
"Id": "20707",
"Score": "0",
"body": "@KonradRudolph thanks, I removed that line."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:07:02.823",
"Id": "12768",
"ParentId": "12765",
"Score": "4"
}
},
{
"body": "<h1>On Style</h1>\n\n<ul>\n<li><p><a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow\">“Quicksort”</a> is customarily written as one word – the method should be called <code>quicksort</code>, not <code>quick_sort</code>. What’s more, this is an implementation detail and a public API shouldn’t reveal this (it’s subject to change), hence <code>sort</code> would be an even better name.</p></li>\n<li><p>Some of your comments are redundant: “Check if the array is having one element or not” – that is (and should be!) obvious from the code. Don’t comment here. Reserve comments to explain <em>why</em> you do something. The next comment (“choose a pivot”) is better since that’s not immediately obvious from the code. However, it would be better to <em>make</em> it obvious in code and maybe have a comment describe <em>how</em> you choose the pivot (e.g. simple median).</p>\n\n<p>The other comments are redundant again.</p></li>\n<li><p>Furthermore, indenting the comments to the correct level would increase readability. As it stands, the comments visually hack the code into pieces.</p></li>\n<li><p>Names: <code>l_list</code> and <code>g_list</code> contain unnecessary information that would easily be inferred from context – <code>list</code>, and their actual function is codified in just one letter. Rename them to <code>lesser</code> and <code>greater</code> or similar.</p>\n\n<p><code>temp_list</code> as a parameter is actually wrong: it’s not really temporary, it’s just the input. And again, <code>list</code> is a bit redundant. In fact, a one-letter identifier is acceptable here (but that’s the exception!). How about <code>a</code> for “array”?</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p>Use the idiomatic <code>[]</code> instead of <code>list()</code> to initialise lists.</p></li>\n<li><p>The first <code>elif</code> is unnecessary, and causes the subsequent code to be indented too much. Remove it. (Also, it should logically be an <code>else</code>, not an <code>elif</code>).</p></li>\n<li><p>Your choice of the pivot is a bit weird. Why two cases? Why not just use the middle? <code>pivot = a[len(a) // 2]</code></p></li>\n<li><p>Your code discards duplicate elements: <code>quick_sort([1, 2, 3, 2])</code> will yield <code>[1, 2, 3]</code>.</p></li>\n<li><p>blufox has already remarked that your <code>merge</code> routine is more convoluted than necessary. In fact, you could just use concatenation here, <code>lesser + [pivot] + greater</code> (but this again discards duplicates)</p></li>\n<li><p>It’s also a good idea to explicitly comment invariants in such algorithmic code.</p></li>\n</ul>\n\n<h1>Putting It Together</h1>\n\n<pre><code>import itertools\n\ndef sort(a):\n def swap(i, j):\n tmp = a[i]\n a[i] = a[j]\n a[j] = tmp\n\n if len(a) < 2:\n return a\n\n lesser = []\n greater = []\n # Swap pivot to front so we can safely ignore it afterwards.\n swap(0, len(a) // 2)\n pivot = a[0]\n\n # Invariant: lesser < pivot <= greater\n for x in itertools.islice(a, 1, None):\n if x < pivot:\n lesser.append(x)\n else:\n greater.append(x)\n\n return sort(lesser) + [pivot] + sort(greater)\n</code></pre>\n\n<h1>Bonus: Algorithmic Considerations</h1>\n\n<p>As blufox noted, this implementation requires more additional memory than necessary. This is acceptable when working with immutable data structures, but becomes quite expensive when used with mutable arrays.</p>\n\n<p>A normal, mutable quicksort implementation consists of two steps:</p>\n\n<ol>\n<li>in-place partitioning along a pivot</li>\n<li>recursive sorting of the two partitions</li>\n</ol>\n\n<p>The second step is trivial; the partitioning and choice of pivot however require some sophistication, otherwise they will have degenerate worst cases (even without considering the worst-case input “sorted array”). The definitive paper in this regard is <a href=\"http://www.cs.fit.edu/~pkc/classes/writing/samples/bentley93engineering.pdf\" rel=\"nofollow\"><em>Engineering a sort function</em></a> by Bentley and McIlroy. It is one of the clearest, most thorough computer science papers ever written and I heartily recommend its reading.</p>\n\n<p>That said, no “toy” implementation will ever replace an industry-strength implementation and attempting to do so is largely a waste of time, so it’s entirely reasonable to deliberately simplify an implementation by ignoring some performance considerations.</p>\n\n<p>In this regard the implementation above fares quite well. Just for the gained understanding I would still suggest that you attempt writing a variant which uses an <a href=\"http://en.wikipedia.org/wiki/Quicksort#In-place_version\" rel=\"nofollow\">in-place partitioning step</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:15:30.887",
"Id": "12825",
"ParentId": "12765",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T06:47:59.967",
"Id": "12765",
"Score": "7",
"Tags": [
"python",
"quick-sort"
],
"Title": "Quick sort in Python"
}
|
12765
|
<p>I have a class which throws a lot of exceptions: </p>
<pre><code> try {
mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
<p>I think this looks messy. Is it ok to just catch a generic <code>Exception</code> and not catch each individual exception if within the <code>catch</code> clause of each exception I'm just printing the stack trace?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-22T19:09:20.287",
"Id": "338928",
"Score": "0",
"body": "multi-catch? might combine a few of them."
}
] |
[
{
"body": "<blockquote>\n <p>is it ok to just catch a generic Exception and not catch each individual exception if within the catch clause of each exception im just printing the stack trace ?</p>\n</blockquote>\n\n<p>Yes, it is ok to just catch a generic <code>Exception</code>. The result will be the same if you only print the stack trace, except that catching a generic <code>Exception</code> also catches unchecked (runtime)exceptions such as <code>NullPointerException</code>s.</p>\n\n<p>But merely printing the stack trace is almost never ok.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:09:57.110",
"Id": "12770",
"ParentId": "12767",
"Score": "8"
}
},
{
"body": "<p>By printing a stack trace, and continuing, you indicate that you can recover from the current errors. Are you sure that you will be able to recover from other errors that may be added to mapper.writeValue in future? If the answer is yes, then perhaps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:12:05.593",
"Id": "12771",
"ParentId": "12767",
"Score": "4"
}
},
{
"body": "<p>It is okay to just catch <code>Exception</code> and print the stack trace.\nHowever rather than catching the top level <code>Exception</code> class, you may want to look at the Java 7 exception handling: <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html\">http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html</a></p>\n\n<p>In your case:</p>\n\n<pre><code>try {\n mapper.writeValue(outStream, myVal);\n} catch (JsonGenerationException | JsonMappingException | IOException e) {\n e.printStackTrace();\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T09:58:55.007",
"Id": "12773",
"ParentId": "12767",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "12770",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T08:05:32.967",
"Id": "12767",
"Score": "8",
"Tags": [
"java",
"json",
"error-handling"
],
"Title": "Catching multiple types of exceptions when writing JSON"
}
|
12767
|
<p>I'm currently getting the <strong>Facebook comments count</strong> over a query request to the Facbeook api.</p>
<p>The problem is, there are about 15 queries on each site which makes it real slow to load (up to 6 seconds)</p>
<p>The next step is to <strong>get the comments count from the array object</strong>, as there's no native PHP function for that i wrote my own.</p>
<p>Is there any possibility to speed things up?</p>
<p><strong>Is there something wrong with my code, which makes it slow, or is this up to the facebook query request?</strong></p>
<p>Here's my code:</p>
<pre><code>function objectToArray($object)
{
if(!is_object($object) && !is_array($object))
return $object;
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=objectToArray($data);
}
return $array;
}
function count_comments($url)
{
$fql = "SELECT commentsbox_count FROM ";
$fql .= "link_stat WHERE url = '".$url."'";
$apifql='https://api.facebook.com/method/fql.query?format=json&query='.urlencode($fql);
$json=file_get_contents($apifql);
$obj = json_decode($json);
$obj= objectToArray($obj);
$obj = $obj[0]['commentsbox_count'];
if($obj == 1)
{
echo '1 comment';
}
else if($obj == 0)
{
echo 'No comments yet';
}
else
{
echo $obj.' comments';
}
}
</code></pre>
<p>Here I'm calling the function:</p>
<pre><code>count_comments('http://example.com'.$data["id"].'');
</code></pre>
<p>Thanks in advance for any hints, tips and solutions!</p>
|
[] |
[
{
"body": "<p>Please use braces <code>{}</code> to wrap your code, even those one line if statements, makes it so much easier to read.</p>\n\n<p>First off, you do know that JSON has an option to output an array right? <code>json_decode( $json, TRUE )</code> returns an array. No need to create a function for it.</p>\n\n<p>\"there's no native PHP function for that\" - If it uses the countable interface, which is any data object I've come across (XML, JSON, SQL, etc...) then you can just use <code>count()</code>. If you have an object that holds the comments I would just try using <code>count()</code> on that first before creating a new query just to get a count.</p>\n\n<p>Make sure you are not calling the \"same\" object twice. I imagine you can just get the whole table into an array then perform array operations on it to get the desired results without having to query the server multiple times. This is probably the biggest reason your program runs so slow. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T17:50:34.143",
"Id": "20729",
"Score": "0",
"body": "That helped me a lot! Thank you for your explanation and tips how to improve my code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T11:48:43.453",
"Id": "20754",
"Score": "0",
"body": "I could reduce the loading time from 6seconds to 600ms! I perform only one query, write the results in an array and output it afterwards. Thanks again! Also thanks for advising me to use `json_decode($json, TRUE)`, so no need to use the function any more!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T14:05:50.393",
"Id": "12835",
"ParentId": "12772",
"Score": "3"
}
},
{
"body": "<p>+1 to @showerhead and:</p>\n\n<ol>\n<li><p><code>file_get_contents</code> returns <code>FALSE</code> on failure (as well as <code>json_decode</code>). You should handle that.</p></li>\n<li><p>Consider caching the results for faster loading time.</p></li>\n<li><p>The <code>$obj</code> name says nothing about the content of the variable. Furthermore, the code uses it for three different things:</p>\n\n<pre><code>$obj = json_decode($json);\n$obj = objectToArray($obj);\n$obj = $obj[0]['commentsbox_count'];\n</code></pre>\n\n<p>I'd call them <code>$json_object</code>, <code>$json_array</code>, and <code>$comments_count</code>. It would improve readability and make the code easier to maintain.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T22:45:41.407",
"Id": "12962",
"ParentId": "12772",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12835",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T09:17:52.577",
"Id": "12772",
"Score": "2",
"Tags": [
"php",
"performance",
"facebook"
],
"Title": "Getting Facebook comments count via FQL"
}
|
12772
|
<p>The <a href="https://en.wikipedia.org/wiki/ADO.NET_Entity_Framework" rel="nofollow noreferrer">ADO.NET Entity Framework</a> (EF) is .NET's Object-Relational Mapping (ORM) tool that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. Either natively, or through third-party libraries, it supports most major RDBM products including SQL Server, MySQL, Oracle, PostgreSQL and SQLite. It also supports Microsoft's "LINQ" syntax and lambda-expressions via the <a href="https://en.wikipedia.org/wiki/ADO.NET_Entity_Framework#LINQ_to_Entities" rel="nofollow noreferrer">LINQ to Entities</a> library.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:31:28.927",
"Id": "12775",
"Score": "0",
"Tags": null,
"Title": null
}
|
12775
|
The ADO.NET Entity Framework is a set of ORM (Object-Relational-Mapping) tools for the .NET Framework, since version 3.5 SP1.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:31:28.927",
"Id": "12776",
"Score": "0",
"Tags": null,
"Title": null
}
|
12776
|
<p>Question goes like this : </p>
<pre><code>input: 1
output:
{}
input: 2
output:
{}{}
{{}}
input: 3
output:
{}{}{}
{{}}{}
{}{{}}
</code></pre>
<p>This is my program : </p>
<pre><code>public class PrintBraces {
int n;
char []braces;
void readData()
{
java.util.Scanner scn=new java.util.Scanner(System.in);
System.out.print("Please enter the value of n : ");
n=scn.nextInt();
}
void manipulate()
{
braces=new char[n*2];
for(int i=0;i<2*n;i+=2)
{
braces[i]='{';
braces[i+1]='}';
}
for(int i=0;i<n;i++)
{
int oddNo=2*i-1;
if(oddNo>0)
{
char temp=braces[oddNo];
braces[oddNo]=braces[oddNo+1];
braces[oddNo+1]=temp;
print();
temp=braces[oddNo];
braces[oddNo]=braces[oddNo+1];
braces[oddNo+1]=temp;
}
else
{
print();
}
}
}
void print()
{
for(int i=0;i<2*n;i++)
{
System.out.print(braces[i]);
}
System.out.println();
}
}
</code></pre>
<hr>
<pre><code>class PrintMain
{
public static void main(String args[])
{
PrintBraces pb=new PrintBraces();
pb.readData();
pb.manipulate();
}
}
</code></pre>
<p>As expected, I get the correct answer.</p>
<p>I have solved it but I think it isn't efficient enough. Can anyone optimise it? And I would love to see any other alternative approaches for the same problem. May be a recursive one?
Also, I am open to any suggestions for improving my programming style. Any good practices that I may be violating in my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:42:54.127",
"Id": "20702",
"Score": "3",
"body": "Why doesn’t the output for `3` contain `{{{}}}`? Are only two levels of nesting allowed?"
}
] |
[
{
"body": "<p>The given problem can be attempted in a slightly different manner. You can see that the pairing corresponds to binary digits with { standing for 1s and } standing for 0s. </p>\n\n<p>For e.g the pairing with the maximum value for say 4 {}'s is 11110000. So all we have to do is to generate every number from 1 to 11110000 and strike out all numbers that do not conform to our requirement - that is, at no point while counting the digits from left in a number, can the number of 1s be lesser than the number of 0s, and also that the total count of 1s and 0s must be equal.</p>\n\n<p>A few optimizations can be done, For e.g, all odd numbers can be eliminated. And the total number of digits have to be even, etc.</p>\n\n<p>If the number of braces are <code>n</code>, then the algorithm is of <code>O(2^n)</code> complexity. So it is not an efficient algorithm. I wonder what the complexity of your algorithm is, and how you can show that your algorithm is indeed correct. </p>\n\n<p>For additional ideas ref: catalan numbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T00:57:11.973",
"Id": "20734",
"Score": "0",
"body": "Excellent idea ... post some code. I am all for non-recursive solutions when they exist."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:03:01.137",
"Id": "12823",
"ParentId": "12777",
"Score": "4"
}
},
{
"body": "<pre><code>public class Solution{\n\n public static void par(int n, int open, int closed, String str) {\n\n if (closed == n) {\n System.out.println(str);\n return;\n }\n\n if (open < n) {\n par(n, open+1, closed, str + \"{\");\n }\n\n if (closed < open) {\n par(n, open, closed+1, str + \"}\");\n }\n }\n\n public static void main(String[] args) throws Exception {\n\n par(Integer.parseInt(args[0]), 0, 0, \"\");\n\n }\n}\n</code></pre>\n\n<p>Output fot the testcase 3:</p>\n\n<pre><code>{{{}}}\n{{}{}}\n{{}}{}\n{}{{}}\n{}{}{}\n</code></pre>\n\n<p>If you need additional speed - you should use the buffered output. Something like this:</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\npublic class Solution{\n\n static BufferedWriter out; \n\n public static void par(int n, int open, int closed, String str) throws IOException {\n\n if (closed == n) {\n out.write(str + \"\\n\");\n return;\n }\n\n if (open < n) {\n par(n, open+1, closed, str + \"{\");\n }\n\n if (closed < open) {\n par(n, open, closed+1, str + \"}\");\n }\n }\n\n public static void main(String[] args) throws IOException {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), \"ASCII\"), 4096);\n par(Integer.parseInt(args[0]), 0, 0, \"\");\n out.flush();\n }\n}\n</code></pre>\n\n<p>For example the first version for 13 takes ~ <strong>17</strong> seconds:</p>\n\n<pre><code>timethis %JAVA_HOME%/bin/java -server Solution 13 >13.txt\n</code></pre>\n\n<p>the buffered output version ~ <strong>0.4</strong> second!</p>\n\n<p>PS. Interesting that jdk1.7.0_04 ~ <strong>5</strong> times faster than that c version:</p>\n\n<pre><code>#include<stdio.h>\n#include<string.h>\n\nunsigned long pairs_count;\nunsigned long *brackets;\nunsigned long found = 0;\n\nvoid print_result()\n{\n unsigned long i, j;\n\n for (i = 0; i < pairs_count; i++) {\n printf(\"(\");\n\n for (j = 0; j < pairs_count; j++)\n if (brackets[j] == i)\n printf(\")\");\n }\n\n printf(\"n\");\n found++;\n}\n\nvoid step(unsigned long start_val, unsigned long pos)\n{\n unsigned long k, i;\n\n if (start_val > pos)\n k = start_val;\n else\n k = pos;\n\n for (i = k; i < pairs_count; i++) {\n brackets[pos] = i;\n\n if (pos == pairs_count - 1)\n print_result();\n else\n step(i, pos + 1);\n }\n}\n\nint main()\n{\n\n scanf(\"%d\", &pairs_count);\n\n brackets = new unsigned long[pairs_count];\n\n if (!brackets) {\n printf(\"Unsufficient memory.n\");\n return (0);\n }\n\n step(0, 0);\n\n delete brackets;\n\n printf(\"Found: %d.n\", found);\n\n return (0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:10:15.603",
"Id": "20706",
"Score": "1",
"body": "Can you guide me through the code? I personally find it difficult to grasp recursive algos and I need to get good at it. So can you suggest me a good source for mastering recursive algos?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:18:00.680",
"Id": "20710",
"Score": "0",
"body": "Nice, very clean implementation (but an explanation would be in order). Now, how to rewrite it using dynamic programming?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T22:49:25.790",
"Id": "20733",
"Score": "0",
"body": "+1 - String concatenation isn't the most efficient thing around. Of course, passing `StringBuilder` or `StringBuffer` wouldn't help much, because you'd need to copy them at each level - This might warrant a custom `CharSequence` or something (as linked list? Although `String` may have this behavior by default...). Code is a lot cleaner than what I was initially coming up with, although a bit of an explanation would be helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T08:25:24.697",
"Id": "20750",
"Score": "0",
"body": "The algorithm is very simple:\n1. The first brace is {\n2. The last brace is }\n3. On the same level } goes right after {\n4. The amount of { braces is equal to amount of the } braces.\n5. Recursion does the rest job."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:05:20.603",
"Id": "12824",
"ParentId": "12777",
"Score": "6"
}
},
{
"body": "<p>Here's my effort. It's a little like @cat_baxter's one. The point I am making here is that if you add loads of comments to your code, sometimes just the effort of doing so makes the code better.</p>\n\n<p>I think this is optimal, i.e. it never starts growing a sequence towards an invalid position, but I don't fancy trying to prove that.</p>\n\n<pre><code>public class PrintBraces {\n public static void main(String[] args) {\n // Do a number of them.\n for (int i = 1; i < 10; i++) {\n System.out.println(\"Print Braces: \" + i);\n printBraces(i);\n }\n }\n\n private static void printBraces(int n) {\n // There will always be n*2 characters in the brace array.\n char[] braces = new char[n * 2];\n // Start at position 0 with 0 opened.\n printBraces(braces, 0, 0);\n }\n\n private static void printBraces(char[] braces, int opened, int offset) {\n // How much space is left in the array?\n int space = braces.length - offset;\n // Are we at the end of the array?\n if (space > 0) {\n // We can open or close so try both.\n // We can only open if there is enough room to close all opened and at least one more.\n if (space > opened) {\n printBraces(braces, opened, offset, true);\n }\n // We can only close if we are opened more than once.\n if (opened > 0) {\n printBraces(braces, opened, offset, false);\n }\n } else {\n // Array is full! Is it legal?\n if (opened == 0) {\n System.out.println(braces);\n } else {\n // Here just for my sanity. Code never gets here - proving we are correct.\n System.out.println(\"?-\" + braces);\n }\n }\n }\n\n private static void printBraces(char[] braces, int opened, int offset, boolean open) {\n // Add that kind of brace and recurse.\n braces[offset] = open ? '{' : '}';\n printBraces(braces, opened + (open ? 1 : -1), offset + 1);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T08:29:12.760",
"Id": "12865",
"ParentId": "12777",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:32:18.457",
"Id": "12777",
"Score": "6",
"Tags": [
"java",
"optimization"
],
"Title": "Printing braces"
}
|
12777
|
<p><a href="http://en.wikipedia.org/wiki/Function_%28computer_science%29" rel="nofollow">From Wikipedia</a>:</p>
<blockquote>
<p>In computer programming, a <strong>subroutine</strong> is a sequence of program instructions that perform a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Subprograms may be defined within programs, or separately in libraries that can be used by multiple programs.</p>
<p>In different programming languages a subroutine may be called a <strong>procedure</strong>, a <strong>function</strong>, a <strong>routine</strong>, a <strong>method</strong>, or a <strong>subprogram</strong>. The generic term <strong>callable unit</strong> is sometimes used.</p>
<p>As the name <em>subprogram</em> suggests, a subroutine behaves in much the same way as a computer program that is used as one step in a larger program or another subprogram. A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (<em>return</em>) to the next instruction after the call once the subroutine's task is done.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:35:40.263",
"Id": "12778",
"Score": "0",
"Tags": null,
"Title": null
}
|
12778
|
A function (also called a procedure, method, subroutine, or routine) is a portion of code intended to carry out a single, specific task.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:35:40.263",
"Id": "12779",
"Score": "0",
"Tags": null,
"Title": null
}
|
12779
|
Database design is the process of specifying the logical and/or physical parts of a database. The goal of database design is to make a representation of some "universe of discourse" - the types of facts, business rules and other requirements that the database is intended to model.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:37:16.017",
"Id": "12781",
"Score": "0",
"Tags": null,
"Title": null
}
|
12781
|
<p>Collections APIs provide developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense, collections work a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:39:01.710",
"Id": "12782",
"Score": "0",
"Tags": null,
"Title": null
}
|
12782
|
Collections APIs provide developers with a set of classes and interfaces that makes it easier to handle collections of objects.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:39:01.710",
"Id": "12783",
"Score": "0",
"Tags": null,
"Title": null
}
|
12783
|
MATLAB is a high-level language and interactive programming environment developed by MathWorks. It is the foundation for a number of other tools, including Simulink and various toolboxes that extend the core capabilities.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:40:10.227",
"Id": "12785",
"Score": "0",
"Tags": null,
"Title": null
}
|
12785
|
Architecture encompasses the process, artifacts and high-level structure of a solution.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:41:02.033",
"Id": "12787",
"Score": "0",
"Tags": null,
"Title": null
}
|
12787
|
<p><a href="http://en.wikipedia.org/wiki/Type_conversion" rel="nofollow">From Wikipedia</a>:</p>
<blockquote>
<p>In computer science, <strong>type conversion</strong>, <strong>typecasting</strong>, and <strong>coercion</strong> are
different ways of, implicitly or explicitly, changing an entity of one
data type into another. This is done to take advantage of certain
features of type hierarchies or type representations. One example
would be small integers, which can be stored in a compact format and
converted to a larger representation when used in arithmetic
computations. In object-oriented programming, type conversion allows
programs to treat objects of one type as one of their ancestor types
to simplify interacting with them.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:42:56.977",
"Id": "12788",
"Score": "0",
"Tags": null,
"Title": null
}
|
12788
|
Casting is a process where an object type is explicitly converted into another type if the conversion is allowed.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:42:56.977",
"Id": "12789",
"Score": "0",
"Tags": null,
"Title": null
}
|
12789
|
Synchronization refers to using controls to maintain a coherent representation, such as processes running the same program (process synchronization).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:44:21.390",
"Id": "12791",
"Score": "0",
"Tags": null,
"Title": null
}
|
12791
|
<p>Linux was created by Linus Torvalds in 1991 as a hobby project, and quickly caught as the only freely available Unix-like system of that time. Today, it's one of the biggest operating systems, most notably is the Android project which runs on Linux.</p>
<p>The Linux kernel is written mostly in C and is released under the <a href="https://www.gnu.org/licenses/gpl-2.0.html" rel="nofollow">GNU GPL v2</a> license. It's one of the biggest open source projects to date with 1,500 developers and over 200 companies contributing to the 4.1 version release June 2015 (<a href="http://lwn.net/Articles/646942/" rel="nofollow">LWN.net</a>).</p>
<h2>Programming under Linux</h2>
<p>Linux is a Unix-like mostly POSIX compliant operating system. The GNU Compiler Suite is the standard compiler. It comes with glibc as the standard C library.</p>
<p>Further reading: <a href="http://www.advancedlinuxprogramming.com/" rel="nofollow">Advanced Linux Programming</a> by CodeSorcery LLC.</p>
<h2>Distributions</h2>
<p>A Linux distribution (or distro) is a bundle of the Linux kernel, a package manager and a set of essential applications. <a href="http://distrowatch.com" rel="nofollow">DistroWatch</a> has a comprehensive list of 277 distros as of July 2015. The highest ranked are Linux Mint, Ubuntu and Debian.</p>
<h2>Statistics</h2>
<ul>
<li><p>48.61% of worldwide device shipments run Android (includes smartphones, tablets, laptops and PCs). (<a href="http://www.gartner.com/newsroom/id/2954317" rel="nofollow">Gartner 2014</a>)</p></li>
<li><p>96.20% of the top 500 supercomputers in the world run Linux. (<a href="http://www.top500.org/statistics/overtime/" rel="nofollow">top500.org 2015</a>)</p></li>
</ul>
<h2>Related tags</h2>
<p><a href="/questions/tagged/unix" class="post-tag" title="show questions tagged 'unix'" rel="tag">unix</a> <a href="/questions/tagged/posix" class="post-tag" title="show questions tagged 'posix'" rel="tag">posix</a></p>
<h2>Related sites</h2>
<ul>
<li><a href="http://unix.stackexchange.com/">Unix and Linux Stack Exchange</a></li>
<li><a href="http://askubuntu.com/">Ask Ubuntu Stack Exchange</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:44:59.703",
"Id": "12792",
"Score": "0",
"Tags": null,
"Title": null
}
|
12792
|
Linux is a free (libre), open source, Unix-like operating system.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:44:59.703",
"Id": "12793",
"Score": "0",
"Tags": null,
"Title": null
}
|
12793
|
The Standard Template Library, or STL, is a C++ library of generic containers, iterators, algorithms, and function objects.
When C++ was standardised, large parts of the STL were adopted into the Standard Library, and these parts in the Standard Library are also sometimes referred to collectively as "the STL".
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:46:14.303",
"Id": "12795",
"Score": "0",
"Tags": null,
"Title": null
}
|
12795
|
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:47:06.097",
"Id": "12797",
"Score": "0",
"Tags": null,
"Title": null
}
|
12797
|
<p>I have a table containing URLs as they should appear in English and equivalent translations of them into other languages. Originally, I was told that there would always be an English translation, so when listing them in the application that updates them I just searched for the ones where <code>iso = 'GB'</code>. However, it turns out that it's entirely possible for there not to be an English translation. </p>
<p>I needed to update my query for generating the list displayed in the application so that it would select the English translation in preference to any other translations that might exist, but if there is no English translation, then use a single example of which other translations there are present (doesn't matter which, just as long as there's a single entry presented to the user). </p>
<p>The query I came up with is as follows. I'd appreciate it if you could give it a sanity check so I can be confident that it's returning correct results. (It appears to do so with the current data set, but it's currently quite a small set). </p>
<pre><code>SELECT `t`.*
FROM (
SELECT `translations_urls`.*
FROM `translations_urls`
ORDER BY iso = 'GB' DESC,
`order` ASC,
`url_gb` ASC
) AS `t`
GROUP BY `url_gb`
</code></pre>
<p>The table schems is as follows: </p>
<pre><code>CREATE TABLE `translations_urls` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`order` INT(10) NOT NULL COMMENT 'Sort order',
`iso` CHAR(2) NOT NULL COMMENT 'ISO country code',
`url_gb` VARCHAR(127) NOT NULL COMMENT 'Original URL',
`url_trans` VARCHAR(127) NOT NULL COMMENT 'Translated URL',
`controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to',
`action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to',
PRIMARY KEY (`id`),
UNIQUE INDEX `iso_url_gb` (`iso`, `url_gb`),
INDEX `url_trans` (`url_trans`),
CONSTRAINT `fk_translations_urls_translations_countries_iso` FOREIGN KEY (`iso`) REFERENCES `translations_countries` (`iso`)
)
COMMENT='URL translations'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=303;
</code></pre>
|
[] |
[
{
"body": "<p>Your query isn't right, and in my opinion, your schema doesn't make sense either.</p>\n\n<p>What is the purpose of the sub-select in your query? Is your query not equivalent to</p>\n\n<pre><code>SELECT * \n FROM `translations_urls` AS `t`\n GROUP BY `url_gb`\n ORDER BY iso = 'GB' DESC, `order` ASC, `url_gb` ASC;\n</code></pre>\n\n<p>Furthermore, what do you intend to achieve with <code>GROUP BY</code>? You aren't using any aggregate functions in your output columns. In fact, with a sane database engine (e.g. PostgreSQL), such a query would generate an error like</p>\n\n<blockquote>\n <p>ERROR: column \"t.id\" must appear in the GROUP BY clause or be used in an aggregate function</p>\n</blockquote>\n\n<hr>\n\n<p>Your schema seems awkward to me, for several reasons:</p>\n\n<ul>\n<li>The <code>url_gb</code> column implies that GB is the original language, which, as you stated, is no longer a valid assumption.</li>\n<li>The use of <code>url_gb</code> to identify a translation's original results in a normalization problem. If the URL of a UK-English document changes, you have to update the <code>url_gb</code> of <em>all</em> of its translations.</li>\n</ul>\n\n<p>Furthermore, translations should have <a href=\"http://en.wikipedia.org/wiki/ISO_639\" rel=\"nofollow\">language codes</a>, not <a href=\"http://en.wikipedia.org/wiki/ISO_3166\" rel=\"nofollow\">country codes</a>. (An exception would be if you were \"translating\" legal contracts, in which case you want a different document per country.)</p>\n\n<p>One solution is to make a self-referential table that could form a tree of documents:</p>\n\n<pre><code>CREATE TABLE `documents`\n( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT\n, `order` INT(10) NOT NULL COMMENT 'Sort order'\n, `iso` VARCHAR(6) NOT NULL COMMENT 'ISO language code'\n, `url` VARCHAR(127) NOT NULL COMMENT 'URL'\n, `controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to'\n, `action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to'\n, `translated_from` INT(10) UNSIGNED COMMENT 'id of document from which this was translated'\n, PRIMARY KEY (`id`)\n, UNIQUE INDEX `iso_url` (`iso`, `url`)\n, FOREIGN KEY (`iso`) REFERENCES `translations_languages` (`iso`)\n, FOREIGN KEY (`translated_from`) REFERENCES `documents` (`id`)\n)\nENGINE=InnoDB;\n</code></pre>\n\n<p>Another approach, which I prefer, is to distinguish between documents and their translations. The advantage of this is that you can nominate one of the translations as the canonical original, to prevent recursion, which is harder to deal with in SQL.</p>\n\n<pre><code>CREATE TABLE `documents`\n( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT\n, `order` INT(10) NOT NULL COMMENT 'Sort order'\n, `canonical` INT(10) UNSIGNED COMMENT 'Canonical (original) translation'\n, `controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to'\n, `action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to'\n, PRIMARY KEY (`id`)\n)\nENGINE=InnoDB;\n\nCREATE TABLE `translations`\n( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT\n, `document_id` INT(10) UNSIGNED NOT NULL\n, `iso` VARCHAR(6) NOT NULL COMMENT 'ISO language code'\n, `url` VARCHAR(127) NOT NULL COMMENT 'URL'\n, PRIMARY KEY (`id`)\n, UNIQUE INDEX `document_id_iso` (`document_id`, `iso`)\n, UNIQUE INDEX `url` (`url`)\n, FOREIGN KEY (`iso`) REFERENCES `translations_languages` (`iso`)\n)\nENGINE=InnoDB;\n\nALTER TABLE `documents`\n ADD FOREIGN KEY (`canonical`) REFERENCES `translations` (`id`);\n</code></pre>\n\n<p>An annoyance with this schema is the mutual foreign key relationship. To add a document, you would first have to insert a document with <code>NULL</code> as the canonical translation, then insert the first translation, then update the document with the <code>id</code> of the first translation.</p>\n\n<hr>\n\n<p>With the latter schema, a query to preferentially return English versions, falling back to a canonical text in another language, would be:</p>\n\n<pre><code>SELECT *\n FROM `documents` AS `d`\n INNER JOIN `translations` AS `t`\n ON `t`.`document_id` = `d`.`id`\n WHERE\n `iso` = 'en' OR\n (`iso` <> 'en' AND `t`.`id` = `d`.`canonical`);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T22:01:22.813",
"Id": "47609",
"Score": "0",
"body": "Thanks for the answer, but I don't remember any of the details of this anymore, and it's now moot anyway as I don't work at that particular place any longer. I didn't expect to see anybody bothering to leave an answer on a question asked nearly 2 years ago!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T20:00:28.413",
"Id": "30008",
"ParentId": "12798",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:48:34.940",
"Id": "12798",
"Score": "2",
"Tags": [
"sql",
"mysql"
],
"Title": "Sanity check on grouping query"
}
|
12798
|
<p><strong><a href="http://www.postgresql.org" rel="nofollow">PostgreSQL</a></strong> (<a href="http://wiki.postgresql.org/wiki/Identity_Guidelines" rel="nofollow">often Postgres</a>) is a powerful, object-relational database system (<b>O</b>RDBMS, to be even more specific).</p>
<p>Open source since 1996, it has a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. Standards compliance is a major focus of the development team. Postgres runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows.</p>
<p>Primary sources for information:</p>
<ul>
<li><a href="http://www.postgresql.org/docs/current/interactive/" rel="nofollow">The comprehensive and clear manual</a></li>
<li><a href="http://wiki.postgresql.org/wiki/Identity_Guidelines" rel="nofollow">The PostgreSQL wiki</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:48:55.393",
"Id": "12799",
"Score": "0",
"Tags": null,
"Title": null
}
|
12799
|
PostgreSQL is an open-source, Relational Database Management System (RDBMS) available for many platforms including Linux, UNIX, MS Windows and Mac OS X.
Please mention your PostgreSQL version when asking questions.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:48:55.393",
"Id": "12800",
"Score": "0",
"Tags": null,
"Title": null
}
|
12800
|
Bitwise refers to a bitwise operation which operates on one or more bit patterns or binary numerals at the level of their individual bits.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:49:19.963",
"Id": "12802",
"Score": "0",
"Tags": null,
"Title": null
}
|
12802
|
<p><a href="http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29" rel="nofollow">From Wikipedia</a>:</p>
<blockquote>
<p>In computer science, a <strong>stack</strong> is a particular kind of abstract data
type or collection in which the principal (or only) operations on the
collection are the addition of an entity to the collection, known as
push and removal of an entity, known as <em>pop</em>. The relation between
the push and pop operations is such that the stack is a
Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the
last element added to the structure must be the first one to be
removed. This is equivalent to the requirement that, considered as a
linear data structure, or more abstractly a sequential collection, the
push and pop operations occur only at one end of the structure,
referred to as the top of the stack. Often a <em>peek</em> or <em>top</em> operation is
also implemented, returning the value of the top element without
removing it.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:50:31.303",
"Id": "12803",
"Score": "0",
"Tags": null,
"Title": null
}
|
12803
|
A stack is a last in, first out (LIFO) abstract data type and data structure. Perhaps the most common use of stacks is to store subroutine arguments and return addresses.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:50:31.303",
"Id": "12804",
"Score": "0",
"Tags": null,
"Title": null
}
|
12804
|
XSLT is a transformation language for XML. Its primary function is to transform XML documents into different output formats, commonly other XML, HTML or plain text.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:50:51.663",
"Id": "12806",
"Score": "0",
"Tags": null,
"Title": null
}
|
12806
|
Merge sort is an O(n log n) comparison-based sorting algorithm.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:51:26.263",
"Id": "12808",
"Score": "0",
"Tags": null,
"Title": null
}
|
12808
|
<p>Recursion is a kind of function call in which a function calls itself. Such functions are also called <strong>recursive</strong> functions. </p>
<p>Some functional programming languages do not define any looping constructs, but rely solely on recursion to repeatedly call code. Likewise, in languages that do provide loops, it is possible for any recursive function to be written using loops without requiring recursion.</p>
<p>This defines two basic approaches to repeatedly call some piece of code.</p>
<ul>
<li><strong>Iterative</strong> approach (Using loop constructs) </li>
<li><strong>Recursive</strong> approach (Using recursion)</li>
</ul>
<p>In addition to program code, recursion can also occur </p>
<ul>
<li>in data structures, where a nested object or array may contain a reference to an element further up the data tree.</li>
<li>in mathematics, where recursion is used to prove statements about more general well-founded structures, such as trees; this generalization, known as <em>structural induction</em>, is used in mathematical logic and computer science.</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-06-20T10:51:55.313",
"Id": "12809",
"Score": "0",
"Tags": null,
"Title": null
}
|
12809
|
Recursion in computer science is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:51:55.313",
"Id": "12810",
"Score": "0",
"Tags": null,
"Title": null
}
|
12810
|
<p><a href="http://www.gnu.org/software/emacs/" rel="nofollow">GNU Emacs</a> is an extensible, customizable text editor. Begun in the mid-1970s as TECO, it was re-written using C and <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/index.html" rel="nofollow">Emacs Lisp</a> to provide portability and an extendable interface. It continues to be actively developed today.</p>
<p>Emacs provides context-sensitive editing modes with syntax coloring, is self documenting, has full Unicode support and extensions to do almost anything. Die-hard Emacs users do most everything from within Emacs: write, compile, run and debug code; read/compose email; browse the web; do project planning etc.</p>
<h2>Useful Links</h2>
<ul>
<li>A <a href="http://www.gnu.org/software/emacs/emacs-paper.html" rel="nofollow">paper</a> by Richard Stallman describing the design of Emacs</li>
<li>The <a href="http://www.emacswiki.org/" rel="nofollow">Emacs Wiki</a>, a collaborative wiki for extensions to Emacs</li>
<li>Wikipedia's <a href="http://en.wikipedia.org/wiki/Emacs" rel="nofollow">Emacs page</a></li>
<li><a href="http://www.h-online.com/open/features/Emacs-the-birth-of-the-GPL-969471.html" rel="nofollow">History of Emacs and GPL</a></li>
<li><a href="http://www.gnu.org/software/emacs/" rel="nofollow">GNU Emacs homepage</a></li>
</ul>
<h2>Wisdom from the stack</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/48006/is-it-worth-investing-time-in-learning-to-use-emacs">Is it worth investing time in learning to use emacs?</a></li>
<li><a href="http://stackoverflow.com/questions/269812/how-to-quickly-get-started-at-using-and-learning-emacs">How to quickly get started at using and learning Emacs</a> </li>
<li><a href="http://stackoverflow.com/questions/2582555/emacs-without-lisp">Emacs without lisp</a></li>
<li>Stack Overflow <a href="http://stackoverflow.com/tags/emacs-lisp/info">emacs-lisp</a> and <a href="http://stackoverflow.com/tags/emacs/info">emacs</a> tags</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:52:57.493",
"Id": "12811",
"Score": "0",
"Tags": null,
"Title": null
}
|
12811
|
GNU Emacs is an extensible, customizable, self-documenting text editor written in C with Emacs Lisp as its extension language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:52:57.493",
"Id": "12812",
"Score": "0",
"Tags": null,
"Title": null
}
|
12812
|
<p>Questions about Sudoku include:</p>
<h3>Validating a Sudoku:</h3>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/6701/sudoku-solver-optimization">Sudoku Solver Optimization</a></li>
<li><a href="https://codereview.stackexchange.com/questions/46033/sudoku-checker-in-java">Sudoku Checker in Java</a></li>
</ul>
<h3>Solving a Sudoku:</h3>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/9281/sudoku-solver-in-haskell">Sudoku solver in Haskell</a></li>
<li><a href="https://codereview.stackexchange.com/questions/1489/please-review-my-sudoku-solving-class-using-php">Sudoku solving class in PHP</a></li>
<li><a href="https://codereview.stackexchange.com/questions/32138/dssudokusolver-a-javascript-sudoku-solving-algorithm">DSSudokuSolver - A JavaScript Sudoku solving algorithm</a></li>
</ul>
<p>and more.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:53:22.267",
"Id": "12813",
"Score": "0",
"Tags": null,
"Title": null
}
|
12813
|
Sudoku (数独 sūdoku?, すうどく) English pronunciation: /suːˈdoʊkuː/ soo-doh-koo is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 sub-grids that compose the grid (also called "boxes", "blocks", "regions", or "sub-squares") contain all of the digits from 1 to 9. The puzzle setter provides a partially completed grid, which typically has a unique solution.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:53:22.267",
"Id": "12814",
"Score": "0",
"Tags": null,
"Title": null
}
|
12814
|
Sed stands for Stream EDitor. It is one of the basic tools in the POSIX environment - it processes one or more files according to an editing script and writes the results to standard output. Created in Bell Labs, it has been around since mid-70s.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:57:02.327",
"Id": "12816",
"Score": "0",
"Tags": null,
"Title": null
}
|
12816
|
<p>Immutability is the inability to modify a variable after it is has been created.</p>
<p>It is a pattern found in many branches of programming; immutable objects are used widely within object oriented languages (<em>such as Python's <code>str</code> type, Java's <code>String</code> and <code>Integer</code> type, .NET's <code>System.String</code>, etc.</em>), functional programming (<em>esp. Haskell and other pure languages</em>), and other paradigms.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:58:00.000",
"Id": "12817",
"Score": "0",
"Tags": null,
"Title": null
}
|
12817
|
Immutability is the inability to modify data after it has been created. Modifications are instead made by copying the data. A property of immutable data is that it is *referentially transparent*.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T10:58:00.000",
"Id": "12818",
"Score": "0",
"Tags": null,
"Title": null
}
|
12818
|
<p>Fortran is a general-purpose, procedural, imperative programming language that is especially used for numeric computation and scientific computing.</p>
<p>It has a long history, and is still evolving: the first language proposal was put together by J. W. Backus in 1953, the first international standard was approved in 1966, and the latest major standard revision (with new features) was written in 2008.</p>
<p>Fortran is widely used in the scientific computing community, and accounts for an important part of numerical codes run in supercomputing facilities.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:01:33.583",
"Id": "12819",
"Score": "0",
"Tags": null,
"Title": null
}
|
12819
|
Fortran is a general-purpose, procedural, imperative programming language that is especially suited for numeric computation and scientific computing.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:01:33.583",
"Id": "12820",
"Score": "0",
"Tags": null,
"Title": null
}
|
12820
|
<p>The D language is statically typed and compiles directly to machine code. It supports many programming styles: imperative, object oriented, functional, and metaprogramming. It's a member of the C syntax family, and its appearance is very similar to that of C++. D was originally developed by <a href="http://en.wikipedia.org/wiki/Walter_Bright" rel="nofollow">Walter Bright</a> and since 2006 <a href="http://en.wikipedia.org/wiki/Andrei_Alexandrescu" rel="nofollow">Andrei Alexandrescu</a> has joined the project.</p>
<p>There are currently two versions of D:</p>
<ul>
<li><p>Version 1 achieved stable status in 2007 and was discontinued on December 31, 2012.</p></li>
<li><p>Version 2, a non-backwards compatible successor is feature complete and currently in the final stages of development.</p></li>
</ul>
<p>Resources:</p>
<ul>
<li><p><a href="https://github.com/D-Programming-Language" rel="nofollow">The D programming language on GitHub.</a></p></li>
<li><p><a href="http://dlang.org/" rel="nofollow">Official website.</a></p></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:03:17.997",
"Id": "12821",
"Score": "0",
"Tags": null,
"Title": null
}
|
12821
|
D is a systems programming language developed by Walter Bright and since 2006 Andrei Alexandrescu. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. Special attention is given to the needs of concurrency, reliability, documentation, quality assurance, management and portability.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T11:03:17.997",
"Id": "12822",
"Score": "0",
"Tags": null,
"Title": null
}
|
12822
|
<p>I have a servlet deployed in a Tomcat Servlet Container in this link, <code>http://localhost:9764/example/servlets/servlet/HelloWorldExample</code>. I want to send a HTTP request to that servlet using Java. Just I want to get the return as a String. Currently I am using this code to do it, Is it OK to use this code?</p>
<pre><code>import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Client {
public static void main(String[] args) {
try {
String webPage = "http://10.100.3.83:9764/example/servlets/servlet/HelloWorldExample";
URL url = new URL(webPage);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.addRequestProperty("Name","andunslg");
urlConnection.addRequestProperty("PW","admin");
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T03:54:51.573",
"Id": "20708",
"Score": "1",
"body": "This appears ok. What problem you are facing ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T03:58:50.887",
"Id": "20709",
"Score": "0",
"body": "Not a problem. Just I want to verify that weather I am using much standard way to do it or is there any other better and efficient way to do it."
}
] |
[
{
"body": "<p>when you are sending any data to the servlet make sure it you send it via POST/GET depending on how sensitive the information is. In your case the user and password is sent through the get which is unsafe since it can be viewed by anyone. </p>\n\n<p>you can add.<code>urlConnection.setRequestMethod(\"POST\");</code> Also to get the response you have to send the request first , which in your case is missing.</p>\n\n<pre><code>dataInput= new DataOutputStream(urlConnection.getOutputStream());\nString content = \"param1=\" + URLEncoder.encode(\"first parameter\") \n + \"&param2=\" \n + URLEncoder.encode(\"the second one...\");\n\ndataInput.writeBytes(content);\ndataInput.flush();\ndataInput.close();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T04:08:56.337",
"Id": "12827",
"ParentId": "12826",
"Score": "2"
}
},
{
"body": "<p>+1 to @chaosguru, and instead of this:</p>\n\n<pre><code>InputStreamReader isr = new InputStreamReader(is);\n\nint numCharsRead;\nchar[] charArray = new char[1024];\nStringBuffer sb = new StringBuffer();\nwhile ((numCharsRead = isr.read(charArray)) > 0) {\n sb.append(charArray, 0, numCharsRead);\n}\nString result = sb.toString();\n</code></pre>\n\n<p>Use Apache Commons IO's <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29\" rel=\"nofollow\"><code>IOUtils.toString</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T12:55:37.013",
"Id": "12829",
"ParentId": "12826",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T03:52:06.413",
"Id": "12826",
"Score": "1",
"Tags": [
"java",
"networking"
],
"Title": "How to access a servlet in Tomcat Contanier using Java"
}
|
12826
|
<p>I am wondering if this is a good and correct way to write the implementation of two web service methods (get/set methods).</p>
<p>The <code>setPerson</code> method can be called from different threads from a pool, so I think the best way is to make the method <code>synchronized</code>. Or is it possible to lock the table when editing to avoid the synchronization on Java?</p>
<pre><code>@Override
public synchronized void setPerson(Person person) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonLibPU");
EntityManager em = emf.createEntityManager();
if(!em.getTransaction().isActive()) {
em.getTransaction().begin();
}
try {
em.merge(person);
em.getTransaction().commit();
emf.getCache().evict(Person.class);
} catch (Exception ex) {
if(em.getTransaction().isActive())
em.getTransaction().rollback();
} finally {
em.close();
}
}
</code></pre>
<p>And here follows the <code>getPerson</code> method. I didn't make it <code>synchronized</code> since it reads from the JPA cache. </p>
<pre><code>@Override
public Person getPerson(int personId) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonLibPU");
EntityManager em = emf.createEntityManager();
try {
return (Person)em.getReference(Person.class, personId);
} catch (javax.persistence.EntityNotFoundException ex) {
return new Person(); // return empty person
} finally {
em.close();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a few notes:</p>\n\n<pre><code>if(!em.getTransaction().isActive()) {\n em.getTransaction().begin();\n}\ntry {\n em.merge(person);\n em.getTransaction().commit(); \n emf.getCache().evict(Person.class);\n} catch (Exception ex) {\n if(em.getTransaction().isActive())\n em.getTransaction().rollback();\n} finally {\n em.close();\n}\n</code></pre>\n\n<p>I'd create a local variable for <code>em.getTransaction()</code> here and move the <code>isActive</code> check inside the <code>try</code> block. </p>\n\n<pre><code>try {\n EntityTransaction transaction = em.getTransaction();\n try {\n if (!transaction.isActive()) {\n transaction.begin();\n }\n em.merge(person);\n transaction.commit(); \n emf.getCache().evict(Person.class);\n } finally {\n if (transaction.isActive()) {\n em.transaction.rollback();\n }\n }\n} finally {\n em.close();\n}\n</code></pre>\n\n<p>It closes the <code>EntityManager</code> in every code path as well as the transaction.</p>\n\n<p>I've removed the exception catching. If you catch it consider at least logging it.</p>\n\n<p>Evicting the whole <code>Person</code> cache every time you save a <code>Person</code> entity does not seem a good idea for performance.</p>\n\n<p>Please note that if something call this method with an active transaction (I'm not sure if it's possible at all) it will returns with a committed or rollbacked, but <em>not</em> active transaction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T06:38:00.357",
"Id": "20744",
"Score": "0",
"body": "Thanks for your suggestion! How about the `synchronize` issue? Can I remove it if I use `em.lock(person, WRITE);` instead? Will any other transaction way for the lock to be released?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T19:59:47.987",
"Id": "20797",
"Score": "0",
"body": "@Rox: To be honest, the `synchronize` smells for me, but I'm afraid I'm not so familiar with EclipseLink to answer this question. I guess there is a better solution than that. This part of your question may fit better on StackOverflow."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T13:59:14.050",
"Id": "12834",
"ParentId": "12833",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T13:26:51.347",
"Id": "12833",
"Score": "2",
"Tags": [
"java",
"synchronization",
"web-services"
],
"Title": "Webservice methods using EclipseLink and database entities"
}
|
12833
|
<p>I use <code>NPOI</code> to copy Excel formula, but can't find an option to do it in a relative way. Therefore, I've written a function to implement it. The task is "easy". When copying a formula <code>A1+B1</code> of <code>C1</code> to <code>C2</code>, the result will be <code>A2+B2</code>. But the formula can do more than that. For example:</p>
<ul>
<li><code>Left(A1, 3)</code> of <code>B1</code> to <code>B2</code> => <code>Left(A2, 3)</code></li>
<li><code>(AB1 - AB$1) * $AB1</code> of <code>AC1</code> to <code>AD2</code> => <code>(AC2 - AC$1) * $AB2</code></li>
<li><code>A1 & "-B1-C1"</code> of <code>B1</code> to <code>B2</code> => <code>A2 & "-B1-C1"</code></li>
</ul>
<p>The difficult part is identifying the cell and handling the <code>$</code>.</p>
<pre><code>public string GetCellForumulaRelative(string formula, int columnOffset, int rowOffset)
{
var cells = formula.Split("+-*/(),:&^>=< ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
// start w/ A-Z
.Where(i => (Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) >= 'A' &&
Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) <= 'Z') ||
Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) == '$')
// end w/ 0-9
.Where(i => Convert.ToChar(i.Substring(i.Length - 1, 1)) >= '0' &&
Convert.ToChar(i.Substring(i.Length - 1, 1)) <= '9');
int startIdx = 0;
foreach (var cell in cells)
{
int sepIdx = cell.IndexOfAny("0123456789".ToCharArray());
if (cell.Substring(sepIdx - 1, 1).Equals("$"))
sepIdx--;
string col = cell.Substring(0, sepIdx);
if (col.StartsWith("$") == false)
col = GetExcelColumnName(ExcelColumnNameToNumber(col) + columnOffset);
string row = cell.Substring(sepIdx);
if (row.StartsWith("$") == false)
row = (Convert.ToInt32(row) + rowOffset).ToString();
startIdx = formula.IndexOf(cell, startIdx);
formula = formula.Substring(0, startIdx) +
col + row +
formula.Substring(startIdx + cell.Length);
startIdx += cell.Length;
}
return formula;
}
</code></pre>
<p>Any suggestions will be appreciated: performance, improvements, one-liners, or bugs.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:42:54.050",
"Id": "20724",
"Score": "1",
"body": "Do you know R1C1 reference style ? It seems to me your are trying to re-invent it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T16:58:07.703",
"Id": "20727",
"Score": "2",
"body": "Have you considered using regular expressions? I get the sudden feeling you could match `@\"\\b$?[A-Z]+$?\\d+\\b\"` and transpose as necessary."
}
] |
[
{
"body": "<p>I haven't used NPOI and I would believe you have valid reasons for using it (I'll take a wild guess at saying the thing is running on a server that doesn't have Excel installed), but for the record, if my memory isn't failing me if you used Microsoft VSTO / Excel Interop, you could use a plain & simple <kbd>Copy</kbd>+<kbd>Paste</kbd> and let Excel do the hard part.</p>\n\n<p>Your code shows how much of a pain this could be otherwise.</p>\n\n<p>That said @ANeves' comment about using <strong>Regular Expressions</strong>, along with @Zonko's comment about <strong>R1C1 references</strong>, could make your code much simpler:</p>\n\n<p>Here's the magic regex: <code>(\\$?[A-Z]+\\$?\\d)(?=([^\"]*\"[^\"]*\")*[^\"]*$)</code></p>\n\n<p>...and the proof (using <a href=\"http://www.ultrapico.com/expresso.htm\" rel=\"nofollow noreferrer\">Expresso</a>):</p>\n\n<p><img src=\"https://i.stack.imgur.com/C7XlP.png\" alt=\"enter image description here\"></p>\n\n<p>So the above regex pattern will spoonfeed you all A1 cell references that you need to analyze - those that aren't surrounded by quotes.</p>\n\n<p>I don't know if NPOI facilitates this in any way (is there a <code>Range</code> object to play with?), but I would highly recommend getting the equivalent R1C1 cell references, so instead of <code>AB$1</code> you get <code>R1C[28]</code>; then you can easily run a [much, <strong>much</strong> simpler] regex on these addresses to get the rows and columns and add your offsets, rebuild the addresses and rebuild the formulas.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T00:37:54.603",
"Id": "35648",
"ParentId": "12837",
"Score": "3"
}
},
{
"body": "<p>You might be interested by the equivalent post on POI (<a href=\"https://stackoverflow.com/questions/1636759/poi-excel-applying-formulas-in-a-relative-way\">https://stackoverflow.com/questions/1636759/poi-excel-applying-formulas-in-a-relative-way</a>).</p>\n\n<p>I have adapted the code from this post to work with C#'s NPOI.</p>\n\n<p>What it simply does is shifting the destination cell row & column ids from the origin cell.</p>\n\n<p>This is made available by the FormulaParser class that extracts ids from the given string formula.</p>\n\n<p>I have tested the below function, it both works on cells & ranges.</p>\n\n<pre><code>public static void CopyUpdateRelativeFormula(ISheet Sheet, ICell FromCell, ICell ToCell)\n{\n if (FromCell == null || ToCell == null || Sheet == null || FromCell.CellType != CellType.Formula) {\n return;\n }\n\n if (FromCell.IsPartOfArrayFormulaGroup()) {\n return;\n }\n\n var MyFormula = FromCell.CellFormula;\n int ShiftRows = ToCell.RowIndex() - FromCell.RowIndex();\n int ShiftCols = ToCell.ColumnIndex() - FromCell.ColumnIndex();\n\n XSSFEvaluationWorkbook WorkbookWrapper = XSSFEvaluationWorkbook.Create((XSSFWorkbook)Sheet.Workbook);\n var Ptgs = FormulaParser.Parse(MyFormula, WorkbookWrapper, FormulaType.Cell, Sheet.Workbook.GetSheetIndex(Sheet));\n\n foreach (void Ptg_loopVariable in Ptgs) {\n Ptg = Ptg_loopVariable;\n if (Ptg is RefPtgBase) {\n // base class for cell references\n RefPtgBase RefPtgBase = (RefPtgBase)Ptg;\n\n if (RefPtgBase.IsColRelative) {\n RefPtgBase.Column = RefPtgBase.Column + ShiftCols;\n }\n\n if (RefPtgBase.IsRowRelative) {\n RefPtgBase.Row = RefPtgBase.Row + ShiftRows;\n }\n } else if (Ptg is AreaPtg) {\n // base class for range references\n AreaPtg RefArea = (AreaPtg)Ptg;\n\n if (RefArea.IsFirstColRelative) {\n RefArea.FirstColumn = RefArea.FirstColumn + ShiftCols;\n }\n\n if (RefArea.IsLastColRelative) {\n RefArea.LastColumn = RefArea.LastColumn + ShiftCols;\n }\n\n if (RefArea.IsFirstRowRelative) {\n RefArea.FirstRow = RefArea.FirstRow + ShiftRows;\n }\n\n if (RefArea.IsLastRowRelative) {\n RefArea.LastRow = RefArea.LastRow + ShiftRows;\n }\n }\n }\n\n MyFormula = FormulaRenderer.ToFormulaString(WorkbookWrapper, Ptgs);\n ToCell.SetCellFormula(MyFormula);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-15T16:21:49.297",
"Id": "234760",
"Score": "2",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-15T15:32:00.660",
"Id": "125780",
"ParentId": "12837",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:04:28.403",
"Id": "12837",
"Score": "6",
"Tags": [
"c#",
"excel"
],
"Title": "Copy Excel formula in a relative way"
}
|
12837
|
<p>I have a custom <code>SPList</code> that has a field <code>Assigned To</code>, now I can add as many items as I want, and they can have same title and same <code>User</code> they are assigned to, but what I want is a script so that I only get the distinct number of user's email address, e.g. if a user is assigned to more then 1 item, I will get there email address just once, here is the code I wrote down but I don't think if its good enough.</p>
<pre><code>using (SPSite site = new SPSite("www.local.com"))
using (SPWeb web = site.OpenWeb())
{
SPList mySourceList = web.Lists["ListName"];
SPQuery mySourceListQuery = new SPQuery();
mySourceListQuery.Query =
"<OrderBy><FieldRef Name='AssignedTo' />" +
"<FieldRef Name='Title' />" +
"</OrderBy>";
SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);
foreach (SPUser user in web.Users)
{
foreach (SPListItem mySourceListItem in mySourceItemColl)
{
name = mySourceListItem["AssignedTo"].ToString();
name = name.Substring(name.IndexOf("#") + 1);
if (user.Name == name)
{
Console.WriteLine(user.Email);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>The <code>my</code> prefixes are unnecessary, I'd call the variables <code>sourceList</code>, <code>sourceListQuery</code>, <code>sourceItems</code> etc.</p></li>\n<li><p>I'd create a method for this:</p>\n\n<pre><code>name = name.Substring(name.IndexOf(\"#\") + 1);\n</code></pre>\n\n<p>I guess <code>removeId</code> could be a good name. The method name would help readers to understand the intent of the writer.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T17:26:54.817",
"Id": "12839",
"ParentId": "12838",
"Score": "2"
}
},
{
"body": "<p>As written, your code will process each item in <code>mySourceItemColl</code> for every user in the site. I would prefer to only go through the collection one time. </p>\n\n<p>As such, I would write it more like this:</p>\n\n<pre><code>using (SPSite site = new SPSite(\"www.local.com\"))\n using (SPWeb web = site.OpenWeb())\n {\n SPList list = web.Lists[\"ListName\"];\n SPQuery query = new SPQuery();\n query.Query =\n \"<OrderBy><FieldRef Name='AssignedTo' />\" +\n \"<FieldRef Name='Title' />\" +\n \"</OrderBy>\";\n SPitemCollection items = list.Getquery(query);\n List<string> emails = new List<string>();\n foreach (SPListItem item in items)\n {\n SPFieldUserValue value = \n new SPFieldUserValue(web, item[\"AssignedTo\"].ToString());\n if (null != value && \n null != value.User && \n !emails.Contains(value.User.Email)) \n {\n emails.Add(value.User.Email);\n Console.WriteLine(value.User.Email);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:11:11.607",
"Id": "12843",
"ParentId": "12838",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:42:18.513",
"Id": "12838",
"Score": "2",
"Tags": [
"c#",
"sharepoint"
],
"Title": "Getting SharePoint users and comparing them with SPList"
}
|
12838
|
<p>I've got a fairly performance sensitive need for fast prefix lookup, and I've built two different implementations trying to optimize for my use case. The first is built off a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a> implementation, and the second uses binary search. Testing them both, the Trie provides faster lookup, and much faster insertion, but dramatically slower initialization, which is my primary concern.</p>
<p>I'm looking for ways to optimize either of these tools, and would very much appreciate help improving initialization time of the Trie, or search/insert time of the binary search.</p>
<p>I know it's a fair bit of code, I <a href="https://gist.github.com/2981061" rel="nofollow">posted it on gist</a> if people find that more convenient.</p>
<p><strong>error.py</strong> Shared exceptions</p>
<pre><code>class UnknownPrefix(Exception):
'''Raised if a given prefix does not map to any items'''
def __init__(self,prefix,*args):
Exception.__init__(self,*args)
self.prefix = prefix
class AmbiguousPrefix(Exception):
'''Raised if a given prefix maps to multiple items'''
def __init__(self,prefix,choices,*args):
Exception.__init__(self,*args)
self.prefix = prefix
self.choices = choices
</code></pre>
<p><strong>tprefix.py</strong> Trie Prefix Implementation</p>
<pre><code>import error;
class Prefix:
'''
A trie datastructure (http://en.wikipedia.org/wiki/Trie) which enables
fast data retrieval by prefix.
Note that for more reasonable lookup, the trie only searches in lower
case. This means there can be colliding strings such as 'prefix' vs 'Prefix'.
In this case, more recent inserts override older ones.
'''
def __init__(self,ls=[]):
self._root = _Node(None,None,True)
self._aliases = {}
for i in ls:
self._root.add(i.lower(),i)
def __getitem__(self, prefix):
'''Return the item with the given prefix.
If more than one item matches the prefix an AmbiguousPrefix exception
will be raised, unless the prefix is the entire ID of one task.
If no items match the prefix an UnknownPrefix exception will be raised.
If an item exactly matches the prefix, it will be returned even if
there exist other (longer) items which match the prefix
'''
matched = self._root[prefix.lower()]
if (matched is None or
(matched.result is None and len(matched.children) == 0) or
# this is needed because prefix will return if prefix
# is longer than necessary, and the necessary part
# matches, but the extra text does not
(matched.key is not None and not matched.key.startswith(prefix.lower()))):
raise error.UnknownPrefix(prefix)
if matched.result is not None:
if matched.result in self._aliases:
return self._aliases[matched.result]
else: return matched.result
else:
raise error.AmbiguousPrefix(prefix,iter(matched))
def prefix(self,item):
'''Return the unique prefix of the given item, or None if not found'''
return self._root.prefix(item.lower())
def pref_str(self,pref,short=False):
'''returns the item with a colon indicating the shortest unique prefix'''
item = self[pref]
pref = self.prefix(item)
tail = item[len(pref):]
return item[:len(pref)]+':'+(tail[:4]+('...' if len(tail) > 4 else '') if short else tail)
def add(self,item):
'''Add an item to the data structure'''
self._root.add(item.lower(),item,0)
def alias(self,alias,item):
'''Add an item to the trie which maps to another item'''
self._aliases[alias] = self[item]
self.add(alias)
def __iter__(self):
return iter(self._root)
class _Node:
'''Represents a node in the Trie. It contains either
an exact match, a set of children, or both
'''
def __init__(self, key, item, final=False):
'''Constructs a new node which contains an item'''
self.final = final
self.key = key
self.result = item
self.children = {}
def _tree(self):
'''Returns a tree structure representing the trie. Useful for debugging'''
return "( %s%s, { %s } )" % (self.result, '*' if self.final else '',
', '.join(["%s: %s" % (k,v._tree()) for (k,v) in self.children.items()]))
def add(self,key,item,depth=0):
'''Adds an item at this node or deeper. Depth indicates
which index is being used for comparison'''
# the correct node has been found, replace result with new value
if self.key is not None and key == self.key:
self.result = item #this would override an old value
return
# this is currently a leaf node, move the leave one down
if self.result is not None and not self.final:
if self.key == None: print(self.key,self.result,key,item)
key_letter = self.key[depth]
self.children[key_letter] = _Node(self.key,self.result,len(self.key)==depth+1)
self.key = None
self.result = None
if len(item) == depth:
self.key = key
self.result = item #this could override an old value
self.final = True
return
letter = key[depth]
if letter in self.children:
child = self.children[letter]
child.add(key,item,depth+1)
else:
self.children[letter] = _Node(key,item,len(key) == depth+1)
def __getitem__(self,prefix):
'''Given a prefix, returns the node that matches
This will either have a result, or if not the prefix
was ambiguous. If None is returned, there was no
such prefix'''
if len(prefix) == 0 or len(self.children) == 0:
return self
letter = prefix[0]
if letter in self.children:
return self.children[letter][prefix[1:]]
else: return None
def prefix(self,item):
'''Given an item (or a prefix) finds the shortest
prefix necessary to reach the given item.
None if item does not exist.'''
if len(item) == 0 or len(self.children) == 0:
return ''
letter = item[0]
if letter in self.children:
child = self.children[letter].prefix(item[1:])
if child is not None:
return letter + child
return None
def __iter__(self):
'''Yields items in and below this node'''
if self.result:
yield self.result
for k in sorted(self.children.keys()):
for res in self.children[k]:
yield res
</code></pre>
<p><strong>bprefix.py</strong> Binary Search Prefix Implementation</p>
<pre><code>import bisect
import error;
class Prefix:
'''
A prefix data structure built on a sorted list, which uses binary search.
Note that for more reasonable lookup, it only searches in lower
case. This means there can be colliding strings such as 'prefix' vs 'Prefix'.
In this case, more recent inserts override older ones.
'''
def __init__(self, ls=[], presorted=False):
self._aliases = {}
self._list = ls if presorted else sorted(ls)
self._keys = [s.lower() for s in self._list]
# Note that since we usually use these methods together, it's wasteful to
# Compute prefix.lower() for both - as such, these methods assume prefix
# is already lower case.
def _getindex(self, prefix):
return bisect.bisect_left(self._keys, prefix)
def _getnextindex(self, prefix):
# http://stackoverflow.com/a/7381253/113632
lo, hi = 0, len(self._keys)
while lo < hi:
mid = (lo+hi)//2
if prefix < self._keys[mid] and not self._keys[mid].startswith(prefix): hi = mid
else: lo = mid+1
return lo
def __getitem__(self, prefix):
'''Return the item with the given prefix.
If more than one item matches the prefix an AmbiguousPrefix exception
will be raised, unless the prefix is the entire ID of one task.
If no items match the prefix an UnknownPrefix exception will be raised.
If an item exactly matches the prefix, it will be returned even if
there exist other (longer) items which match the prefix
'''
pre = prefix.lower()
ret = self._list[self._getindex(pre):self._getnextindex(pre)]
if ret:
if len(ret) == 1 or ret[0].lower() == pre:
return ret[0]
raise error.AmbiguousPrefix(prefix,ret)
raise error.UnknownPrefix(prefix)
def prefix(self, item):
'''Return the unique prefix of the given item, or None if not found'''
ln = len(self._keys)
item = item.lower()
index = self._getindex(item)
if index >= ln:
return None
match = self._keys[index]
if not match.startswith(item):
return None
siblings = []
if index > 0:
siblings.append(self._keys[index-1])
if index < ln-1:
siblings.append(self._keys[index+1])
if not siblings: #list contains only item
return match[0]
return self._uniqueprefix(match,siblings)
def _uniqueprefix(self,match,others):
'''Returns the unique prefix of match, against the set of others'''
ret = []
#print("START:",match,others)
while match:
others = [s[1:] for s in others if s and s[0] == match[0]]
ret.append(match[0])
match = match[1:]
#print("WHILE:",match,others,''.join(ret))
if not others:
return ''.join(ret)
return None
def add(self,item):
'''Add an item to the data structure.
This uses list.insert() which is O(n) - for many insertions,
it may be dramatically faster to simply build a new Prefix entirely.'''
lower = item.lower()
index = self._getindex(lower)
# If overwriting same key
if index < len(self._keys) and self._keys[index] == lower:
self._list[index] = item
else:
self._keys.insert(index,lower)
self._list.insert(index,item)
def alias(self,alias,item):
'''Add an item to the trie which maps to another item'''
self._aliases[alias] = self[item]
self.add(alias)
def pref_str(self,pref,short=False):
'''returns the item with a colon indicating the shortest unique prefix'''
item = self[pref]
pref = self.prefix(item)
tail = item[len(pref):]
return item[:len(pref)]+':'+(tail[:4]+('...' if len(tail) > 4 else '') if short else tail)
def __iter__(self):
return iter(self._list)
</code></pre>
<p><strong>test.py</strong> Series of testing / timing functions</p>
<pre><code>import hashlib,time
import bprefix,tprefix
def timed(f):
def func(*args):
start = time.time()
ret = f(*args)
took = time.time() - start
print("%s took %f" % (f.__name__,took))
return ret
return func
def get_generator(top=250000,static="Static_String"):
return (hashlib.sha1((static+str(i)).encode('utf-8')).hexdigest() for i in range(top))
@timed
def build_from_list(cls):
return cls(get_generator())
@timed
def build_from_adds(cls):
pref = cls()
for s in get_generator(10000):
pref.add(s)
return pref
@timed
def add_to(obj):
for s in get_generator(10000,"Different_String"):
obj.add(s)
@timed
def get(obj,loops=10000):
for _ in range(loops):
obj['000188']
obj['1971e']
obj['336f7']
obj['4d120']
obj['66ada']
obj['80736']
obj['99cb0']
obj['b38f3']
obj['ccfd9e8']
obj['e61df']
@timed
def prefix(obj,loops=10000):
for _ in range(loops):
obj.prefix('00018855b442bfba15fae6949982ef63d9eba1c9')
obj.prefix('1971e17df8ee57f0dcceccc869db454b7c6b7a54')
obj.prefix('336f7b09c7c0c933b1f26ca09a84585818046e6b')
obj.prefix('4d1209fadf843f65bd2beee37db552134a930395')
obj.prefix('66adaf0cb611d71554153631611f7904781addef')
obj.prefix('80736f454201d96c4c795bb5e21778550a9cbef0')
obj.prefix('99cb006fd81cb84cfbae834ed7b7f977c29af249')
obj.prefix('b38f3561591650708fce739536ac504f86fecdf5')
obj.prefix('ccfd9e8211621666c55f911d1ff3f13ab93f696e')
obj.prefix('e61df82a0c2f59394eb9bd752e93b9c011df5be2')
@timed
def iter(obj):
for s in obj:
len(s)
def run_tests(cls):
pref = build_from_list(cls)
build_from_adds(cls)
add_to(pref)
get(pref)
prefix(pref)
iter(pref)
if __name__ == '__main__':
print("TRIE STRUCTURE")
run_tests(tprefix.Prefix)
print("BINARY SEARCH STRUCTURE")
run_tests(bprefix.Prefix)
</code></pre>
<p><strong>Output of test.py</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>TRIE STRUCTURE
build_from_list took 5.736888
build_from_adds took 0.189277
add_to took 0.193403
get took 1.103995
prefix took 1.000542
iter took 1.205267
BINARY SEARCH STRUCTURE
build_from_list took 1.382333
build_from_adds took 0.123948
add_to took 2.092292
get took 2.206803
prefix took 2.141418
iter took 0.071968
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:34:13.210",
"Id": "20751",
"Score": "1",
"body": "Do you think about pure C character trie implementation, wrapped into python extension like:https://github.com/buriy/python-chartrie"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T10:13:42.870",
"Id": "20752",
"Score": "0",
"body": "Your errors could probably just be KeyError and ValueError. Avoid introducing new types unless they really do need special handling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T13:52:58.100",
"Id": "20760",
"Score": "0",
"body": "@cat_baxter - I do, but C is outside my expertise. I'll see if I can't get your link to work though, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T13:56:54.770",
"Id": "20761",
"Score": "0",
"body": "@Daenyth - Hmm, I thought of them both as types of KeyErrors - you think Ambiguous should be a ValueError? They do provide additional information, access to the input and the error, and I use that additional information, does that count as special handling? It would make sense I think for them to inherit from Key/ValueError, rather than Exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T14:13:25.973",
"Id": "20766",
"Score": "0",
"body": "Is there a case where you'd handle your error differently than a KeyError? Or ValueError for invalid (duplicate) input? If the only thing that's different is the name of the exception, just put that information in the error message and use a builtin type - it makes your tools easier to use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T15:49:06.387",
"Id": "20785",
"Score": "0",
"body": "@Daenyth well my program uses prefix lookups for several different structures (IDs, usernames, commands, etc.) and the behavior is different depending on the use case, so it's quite helpful for me to access the passed prefix and list of choices directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T15:19:29.490",
"Id": "20949",
"Score": "0",
"body": "@cat_baxter With the help of the developer, I gave the C implementation you linked to a try, but unfortunately it's not built to enable longest prefix match."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-16T21:39:42.493",
"Id": "25436",
"Score": "0",
"body": "You may also try http://pypi.python.org/pypi/datrie/ which is an another fast trie implementation with many features."
}
] |
[
{
"body": "<p>If you need performance I would suggest <a href=\"http://biopython.org\" rel=\"nofollow\">BioPython Library</a> It has nice and very fast implementation of trie with prefix search, serialization, etc.</p>\n\n<p>It's a small example using word file (~179.000 words):</p>\n\n<pre><code>from Bio import trie\nimport StringIO\nimport time\n\nwords = open('twl06.txt').read().split()\n\nstime = time.time()\nt = trie.trie()\nfor word in words:\n t[word] = 1\nprint \"Building time (s)\", time.time()-stime\n\nstime = time.time()\nprint t.with_prefix(\"HELLO\")\nprint \"Searching time (s)\", time.time()-stime\n\nstime = time.time()\nf = open('trie.bin','wb')\ntrie.save(f, t)\nf.close()\nprint \"Serialization time time (s)\", time.time()-stime\n\nstime = time.time()\nf = open('trie.bin','rb')\nt1 = trie.load(f)\nf.close()\nprint \"Deserialization time time (s)\", time.time()-stime\n\nprint t1.with_prefix(\"HELLO\")\n</code></pre>\n\n<p>And the output:</p>\n\n<pre><code>d:\\python27\\python test.py\nBuilding time (s) 0.18799996376\n['HELLO', 'HELLOED', 'HELLOES', 'HELLOING', 'HELLOS']\nSearching time (s) 0.0\nSerialization time time (s) 0.953000068665\nDeserialization time time (s) 0.766000032425\n['HELLO', 'HELLOED', 'HELLOES', 'HELLOING', 'HELLOS']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-26T08:53:47.947",
"Id": "13065",
"ParentId": "12841",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T18:57:02.350",
"Id": "12841",
"Score": "10",
"Tags": [
"python",
"performance",
"binary-search",
"lookup"
],
"Title": "Implementations of prefix lookup tables"
}
|
12841
|
<p><a href="http://backbonejs.org" rel="nofollow">Backbone.js</a> is a client-side JavaScript framework that gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.</p>
<p>Backbone.js uses <a href="/questions/tagged/underscore.js" class="post-tag" title="show questions tagged 'underscore.js'" rel="tag">underscore.js</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:22:29.670",
"Id": "12844",
"Score": "0",
"Tags": null,
"Title": null
}
|
12844
|
Backbone.js is a JavaScript framework that provides structure to RESTful web applications.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:22:29.670",
"Id": "12845",
"Score": "0",
"Tags": null,
"Title": null
}
|
12845
|
SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:23:33.927",
"Id": "12847",
"Score": "0",
"Tags": null,
"Title": null
}
|
12847
|
<p><a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/index.html" rel="nofollow">Emacs Lisp</a> is the extension language for the <a href="http://www.gnu.org/software/emacs/" rel="nofollow">GNU Emacs text editor</a>, and in fact, most of the functionality of Emacs is implemented using Emacs Lisp. Users generally customize Emacs' behavior by adding Emacs Lisp statements to their <code>.emacs</code> file, or writing separate packages. A guide to learning Emacs Lisp for non-programmers can be found <a href="http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/index.html" rel="nofollow">here</a>.</p>
<p>Emacs Lisp differs from most other lisps in two main ways:</p>
<ol>
<li>It has special features for scanning and parsing text, as well as features for handling files, buffers, arrays, displays, and subprocesses. This is due to the fact that it is designed to be used in a text editor</li>
<li>It uses primarily <a href="http://en.wikipedia.org/wiki/Scope_%28programming%29#Dynamic_scoping" rel="nofollow">dynamic scope</a> as opposed to lexical scope. This was done very intentionally, the reasons are well explained in the <a href="http://www.gnu.org/software/emacs/emacs-paper.html#SEC17" rel="nofollow">1981 paper</a> on Emacs. Lexical scope has been introduced only recently and, while not yet widely adopted, is expected to become increasingly important in future versions according to <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Lexical-Binding.html" rel="nofollow">the manual</a>.</li>
</ol>
<h2>Wisdom from the Stack</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/154097/whats-in-your-emacs">What's in your .emacs?</a></li>
<li><a href="http://stackoverflow.com/questions/41522/tips-for-learning-elisp">Tips for learning Elisp?</a></li>
<li><a href="http://stackoverflow.com/questions/2241111/lisp-community-quality-tutorials-resources">Lisp Community - Quality tutorials/resources</a></li>
<li><a href="http://stackoverflow.com/questions/2087532/troubleshooting-techniques-for-emacs-and-elisp">Troubleshooting techniques for Emacs and Elisp</a> </li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:24:26.437",
"Id": "12848",
"Score": "0",
"Tags": null,
"Title": null
}
|
12848
|
Emacs Lisp is the extension language for the GNU Emacs text editor, and in fact, most of the functionality of Emacs is implemented using Emacs Lisp. Users generally customize Emacs' behavior by adding Emacs Lisp statements to their .emacs, or writing separate packages.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:24:26.437",
"Id": "12849",
"Score": "0",
"Tags": null,
"Title": null
}
|
12849
|
<p>RSpec is a <a href="http://en.wikipedia.org/wiki/Behavior-driven_development" rel="nofollow">behaviour-driven development</a> (BDD) tool for Ruby programmers. BDD is an approach to software development that combines <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow">test-driven development</a> (TDD), <a href="http://en.wikipedia.org/wiki/Domain-driven_design" rel="nofollow">domain-driven design</a> (DDD), and acceptance test-driven planning (ATDP). RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:27:16.693",
"Id": "12850",
"Score": "0",
"Tags": null,
"Title": null
}
|
12850
|
RSpec is a behaviour-driven development (BDD) framework for the Ruby language.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:27:16.693",
"Id": "12851",
"Score": "0",
"Tags": null,
"Title": null
}
|
12851
|
<p>Web services can either be defined using the Web Services Description Language (WSDL) and consumed via Simple Object Access Protocol (SOAP), or follow a Representational State Transfer (REST) model.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:28:38.920",
"Id": "12852",
"Score": "0",
"Tags": null,
"Title": null
}
|
12852
|
<h1>What is Groovy?</h1>
<p>Groovy is a dynamic object-oriented programming language for the Java virtual machine (JVM) that can be used anywhere Java is used. The language can be used to combine Java modules, extend existing Java applications and write new applications.</p>
<p>Groovy can serve as a scripting language for developers new to the Java platform and can also be useful for veteran Java developers interested in enhancing the expediency and flexibility of that language.</p>
<p>Groovy has a Java-like syntax and works seamlessly with Java bytecode. Many of the language's features resemble those of Perl, Python, Ruby and Smalltalk.</p>
<p><em>Excerpt taken from <a href="http://whatis.techtarget.com/definition/Groovy" rel="nofollow">WhatIs.com</a></em></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:29:13.990",
"Id": "12854",
"Score": "0",
"Tags": null,
"Title": null
}
|
12854
|
Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:29:13.990",
"Id": "12855",
"Score": "0",
"Tags": null,
"Title": null
}
|
12855
|
Pthreads (POSIX Threads) is a standardised C-based API for creating and manipulating threads on a POSIX-compliant system. It is defined by the standard "POSIX.1c, Threads extensions (IEEE Std 1003.1c-1995)", and subsequently by the Single Unix Specification.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:34:23.640",
"Id": "12857",
"Score": "0",
"Tags": null,
"Title": null
}
|
12857
|
<p>I am new to Python and want to have a "pythonic" coding style from the very beginning. Following is a piece of codes I wrote to generate all combinations and permutations of a set of symbols, e.g. <code>abc</code> or <code>123</code>. I mainly seek for suggestions on code style but comments on other aspects of codes are also welcome. </p>
<pre><code>import random as rd
import math as m
def permutationByRecursion(input, s, li):
if len(s) == len(input):
li.append(s)
for i in range(len(input)):
if input[i] not in s:
s+=input[i]
permutationByRecursion(input, s, li)
s=s[0:-1]
def combinationByRecursion(input, s, idx, li):
for i in range(idx, len(input)):
s+=input[i]
li.append(s)
print s, idx
combinationByRecursion(input, s, i+1, li)
s=s[0:-1]
def permutationByIteration(input):
level=[input[0]]
for i in range(1,len(input)):
nList=[]
for item in level:
nList.append(item+input[i])
for j in range(len(item)):
nList.append(item[0:j]+input[i]+item[j:])
level=nList
return nList
def combinationByIteration(input):
level=['']
for i in range(len(input)):
nList=[]
for item in level:
nList.append(item+input[i])
level+=nList
return level[1:]
res=[]
#permutationByRecursion('abc', '', res)
combinationByRecursion('abc', '', 0, res)
#res=permutationByIteration('12345')
print res
print combinationByIteration('abc')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:18:53.517",
"Id": "20745",
"Score": "1",
"body": "Just in case you didn't know, python has permutations and combinations in itertools package in stdlib."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T14:54:13.820",
"Id": "20881",
"Score": "0",
"body": "@blufox, i am aware of it, just wrote the program for practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-04T09:40:04.770",
"Id": "21498",
"Score": "0",
"body": "@pegasus, I know blufox and cat_baxter pointed out itertools and I assume you've seen it but for anybody else [the python docs contain](http://docs.python.org/library/itertools.html#itertools.permutations) code samples for both permutation and combination"
}
] |
[
{
"body": "<p>Just use the standard modules :)</p>\n\n<pre><code>import itertools\nfor e in itertools.permutations('abc'):\n print(e)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T14:55:29.370",
"Id": "20882",
"Score": "1",
"body": "thanks, I am aware of it. Just wrote it for practicing python"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:08:48.337",
"Id": "12860",
"ParentId": "12858",
"Score": "10"
}
},
{
"body": "<p>A small change, In python, it is more idiomatic to use generators to generate items rather than to create lists fully formed. So,</p>\n\n<pre><code>def combinationG(input):\n level=['']\n</code></pre>\n\n<p>You could directly enumerate on each character here.</p>\n\n<pre><code> for v in input:\n nList=[]\n for item in level:\n new = item + v\n</code></pre>\n\n<p>Yield is the crux of a generator.</p>\n\n<pre><code> yield new\n nList.append(new)\n level+=nList\n</code></pre>\n\n<p>Using it </p>\n\n<pre><code>print list(combinationG(\"abc\"))\n</code></pre>\n\n<p>Note that if you want access to both index and value of a container you can use <code>for i,v in enumerate(input)</code></p>\n\n<p>Here is the recursive implementation of permutation. Notice that we have to yield on the value returned by the recursive call too.</p>\n\n<pre><code>def permutationG(input, s):\n if len(s) == len(input): yield s\n for i in input:\n if i in s: continue\n s=s+i\n for x in permutationG(input, s): yield x\n s=s[:-1]\n\n\nprint list(permutationG('abc',''))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:34:18.240",
"Id": "12862",
"ParentId": "12858",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "12862",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T04:47:38.713",
"Id": "12858",
"Score": "8",
"Tags": [
"python",
"reinventing-the-wheel"
],
"Title": "Generating all combinations and permutations of a set of symbols"
}
|
12858
|
<p><strong>Problem</strong>
Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.</p>
<p><img src="https://i.stack.imgur.com/VN3Ue.gif" alt="enter image description here">
How many routes are there through a 2020 grid?</p>
<p><strong>Solution</strong>
Here is my solution</p>
<pre><code> def step(i,j):
if(i==20 or j==20):
return 1
return step(i+1,j)+step(i,j+1)
print step(0,0)
</code></pre>
<p>But this takes too long to run, how can this be optimized?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:51:30.230",
"Id": "20746",
"Score": "2",
"body": "How to add memoization? Write a decorator to store the results. This is a common homework problem so I'll leave it at that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T08:04:52.757",
"Id": "20747",
"Score": "0",
"body": "@JeffMercado I tried doing that and it wasn't working, but it worked now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T08:10:23.140",
"Id": "20748",
"Score": "0",
"body": "a google search returns http://en.wikipedia.org/wiki/Central_binomial_coefficient"
}
] |
[
{
"body": "<p>Finally my memoization technique worked and the result appears in less than a sec</p>\n\n<pre><code> cache = []\nfor i in range(20):\n cache.append([])\n for j in range(20):\n cache[i].append(0)\n\ndef step(i,j):\n if(i==2 or j==2):\n return 1\n if(cache[i][j]>0):\n return cache[i][j]\n cache[i][j] = step(i+1,j)+step(i,j+1)\n return cache[i][j]\nprint step(0,0)\n</code></pre>\n\n<p>Another optimization I have added (since step(i,j) is same as step(j,i)) </p>\n\n<pre><code> cache = []\nfor i in range(20):\n cache.append([])\n for j in range(20):\n cache[i].append(0)\n\ndef step(i,j):\n if(i==20 or j==20):\n return 1\n if(cache[i][j]>0):\n return cache[i][j]\n cache[i][j] = step(i+1,j)+step(i,j+1)\n cache[j][i] = cache[i][j]\n return cache[i][j]\nprint step(0,0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T08:04:15.927",
"Id": "12863",
"ParentId": "12861",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "12863",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:29:44.907",
"Id": "12861",
"Score": "2",
"Tags": [
"python",
"project-euler"
],
"Title": "How do I add memoization to this problem?"
}
|
12861
|
<p>Open source software is software distributed under an open source license. Such a license specifially allow anyone to copy, modify and redistribute the source code without paying royalties or fees. There are dozens of open source licenses. To determine whether a particular license should be considered an Open Source License, the <a href="http://opensource.org/" rel="nofollow">Open Source Initiative</a> has created an <a href="http://opensource.org/docs/osd" rel="nofollow">Open Source Definition</a>.</p>
<p>Open source code often, but not always, evolves through community cooperation. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:50:57.147",
"Id": "12866",
"Score": "0",
"Tags": null,
"Title": null
}
|
12866
|
Design pattern to reduce coupling between components, by dynamically injecting into a software component dependencies that it needs to function.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:51:50.877",
"Id": "12869",
"Score": "0",
"Tags": null,
"Title": null
}
|
12869
|
<h2>Definition:</h2>
<p>SharePoint 2016 is Microsoft's document management and collaboration tool with a software-as-a-service strategy at its core. Like SharePoint 2013, the product is offered in the cloud as part of the Office 365 suite and is known as SharePoint Online; the on-premises version is known as SharePoint Server 2016.</p>
<p>SharePoint comprises a multipurpose set of Web technologies backed by a common technical infrastructure. By default, SharePoint has a Microsoft Office-like interface, and it is closely integrated with the Office suite.</p>
<h2>Products:</h2>
<p>This family of products include:</p>
<ul>
<li>Microsoft SharePoint 2010</li>
<li>Microsoft SharePoint 2013</li>
<li>Microsoft SharePoint 2016</li>
<li>Microsoft SharePoint Online (Office 365)</li>
<li>Microsoft Office SharePoint Server</li>
<li>Windows SharePoint Services</li>
<li>Microsoft SharePoint Foundation</li>
<li>Microsoft Search Server</li>
<li>Microsoft SharePoint Designer</li>
<li>Microsoft SharePoint Workspace</li>
</ul>
<h2>Links:</h2>
<p><a href="https://products.office.com/en-us/sharepoint/sharepoint-server" rel="nofollow noreferrer">https://products.office.com/en-us/sharepoint/sharepoint-server</a>
<a href="https://products.office.com/en/sharepoint/collaboration" rel="nofollow noreferrer">https://products.office.com/en/sharepoint/collaboration</a>
<a href="https://en.wikipedia.org/wiki/SharePoint" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/SharePoint</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:52:53.250",
"Id": "12870",
"Score": "0",
"Tags": null,
"Title": null
}
|
12870
|
The computer program yacc is a parser generator developed by Stephen C. Johnson at AT&T for the Unix operating system.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:53:26.673",
"Id": "12873",
"Score": "0",
"Tags": null,
"Title": null
}
|
12873
|
Simple Object Access Protocol (SOAP) is a protocol specification for exchanging structured information in the implementation of Web Services.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:55:11.087",
"Id": "12875",
"Score": "0",
"Tags": null,
"Title": null
}
|
12875
|
<p>The performance of applications is often a paramount concern for mission-critical systems. If your question pertains to execution-time optimization, whether it be database queries, algorithms, or anything that deals with speed or throughput, consider using this tag.</p>
<p>The two main measures of performance are</p>
<ol>
<li><strong>Throughput</strong> (how many in a time frame). Example of units: transactions per second (TPS), megabytes per second (MB/s), gigabits per second (Gb/s), messages/request/pages per second.</li>
<li><strong>Latency</strong> (how long for an action). For example, seek time of 8 ms and search time of 100 ms.</li>
</ol>
<p>Latency is often qualified with a statistical measure. Note: latencies usually don't follow a <a href="https://en.wikipedia.org/wiki/Normal_distribution" rel="nofollow noreferrer">normal distribution</a> and have very high upper limits compared with the average latency. As such the <a href="https://en.wikipedia.org/wiki/Standard_deviation" rel="nofollow noreferrer">standard deviation</a> is not useful.</p>
<ul>
<li>Average latency. The average of all the latencies.</li>
<li>Typical or <a href="https://en.wikipedia.org/wiki/Median" rel="nofollow noreferrer">median</a> latency. The mid-point of the range of possible latencies. This is usually 50% to 90% of the average latency. As this is the lowest figure it is often reported by vendors.</li>
<li>Percentile latency. The figure is less than or equal to N% of the time. That is, 99 percentile if the latency is not more than this, 99 times out of 100.</li>
<li>Worst or maximum latency. The highest latency measured.</li>
</ul>
<p>When seeking to improve performance: prototype and measure first, optimize only if and where needed. A majority of languages have ways of <a href="https://en.wikipedia.org/wiki/Profiling_(computer_programming)" rel="nofollow noreferrer">profiling</a> your code, which can help you determine which parts of your code take the most time to execute. For example, Python has <a href="https://docs.python.org/3/library/profile.html" rel="nofollow noreferrer">several profilers</a>, and a popular Java profiler could be <a href="https://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a>.</p>
<p><strong>See also:</strong> <a href="/questions/tagged/optimization" class="post-tag" title="show questions tagged 'optimization'" rel="tag">optimization</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-06-21T09:58:05.683",
"Id": "12876",
"Score": "0",
"Tags": null,
"Title": null
}
|
12876
|
Performance is a subset of Optimization: performance is the goal when you want the execution time of your program or routine to be optimal.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T09:58:05.683",
"Id": "12877",
"Score": "0",
"Tags": null,
"Title": null
}
|
12877
|
<p>I'm pretty sure there's a way to make this "3 times" duplicated code into only one. Any idea how to do this?</p>
<pre><code>if (typeof sync.create!='undefined') {
for (var i = 0; i <sync.create.length; i++) {
sync.create[i].modified.id_partenaire=false;
};
}
if (typeof sync.update!='undefined') {
for (var i = 0; i <sync.update.length; i++) {
sync.update[i].modified.id_partenaire=false;
};
}
if (typeof sync.destroy!='undefined') {
for (var i = 0; i <sync.destroy.length; i++) {
sync.destroy[i].modified.id_partenaire=false;
};
}
</code></pre>
|
[] |
[
{
"body": "<p>If this should be executed on all properties of <code>sync</code> in general, i'd go with a <code>for..in</code> loop. </p>\n\n<pre><code>for(var prop in sync){\n if(sync.hasOwnProperty(prop) && typeof sync[prop] !== 'undefined'){\n var i=0, l = sync[prop].length;\n for (i; i < l; i+=1) {\n sync[prop][i].modified.id_partenaire=false;\n };\n }\n}\n</code></pre>\n\n<p>Otherwise, if there are more properties and this should only be applied to these 3, Esailija's answer works better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T09:12:07.443",
"Id": "20852",
"Score": "0",
"body": "I didn't want on all properties, but thank you very much for you suggestion, this may help for other object / properties manipulations in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T11:05:17.170",
"Id": "12881",
"ParentId": "12879",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T10:52:04.107",
"Id": "12879",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Handling create, update, and destroy for sync"
}
|
12879
|
<p>I am developing data-interfacing that converts between two different data models.
However, I must be sure that all required fields exist. Therefore I have written this utility class that I can easily use to verify required fields.</p>
<p>However I am unsure whether this is the best way because of the expression that needs to be compiled and the usage of reflection. Any feedback is welcome!</p>
<p><strong>Usage</strong></p>
<pre><code> public OutputDataElement DetermineRetailTransactionShopperType(IHeaderEntity headerEntity)
{
Ensure.IsNotNull(() => headerEntity);
Ensure.IsNotNull(() => headerEntity.ShopId, "headerEntity");
// Some mapping logic removed from the example
}
</code></pre>
<p><strong>Utility</strong></p>
<pre><code>/// <summary>
/// Helper class able to ensure expectations
/// </summary>
public static class Ensure
{
public static void IsNotNull<T>(Expression<Func<T>> property) where T : class
{
IsNotNullImpl(property, null);
}
public static void IsNotNull<T>(Expression<Func<T>> property, string paramName) where T : class
{
IsNotNullImpl(property, paramName);
}
private static void IsNotNullImpl<T>(Expression<Func<T>> property, string paramName) where T : class
{
// Compile the linq expression
Func<T> compiledFunc = property.Compile();
// Invoke the linq expression to get the value
T fieldValue = compiledFunc.Invoke();
// Check whether we have a value
if ((fieldValue is string && fieldValue.ToString() == string.Empty) || (fieldValue == null))
{
// We have no value. Get the initial expression
var expression = (MemberExpression)property.Body;
// log information about the expression that failed
throw new ArgumentException(string.Format("Missing required field '{0}'", expression.Member.Name), string.IsNullOrEmpty(paramName) ? null : paramName);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't see any unnecessary reflection in your code.</p>\n\n<p>One think that could be simplified is your check for <code>string.Empty</code>:</p>\n\n<pre><code>if (fieldValue == null || fieldValue as string == string.Empty)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T23:58:50.053",
"Id": "21611",
"Score": "0",
"body": "Hmm, Just because `fieldValue != null`, doesn't mean you can cast it as a string without throwing an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-06T00:47:15.153",
"Id": "21613",
"Score": "0",
"body": "I just simplified the code that was in the question. I don't understand why would it have to throw an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-06T03:56:39.980",
"Id": "21615",
"Score": "0",
"body": "He checked fieldValue is string before casting it to a string. If you cast something that's not a string to a string it's not the same as calling Object.ToString() - it will cause an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-06T07:24:44.113",
"Id": "21631",
"Score": "0",
"body": "That's exactly why I'm using `as`. It will never throw an exception. If the object is a different type, it will return `null`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T13:09:04.460",
"Id": "12886",
"ParentId": "12882",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "12886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T11:42:44.380",
"Id": "12882",
"Score": "4",
"Tags": [
"c#",
"linq",
"reflection"
],
"Title": "Usage of Expression<Func<T>>"
}
|
12882
|
<p>I've been learning Python 2.7 for about a week now and have written a quick program to ask for names of batters and printing a score sheet. I have then added the names to a list which I will use more in other future functions.</p>
<p>I have a few questions:</p>
<ol>
<li><p>I feel like there is too much repetition in my code, such as the prompting for each batter and all the printing. I am trying to figure out how I could use a loop to do these for me. Since I know I need 11 batters a <code>for</code> loop would be best but I need to make a new variable each time, how can I do this?</p></li>
<li><p>I have been reading around about the use of <code>global</code>. I can't seem to get a definite answer but is this the correct use if I want to use a variable from one function in multiple others?</p></li>
</ol>
<p></p>
<pre><code>def Input_Players():
global First, Second, Third, Fourth, Fith, Sixth, Seventh, Eigth, Ninth, Tenth, Eleventh
First = [raw_input("Name of 1st Batsman > ")]
Second = [raw_input("Name of 2nd Batsman > ")]
Third = [raw_input("Name of 3rd Batsman > ")]
Fourth = [raw_input("Name of 4th Batsman > ")]
Fith = [raw_input("Name of 5th Batsman > ")]
Sixth = [raw_input("Name of 6th Batsman > ")]
Seventh = [raw_input("Name of 7th Batsman > ")]
Eigth = [raw_input("Name of 8th Batsman > ")]
Ninth = [raw_input("Name of 9th Batsman > ")]
Tenth = [raw_input("Name of 10th Batsman > ")]
Eleventh = [raw_input("Name of 11th Batsman > ")]
def Print_Score_Sheet():
total_chars = 56
Batsman = First + Second + Third + Fourth + Fith + Sixth + Seventh + Eigth + Ninth + Tenth + Eleventh
print "1." + Batsman[0] + "." * (total_chars - len(Batsman[0]) + 2)
print "2." + Batsman[1] + "." * (total_chars - len(Batsman[1]) + 2)
print "3." + Batsman[2] + "." * (total_chars - len(Batsman[2]) + 2)
print "4." + Batsman[3] + "." * (total_chars - len(Batsman[3]) + 2)
print "5." + Batsman[4] + "." * (total_chars - len(Batsman[4]) + 2)
print "6." + Batsman[5] + "." * (total_chars - len(Batsman[5]) + 2)
print "7." + Batsman[6] + "." * (total_chars - len(Batsman[6]) + 2)
print "8." + Batsman[7] + "." * (total_chars - len(Batsman[7]) + 2)
print "9." + Batsman[8] + "." * (total_chars - len(Batsman[8]) + 2)
print "10." + Batsman[9] + "." * (total_chars - len(Batsman[9]) + 1)
print "11." + Batsman[10] + "." * (total_chars - len(Batsman[10]) + 1)
Input_Players()
Print_Score_Sheet()
</code></pre>
|
[] |
[
{
"body": "<p>If you find yourself using serialized variable names (player1, player2, etc) it is a pretty sure sign you should be using a list or dictionary instead.</p>\n\n<p>Global is useful if, in a function, you are using a variable from a higher scope and need to store changes back to it. In most cases, it is better to return the result from the function instead of trying to 'smuggle it out' this way.</p>\n\n<pre><code>def get_player(n):\n return raw_input('Name of Batsman {} > '.format(n)).strip()\n\ndef get_players(num_players=11):\n return [get_player(i) for i in xrange(1,num_players+1)]\n\ndef score_sheet(players, width=56, fillchar='.'):\n lines = ('{}. {} '.format(*x).ljust(width, fillchar) for x in enumerate(players, 1))\n return '\\n'.join(lines)\n\ndef main():\n print score_sheet(get_players())\n\nif __name__==\"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:49:12.150",
"Id": "20771",
"Score": "0",
"body": "It is in functions, just not indented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:58:32.053",
"Id": "20772",
"Score": "1",
"body": "Writing your own rightfill is redundant: you could utilise something similar to format('test', '.<56')"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:06:36.357",
"Id": "20773",
"Score": "0",
"body": "@Jon Clements: thank you, I was not aware of that. Updated to incorporate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:20:53.197",
"Id": "20774",
"Score": "0",
"body": "@Jon Clements: on second thought, I prefer Blender's str.ljust() - but still, it was a good suggestion."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:48:31.777",
"Id": "12890",
"ParentId": "12889",
"Score": "2"
}
},
{
"body": "<p>I would structure the code like this:</p>\n\n<pre><code>def input_players(total=11):\n players = []\n\n for index in range(total):\n player = raw_input('Name of Batsman {} > '.format(index + 1))\n players.append(player)\n\n return players\n\ndef print_score_sheet(batsmen, total_chars=56):\n for index, batsman in enumerate(batsmen, 1):\n print '{}. {} '.format(index, batsman).ljust(total_chars, fillchar='.')\n\nif __name__ == '__main__':\n players = input_players(11)\n print_score_sheet(players)\n</code></pre>\n\n<p>Some tips:</p>\n\n<ul>\n<li>If you use a set of variables like <code>Player1</code>, <code>Player2</code>, <code>PlayerN</code>, you should be using a <code>list</code> to store them.</li>\n<li>Your functions should do what they say. <code>input_players()</code> should return a list of players, nothing more, nothing less.</li>\n<li>Get into the habit of including the <code>if __name__ == '__main__':</code> block. The stuff inside of the block is executed only if you run the Python script directly, which is good if you have multiple modules.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:07:13.190",
"Id": "20775",
"Score": "5",
"body": "Minor improvement, you could use `enumerate(batsmen, 1)` which would avoid having to use `index + 1`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:08:31.273",
"Id": "20776",
"Score": "0",
"body": "Thanks, I didn't know there was a better way of doing the `i + 1` thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T00:13:31.260",
"Id": "20777",
"Score": "1",
"body": "Another tip I'd add is that the OP should look at [PEP 8](http://www.python.org/dev/peps/pep-0008/), purely to get a feel for Python conventions with regard to naming. His current use of initial caps will confuse experienced devs expecting classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T07:06:32.520",
"Id": "20778",
"Score": "0",
"body": "Thanks for the help. Yes it looks like I need to read up a bit more on manipulating lists, that .append looks like exactly what I need."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:52:56.237",
"Id": "12891",
"ParentId": "12889",
"Score": "13"
}
},
{
"body": "<p>Wherever anyone uses <code>global</code>, that is a strong indication that a class should be used instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T23:05:48.957",
"Id": "20981",
"Score": "0",
"body": "Why a class rather than just passing around function return values? In particular in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-24T04:55:30.107",
"Id": "21012",
"Score": "0",
"body": "@weronika For starters, because there are numerical and non-numerical relationships between the values. By factoring it into a single kind of value, that relationship can be made explicit. In this case, it would be enough to simply create a size-eleven tuple, and pass that as a single value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T21:48:11.170",
"Id": "12892",
"ParentId": "12889",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "12891",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T20:45:44.867",
"Id": "12889",
"Score": "5",
"Tags": [
"python",
"python-2.x"
],
"Title": "Printing a score sheet for baseball batters"
}
|
12889
|
<p>I'm in the process of building some templates for Joomla, and although it all works as desired, I can't help thinking that there has to be a more elegant way to do this in PHP than my current approach. For the record, I'm still reasonably new to PHP!</p>
<p>Using collapsible module positions, I need to assign various CSS classes to a div depending on how many modules are published on a particular row. The code I wrote is below;</p>
<pre><code> if (($footer1 != "0") && ($footer2 == "0") && ($footer3 == "0")) {
$footerWidth = 'full';
}
elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 == "0")) {
$footerWidth = 'full';
}
elseif (($footer1 == "0") && ($footer2 == "0") && ($footer3 != "0")) {
$footerWidth = 'full';
}
elseif (($footer1 != "0") && ($footer2 != "0") && ($footer3 == "0")) {
$footerWidth = 'one_half';
}
elseif (($footer1 != "0") && ($footer2 == "0") && ($footer3 != "0")) {
$footerWidth = 'one_half';
}
elseif (($footer1 == "0") && ($footer2 != "0") && ($footer3 != "0")) {
$footerWidth = 'one_half';
}
else {
$footerWidth = 'one_third';
}
</code></pre>
<p>I then use the following code in the template itself to check for modules published;</p>
<pre><code> <?php if ($footer1 > 0) : ?>
<div class="<?php echo htmlspecialchars($footerWidth); ?>">
<jdoc:include type="modules" name="footer1" style="html5" />
</div>
<?php endif; ?>
<?php if ($footer2 > 0) : ?>
<div class="<?php echo htmlspecialchars($footerWidth); ?>">
<jdoc:include type="modules" name="footer2" style="html5" />
</div>
<?php endif; ?>
<?php if ($footer3 > 0) : ?>
<div class="<?php echo htmlspecialchars($footerWidth); ?>">
<jdoc:include type="modules" name="footer3" style="html5" />
</div>
<?php endif; ?>
</code></pre>
<p>Can anyone suggest / recommend a better approach? It just seems like a lot of code for a simple function.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:48:21.540",
"Id": "20780",
"Score": "0",
"body": "I'd imagine there as many ways to accomplish it as there are developers. We generally use Rockettheme templates. Most of them accomplish what you're trying to do, with the newer ones using the [Gantry Framework](http://www.gantry-framework.org/). There are several [free templates](http://www.rockettheme.com/joomla-templates) that you could download in review to see how they're doing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:50:00.030",
"Id": "20781",
"Score": "0",
"body": "The Joomla shop I work in uses these, they're pretty good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:59:43.153",
"Id": "20782",
"Score": "0",
"body": "Thanks, I'm familiar with RocketTheme and have used them in the past. I'm really looking to move away from bulky frameworks though. Plus, re-factoring RT templates to responsive designs is more work than building from scratch!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T16:00:58.630",
"Id": "20783",
"Score": "0",
"body": "no doubt, just thought their design might shed some light on how you're doing it - good luck! :\n)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T17:35:25.150",
"Id": "20784",
"Score": "0",
"body": "Yeah, I did look over their stuff initially but, as it's a complex framework and my understanding of PHP is somewhat limited, I wound up even more confused! Thanks though :)"
}
] |
[
{
"body": "<p>Something somewhat confusing is the comparison to of each $footer# to the string '0' then later comparing it to greater than integer 0. This is practically the definition of weakly typed languages. If you know what $footer# variables actually contain you might be able to simplify this, but here is a fully functioning replacement to the first code block.</p>\n\n<p>One could simplify this a bit, but the core concepts are there. '0' casts to False, and True casts to 1. There are plenty of other ways to accomplish the same thing, especially if you have significantly more incoming $footer#'s, or if they are stored in something iteratable like an array. </p>\n\n<pre><code>//$footer1 = '10';\n//$footer2 = '-5';\n//$footer3 = '0';\n\n$footer1Bool = (bool) $footer1;\n$footer2Bool = (bool) $footer2;\n$footer3Bool = (bool) $footer3;\n\n$footer1Int = (int) $footer1Bool;\n$footer2Int = (int) $footer2Bool;\n$footer3Int = (int) $footer3Bool;\n\n$footerCombined = $footer1Int + $footer2Int + $footer3Int;\n\nif ( $footerCombined >= 3 ) {\n $footerWidth = 'one_third';\n} else if ( $footerCombined == 2 ) {\n $footerWidth = 'one_half';\n} else {\n $footerWidth = 'full';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T05:50:49.503",
"Id": "20829",
"Score": "0",
"body": "Though the casts explicitly state your intentions, given that we know they compare properly to '0', you could forget the bools and just go straight to integers as $footer1Int = ($footer1 == '0')? 0 : 1; etc for each of them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:10:02.963",
"Id": "12897",
"ParentId": "12893",
"Score": "2"
}
},
{
"body": "<p>I'm afraid I don't know what <code>$footer1</code>, <code>$footer2</code>, and <code>$footer3</code> are. Either in PHP nor in HTML. These are just not that descriptive and I can't imagine a need for 3 footers, nor why their values would be numerical. I can imagine say, a copyright, bottom_nav_bar, and other similar things that might be mistaken as footers. But I digress, this is probably just example code.</p>\n\n<p>Also, I can't tell if its just CR's code indentation is off again, or if you really have all those if/else statements and their contents on the same level. If the later, please indent your code whenever you enter a statement, loop, function, etc.. as it will make reading your code so much easier. If the former, you can ignore this part.</p>\n\n<p>Now, on to the actual code. This suggestion is pretty similar to Jared's, and I agree with what I think he was driving at. These should really be set as booleans. However, there's probably a better way to get them as such without needing to typecast, such as changing them at the source. If their current values are important and that is not an option, maybe typecasting can't be helped. But depending on what the range of these values are, maybe it won't be necessary after all. Assuming it is either a value of 0 or 1, then you could do the following.</p>\n\n<pre><code>$footers = compact( 'footer1', 'footer2', 'footer3' );//get footers into array\nsort( $footers );//sort array so it is in numerical order\n$code = implode( '', $footers );//combine array to string for code to test\n\nswitch( $code ) {\n case '001': $footerWidth = 'full'; break;\n case '011': $footerWidth = 'one_half'; break;\n default: $footerWidth = 'one_third'; break;\n}\n</code></pre>\n\n<p>This can be adapted for any single digit number (1-9), but I'm assuming the range is as above. Again, this can probably be simplified if I knew the application to which it was being applied. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T11:01:04.387",
"Id": "20937",
"Score": "0",
"body": "This is exactly the sort of thing I was looking for. Thank you. I'm fairly new to PHP, so the if/else statements seemed like the most logical approach. I never even considered using arrays. \n\nFor reference, the `$footer1`, `$footer2` & `$footer3` refer to individual module \"blocks\" along a single footer row in a Joomla template. It allows the insertion of up to three columns within the footer. Probably not the most semantic approach, I know.\n\nThanks again, this is very useful and far simpler than my approach!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:22:27.480",
"Id": "12910",
"ParentId": "12893",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12910",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-20T15:28:17.067",
"Id": "12893",
"Score": "3",
"Tags": [
"beginner",
"php",
"joomla"
],
"Title": "Joomla PHP Template Logic"
}
|
12893
|
<pre><code>var searchDetails = "";
searchDetails += $("#last-name").val();
searchDetails += searchDetails != "" ? " "+$("#first-name").val() : $("#first-name").val();
searchDetails += searchDetails != "" ? " "+$("#middle-name").val() : $("#middle-name").val();
if ($("#dob-dd").val() != "" || $("#dob-mm").val() != "" || $("#dob-yyyy").val() != "") {
searchDetails += searchDetails != "" ? ", " : "";
searchDetails += "date of birth: ";
searchDetails += ($("#dob-dd").val() != "" ? $("#dob-dd").val() : "xx") + ".";
searchDetails += ($("#dob-mm").val() != "" ? $("#dob-mm").val() : "xx") + ".";
searchDetails += ($("#dob-yyyy").val() != "" ? $("#dob-yyyy").val() : "xx") + ".";
}
if ($("#passport-id").val() != "") {
searchDetails += searchDetails != "" ? ", " : "";
searchDetails += "passport " + $("#passport-id").val();
}
</code></pre>
<p><code>searchDetails</code> should contain values like (depending on what user has input):</p>
<pre><code>lastName firstName middleName, date of birth dd.mm.yyyy, passport 123456789
firstName middleName, date of birth dd.xx.yyyy
lastName firstName, date of birth dd.mm.xxxx
date of birth dd.mm.xxxx, passport 123456789
lastName firstName middleName
passport 123456789
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-25T01:26:31.697",
"Id": "21047",
"Score": "0",
"body": "Shouldn't the fallback value for `dob-yyyy` be `xxxx`? Your code only uses `xx` for the year, but your examples show `xxxx`"
}
] |
[
{
"body": "<p>Firstly, I'd create a helper function for the <code>!= \"\"</code> check:</p>\n\n<pre><code>function isEmptyString(value) {\n if (value == \"\") {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>It would make the code easier to read.</p>\n\n<p>Then I'd extract out a function for sturctures like <code>($(\"#dob-dd\").val() != \"\" ? $(\"#dob-dd\").val() : \"xx\") + \".\"</code>:</p>\n\n<pre><code>function wrapDateOfBirth(id) {\n return ($(id).val() != \"\" ? $(id).val() : \"xx\") + \".\";\n}\n</code></pre>\n\n<p>and structures like <code>searchDetails != \"\" ? \" \"+$(\"#first-name\").val() : $(\"#first-name\").val();</code>:</p>\n\n<pre><code>function wrapSearchDetails($value, $id) {\n return $value != \"\" ? \" \" + $($id).val() : $($id).val();\n}\n</code></pre>\n\n<p>They would remove some duplication.</p>\n\n<p>Furthermore, the <code>wrapSearchDetails</code> function could be written like this too:</p>\n\n<pre><code>function wrapSearchDetails(value, id) {\n return (isEmptyString(value) ? \"\" : \" \") + $(id).val();\n}\n</code></pre>\n\n<p>The <code>wrapDateOfBirth</code> function also could be simplified:</p>\n\n<pre><code>function wrapDateOfBirth(id) {\n var value = $(id).val();\n return (isEmptyString(value) ? \"xx\" : value) + \".\";\n}\n</code></pre>\n\n<p>Finally, a <code>getDefaultIfEmpty</code> function also could improve the readability of the <code>wrapDateOfBirth</code> function:</p>\n\n<pre><code>function getDefaultIfEmpty(value, defaultValue) {\n if (isEmptyString(value)) {\n return defaultValue;\n }\n return value;\n}\n\nfunction wrapDateOfBirth(id) {\n var value = $(id).val();\n return getDefaultIfEmpty(value, \"xx\") + \".\";\n}\n</code></pre>\n\n<p>(I have not tested the code, please feel free to edit if you find any typo/etc.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T18:45:48.920",
"Id": "20957",
"Score": "2",
"body": "Nicely detailed walkthrough. A few comments though: The `isEmptyString` function is equivalent to just writing `!value`, since a zero-length string is false'y. But you might want to check for whitespace-only strings, and/or do strict comparisons (`===`) against `\"\"`, in which case the function is a good place to implement it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T19:18:53.103",
"Id": "20959",
"Score": "0",
"body": "@Flambino: For the `== \"\"` comparison you don't have to know that *a zero-length string is false*, so I think it's easier to understand and therefore less error-prone. I agree with the second sentence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T19:43:07.063",
"Id": "20961",
"Score": "0",
"body": "True, `== \"\"` is easier to understand. JavaScript's ideas on what is and what isn't false'y can trip anyone up. Something else, though: Your functions might benefit from consistent parity/signatures. Right now, some take both value and ID, and some take only the ID."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T19:36:53.957",
"Id": "12900",
"ParentId": "12898",
"Score": "1"
}
},
{
"body": "<p>An alternative is to use arrays. Perhaps more cryptic at first glance, but makes good use of <code>join()</code>, and jQuery's utility functions:</p>\n\n<pre><code>function composeSearchDetails() {\n var name, dob, passport, searchDetails;\n\n // Get the name\n name = [\n $(\"#last-name\").val(),\n $(\"#first-name\").val(),\n $(\"#middle-name\").val()\n ];\n\n // Strip out empty and all-whitespace strings\n name = jQuery.grep(name, function (value) {\n return jQuery.trim(value) !== \"\"; // false if string is empty or all-whitespace\n });\n\n // Join if not empty\n name = name.length ? name.join(\" \") : false;\n\n // Get the DoB parts, or their fallback (\"xx\") values \n dob = [\n jQuery.trim($(\"#dob-dd\").val()) || \"xx\",\n jQuery.trim($(\"#dob-mm\").val()) || \"xx\",\n jQuery.trim($(\"#dob-yyyy\").val()) || \"xxxx\"\n ];\n\n // Join\n dob = dob.join(\".\");\n\n // Check that there's at least 1 non-X value\n dob = /[^x.]/.test(dob) ? \"date of birth \" + dob : false;\n\n // Get the passport\n passport = jQuery.trim($(\"#passport-id\").val());\n passport = passport ? \"passport \" + passport : false;\n\n // Put it together\n searchDetails = [name, dob, passport];\n\n // Get rid of false parts\n searchDetails = jQuery.grep(searchDetails, function (value) { return value; });\n\n // Join and return\n return searchDetails.join(\", \");\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/m4JZn/\" rel=\"nofollow\">Here's a live demo</a></p>\n\n<p><em>Note: <code>jQuery.grep</code> can be replaced with the native ECMA5 <code>.filter</code> function, if available</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T19:37:02.483",
"Id": "12986",
"ParentId": "12898",
"Score": "1"
}
},
{
"body": "<ul>\n<li><code>!= \"\"</code> checks are unnecessary - <code>.val()</code> always returns a string, and every string but <code>\"\"</code> evaluates to <code>true</code>.</li>\n<li>Don't call $(id).val() repeatedly; cache the result the first time.</li>\n<li>Build it up as an array then, at the end, use <code>.join()</code>. This avoids all the checks to <code>searchDetails != \"\" ? \", \" : \"\"</code>.</li>\n<li>in javascript, logical operators return the last value, not a boolean cast of the last value. What that means in that instead of calling <code>str ? str : \"xx\"</code>, you can write <code>str || 'xx'</code>.</li>\n</ul>\n\n<p>Here's my take on your problem.</p>\n\n<pre><code>function getSearchDetails() {\n var searchDetails = [],\n firstName = $('#first-name').val(),\n middleName = $('#middle-name').val(),\n lastName = $('#last-name').val(),\n dobD = $('#dob-dd').val(),\n dobM = $('#dob-mm').val(),\n dobY = $('#dob-yyyy').val(),\n passportID = $('#passport-id').val();\n\n if (firstName || middleName || lastName) {\n searchDetails.push([\n lastName,\n firstName,\n middleName\n ].join(' ').replace(/(^| )( +|$)/g, ''));\n }\n if (dobD || dobM || dobY) {\n searchDetails.push(\n 'date of birth: ' +\n (dobD || 'xx') + '.' +\n (dobM || 'xx') + '.' +\n (dobY || 'xx') + '.';\n );\n }\n if (passportID) {\n searchDetails.push('passport ' + passportID);\n }\n return searchDetails.join(', ');\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-24T18:07:24.557",
"Id": "21038",
"Score": "0",
"body": "Nice and concise, but it always includes the name part, even if the name fields are blank (and it doesn't ignore all-whitespace input, although neither does the original code). I set up [a jsfiddle](http://jsfiddle.net/Evmqu/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-25T01:17:07.813",
"Id": "21046",
"Score": "0",
"body": "@Flambino thanks, I missed that - answer updated. The whitespace part was intentional though, as LA_ seems satisfied with the code's current functionality."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T21:17:19.873",
"Id": "12989",
"ParentId": "12898",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T18:12:35.927",
"Id": "12898",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "How to simplify code, which adds spaces and commas if field value is not empty?"
}
|
12898
|
<p>I have the following code, but I don't know how to make it run faster.</p>
<pre><code>SELECT lot.order as lot_order,
lot.title as lot_title,
lot.id as lot_id,
lot.id_auction,
IF (
(SELECT bid
FROM bid
WHERE lot.id = bid.id_lot
ORDER BY bid.date DESC
LIMIT 0,1) > lot.bid_minimum,
(SELECT bid
FROM bid
WHERE lot.id = bid.id_lot
ORDER BY bid.date DESC
LIMIT 0,1),
lot.bid_minimum
) AS bid,
youtube,
(SELECT path_image
FROM lot_album
WHERE lot_album.id_lot = lot.id
AND order = 1) as image_featured
FROM lot
WHERE lot.excluded <> 1
AND lot.id_auction = 42
ORDER BY lot.order ASC
</code></pre>
<p>As you can see, I have the <code>IF</code> to check if the value of the select is <code>> bid.minimum</code>. The only way to improve this is check it on the programming language (PHP/.NET...) or there is another way?</p>
<hr>
<ul>
<li>"lot_album" is a table where you can have lots of images, but also
none. But only one image per lot will have order 1 so that image will
be the "image_featured".</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:47:50.830",
"Id": "20808",
"Score": "0",
"body": "I think English table and column names would improve readability a lot for the majority of users here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T21:55:24.423",
"Id": "20809",
"Score": "0",
"body": "Always try and limit your queries as that will save a lot of time. As I'm not sure what you're retrieving etc then I'm not sure if it is appropriate here, but yeah Limit queries, try to minimize the amount of sub-queries you have as that always takes a lot of time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T04:24:59.283",
"Id": "20827",
"Score": "0",
"body": "I'll change the names to make things easy to read. sorry about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T07:54:08.127",
"Id": "20839",
"Score": "0",
"body": "You could potentially adjust http://stackoverflow.com/a/2111420/567864 to do away with the sub queries and only have to do an IF. Am not sure how that would compare to subquery performance though. (I suspect it would be better with careful indexing.)"
}
] |
[
{
"body": "<p>This should be a little better. I believe joins are faster than nested selects, and that if with nested select may or may not select twice or use cached response. I can't think of a good way of getting rid of the one nested select. Otherwise, maybe you could write it as a stored procedure or virtual table. (Note* any spelling mistakes of table or column names are a result of autocorrect)</p>\n\n<pre><code>SELECT lote.ordem as lote_ordem, \nlote.titulo as lote_titulo, \nlote.codigo as lote_codigo, \nlote.codigo_leilao, \nGREATEST( \n (SELECT lance \n FROM lance \n WHERE lote.codigo = lance.codigo_lote \n ORDER BY lance.data DESC \n LIMIT 0,1), \n lote.lance_minimo \n) AS lance2, \nyoutube, \nyoutube, \n-- lance.codigo_cadastro, \nlote_album.caminho_imagem as imagem_destaque, \nFROM lote\nLEFT JOIN lote_album\nON lote_album.codigo_lote = lote.codigo \nWHERE lote.excluido <> 1\nAND lote.codigo_leilao = 42 \nAND lote_album.ordem = 1\nORDER BY lote.ordem ASC\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T11:37:50.467",
"Id": "20857",
"Score": "0",
"body": "Really good idea about the GREATEST.The \"imagem_destaque\" is not possible (I GUESS) to get as a JOIN because there are tons of imgs there and sometimes none. So if I put it as an AND, this should remove some results (when the img are NULL). Right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T14:39:33.813",
"Id": "20877",
"Score": "0",
"body": "I think the \"imagem_detaque\" will work in the JOIN, note that I moved the condition for that table to the whole WHERE clause, \"AND lote_album.ordem = 1\". I'm not sure what you mean by remove some results where the img are NULL. If you want to not have a row returned if the img is NULL you should add a clause to the WHERE like \"AND imagem_destaque IS NOT NULL\". This will lower the total amount of rows returned. If you mean that the JOIN will limit the rows returned to only where the img is not NULL, that is not the case because I used an outer join."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T19:05:03.367",
"Id": "20902",
"Score": "0",
"body": "The GREATEST didn't work. He brings a \"lance(bid)\" OR \"NULL\", even \"lance_minimo(minimum_bid)\" is not null"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-23T01:16:43.720",
"Id": "20932",
"Score": "0",
"body": "But the image part worked really perfect. I'm taking yours as the right answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T06:16:05.610",
"Id": "12920",
"ParentId": "12902",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12920",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:07:36.800",
"Id": "12902",
"Score": "2",
"Tags": [
"performance",
"mysql",
"sql"
],
"Title": "Inner select performance"
}
|
12902
|
<p>Guava is the open-sourced version of Google's core Java libraries that aims to make working in the Java language more pleasant and more productive.</p>
<p>It contains several core libraries that Google rely on in their Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, basic string processing, I/O, etc. </p>
<p>Requires JDK 1.6 or higher (as of 12.0).</p>
<p>Downloads and more information: <a href="https://github.com/google/guava" rel="nofollow">https://github.com/google/guava</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:14:34.107",
"Id": "12903",
"Score": "0",
"Tags": null,
"Title": null
}
|
12903
|
The Guava project is a set of Java core libraries. They include collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O etc.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:14:34.107",
"Id": "12904",
"Score": "0",
"Tags": null,
"Title": null
}
|
12904
|
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:15:25.877",
"Id": "12906",
"Score": "0",
"Tags": null,
"Title": null
}
|
12906
|
<p>Forth, invented in 1958, released in the 70's. Rather than using arguments passed to functions, it used words that implicitly operated on the top of the stack. The fallowing is valid Forth code:</p>
<pre><code>: double \ Define the word, double.
( x -- x+x) \ The comment in the ()'s says this function consumes the top stack element and leaves its double.
dup ( x -- x x) \ Dup duplicates the top element.
+ ( x x -- x+x)
; \ End the word definition
: triple dup ( x -- x x) double ( x x -- x x+x) + ( x x+x -- x+x+x) ;
</code></pre>
<p>Note that each paren comment allows a space after opening. Forth's parser looks for words separated by whitespace; '(' is a word that tells Forth that the text until the next ')' is a comment. '(x' tells Forth to run the word, '(x'.</p>
<p>This simplicity makes Forth incredibly easy to implement, and many derivatives with varying features fallowed. </p>
<p>PostScript came along in 1982 and took advantage of the fact that stack-based languages work well in resource-limited environments to work as a scripting language for laser printers, producing various types of graphics. RPL took advantage of this to make a programming language for some of Hewlett-Packard's graphing calculators.</p>
<p>Joy appeared in the early 2000's, calling itself a concatenative language, bearing no inheritance from Forth except for being stack-based. It introduced the higher-level, more functional concept of combinators. This spawned Cat, Factor, and several other languages. Factor uses concepts from both Joy and Forth; in it, triple can be written as such, using a combinator:</p>
<pre><code>: triple ( x -- x*3 ) [ double ] [ + ] bi
</code></pre>
<p>Here, bi tells Factor to first double x, but keep x on top, unchanged, so after double executes, the stack looks like this: ( x+x x ). Then the addition gets applied and we have x*3. (This example is not intended to show why one would use combinators over regular composition.)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:50:49.920",
"Id": "12908",
"Score": "0",
"Tags": null,
"Title": null
}
|
12908
|
Stack oriented (or based) languages, more recently referred to as concatenative languages, use a global stack for implicit argument passing. In terms of functional programming, they focus on function composition over lambda calculus. The first stack-based language was Forth.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T20:50:49.920",
"Id": "12909",
"Score": "0",
"Tags": null,
"Title": null
}
|
12909
|
<p>What would be the most <em>efficent</em> way to calculate this?</p>
<pre><code>var reportLimit = 96*1024;
IEnumerable<int> memoryInUse =
things
.Where(sample => sample.IsOn)
.Select(sample => sample.MemoryInMb)
.ToArray();
int totalUnderReportLimit = memoryInUse.Where(ram => ram <= memoryCalcFactor).Sum();
int totalOverEqualReportLimit = memoryInUse.Count(ram => ram > memoryCalcFactor) * memoryCalcFactor;
return totalUnderReportLimit + totalOverEqualReportLimit;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T23:10:48.023",
"Id": "20812",
"Score": "1",
"body": "If you want to find out what is faster, running benchmarks is *exactly* what you should do. I'm not sure why are you avoiding that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T23:16:45.207",
"Id": "20813",
"Score": "0",
"body": "I agree, the ToArray() seems unnecessary here."
}
] |
[
{
"body": "<p>I guess one way to potentially speed it up (if the issue was with running over the enumerable twice) would be to use a foreach. However, I don't think it's as readable as your solution;</p>\n\n<pre><code>int countOverLimit = 0;\n\nforeach(var ram in memoryUse)\n{\n if(ram <= memoryCalcFactor)\n {\n totalUnderReportLimit += ram;\n } \n else if(ram > memoryCalcFactor)\n {\n countOverLimit++;\n }\n}\n\ntotalOverEqualReportLimit = countOverLimit * memoryCalcFactor;\n\nreturn totalUnderReportLimit + totalOverEqualReportLimit;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T00:00:36.260",
"Id": "12914",
"ParentId": "12911",
"Score": "3"
}
},
{
"body": "<p>Well here's my take on it. If you want <em>efficient</em> in terms of speed, write a loop. LINQ is not for writing fast code, it's for writing <em>concise</em> code.</p>\n\n<p><code>memoryInUse</code> is just a collection of the memory counts of all the machines that are on. You then essentially partition those machines by some <code>memoryCalcFactor</code> to do some calculation.</p>\n\n<p>The call to <code>ToArray()</code>, while somewhat helpful (you do the filter/projection once) isn't really needed. You can perform your calculation in one pass and therefore don't need it at all. Look at the following lines in your calculation:</p>\n\n<pre><code>var x = memoryInUse.Where(ram => ram <= memoryCalcFactor).Sum();\nvar y = memoryInUse.Count(ram => ram > memoryCalcFactor) * memoryCalcFactor;\nreturn x + y;\n</code></pre>\n\n<p>What are we doing here?</p>\n\n<ol>\n<li>Adding up all the sizes that are less than some factor</li>\n<li>Counting all those that are greater than that factor multiplying by that factor.</li>\n<li>Adding the previous results</li>\n</ol>\n\n<p>Looking at this at a much higher level, what are we doing here? We're adding up the sizes limiting each size by some factor (a maximum). Write your code to do <em>that</em>.</p>\n\n<p>This is how I'd write it:</p>\n\n<pre><code>var memorySizes = machines\n .Where(machine => machine.IsOn)\n .Select(machine => machine.MemoryInMB);\nvar result = memorySizes.Sum(size => Math.Max(size, memoryCalcFactor));\n</code></pre>\n\n<p>Otherwise if you don't want to take the performance hit LINQ will give you and use a loop, here's the equivalent:</p>\n\n<pre><code>var sum = 0;\nforeach (var machine in machines)\n{\n if (machine.IsOn)\n {\n sum += Math.Max(machine.MemoryInMB, memoryCalcFactor);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-25T21:29:13.593",
"Id": "21104",
"Score": "0",
"body": "A .where(...).aggregate(...) should I would think perform an identical single loop... though the aggregate function can feel a little strange to folks not familiar with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-25T23:57:57.560",
"Id": "21109",
"Score": "0",
"body": "@Jimmy: Yeah, I initially started off using aggregate when thinking about this until I realized we were just adding every number in some form."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T00:21:40.530",
"Id": "12916",
"ParentId": "12911",
"Score": "10"
}
},
{
"body": "<p>+1 to @Jeff. Staying at low level (if there is not a more effective algorithm) and in languages which does not support LINQ I'd create two methods with single responsibilities (<code>calculateTotalUnderReportLimit</code> and <code>calculateTotalOverEqualReportLimit</code>, for example). If it was a performance bottleneck it still could be optimized but until that it would be easier to read and maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T07:48:52.773",
"Id": "12923",
"ParentId": "12911",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "12916",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-21T22:37:39.657",
"Id": "12911",
"Score": "5",
"Tags": [
"c#",
"linq"
],
"Title": "Simple LINQ statement for report limit"
}
|
12911
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.