body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Please review for readability.</p>
<pre><code>/*
Takes a screenshot of the current tab, then scales it to width and height.
Returns null if the tab is smaller than width and height.
Crops the screenshot to maintain aspect ratio.
Also crops the screenshot to avoid scaling down by more maximumScaleFactor.
*/
var GetCurrentScreenshot = function (width, height, maximumScaleFactor) {
return new RSVP.Promise(function (resolve) {
chrome.tabs.captureVisibleTab(null, { format: 'png' }, function (dataURL) {
var sourceImage = new Image();
sourceImage.onload = function () {
var canvas = document.createElement("canvas");
var cropWidth = sourceImage.width;
var cropHeight = sourceImage.height;
if (cropWidth < width || cropHeight < height) {
resolve(null);
return;
}
var outputRatio = width / height;
var inputRatio = cropWidth / cropHeight;
if (outputRatio > inputRatio) {
cropHeight = cropWidth / outputRatio;
} else {
cropWidth = cropHeight * outputRatio;
}
//This should be impossible
if (cropWidth > sourceImage.width) cropWidth = sourceImage.width;
if (cropHeight > sourceImage.height) cropHeight = sourceImage.height;
if (cropWidth > width * maximumScaleFactor) {
cropHeight = cropHeight / (cropWidth / (width * maximumScaleFactor));
cropWidth = width * maximumScaleFactor;
}
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(sourceImage, 0, 0, cropWidth,
cropHeight, 0, 0, width, height);
resolve(canvas.toDataURL());
};
sourceImage.src = dataURL;
});
});
};
</code></pre>
|
[] |
[
{
"body": "<p>I'd break out that inner function - easier to see where it starts and ends.</p>\n\n<pre><code>/*\nTakes a screenshot of the current tab, then scales it to width and height.\nReturns null if the tab is smaller than width and height.\nCrops the screenshot to maintain aspect ratio.\nAlso crops the screenshot to avoid scaling down by more maximumScaleFactor.\n*/\nvar GetCurrentScreenshot = function (width, height, maximumScaleFactor) {\n return new RSVP.Promise(function (resolve) {\n\n var func = function (dataURL) {\n var sourceImage = new Image();\n sourceImage.onload = function () {\n var canvas = document.createElement(\"canvas\");\n var cropWidth = sourceImage.width;\n var cropHeight = sourceImage.height;\n if (cropWidth < width || cropHeight < height) {\n resolve(null);\n return;\n }\n var outputRatio = width / height;\n var inputRatio = cropWidth / cropHeight;\n if (outputRatio > inputRatio) {\n cropHeight = cropWidth / outputRatio;\n } else {\n cropWidth = cropHeight * outputRatio;\n }\n\n //This should be impossible\n if (cropWidth > sourceImage.width) cropWidth = sourceImage.width;\n if (cropHeight > sourceImage.height) cropHeight = sourceImage.height;\n\n if (cropWidth > width * maximumScaleFactor) {\n cropHeight = cropHeight / (cropWidth / (width * maximumScaleFactor));\n cropWidth = width * maximumScaleFactor;\n }\n\n canvas.width = width;\n canvas.height = height;\n canvas.getContext(\"2d\").drawImage(sourceImage, 0, 0, cropWidth,\n cropHeight, 0, 0, width, height);\n resolve(canvas.toDataURL());\n };\n sourceImage.src = dataURL;\n };\n chrome.tabs.captureVisibleTab(null, {\n format: 'png'\n }, func);\n });\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:26:50.177",
"Id": "65280",
"Score": "0",
"body": "Personally, I prefer the original version, since I read it as, \"Capture the Visible tab, then do stuff,\" which your proposal loses. I suppose I could have the best of both worlds by wrapping captureVisibleTab in a promise, but that strikes me as overkill."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:05:08.043",
"Id": "39022",
"ParentId": "39012",
"Score": "0"
}
},
{
"body": "<p><strong>Breaking out the callback function</strong></p>\n\n<p>I would break out that function as well, though I would give it a better name than <code>func</code>, mayhaps <code>drawScaledScreenshot</code>?</p>\n\n<p><strong>Functionality</strong></p>\n\n<ul>\n<li><p>CR is not the best place to discuss functionality, but why would you not draw the image if the tab size is too small, it does not seem to make sense.</p></li>\n<li><p>Also, why would you only check for width going over the maximumScaleFactor ? I would check height as well.</p></li>\n</ul>\n\n<p><strong>Scope</strong></p>\n\n<p>I feel the following <code>var</code>s could have been declared outside of the <code>drawScaledScreenshot</code> function, since they only depend on <code>width</code> and <code>height</code>.</p>\n\n<pre><code>var outputRatio = width / height;\nvar maximumCropWidth = width * maximumScaleFactor; //You calc this several times\n</code></pre>\n\n<p><strong>Paranoia</strong></p>\n\n<p>If you truly think it is impossible, then it should not be in the code</p>\n\n<pre><code>//This should be impossible\nif (cropWidth > sourceImage.width) cropWidth = sourceImage.width;\nif (cropHeight > sourceImage.height) cropHeight = sourceImage.height;\n</code></pre>\n\n<p>If you think it is possible, then I would suggest you convert this to the more readble</p>\n\n<pre><code>//This should not be needed\ncropWidth = Math.min( cropWidth, sourceImage.width);\ncropHeight = Math.min( cropHeight, sourceImage.height);\n</code></pre>\n\n<p>Notice that if <code>width * maximumScaleFactor</code> is exceeded, you can still get a <code>cropHeight > sourceImage.height</code>..</p>\n\n<p>Furtermore, I would be more paranoid that the caller forgets to provide <code>maximumScaleFactor</code> and would add a </p>\n\n<pre><code>maximumScaleFactor = maximumScaleFactor || 10; //Or whatever is reasonable\n</code></pre>\n\n<p>Finally, since you are dividing by <code>height</code>, I would verify that <code>height</code> is not zero.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T19:26:09.193",
"Id": "39672",
"ParentId": "39012",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39672",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T16:04:14.080",
"Id": "39012",
"Score": "0",
"Tags": [
"javascript",
"image"
],
"Title": "Screenshot-scaling code"
}
|
39012
|
<p>Here's <a href="http://projecteuler.net/problem=451" rel="nofollow">Project Euler problem 451</a>: </p>
<blockquote>
<p>Consider the number \$15\$.
There are eight positive numbers less than \$15\$ which are coprime to \$15\$:
\begin{align*} 1, 2, 4, 7, 8, 11, 13, 14. \end{align*}
The modular inverses of these numbers modulo \$15\$ are:
\begin{align*} 1, 8, 4, 13, 2, 11, 7, 14 \end{align*}
because</p>
<p>\begin{align*}
1 \times 1 \mod 15 &= 1 \\
2 \times 8 = 16 \mod 15 &= 1 \\
4 \times 4=16 \mod 15 &= 1 \\
7 \times 13=91 \mod 15 &= 1 \\
11 \times 11=121 \mod 15 &= 1 \\
14 \times 14=196 \mod 15 &= 1
\end{align*}</p>
<p>Let \$I(n)\$ be the largest positive number \$m\$ smaller than \$n − 1\$ such that the modular inverse of \$m\$ modulo \$n\$ equals \$m\$ itself.
So \$I(15) = 11\$.
Also \$I(100) = 51\$ and \$I(7) = 1\$.</p>
<p>Find \$\sum I(n)\$ for \$3 \leq n \leq 2 \times 10^7\$.</p>
</blockquote>
<p>I realised that because they are symmetrical, we can search for the smallest ones (of course skipping the trivial case \$1^2 = 1 \mod n\$). I also realised that if \$n\$ is divisible by a prime, I don't need to test multiples of that prime. I currently devised a implementation for the first four primes, as I think they are the ones that have the most impact. Anyways, here's my code. However, I must warn you, that in trying to optimise for speed, this one is <em>very</em> memory inefficient (needs around 2.5 GB).</p>
<pre><code>upto=2*10**7+1
a = [True] * upto
p = []
for n in range(2,upto):
if a[n]:
p.append(n)
for k in range(2,(upto+n-1)//n):
a[k*n] = False
p=set(p)
su=0
squ=list(map(lambda x: x*x, range(upto)))
print('primes and squares ready')
s2 = set(range(0,upto,2))# for testing divisibility
s3 = set(range(0,upto,3))
s5 = set(range(0,upto,5))
s7 = set(range(0,upto,7))
r=[]
r.append([])
r.append([])
r[0].append([])
r[0].append([])
r[1].append([])
r[1].append([])
r[0][0].append([])
r[0][0].append([])
r[0][1].append([])
r[0][1].append([])
r[1][0].append([])
r[1][0].append([])
r[1][1].append([])
r[1][1].append([])
r[0][0][0].append(range(2,upto))# for iterating
r[1][0][0].append(filter(lambda x: x not in s2, range(upto)))
r[0][1][0].append(filter(lambda x: x not in s3, range(upto)))
r[0][0][1].append(filter(lambda x: x not in s5, range(upto)))
r[0][0][0].append(filter(lambda x: x not in s7, range(upto)))
print('list pre generated')
r[1][1][0].append(filter(lambda x: x in r[1][0][0][0], r[0][1][0][0]))
r[1][1][1].append(filter(lambda x: x in r[0][0][1][0], r[1][1][0][0]))
r[0][1][1].append(filter(lambda x: x in r[0][0][1][0], r[0][1][0][0]))
r[1][0][1].append(filter(lambda x: x in r[0][0][1][0], r[1][0][0][0]))
r[1][0][1].append(filter(lambda x: x in r[1][0][1][0], r[0][0][0][1]))
r[1][0][0].append(filter(lambda x: x in r[1][0][0][0], r[0][0][0][1]))
r[1][1][0].append(filter(lambda x: x in r[1][1][0][0], r[0][0][0][1]))
r[1][1][1].append(filter(lambda x: x in r[0][0][0][1], r[1][1][1][0]))
r[0][1][1].append(filter(lambda x: x in r[0][0][0][1], r[0][1][1][0]))
r[0][0][1].append(filter(lambda x: x in r[0][0][1][0], r[0][0][0][1]))
r[0][1][0].append(filter(lambda x: x in r[0][1][0][0], r[0][0][0][1]))
print('set up complete')
for n in range(3,upto):
if n in p:
su+=1
print('testing', n)
else:
if n in s2:
d2=1
else:
d2=0
if n in s3:
d3=1
else:
d3=0
if n in s5:
d5=1
else:
d5=0
if n in s7:
d7=1
else:
d7=0
for x in r[d2][d3][d5][d7]:
if squ[x]%n==1:
su+=n-x
break
print(su)
</code></pre>
<p>I have tried optimising the speed of division testing using sets, and pre-generated all the generators or lists (I wasn't sure about the performance in this case, so I tried both). I must say the code runs fast at first, checking the first 100,000 moduli in under a minute, however close to a million is slow substantially. Although <a href="http://docs.python.org/3/library/profile.html#module-cProfile" rel="nofollow"><code>cProfile</code></a> doesn't time built-in functions I believe the majority of time is spent in the <code>for x in r[d2][d3][d5][d7]:</code> loop.</p>
<p>I'm not sure if the algorithm I'm using is wrong and faster ones exist, or if my code is simply inefficient (Project Euler claims the problem can be computed in under a minute, not sure if this is the case with Python though).</p>
<p>As this is a project to benefit my understanding of programming, and algorithms, please don't post full solutions but rather guidance and pointers.</p>
|
[] |
[
{
"body": "<p>I'm not really sure I understand your code; it's not really organized in a way that aids readability. Use functions, so that I don't need to spend a minute or more reading the first few lines of the program to understand that they should be</p>\n\n<pre><code>def computePrimesUpTo(n):\n sieve = [True] * n\n p = []\n for i in range(2, n): # In Python2, use xrange instead\n if sieve[i]:\n p.append(i)\n for multiple in range(2 * i, n, i):\n sieve[multiple] = False\n return set(p)\nprimes = computePrimesUpTo(upTo)\n</code></pre>\n\n<p>Now at a glance, I can see that <code>if n in primes</code> is checking whether n is a prime number, and I can see that you're using the Sieve of Eratosthenes to compute them. (Note: <code>p</code> is not the worst offender here; in fact, it's the easiest to figure out. It's taken me several reads through your code to figure out what <code>r</code> is supposed to be.)</p>\n\n<p>However, it looks like you're precomputing <code>x*x</code> for <code>x</code> in [0, 2*10^7], as well as lists of all multiples of 2, 3, 5, and 7 in the same range. This belies a fundamental misunderstanding of what is expensive in modern processors. <code>x</code> will be in a register, or in the worst case in the L1 cache, and squaring it will require a single instruction (less than a nanosecond). <code>squ[x]</code> will frequently not be in any of your CPU's memory caches; as a rule of thumb a cache miss costs 100 ns (And that's if it hasn't been swapped out of main memory onto disk! See <a href=\"http://highscalability.com/numbers-everyone-should-know\" rel=\"nofollow\">this list of numbers every programmer should know</a>). Not only that, but by reading from them, you'll push something else out of your cache, slowing down everything else. <code>squ</code>, <code>s2</code>, <code>s3</code>, <code>s5</code>, and <code>s7</code> are likely slowing your program down by a noticeable amount.</p>\n\n<p>I am less sure about your <code>r</code>s; they may help or hurt. However, the computation of <code>r[1][1][0]</code>, etc. is not as fast as it might be; the <code>in</code> operation of python lists is O(n). Try implementing this function:</p>\n\n<pre><code>def list_intersection(a, b):\n \"\"\"Computes the intersection of two sorted iterables.\n\n Returns a list; requires O(len(a) + len(b)) time.\n \"\"\"\n pass\n</code></pre>\n\n<hr>\n\n<p>OK, now let's talk algorithm.</p>\n\n<p>First of all, when computing <code>l(n)</code> there's no need to consider numbers less than or equal to <code>sqrt(n)</code>. To take advantage of that, you might reverse the <code>r[w][x][y][z]</code> lists and iterate over them backward, with a check for each <code>n</code> that <code>r[d2][d3][d5][d7][-1] > sqrt(n)</code>. This will give you a small benefit.</p>\n\n<p>I think you had the right insight: If you're computing the coprimes separately for each <code>n</code>, </p>\n\n<pre><code>for c in [c for c in range(2,n) if is_coprime(c, n)]: if (c*c)%n == 1: break\n</code></pre>\n\n<p>is much slower than</p>\n\n<pre><code>for c in range(2,n): if (c*c)%n == 1: break\n</code></pre>\n\n<p>Filtering down <code>range(2,n)</code> is useful, but there's diminishing returns: filtering out factors of <code>p</code> gets you at most <code>1/p</code> speed-up while computing <code>l(n)</code> with an additional cost that's O(<code>upTo</code>). Still, any test you do in your <code>for x in r[...]</code> loop will only slow you down (since <code>if (x*x)%n == 1</code> is essentially as fast as you can get), so the only speedup you can gain is by reducing the size of the <code>r</code> lists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T18:12:29.907",
"Id": "65419",
"Score": "0",
"body": "Basically calculating so faster then reading from disk, so I overdoing it?\nAlso good tip with the beginning from square root, would up vote but not enough rep :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T18:29:57.267",
"Id": "65420",
"Score": "0",
"body": "In Python, `x*x` returns a reference to a new integer object and allocates it on the heap, while `squ[x]` returns a reference to an existing object. The latter can indeed be a little faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T20:37:16.573",
"Id": "65423",
"Score": "0",
"body": "Yikes, I hadn't considered that. I still think that putting 100s of MBs into RAM and doing random access is going to be pretty slow; I suppose it depends on python's malloc implementation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T19:39:08.590",
"Id": "39060",
"ParentId": "39015",
"Score": "3"
}
},
{
"body": "<p>You should find an algorithm finding the root square of 1 module n.</p>\n\n<pre><code>x^2 = 1 mod n\n</code></pre>\n\n<p>To do that:</p>\n\n<ul>\n<li>Factorize n in prime factor. <code>n = p1^e1 * p2^e2 * ... * pk^ek</code></li>\n<li>Find the root for all prime <code>xi^2 = 1 mod pi^ei</code>. easy, it is 1 and -1 (or pi^ei - 1)</li>\n<li>Then use the Chinese theorem to find the solution for x (<code>x = x1 mod x1^e1</code>, <code>x = ...</code>, <code>x = xk mod pk^ek</code> (<code>xi</code> can take 2 value so you will have k^2 answer)</li>\n</ul>\n\n<p>you just need to take the solution which meet your condition</p>\n\n<p><em>EDIT:</em></p>\n\n<p>I made a mistake about the power of prime root square result:</p>\n\n<ul>\n<li>1 and -1 are the root square of <code>xi^2 = 1 mod pi^ei</code> but there may be other when <code>e1 != 1</code></li>\n<li>for example: n= 16 we have <code>x^2 = 1 mod 2^4</code> where 9 is also a solution too (9*9 = 81 = 1)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T15:57:35.213",
"Id": "74460",
"Score": "0",
"body": "for `x^2 = 1 mod 2^k` allow 4 solution after k >= 3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T05:07:06.567",
"Id": "43016",
"ParentId": "39015",
"Score": "2"
}
},
{
"body": "<p>I think you are going in the wrong direction.</p>\n\n<p>1)\nInstead of using your lengthy program block to initialize <code>r</code> you can use</p>\n\n<pre><code>r=[[[None,None],[None,None]],[[None,None],[None,None]]]\nr[0][0][0]=range(2,upto)\n...\n</code></pre>\n\n<p>of course it is also possible to use </p>\n\n<pre><code>r=[[[[],[]],[[],[]]],[[[],[]],[[],[]]]] \n</code></pre>\n\n<p>this looks like more funny but is rather confusing\nso I prefer the first solution</p>\n\n<p>2)\nwhat youd did</p>\n\n<pre><code>for n in range(2,upto):\n if a[n]:\n for k in range(2,(upto+n-1)//n):\n a[k*n] = False\n</code></pre>\n\n<p>this tooks 40 seconds on my notebook</p>\n\n<p>what you want</p>\n\n<pre><code>for n in range(2,upto):\n if a[n]:\n for k in range(2*n,upto,n):\n a[k] = False\n</code></pre>\n\n<p>this tooks 30 seconds on my notebook. That difference is not essential but your loop is more complex <strong>and</strong> slower.</p>\n\n<p>3)\nIt does not make any sense to store the square numbers instead of calculating them. It may make sense to store the calculation of time consuming calculations, but not the result of a simple fast operation like squaring.</p>\n\n<p>The same is true for <code>%</code> and <code>//</code>.</p>\n\n<p>I did not get the idea of your algorithm and don't want to decipher the rest of your program. </p>\n\n<hr>\n\n<p>So you should rewrite the program without using the lists s2,s3,s5,s7 and r.\nAlso you should be aware that if you use functional programming there are a lot of readers that are not familiar with and that therefore won't review your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-07T00:40:41.027",
"Id": "64939",
"ParentId": "39015",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T17:52:16.903",
"Id": "39015",
"Score": "6",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge",
"python-3.x"
],
"Title": "Performance of modular square root"
}
|
39015
|
<p>I have a specific method that I like because it lets me decide whether or not I want to use the default. If I want anything different I enter in <code>:option => value</code> otherwise I get the default. Here's a concrete example that works, but is a little ugly.</p>
<p>How can I accomplish the same thing in a more elegant manner?</p>
<pre><code>def connect_to_oracle opts = {}
host_name = opts[:host_name]
host_name ||= 'a_default_host_name'
db_name = opts[:db_name]
db_name ||= 'a_default_db_name'
userid = opts[:userid]
userid ||= 'a_default_userid'
password = opts[:password]
password ||= 'a_default_password'
url = "jdbc:oracle:thin:#{userid}/#{password}@#{host_name}:1521:#{db_name}"
$db = Sequel.connect(url)
end
</code></pre>
|
[] |
[
{
"body": "<p>You don't need the <code>||=</code> you can use <code>||</code>:</p>\n\n<pre><code>def connect_to_oracle( opts = {} )\n host_name = opts[:host_name] ||'a_default_host_name'\n db_name = opts[:db_name] || 'a_default_db_name'\n userid = opts[:userid] || 'a_default_userid'\n password = opts[:password] ||'a_default_password'\n\n url = \"jdbc:oracle:thin:#{userid}/#{password}@#{host_name}:1521:#{db_name}\"\n $db = Sequel.connect(url)\nend\n</code></pre>\n\n<p>Another approach is <code>Hash.merge</code>:</p>\n\n<pre><code>DEFAULT = {\n host_name: 'a_default_host_name',\n db_name: 'a_default_db_name',\n userid: 'a_default_userid',\n password: 'a_default_password',\n}\n\ndef connect_to_oracle( opts = {} )\n opts = DEFAULT.merge(opts)\n\n host_name = opts[:host_name]\n db_name = opts[:db_name]\n userid = opts[:userid]\n password = opts[:password]\n\n url = \"jdbc:oracle:thin:#{userid}/#{password}@#{host_name}:1521:#{db_name}\"\n $db = Sequel.connect(url)\nend\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>DEFAULT = {\n host_name: 'a_default_host_name',\n db_name: 'a_default_db_name',\n userid: 'a_default_userid',\n password: 'a_default_password',\n}\n\ndef connect_to_oracle( interface_opts = {} )\n opts = DEFAULT.merge(interface_opts )\n\n url = \"jdbc:oracle:thin:%s/%s@%s:1521:%s\" % [\n opts[:userid],\n opts[:password],\n opts[:host_name],\n opts[:db_name],\n ]\n $db = Sequel.connect(url)\nend\nconnect_to_oracle()\nconnect_to_oracle(:host_name => :xxxxxxxx)\n</code></pre>\n\n<p>I prefer the version with <code>merge</code>. So I get a constant with all default parameters in my documentation.</p>\n\n<p>Another advantage: I can easily add checks if my interface contains correct keys.</p>\n\n<p>Example:</p>\n\n<pre><code>DEFAULT = {\n host_name: 'a_default_host_name',\n db_name: 'a_default_db_name',\n userid: 'a_default_userid',\n password: 'a_default_password',\n}\n\ndef connect_to_oracle( myopts = {} )\n (myopts.keys - DEFAULT.keys).each{|key|\n puts \"Undefined key #{key.inspect}\"\n }\n opts = DEFAULT.merge(myopts)\n\n url = \"jdbc:oracle:thin:%s/%s@%s:1521:%s\" % [\n opts[:userid],\n opts[:password],\n opts[:host_name],\n opts[:db_name],\n ]\n #~ $db = Sequel.connect(url)\nend\nconnect_to_oracle(:host_nam => :xxxxxxxx)\n</code></pre>\n\n<p>My method call contains an error (forgotten 'e'), but when you call it, you get a warning <code>Undefined key host_nam</code>. This often helps to detect errors. (in a real scenario I replace the puts with a logger-warning/error).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:35:57.463",
"Id": "65281",
"Score": "1",
"body": "`.dup.update` can also be expressed as `.merge`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:45:20.680",
"Id": "65283",
"Score": "1",
"body": "@WayneConrad Thanks. I already used it in the past, but it seems I forgot it again. I adapted my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-08T23:42:04.070",
"Id": "351834",
"Score": "0",
"body": "Be very careful with boolean hash parameters using the `key = ops[:key] || default` if you try to pass in false it will always default. One way around it would be to do something like `key = ops[:key].nil? ? true : ops[:key]` you could try to shorten this up by assuming that if they pass in that key it's going to be false rather than the default value, but then you run the risk that they pass in the same value as the default (assuming it's true) and you falsely presume it to be false. You could also invert your values so the default is false rather than true, but loose readability."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:07:17.757",
"Id": "39024",
"ParentId": "39017",
"Score": "24"
}
},
{
"body": "<p>If you are using Ruby 2.0 or better you can use keyword arguments to accomplish this very cleanly. In the past (pre 2.0) I have used a custom helper method to duplicate this functionality. The call to the helper would look like this:</p>\n\n<pre><code>opts.set_default_keys!({your: \"default\", values: \"go here\"})\n</code></pre>\n\n<p>The helper would be a relatively safe monkey patch on Hash and would only replace the unset keys with the default values and leave the existing values as they are.</p>\n\n<p>For documentation on keyword arguments in Ruby >= 2.0 visit <a href=\"http://www.ruby-doc.org/core-2.1.0/doc/syntax/methods_rdoc.html#label-Arguments\" rel=\"noreferrer\">rdoc.org - methods.rdoc</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:17:38.340",
"Id": "39025",
"ParentId": "39017",
"Score": "4"
}
},
{
"body": "<p>In raw Ruby, you can use <code>Hash#merge</code>. Since keys in the hash in argument will win, you can write that this way:</p>\n\n<pre><code>opts = {host_name: \"a_default_host_name\", db_name: \"a_default_db_name\"}.merge(opts)\n</code></pre>\n\n<p>If you use Rails framework, you can use the very convenient and elegant <code>Hash#reverse_merge!</code> method that edits the var itself (as the bang reminds you)</p>\n\n<pre><code>opts.reverse_merge!(host_name: \"a_default_host_name\", db_name: \"a_default_db_name\")\n</code></pre>\n\n<p>Note: You can use Active Support extensions (very useful little pieces of software that improves Ruby) without using all Rails framework, just load the extension you want, in this case it would be :</p>\n\n<pre><code>require 'active_support/core_ext/hash/reverse_merge'\n</code></pre>\n\n<p>Source: <a href=\"http://guides.rubyonrails.org/active_support_core_extensions.html#reverse-merge-and-reverse-merge-bang\">Rails Guides</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T19:07:31.773",
"Id": "73495",
"ParentId": "39017",
"Score": "8"
}
},
{
"body": "<p><strong>For newer ruby versions</strong></p>\n\n<p>Since Ruby 2.1 keyword arguments are the best option.</p>\n\n<pre><code>def initialize(person:, greeting: \"Hello\")\nend\n</code></pre>\n\n<p>Here, person is required while greeting is not. If you don't pass person, you will get an <code>ArgumentError: missing keyword: person</code>.</p>\n\n<p>The semantics of calling a method with keyword arguments are identical to a hash.</p>\n\n<pre><code>Greeter.new(greeting: \"Hey\", person: \"Mohamad\")\n</code></pre>\n\n<hr>\n\n<p><strong>For older ruby versions</strong></p>\n\n<p>For older versions of Ruby (pre 2.1), one can use fetch<a href=\"http://www.ruby-doc.org/core-2.1.5/Hash.html#method-i-fetch\" rel=\"nofollow noreferrer\"><code>fetch</code></a>.</p>\n\n<p>Using <code>fetch</code> has two advantages:</p>\n\n<ol>\n<li>It lets you set default values</li>\n<li>It raises an error if you don't specify a default</li>\n</ol>\n\n\n\n<pre><code>def initialize(options = {})\n @greeting = options.fetch(:greeting, \"Hello\")\n @person = options.fetch(:person)\nend\n</code></pre>\n\n<p>If you attempt to instantiate an object without passing a <code>:person</code>, Ruby will raise an error. While <code>:greeting</code> will default to <em>hello</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-12-12T20:29:30.813",
"Id": "73503",
"ParentId": "39017",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "39024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T19:03:28.817",
"Id": "39017",
"Score": "29",
"Tags": [
"ruby"
],
"Title": "Setting defaults in a Ruby options hash"
}
|
39017
|
<p>I've just complete a Pig Latin translator as a code kata and I was hoping someone would review it for me.</p>
<p>Here is the kata:</p>
<pre><code>PigLatin Kata
Create a PigLatin class that is initialized with a string
- detail: The string is a list of words separated by spaces: 'hello world'
- detail: The string is accessed by a method named phrase
- detail: The string can be reset at any time without re-initializing
- example: PigLatin.new('hello world')
completed (Y|n):
Translate Method
Create a translate method that translates the phrase from english to pig-latin.
- detail: The method will return a string.
- detail: The empty string will return nil.
- example: "" translates to nil
completed (Y|n):
Translate words that start with vowels.
- detail: Append "ay" to the word if it ends in a consonant.
- example: "ask" translates to "askay"
- detail: Append "yay" to the word if it ends with a vowel.
- example: "apple" translates to "appleyay"
- detail: Append "nay" to the word if it ends with "y".
- example: "any" translates to "anynay"
completed (Y|n):
Translate a word that starts with a single consonant.
- detail: Removing the consonant from the front of the word.
- detail: Add the consonant to the end of the word.
- detail: Append 'ay' to the resulting word.
- example: "hello" translates to "ellohay"
- example: "world" translates to "orldway"
completed (Y|n):
Translate words that start with multiple consonants.
- detail: Remove all leading consonants from the front of the word.
- detail: Add the consonants to the end of the word.
- detail: Append 'ay' to the resulting word.
- example: "known" translates to "ownknay"
- example: "special" translates to "ecialspay"
completed (Y|n):
Support any number of words in the phrase.
- example: "hello world" translates to "ellohay orldway"
- detail: Each component of a hyphenated word is translated seperately.
- example: "well-being" translates to "ellway-eingbay"
completed (Y|n):
Support capital letters.
- detail: If a word is captalized, the translated word should be capitalized.
- example: "Bill" translates to "Illbay"
- example: "Andrew" translates to "Andreway"
completed (Y|n):
Retain punctuation.
- detail: Punctuation marks should be retained from the source to the translated string
- example: "fantastic!" tranlates to "anfasticfay!"
- example: "Three things: one, two, three." translates to "Eethray ingsthay: oneyay, otway, eethray."
completed (Y|n):
Congratulations!
- Create a PigLatin class that is initialized with a string 00:12:52
- Create a translate method that translates the phrase from english to p 00:03:00
- Translate words that start with vowels. 00:08:56
- Translate a word that starts with a single consonant. 00:04:32
- Translate words that start with multiple consonants. 00:08:08
- Support any number of words in the phrase. 00:25:19
- Support capital letters. 00:05:05
- Retain punctuation. 00:17:00
----------------------------------------------------------------------
Total Time taking PigLatin kata: 01:24:52
</code></pre>
<p>And my specs:</p>
<pre><code>require 'spec_helper'
require 'piglatin'
describe PigLatin do
let(:pig_latin) { PigLatin.new(string) }
let(:string) { "hello world" }
describe "new" do
specify { expect { pig_latin }.to_not raise_error }
end
describe ".phrase" do
subject { pig_latin.phrase }
it { should eq("hello world") }
it "can reset the phrase" do
pig_latin
pig_latin.phrase = "world hello"
subject.should eq("world hello")
end
end
describe ".translate" do
subject { pig_latin.translate }
its(:class) { should eq(String) }
context "empty string" do
let(:string) { "" }
it { should eq(nil) }
end
context "words that start with vowels" do
let(:string) { "ask" }
it { should eq("askay") }
context "and also ends with a vowel" do
let(:string) { "apple" }
it { should eq("appleyay") }
end
context "and ends with y" do
let(:string) { "any" }
it { should eq("anynay") }
end
end
context "words that start with a single consonant" do
let(:string) { "hello" }
it { should eq("ellohay") }
end
context "words that start with multiple consonants" do
context "known" do
let(:string) { "known" }
it { should eq("ownknay") }
end
context "special" do
let(:string) { "special" }
it { should eq("ecialspay") }
end
end
context "multiple words" do
let(:string) { "hello world" }
it { should eq("ellohay orldway") }
context "hyphenated words" do
let(:string) { "well-being" }
it { should eq("ellway-eingbay") }
end
end
context "Capitalization" do
context "Bill" do
let(:string) { "Bill" }
it { should eq("Illbay") }
end
context "Andrew" do
let(:string) { "Andrew" }
it { should eq("Andreway") }
end
end
context "Retain Punctuation" do
context "fantastic!" do
let(:string) { "fantastic!" }
it { should eq("antasticfay!") }
end
context "Three things: one, two, three." do
let(:string) { "Three things: one, two, three." }
it { should eq("Eethray ingsthay: oneyay, otway, eethray.") }
end
end
end
end
</code></pre>
<p>And, finally, the <code>PigLatin</code> class:</p>
<pre><code>class PigLatin
attr_accessor :phrase
def phrase=(string)
@phrase = string
end
alias :initialize :phrase=
def translate
return nil if (@phrase.empty?)
word_array = @phrase.split(/\s/)
word_array.collect! do |word|
translate_word(word)
end
translated_phrase = word_array.join(" ")
return translated_phrase
end
private
def translate_word word
words = word.split("-")
words.collect! do |word|
punctuation = word.slice!(/\W/)
if (word[0] =~ /[aeiou]/i)
case word[-1]
when /[aeiou]/
word += "yay"
when /y/
word += "nay"
else
word += "ay"
end
else
consonants = word.slice!(/^[^aeiou]*/)
word.capitalize! if (consonants.downcase!)
word += consonants + "ay"
end
if (punctuation)
word << punctuation
end
word
end
return words.join("-")
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Good marks for:</p>\n\n<ul>\n<li>Formatting</li>\n<li>Naming</li>\n<li>Each spec tests just one thing</li>\n<li>Coverage of edge cases such as empty string.</li>\n</ul>\n\n<p>I think I would change the name from PigLatin to PigLatinTranslator. I can't think of a \"pig latin\" as a thing.</p>\n\n<p>Was the API required by the challenge? If not, I'd consider simplifying it.\nThere's not much reason for the translator to have any state. You can simplify it if the #translate method takes the string to be translated. You won't need the accessors or the #initialize method.</p>\n\n<p>That #translate returns nil if the phrase is an empty string is a little surprising. I expect it to return an empty string.</p>\n\n<p>Instead of splitting on white space, consider using gsub to scan for words and replace them. If you do that, you can remove all of #translate_word's special handling of punctuation:</p>\n\n<pre><code> def translate\n return nil if @phrase.empty?\n @phrase.gsub(/\\w+/) do |word|\n translate_word(word)\n end\n end\n</code></pre>\n\n<p><code>return word</code> at the end of #translate_word can be simply <code>word</code>. The only reason to use the <em>return</em> keyword is for a return before the end of the method.</p>\n\n<p>The sequence <code>aeiou</code> might deserve to be a constant:</p>\n\n<pre><code>VOWEL = 'aeiou'\n\n ...\n\n if word[0] =~ /[#{VOWEL}]/i\n ...\n when /[#{VOWEL}]/\n ...\n consonants = word.slice!(/[^#{VOWEL}]*/)\n</code></pre>\n\n<p>Handling of capitalization can be handled by, at the beginning of the function, noticing whether or not the word is capitalized, and then downcasing it:</p>\n\n<pre><code>is_capitalized = word =~ /^A-Z/\nword = word.downcase\n</code></pre>\n\n<p>and at the end, capitalizing it again if needed.</p>\n\n<pre><code>word = word.capitalized if is_capitalized\n</code></pre>\n\n<p>This removes considerations of case from the rest of the function.</p>\n\n<p>Expressions like <code>word[0] =~ /.../</code> can be replaced with <code>word =~ /^.../</code>. Similarly, <code>word[1] =~ /.../</code> can be replaced with `word =~ /...$/</p>\n\n<p>Taken altogether, these suggestions yield a #translate_word more like this:</p>\n\n<pre><code> def translate_word(word)\n is_capitalized = word =~ /^[A-Z]/\n word = word.downcase\n if (word =~ /^#{VOWEL}/i)\n case word\n when /#{VOWEL}$/\n word += \"yay\"\n when /y$/\n word += \"nay\"\n else\n word += \"ay\"\n end\n else\n consonants = word.slice!(/^[^#{VOWEL}]*/)\n word += consonants + \"ay\"\n end\n word = word.capitalize if is_capitalized\n word\n end\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:34:46.470",
"Id": "65991",
"Score": "0",
"body": "Thanks for the notes. This is really helpful. Re: `return word` I like explicitly writing return. I know it's not necessary but -- maybe because I'm an old-school C guy -- it looks better to me. I use parenthesis and stuff too ;) Re: state, I was modeling the class off of String, etc... where you have state and then perform operations from there. It might make sense to subclass String and add a `translate` method to out put pig latin ... Anyway, thanks again for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T20:35:53.020",
"Id": "65992",
"Score": "0",
"body": "@user341493 - Thank you for the fun question, and for considering my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T21:12:16.913",
"Id": "39028",
"ParentId": "39019",
"Score": "2"
}
},
{
"body": "<p>Here is another way to write the <code>translate_word</code> method. I decided to subclass <code>String</code>, thinking it might improve readability. </p>\n\n<pre><code>class Vowel < String; end\nclass Consonant < String; end\nclass Y < Consonant; end\n\nYAY = %w[y a y]\nNAY = %w[n a y]\nAY = %w[a y]\n\ndef assign_chars_to_classes(word)\n raise ArgumentError, \"Choked on #{word}\" unless word =~ /^[a-z]*$/i\n word.downcase.chars.each_with_object([]) do |c,a|\n a << if \"aeiou\".include?(c)\n Vowel.new(c)\n elsif c == 'y' \n Y.new(c)\n else\n Consonant.new(c)\n end\n end\nend\n\ndef translate_word(word)\n return nil if word.empty?\n w = assign_chars_to_classes(word)\n case w.first\n when Vowel\n w +=\n case w.last\n when Vowel \n YAY\n when Y\n NAY\n else # Consonant\n AY\n end \n else # begins with a consonant\n while w.first === Consonant\n w.rotate!\n end if w.find {|c| c === Vowel}\n w += AY \n end\n w.first.capitalize! if word[0] == word[0].capitalize\n w.join\nend \n\np translate_word('') # => nil\np translate_word('ask') # => 'askyay' \np translate_word('apple') # => 'appleyay'\np translate_word('any') # => 'anynay'\np translate_word('d') # => 'day'\np translate_word('dog') # => 'ogday'\np translate_word('Phony') # => 'Onyphay'\np translate_word('zzzzi') # => 'izzzzay'\np translate_word('cat3') # => 'Choked on cat3 (ArgumentError)'\n</code></pre>\n\n<p>Consider the word 'Phony'. The first step is</p>\n\n<pre><code>w = assign_chars_to_classes('Phony') # => [\"p\", \"h\", \"o\", \"n\", \"y\"]\n</code></pre>\n\n<p>where</p>\n\n<pre><code>w.map(&:class) # => [Consonant, Consonant, Vowel, Consonant, Y]\n</code></pre>\n\n<p>As <code>w.first => \"p\"</code> is of class <code>Consonant</code> (recall <code>case</code> uses <code>===</code>), we see if <code>w</code> contains any vowels:</p>\n\n<pre><code>if w.find {|c| c === Vowel} # => \"o\"\n</code></pre>\n\n<p>As <code>w</code> contains at least one vowel, we move the leading consonants (\"p\" and \"h\") to the end:</p>\n\n<pre><code>while w.first === Consonant\n w.rotate!\nend # => [\"o\", \"n\", \"y\", \"p\", \"h\"]\n</code></pre>\n\n<p>capitalize the first element of <code>w</code> if the <code>word</code> is capitalized:</p>\n\n<pre><code>w.first.capitalize! if word[0] == word[0].capitalize\n # w => [\"O\", \"n\", \"y\", \"p\", \"h\", \"a\", \"y\"]\n</code></pre>\n\n<p>and join the elements of <code>w</code>:</p>\n\n<pre><code>w.join # => \"Onyphay\" \n</code></pre>\n\n<p>Edit: I initially had</p>\n\n<pre><code>w = w.chunk {|c| c.is_a? Consonant}.map(&:last).rotate.flatten + AY\n</code></pre>\n\n<p>in place of</p>\n\n<pre><code>while w.first === Consonant\n w.rotate!\nend if w.find {|c| c === Vowel}\n</code></pre>\n\n<p>but prefer what I have now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T04:56:48.057",
"Id": "65471",
"Score": "0",
"body": "Here `case w.first\n when Vowel\n w +=` I think you forgot to increment `w`..as I am seeing it as `w +=` only.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:18:51.907",
"Id": "65607",
"Score": "0",
"body": "@Arup, I'm appending what is returned by `case` to `w`. I just formatted it this way so `case w.last` would stand alone (i.e., line-continuation character `\\\\` not required)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T08:25:29.500",
"Id": "39080",
"ParentId": "39019",
"Score": "1"
}
},
{
"body": "<p>Expanding on part of Wayne's post, but taking a more declarative approach which avoids the case statement and makes the high level logic more visible, I came up with this:</p>\n\n<pre><code>VOWEL = \"[aeiou]\"\ndef translate_word(word)\n restore_capitalization = (word =~ /^[A-Z]/) ? :capitalize : :to_s\n ret = word.downcase\n\n ret = (ret =~ /^#{VOWEL}/i) ? vowel_translator(ret) : consonant_translator(ret)\n ret.send(restore_capitalization)\nend\n\ndef vowel_translator(word)\n suffixes = [ {re: /#{VOWEL}$/, suffix: 'yay'}, {re: /y$/, suffix: 'nay'}, {re: /./, suffix: 'ay'} ]\n correct_suffix = suffixes.find {|h| word =~ h[:re]}[:suffix]\n word + correct_suffix\nend\n\ndef consonant_translator(word)\n consonants = word.slice!(/^[^#{VOWEL}]*/)\n word + consonants + \"ay\"\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T16:25:31.247",
"Id": "66796",
"Score": "0",
"body": "An interesting approach! I would consider `word = word.downcase`; when practical, a function should either have side effects (such as modifying the argument) and return no value, or have no side effects and return a value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T18:28:04.840",
"Id": "66809",
"Score": "0",
"body": "Thanks Wayne. Isn't `word.downcase!` an example of having side effects (it mutates `word`) and returning no value? Of course, technically *all* ruby methods return some value, but here the value isn't used, so as far as the client code is concerned it is returning no value. Although for clarity I am tempted to rewrite the first line of the method as `ret = word.downcase`, leave the 2nd line as is, and then replace all occurences of `word` in the last 2 lines with `ret`. This breaks the method up into an \"intro\" section and a \"body\", per Avdi Grimm, a technique I like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T18:32:27.180",
"Id": "66810",
"Score": "0",
"body": "I meant #translate_word, which is currently both returning a value and modifying its argument. @Avdi Grimm is smart-do you have a link to where he suggested that technique?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T18:48:39.380",
"Id": "66816",
"Score": "1",
"body": "Ah, yes good point. My other suggestion would answer that critique as well. I think I'll go ahead and make the edit. I believe that technique is a big theme of \"Confident Ruby\", and I think also discussed in [this video](https://www.youtube.com/watch?v=T8J0j2xJFgQ)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T12:22:18.983",
"Id": "39801",
"ParentId": "39019",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39028",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T19:27:40.807",
"Id": "39019",
"Score": "2",
"Tags": [
"ruby",
"rspec",
"pig-latin"
],
"Title": "Pig Latin Code Kata"
}
|
39019
|
<ul>
<li>I want to first search for a specific regular expression.</li>
<li>If it is not found then I would like to search for another regular expression</li>
<li>If that one is also not found then I would like to search for a third</li>
<li>(And so on...)</li>
</ul>
<p>Whenever a matching regular expression is found, I want to return a String array containing:</p>
<ul>
<li>The text before the match</li>
<li>The match itself</li>
<li>The text after the match</li>
</ul>
<p>I've only come up with this horribly if-else nesting way of doing it. There's gotta be a better (more extensible and more clean) way but I can't come up with how...</p>
<p>Here is the code, it is currently only containing two regular expressions to search for and it's getting nasty already:</p>
<pre><code>private static String[] findNumbers(String string) {
Matcher match = Pattern.compile("\\d+[\\:\\.\\,]\\d+").matcher(string);
if (match.find()) {
String found = string.substring(match.start(), match.end());
return new String[]{ string.substring(0, match.start()),
found, string.substring(match.end()) };
}
else {
match = Pattern.compile("\\d{3,}").matcher(string);
if (match.find()) {
String found = string.substring(match.start(), match.end());
return new String[]{ string.substring(0, match.start()),
found, string.substring(match.end()) };
}
else {
// Another if-else could be added here
return new String[]{ string, "", "" };
}
}
}
@Test
public void test() {
assertArrayEquals(new String[]{ "ABC ", "2000", " DEF" }, findNumbers("ABC 2000 DEF"));
assertArrayEquals(new String[]{ "42 ABC ", "2000", " DEF" }, findNumbers("42 ABC 2000 DEF"));
assertArrayEquals(new String[]{ "42 ABC ", "18:47", " DEF" }, findNumbers("42 ABC 18:47 DEF"));
}
</code></pre>
<p>I want to put priority to one regular expression before trying the next, that's why I have written this code.</p>
|
[] |
[
{
"body": "<p>You could use the <code>(expression1|expression2|expression3)</code> syntax. It makes for a long string, but you won't have to nest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:24:20.567",
"Id": "65279",
"Score": "4",
"body": "Good instinct, but it wouldn't behave the same way as the original. Your solution would produce the leftmost longest match. The original falls back only when the first expression fails to match at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:17:22.490",
"Id": "65516",
"Score": "0",
"body": "Any developer worth their salt should be able to write a regex that looks like this: \"^(.*)(matchthis|matchthat|matchsomethingelse)(.*)$\". It's not that hard at all. I was merely suggesting that the OP employ the use of the grouping construct in the middle to prevent the need for iteration, BUT without deconstructing his code to write an exact working answer FOR him."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T12:46:00.350",
"Id": "79581",
"Score": "1",
"body": "@codenoire the problem is, in description OP states: matchtis-> remove matches; matchthat -> remove matches; matchsomethingelse -> removematches. and your approach does not fulfil the requirement that the code outputs the same results as before... This makes your answer incorrect. either correct your answer or delete it, please.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T13:10:24.107",
"Id": "79593",
"Score": "1",
"body": "I've edited the question part to make it look more like a real answer. You should add a bit of explanation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:01:28.310",
"Id": "39021",
"ParentId": "39020",
"Score": "-3"
}
},
{
"body": "<p>Nesting is not necessary, you can iterate instead...</p>\n\n<p>But first:</p>\n\n<ul>\n<li>naming the input String <code>string</code> can be confusing. Of course it's a string, what is it used for though?</li>\n<li>there is no need to escape the values inside the <code>[...]</code> construct. the pattern: <code>\"\\\\d+[:.,]\\\\d+\"</code> is just fine, and more readable.</li>\n<li>you should be pre-compiling and then reusing the patterns, instead of re-compiling them every time.</li>\n</ul>\n\n<p>Consider the following:</p>\n\n<pre><code>private static final Pattern[] patternorder = { \n Pattern.compile(\"\\\\d+[:.,]\\\\d+\"),\n Pattern.compile(\"\\\\d{3,}\")\n};\n\nprivate static String[] findNumbers(String input) {\n for (Pattern pat : patternorder) {\n Matcher match = pat.matcher(input);\n if (match.find()) {\n return new String[] {\n input.substring(0, match.start()),\n input.substring(match.start(), match.end()),\n input.substring(match.end()),\n };\n }\n }\n return new String[]{input, \"\", \"\"};\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:40:07.493",
"Id": "65282",
"Score": "0",
"body": "Ah, apparently `.` don't match every character when inside `[]`!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:05:53.440",
"Id": "39023",
"ParentId": "39020",
"Score": "10"
}
},
{
"body": "<p>Using <strong>capturing group</strong> with <strong>alternation</strong> ,no loop should be required.</p>\n\n<pre><code>private static final Pattern patternorder = Pattern.compile(\"(\\d+[\\:\\.\\,]\\d+)|(\\d{3,})\"); \n private static String[] findNumbers(String input) {\n\n Matcher match = pat.matcher(input);\n if (match.find()) {\n if(match.group(1)!=null){\n return processMatchGroup(match.group(1)); //apply substring functions \n } \n if(match.group(2)!=null){\n return processMatchGroup(match.group(2)); \n }\n}\nreturn new String[]{input, \"\", \"\"}; \n}\n</code></pre>\n\n<p>One of community member replied that alternation will produce leftmost longest match which is true for text directed engine. But if used in Java, Perl, .NET, JavaScript etc ,these works with regex directed engine which gives leftmost eager search. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-07T06:03:17.353",
"Id": "189029",
"ParentId": "39020",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T19:47:22.843",
"Id": "39020",
"Score": "13",
"Tags": [
"java",
"strings",
"regex"
],
"Title": "Recursive Regular Expressions"
}
|
39020
|
<p>I'm trying to make a simple UI to better understand how interfaces and the <code>System.Windows.Forms</code> Controls behave.</p>
<p>Like the above namespace, I will be able to get and set the Focus on a particular control, with a helper method to drill down to see which Control (or child Control) actually has the focus. I'm pretty rubbish for recusion.</p>
<p>Here's what I have so far:</p>
<pre><code>public class Control
{
public bool CanFocus { get; set; }
public bool HasFocus { get; set; }
public Control GetFocus()
{
if (HasFocus)
return this;
foreach (Control c in Children)
{
if (c.HasFocus)
c.GetFocus();
}
return null;
}
}
</code></pre>
<p>My thought process is that it should return the immediate control if it has focus. If not, it will recurse through each of its children. If that child has the focus, it will return that child, and if not, will find the next one, repeating until a default case (null) is reached.</p>
<p>I had thought about a ContainsFocus field as well, but it "sort of" overlaps with what I'm doing here. I considered a helper method with the signature <code>bool FindFocus(out Control result)</code>, but it felt unwieldy. Also, I am concerned with invoking <code>foreach</code> within a recursive function.</p>
<p>I appreciate any insight into this.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Here's what I have so far</p>\n</blockquote>\n\n<p>The code you wrote doesn't quite work properly; because, depending on the behaviour (which isn't clearly defined) of your <code>HasFocus</code> property:</p>\n\n<ul>\n<li>Either it will return too early (it returns immediately, if this.HasFocus is true when a child has focus)</li>\n<li>Or it will return null (it doesn't descend, if child.HasFocus is false when a grandchild has the focus).</li>\n</ul>\n\n<p>I don't quite understand your question: <code>Control</code> is a System class, so how are you supplying source code for it? I'm guessing you're using it as an example and writing pseudo-code.</p>\n\n<p>To avoid confusion, I'm going to:</p>\n\n<ul>\n<li>Assume you're writing code for the standard <code>System.Windows.Forms.Control</code> class</li>\n<li>Assume that Control has the standard <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.containsfocus%28v=vs.110%29.aspx\" rel=\"nofollow\">ContainsFocus</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focused%28v=vs.110%29.aspx\" rel=\"nofollow\">Focused</a> properties</li>\n<li>Write a class which defines GetFocus has a new <a href=\"http://msdn.microsoft.com/en-us//library/bb383977.aspx\" rel=\"nofollow\">extension method</a></li>\n</ul>\n\n<p>I suggest:</p>\n\n<pre><code>public static class ControlExtensions\n{\n public static Control GetFocus(this Control control)\n {\n if (control.Focussed)\n return this;\n\n foreach (Control child in Children)\n {\n if (!child.ContainsFocus)\n continue;\n return GetFocus(child); // recurses\n }\n\n return null;\n }\n}\n</code></pre>\n\n<p>Or, assuming that it is your own Control class as you wrote it in the OP, I would implement its recursive GetFocus as follows:</p>\n\n<pre><code>public class Control\n{\n public bool CanFocus { get; set; }\n public bool HasFocus { get; set; }\n\n public Control GetFocus()\n {\n if (HasFocus)\n return this;\n\n foreach (Control child in Children)\n {\n Control found = child.GetFocus();\n if (found != null)\n return found;\n }\n\n return null;\n }\n\n public bool ContainsFocus\n {\n get { return GetFocus() != null; }\n }\n}\n</code></pre>\n\n<p>In this second implementation, the GetFocus implementation doesn't call ContainsFocus:</p>\n\n<ul>\n<li>Because ContainsFocus calls GetFocus</li>\n<li>Because ContainsFocus descends the tree of children in order to decide whether to return true, so GetFocus might as well do the same (descend the tree of children) but return the actual Control instead of just returning bool.</li>\n</ul>\n\n<p>Beware that your HasFocus implementation (as coded above) isn't good enough: because you must ensure that only one Control has the focus (so if you set the focus, then you need to remove focus from whichever control previously had the focus, if there is one).</p>\n\n<blockquote>\n <p>I considered a helper method with the signature <code>bool FindFocus(out Control result)</code>, but it felt unwieldy.</p>\n</blockquote>\n\n<p>It's enough to return <code>null</code> if there is no focus.</p>\n\n<p>You might want to return bool if you want to return additional information; for example:</p>\n\n<pre><code>Customer customer;\nbool success = FetchCustomer(customerId, out customer);\nif (!success)\n{\n // fetch failed because database or network is down\n}\nelse\n{\n if (customer == null)\n {\n // fetch successfully says that there is no such customer\n }\n else\n {\n // fetch successfully returned the requested customer\n }\n}\n</code></pre>\n\n<p>In your example however the GetFocus algorithm/implementation cannot 'fail', so returning <code>Control</code> is enough (instead of returning bool as well as having an <code>out</code> parameter).</p>\n\n<p>Having an <code>out</code> parameter is necessary if <code>null</code> is a valid value: for example <a href=\"http://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx\" rel=\"nofollow\">the Dictionary.TryGetValue method</a> (because a Dictionary can contains nulls, so it needs a bool to say whether it's in the dictionary at all).</p>\n\n<p>Having a bool with an out parameter is also necessary <a href=\"https://www.google.com/search?q=c%23+class+struct\" rel=\"nofollow\">if the type in question is a struct instead of a class</a>: because a struct cannot be null. In this case though, Customer is a class not a struct.</p>\n\n<blockquote>\n <p>Also, I am concerned with invoking foreach within a recursive function.</p>\n</blockquote>\n\n<p>Why? It's not a problem per se.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T22:15:02.717",
"Id": "39030",
"ParentId": "39027",
"Score": "4"
}
},
{
"body": "<p>Shouldn't need any recursion or iteration if you set all the controls to the same Enter event handler. Simply set a class level control object to sender whenever the event handler fires.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T00:35:09.907",
"Id": "65727",
"Score": "0",
"body": "This answer gets the checkmark since it solves my problem perfectly. Rather than having to muck with dependencies and recursion, I can just raise an event on the manager class, and have everything update accordingly. @ChrisW's answer is fantastic however, because it explains everything in depth."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:33:50.040",
"Id": "39036",
"ParentId": "39027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39036",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T20:52:29.987",
"Id": "39027",
"Score": "3",
"Tags": [
"c#",
"recursion",
"user-interface"
],
"Title": "Custom UI - Seeing which control has focus"
}
|
39027
|
<p>I've been coding for a while, but this is the first actual project I've made. I generally do contest programming, and as you might imagine, good code practices are not exactly the top priority. I'd appreciate any pointers, whether overall design of the program, or variable naming, or things that I should have split up into more functions.</p>
<p>Note: This program crawls the HTML of a Schoolloop page, retrieves whether it's a percentage based final or points based, and outputs the grade on the final required to get a specific grade.</p>
<pre><code>function httpGet(theUrl){ //gets raw_html code of page. Credit to Stackoverflow user Joan
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
//#########################################################################################################################
var raw_raw_html=String(httpGet(document.URL));
var value_final_percent, needed_grade, current_grade, name, period, id; //value_final_percent=percentage of final, needed_grade=needed grade, current_grade=current grade, id=name+period
var max_in_category, ccat, tpoints, cpoints; //max_in_category=total in category, ccat=current points in category
var final_points;
var start;
var is_weighted;
max_in_category={};
ccat={};
tpoints=0;
cpoints=0;
$("<div/>", {id: "needed_grades"}).appendTo("#page_title");
$("<div/>", {id: "popup", style:visibility="hidden"}).appendTo("#container_page");
//This line is the raw_html for the popup. Probably a better solution, but eh.
popup.innerHTML+=('<form id="user_final" method="GET">' +
'<input type="text" name="inputbox">' +
'</form> ' +
'' +
'<select id="type_final"> ' +
'<option value="percent">Percentage</option>' +
'<option value="points" selected>Points</option>' +
'</select>');
var needed_grade=document.getElementById("needed_grades");
needed_grade.style.fontSize = "25px";
//##########################################################################################################################
//this prevents the default action(going to another page)
//and closes the popup.
$('#popup').keydown(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER){
update();
$("#popup").dialog("destroy");
}
});
function exist(int index){
return index==-1 ? false : true;
}
function find_values(){ //Finds the value of value_final_percent, name, current_grade
start=raw_html.indexOf("<td class='list_label' nowrap>Weight:</td>"); //The marker used if the class is percentage based. except for Mr. Daniel
if(start!=-1){
is_weighted=true;
} else{
is_weighted=false;
}
console.log(start);
if(!is_weighted){
var limit=raw_html.indexOf("Grade Trend");
console.log("Grade Trend", limit);
var cur=0;
while(cur < limit && cur!=-1 && t!=-1 && score!=-1 && begin!=-1){
var t=raw_html.indexOf('style="width: 265px;"', cur+1); //finds the category it belongs in.
if(t==-1) break;
var begin=raw_html.indexOf(">", t);
var end=raw_html.indexOf("<br", begin);
var cat=raw_html.substring(begin+1, end);
var score=raw_html.indexOf("Score:", end); //finds points achieved on assignment.
var check=raw_html.indexOf('<b class="red">', score);
if(check-score<30&&check!=-1){ //workaround for zeros.
begin=raw_html.indexOf(">", check);
end=raw_html.indexOf("</b>", begin);
}
else{
begin=raw_html.indexOf(" ", score);
end=raw_html.indexOf("</div", begin);
}
var gotscore=raw_html.substring(begin+1, end);
begin=Math.min(raw_html.indexOf("/ ", end), raw_html.indexOf("-", end)); //finds max points on assignment
if(raw_html[begin]=='-'){ //workaround for extra credit.
outof="0";
cur=begin;
}
else{
end=raw_html.indexOf(" =", begin);
outof=raw_html.substring(begin+2, end);
}
cur=end;
if(cat in max_in_category){
max_in_category[cat]=parseInt(max_in_category[cat])+parseInt(outof);
ccat[cat]=parseInt(ccat[cat])+parseInt(gotscore);
} else{
max_in_category[cat]=outof;
ccat[cat]=gotscore;
}
tpoints+=parseInt(outof);
cpoints+=parseInt(gotscore);
/*console.log(cat);
console.log(ccat[cat]);
console.log(max_in_category[cat]);
console.log("#1:"+gotscore);
console.log("#2:"+outof);*/
}
}
else if(!is_weighted){ //If this is a percentage based final
start=raw_html.toLowerCase().indexOf("final", start);
//console.log(start);
if(!is_weighted) {
value_final_percent=raw_html.substring(raw_html.toLowerCase().indexOf("wrap>", start)+5, raw_html.toLowerCase().indexOf("%", start));
}
var t=raw_html.indexOf("Score:");
current_grade=raw_html.substring(t+17, raw_html.indexOf("%", t));
}
var t=raw_html.indexOf('"logged_in"'); //finds name of user
var begin=raw_html.indexOf(">", t);
var end=raw_html.indexOf("<", begin);
name=raw_html.substring(begin+1, end);
t=raw_html.indexOf("nowrap>Period"); //finds period
//console.log(t);
begin=raw_html.indexOf(":", t);
end=raw_html.indexOf("<img", begin);
period=raw_html.substring(begin+2, end);
id=name+period;
}
function update(){ //This is called when the user modifies the value of the final, and closes dialog box
console.log("update");
var display_box=document.getElementById("type_final");
if(display_box.options[display_box.selectedIndex].value=="percent"){
value_final_percent=document.getElementById("user_final").inputbox.value;
localStorage["value_final_percent"+id]=value_final_percent;
console.log(value_final_percent);
if(start){
current_grade=cpoints/tpoints;
}
update_percent();
}
if(t.options[t.selectedIndex].value=="points"){
if(start==-1){
final_points=document.getElementById("user_final").inputbox.value;
localStorage["fpoints"+id]=final_points;
//console.log(tpoints);
update_points();
}
}
}
function update_percent(){ //This modifies the raw_html to display the percentage needed, ONLY percent based finals.
var cp=((current_grade/100.0)*(1.0-(value_final_percent/100.0))).toFixed(4);
needed_grade.innerHTML="";
t=((.9-cp)/(value_final_percent/(100.0*100.0))).toFixed(2);
needed_grade.innerHTML+="A: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp"
t=((.8-cp)/(value_final_percent/(100.0*100.0))).toFixed(2);
needed_grade.innerHTML+="B: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
t=((.7-cp)/(value_final_percent/(100.0*100.0))).toFixed(2);
needed_grade.innerHTML+="C: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
t=((.6-cp)/(value_final_percent/(100.0*100.0))).toFixed(2);
needed_grade.innerHTML+="D: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
}
function update_points(){
var cp=cpoints;
var fp=parseInt(final_points);
needed_grade.innerHTML="";
t=((.9*(tpoints+fp)-cp)/final_points*100.0).toFixed(2);
needed_grade.innerHTML+="A: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
t=((.8*(tpoints+fp)-cp)/final_points*100.0).toFixed(2);
needed_grade.innerHTML+="B: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
t=((.7*(tpoints+fp)-cp)/final_points*100.0).toFixed(2);
needed_grade.innerHTML+="C: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
t=((.6*(tpoints+fp)-cp)/final_points*100.0).toFixed(2);
needed_grade.innerHTML+="D: "+((t<0)?"Impossible ":t+"&nbsp")+"&nbsp&nbsp";
}
function adjustFinal(){ //creates a dialog box whenever the button afbutton is pressed.
/*var link = document.getElementById("afbutton");
link.addEventListener("click", function(){
alert("HI");
})*/
//prompt("Enter a value:", "");
$("#popup").dialog({
draggable: false,
modal: true,
position: {my: "center", at: "center"},
buttons: {"Done": function(){$(this).dialog("close"); update()}}
});
}
if (document.title.indexOf("Progress Report") != -1) {
find_values();
if(("value_final_percent"+id) in localStorage){ //checks to see if a final percentage has already been manually entered.
value_final_percent=parseInt(localStorage["value_final_percent"+id]);
}
if(("fpoints"+id) in localStorage){
final_points=localStorage["fpoints"+id];
update_points();
}
console.log(start);
if(!is_weighted){
update_percent();
}
$("<button/>", {id: "afbutton", click: adjustFinal, text: "Click to adjust finals value"}).appendTo("#page_title");
}
</code></pre>
|
[] |
[
{
"body": "<p>Ok a few things.</p>\n\n<p><em>JSHint</em></p>\n\n<p>First I'd run the code through <a href=\"http://www.jshint.com/\" rel=\"nofollow\">jshint</a> to conform to get some of the easy stuff out of the way. Depending on what editor you're using there are often plugins that will validate your JS with JSHint.</p>\n\n<p><em>Variable Names</em></p>\n\n<p>The general convention in javascript is to use camelcase for variable naming. All built in javascript functions are done in camelcase (i.e. <code>document.getElementById</code>).</p>\n\n<p><em>Variable Declaration</em></p>\n\n<p>I'd also be more consistent with where you declare your variables. They should all be at the top of the function due to hoisting. It's also good practice to declare a javascript namespace so that you do not create a bunch of global variables like you have. Always use <code>var</code> before declaring a variable.</p>\n\n<p><em>jQuery</em></p>\n\n<p>It looks like you're using jQuery in your document, so you might as well take advantage of some of the utilities that it comes with to make your life easier.</p>\n\n<p>Cache the <code>$('#popup')</code> in a variable <code>var $popup = $('#popup')</code> so you don't have to keep reselecting the element. Use jQuery's <code>html</code> function instead of <code>innerHTML</code> (ie <code>$popup.html('myhtmlstring')</code>.</p>\n\n<p>Use jQuery selectors if you've included it in the page. No need to use <code>getElementById</code>.</p>\n\n<p>Use jQuery's <code>$.get</code> function instead of your own http get method.</p>\n\n<p><em>Other</em></p>\n\n<p><code><div/></code> is not valid html. It should be <code><div></div></code>.</p>\n\n<pre><code>if(start!=-1){\n is_weighted=true;\n} else{\n is_weighted=false;\n} \n</code></pre>\n\n<p>Can be simplified to <code>is_weighted = start !== -1</code></p>\n\n<p>Please remove <code>console.log</code>s and <code>comments</code> before code review.</p>\n\n<p><code>exist</code> function is unused and not useful.</p>\n\n<p>There seems to be a lot of code here and it's a bit out of scope to refactor logic, but I'd say that this could be more concise and better written by trying to separate logic from presentation. Right now your html is mixed right in with all this crazy logic which makes the code very unmaintainable.</p>\n\n<p>Hope this gives you something to start with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T06:02:06.447",
"Id": "65628",
"Score": "0",
"body": "Thanks. What do you mean by separating logic from presentation? Like should I store the html code in variables, and use those in functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T08:23:56.293",
"Id": "65748",
"Score": "0",
"body": "It's the idea that functions that have to do with logic should just contain logic and then use the output of those to determine what the presentation is. The philosophy is that the presentation changes much more rapidly than the logic so it's good to separate them to reduce bugs. I'd do a google search on 'MVC' or 'separation of presentation from logic' to find a good guide."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T11:38:01.167",
"Id": "39085",
"ParentId": "39032",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39085",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T01:10:54.570",
"Id": "39032",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"google-chrome"
],
"Title": "Automated finals calculator in JavaScript/jQuery"
}
|
39032
|
<p>I had an overloaded method, but Grails doesn't allow overloaded methods in controller actions. The overloaded method looked like this:</p>
<pre><code>def punch(User user, User source) {
user.userVersion++
punch(user, source, null, null)
}
def punch(User user, User source, String latitude, String longitude) {
UserPunch userPunch = new UserPunch()
userPunch.punchClockStatus = user.punchClockStatus
userPunch.user = user
userPunch.job = user.job
userPunch.task = user.task
userPunch.date = new Date()
userPunch.source = source
userPunch.save(flush: true)
if (latitude != null) {
userPunch.latitude = latitude
userPunch.longitude = longitude
}
if (userPunch.hasErrors())
userPunch.errors.each {
log.error it
}
}
</code></pre>
<p>In order to get around the restrictions on overloaded methods, I used a try/catch, like this:</p>
<pre><code>def punch(User user, User source, String latitude, String longitude) {
UserPunch userPunch = new UserPunch()
userPunch.punchClockStatus = user.punchClockStatus
userPunch.user = user
userPunch.job = user.job
userPunch.task = user.task
userPunch.date = new Date()
userPunch.source = source
userPunch.save(flush: true)
try {
userPunch.latitude = latitude
userPunch.longitude = longitude
} catch (MissingPropertyException e) {
user.userVersion++
}
if (userPunch.hasErrors())
userPunch.errors.each {
log.error it
}
}
</code></pre>
<p>Does this look like it will work right? Does anyone have a better solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T02:08:40.910",
"Id": "65293",
"Score": "0",
"body": "Shouldn't this also be tagged with the \"Groovy\" tag?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:00:19.127",
"Id": "65295",
"Score": "4",
"body": "Why are you asking if it will work right? Have you tried?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T19:02:59.860",
"Id": "65342",
"Score": "0",
"body": "I'm upgrading someone else's code from Grails 1.7 to Grails 2.3.4, so it has multiple compiler errors. I haven't even gotten it to run yet. This was one of them that I'm hoping I fixed, but just because it cleared the compiler error doesn't mean it will work correctly in runtime. I can't do unit testing until I fix all the other compiler errors."
}
] |
[
{
"body": "<p>If you use default parameters, you won't need to overload the function.</p>\n\n<pre><code>def punch(User user, User source, String latitude=null, String longitude=null)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-17T08:02:36.800",
"Id": "128005",
"Score": "1",
"body": "Default parameter values are not allowed in controller methods, same as overloading."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-28T13:47:05.513",
"Id": "61344",
"ParentId": "39033",
"Score": "2"
}
},
{
"body": "<p>Controller actions may not be overloaded but non-action methods can be. So you can do something like this to keep the code as similar to the original as possible:</p>\n\n<pre><code>def punch(User user, User source, String latitude, String longitude) {\n if (latitude != null) punchImpl(user, source, latitude, longitude)\n else punchImpl(user, source)\n}\n\nprotected punchImpl(user, source) {\n ...\n}\n\nprotected punchImpl(user, source, latitude, longitude) {\n ...\n}\n</code></pre>\n\n<p>Then you may as well think about putting the punch method overloads inside a service since controllers shouldn't contain \"business\" logic anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-17T08:11:42.180",
"Id": "70063",
"ParentId": "39033",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T01:46:07.367",
"Id": "39033",
"Score": "2",
"Tags": [
"groovy",
"operator-overloading",
"grails"
],
"Title": "Grails overloaded controller workaround"
}
|
39033
|
<p>I have been slowly getting more and more "at home" with Android development and I would like some guidance. I have made an app that uses a <code>ListActivity</code>, that attaches to an SQLite DB. I'm using the <code>onListItemClick</code> function to fire up a "single record view" where I can delete and edit the record. There is also a way to edit the record from the list view by using the Context Menu and selecting so there are potentially 2 ways to edit a record.</p>
<ul>
<li>Directly from a ListView via Context Menu</li>
<li>Selecting Edit from a single record view</li>
</ul>
<p>Both the single record view and the edit view are being handled by the same Activity (not sure if this is common practice or not). Now having been a programmer for some time something tells me that I am not doing this in the best way that I could so I thought I would submit it for code review. So here is the "overly-complicated feeling" Activity which I have commented to try and help understand my logic. I did think that this might be something I should be using a FrameLayout for but don't really know if that is the best way to do things. I am still new to Android dev so have a <strong>lot</strong> to learn.</p>
<pre><code>public class CardActivity extends Activity implements OnClickListener {
private Card card;
private EditText questionEdit;
private EditText answerEdit;
private CardSQLiteHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new CardSQLiteHelper(this);
dbHelper.open();
Bundle b = getIntent().getExtras();
if(b == null) { // Coming in from Add there is no card in the Intent
card = new Card();
setupEdit();
} else if( b.containsKey(Intent.ACTION_VIEW)) { // Coming in from View the card is stored using the ACTION_VIEW key
card = (Card) b.get(Intent.ACTION_VIEW);
setupView();
} else { // Coming from Edit the card is stored using the ACTION_EDIT key
card = (Card) b.get(Intent.ACTION_EDIT);
setupEdit();
}
}
/**
* Sets up the view for editing using the right layout and registering the buttons
*/
private void setupEdit() {
setContentView(R.layout.card_edit);
questionEdit = (EditText) findViewById(R.id.questionEditText);
answerEdit = (EditText) findViewById(R.id.answerEditText);
questionEdit.setText(card.getQuestion());
answerEdit.setText(card.getAnswer());
Button saveButton = (Button) findViewById(R.id.cardSaveButton);
Button cancelButton = (Button) findViewById(R.id.cardCancelButton);
saveButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
/**
* Sets up the view for "Single record View" mode displaying the data and offering a Delete and Edit button
*/
private void setupView() {
setContentView(R.layout.card_view);
TextView questionText = (TextView) findViewById(R.id.questionTextView);
TextView answerText = (TextView) findViewById(R.id.answerTextView);
questionText.setText(card.getQuestion());
answerText.setText(card.getAnswer());
Button deleteButton = (Button) findViewById(R.id.cardDeleteButton);
Button editButton = (Button) findViewById(R.id.cardEditButton);
deleteButton.setOnClickListener(this);
editButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cardEditButton:
// Clicked the Edit button in the "Single record view" so we switch to an Edit view
setupEdit();
break;
case R.id.cardDeleteButton:
// Delete is easy, just nuke the card and return an OK result
dbHelper.deleteCard(card);
setResult(RESULT_OK);
finish();
break;
case R.id.cardCancelButton:
// Cancel again is easy, do nothing and return the CANCELLED result
setResult(RESULT_CANCELED);
finish();
break;
case R.id.cardSaveButton:
// Save is not hard just a bit lengthy because of the things we need to do
// Check there is content in the Question EditText
if(questionEdit.getText().toString().length() == 0) {
Toast.makeText(this, "Your question must have some text", Toast.LENGTH_LONG).show();
break;
}
// Check there is content in the Answer EditText
if(answerEdit.getText().toString().length() == 0) {
Toast.makeText(this, "Your answer must have some text", Toast.LENGTH_LONG).show();
break;
}
// Put the text into my object
card.setQuestion(questionEdit.getText().toString());
card.setAnswer(answerEdit.getText().toString());
// If the card has no ID then we are adding a new card
if(card.getId() == 0) {
dbHelper.addCard(card);
} else {
dbHelper.updateCard(card);
}
setResult(RESULT_OK);
finish();
break;
}
}
}
</code></pre>
<p>As requested this is a bit more of an explanation of what the app does. It's a basic app that I am using as a learning process, of a revision or learning card system. The end user can add & remove cards from a list which they can store a Question and Answer on as if you were using them to revise for an exam, eventually I will give the user a way to randomise the cards and answer the relevant question as well as provide more ways to store data and get between the cards.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T05:24:40.183",
"Id": "65304",
"Score": "0",
"body": "Do you think you could provide a little more context for what the app does? I think I understand most of what's going on, but it helps to have an explanation behind it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T07:10:01.513",
"Id": "65305",
"Score": "0",
"body": "Certainly I will edit the main text"
}
] |
[
{
"body": "<p>One of the tenets fo <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID programming</a> (the first one, in fact) is that classes should have a single responsibility.</p>\n\n<p>Here you have a class which has two distinct functions: view a card ; edit a card.</p>\n\n<p>The code complexity you have introduced just to differentiate between the uses of your class is more than the complexity of what you would have if you had two classes.</p>\n\n<p>Your instinct is right, you are not doing this the right way.</p>\n\n<p>In this particular case, I would recommend copy/pasting the class, and making each version a specialization for either View or Edit. The <code>setupEdit</code> and <code>setupView</code> should instead be incorporated in to the <code>onCreate()</code> method. The <code>onClick()</code> logic can be split quite simply as well.</p>\n\n<p>What is nice about this is that the code becomes much more reusable... you can have the two specialized classes, and adding a new way to access the Activity (swiping '>next', etc.) would be much easier to do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T00:40:30.803",
"Id": "40704",
"ParentId": "39034",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T02:28:10.810",
"Id": "39034",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Activity using multiple layouts"
}
|
39034
|
<p>I'm working on a Project Euler problem and am trying to get the smallest prime factor of a <code>BigInteger</code>:</p>
<pre><code>private static BigInteger smallestPrimeFactor( BigInteger n ){
for( BigInteger i = new BigInteger("2"); n.compareTo(i) >= 0 ; i = i.add(BigInteger.ONE) ){
while( n.mod(i) == BigInteger.ZERO )
return i;
}
}
return BigInteger.ZERO;
}
</code></pre>
<p>I have basically just made adjustments to a code snippet I found online. They had something with <code>n = n.divide(i)</code>, which I believe was to make things prime, but I wanted to save time just getting the smallest. Is there a better/faster way to go about doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:47:36.870",
"Id": "65298",
"Score": "0",
"body": "@boxed__l it will be prime, because the lowest factor is always prime ... if it was not prime, then the lowest prime-factor of the non-prime value would have been checked already"
}
] |
[
{
"body": "<p><code>BigInteger</code> should be compared using <code>compareTo()</code> rather than <code>==</code></p>\n\n<p>One optimization would be (search space):</p>\n\n<pre><code>private static BigInteger smallestPrimeFactor( BigInteger n ){\n BigInteger two=new BigInteger(\"2\");\n if(n.mod(two).compareTo(BigInteger.ZERO)==0){\n return two; \n }\n for( BigInteger i = new BigInteger(\"3\"); n.compareTo(i) >= 0 ; i = i.add(two) ){\n if( n.mod(i).compareTo(BigInteger.ZERO)==0)\n return i;\n }\n }\n return BigInteger.ZERO;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:57:22.377",
"Id": "39037",
"ParentId": "39035",
"Score": "3"
}
},
{
"body": "<p>Factors to consider</p>\n\n<ol>\n<li><p>If number 2 is not a factor, then all large even numbers will not be factors. Therefore, checking only the odd numbers is sufficient.</p></li>\n<li><p>For integers <code>i x j = n</code>, if <code>i</code> is larger than the square root of <code>n</code>, then <code>j</code> has to be smaller than the square root of <code>n</code> (Therefore, already checked). Hence, numbers higher than the square root of <code>n</code> do not have to be checked as candidates for prime factors.</p>\n\n<pre><code>private static BigInteger smallestPrimeFactor(BigInteger n) {\n BigInteger two = new BigInteger(\"2\");\n if (n.mod(two).compareTo(BigInteger.ZERO) == 0) {\n return two;\n }\n\n for (BigInteger i = new BigInteger(\"3\"); n.compareTo(i.multiply(i)) >= 0; i = i.add(two)) { \n if (n.mod(i).compareTo(BigInteger.ZERO) == 0) {\n return i;\n }\n }\n return n;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:59:07.697",
"Id": "39038",
"ParentId": "39035",
"Score": "4"
}
},
{
"body": "<p>This is an interesting requirement, prime-factoring a BigInteger....</p>\n\n<p>First up, though, you should never, <strong>never</strong> be doing identity comparisons on BigInteger.ZERO:</p>\n\n<pre><code>.... n.mod(i) == BigInteger.ZERO ...\n</code></pre>\n\n<p>This should be:</p>\n\n<pre><code>n.mod(i).equals(BigInteger.ZERO)\n</code></pre>\n\n<p>Second, why do you have a while-condition for your exit?</p>\n\n<pre><code> while( n.mod(i) == BigInteger.ZERO )\n return i;\n }\n</code></pre>\n\n<p>That should be an <code>if</code>, surely?</p>\n\n<p>EDIT: You should seriously consider having a pre-calculated set of prime numbers. You can get these lists from many places on the net. This will save a bunch of time. I have found a large number <code>123456789012345678987654351</code> which illustrates how slow these algorithms can be.... </p>\n\n<p>BigInteger arithmatic is much, much slower than primitive arithmatic. But, you can significantly reduce your BigInteger arithmatic.</p>\n\n<p>Boxed__l is correct about doing 2 as a special-case, and then only checking odd numbers. This will reduce your computations significantly, but, let me suggest another, different approach.</p>\n\n<p>First, if the BigInteger number is smaller than Long.MAX_VALUE there is no reason to use BigInteger. I would recommend that you implement the algorithm multiple ways, one using <code>long</code>, and the other using <code>BigInteger</code>.</p>\n\n<p>Now, I would then have a 'entry' method that looks like:</p>\n\n<pre><code>private static final BigInteger MAXLONG = BigInteger.valueOf(Long.MAX_VALUE);\nprivate static final BigInteger BIGTWO = BigInteger.valueOf(2);\n\nprivate static BigInteger smallestPrimeFactor( BigInteger n ) {\n if (n.compareTo(BigInteger.ONE) <= 0) {\n return BigInteger.ZERO;\n }\n if (n.mod(BIGTWO).equals(BigInteger.ZERO)) {\n return BIGTWO;\n }\n if (n.compareTo(MAXLONG) <= 0) {\n // for 'small' n's use a simple long-based prime-factor.\n return BigInteger.valueOf(smallestPrimeFactor( n.longValue() ));\n }\n // use special BigInteger code for this...\n return internalPrimeFactor(n);\n}\n</code></pre>\n\n<p>OK, so, what I am saying, is use the fast mechanisms where it is possible. The implementation of the <code>long</code> based solution should be 'trivial'. Use the recommendations others have suggested (treat 2 as a special case, then only work with odd values).</p>\n\n<p>Now, as for your <code>internalPrimeFactor(BigInteger)</code> method, I <strong>still</strong> recommend you stay in <code>long</code> space as much as you can....</p>\n\n<p>By doing it this way, you will only resrt to slow BigInteger math for large input values, and, even then it will be relatively fast until you get to very large prime numbers....</p>\n\n<p>By my calculations, that will probably take you a couple of days to get to (in order to first search all the prime values less than Long.MAX_VALUE).</p>\n\n<p>Consider the functions:</p>\n\n<pre><code>private static final BigInteger MAXLONG = BigInteger.valueOf(Long.MAX_VALUE);\nprivate static final BigInteger BIGTWO = BigInteger.valueOf(2);\n\nprivate static BigInteger smallestPrimeFactor( BigInteger n ) {\n if (n.compareTo(BigInteger.ONE) <= 0) {\n return BigInteger.ZERO;\n }\n if (n.mod(BIGTWO).equals(BigInteger.ZERO)) {\n return BIGTWO;\n }\n if (n.compareTo(MAXLONG) <= 0) {\n // for 'small' n's use a simple long-based prime-factor.\n return BigInteger.valueOf(smallestPrimeFactor( n.longValue() ));\n }\n // use special BigInteger code for this...\n return internalPrimeFactor(n);\n}\n\nprivate static final long smallestPrimeFactor(long n) {\n if (n < 1) {\n return 0;\n }\n if (n % 2 == 0) {\n return 2;\n }\n // only need aproximate end-point... even if n is larger than 48 bits\n // (the largest accurate integer number in double),\n // the sqrt will be only off by 1 at most.\n long root = (long)(Math.sqrt(n)) + 1;\n for (long i = 3; i <= root; i += 2) {\n if (n % i == 0) {\n return i;\n }\n }\n // it's prime!\n return n;\n}\n\n/**\n * From http://faruk.akgul.org/blog/javas-missing-algorithm-biginteger-sqrt/\n */\npublic static final BigInteger sqrt(BigInteger n) {\n BigInteger a = BigInteger.ONE;\n BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger(\"8\")).toString());\n while(b.compareTo(a) >= 0) {\n BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());\n if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE);\n else a = mid.add(BigInteger.ONE);\n }\n return a.subtract(BigInteger.ONE);\n}\n\nprivate static final BigInteger internalPrimeFactor(BigInteger n) {\n // only call this method when n > Long.MAX_VALUE\n // See this SO Question: http://stackoverflow.com/a/4407884/1305253\n // and using the code from this blog: http://faruk.akgul.org/blog/javas-missing-algorithm-biginteger-sqrt/\n BigInteger root = sqrt(n);\n // keep a limit in `long` space, swap to BigInteger space when we need to.\n long maxlimit = root.compareTo(MAXLONG) > 0 ? Long.MAX_VALUE : root.longValue();\n // only need to start from 3, 2 has been dealt with....\n\n for( long i = 3; i <= maxlimit ; i += 2 ){\n if( n.mod(BigInteger.valueOf(i)).equals(BigInteger.ZERO) ) {\n return BigInteger.valueOf(i);\n }\n }\n\n // OK, no prime factor found less than Long.\n // resort to using BigInteger arithmatic in the loop.\n // MAXLONG is odd, we can go from there.\n for( BigInteger i = MAXLONG; root.compareTo(i) >= 0 ; i = i.add(BIGTWO)) {\n if( n.mod(i).equals(BigInteger.ZERO) ) {\n return i;\n }\n }\n // it's prime!\n return n;\n}\n</code></pre>\n\n<p>Out of interest, the difference between long-based and BigInteger performance is large. Here are the time differences for a set of calculations where the (long) calculation does <code>(n % i) == 0</code> and the (BI) calculation does <code>n.mod(BigInteger.valueOf(i).equals(BigInteger.ZERO)</code></p>\n\n<pre><code>First prime factor of 2305843009213693965 is 3 in 0.000003sec (long) and 0.001277sec (BI) \nFirst prime factor of 2305843009213693967 is 2305843009213693967 in 7.946315sec (long) and 63.071495sec (BI) \nFirst prime factor of 2305843009213693969 is 37 in 0.000005sec (long) and 0.000984sec (BI) \nFirst prime factor of 2305843009213693971 is 3 in 0.000003sec (long) and 0.000978sec (BI) \nFirst prime factor of 2305843009213693973 is 2305843009213693973 in 7.892226sec (long) and 62.610628sec (BI) \nFirst prime factor of 2305843009213693975 is 5 in 0.000005sec (long) and 0.000944sec (BI) \nFirst prime factor of 2305843009213693977 is 3 in 0.000004sec (long) and 0.000913sec (BI) \nFirst prime factor of 2305843009213693979 is 727 in 0.000015sec (long) and 0.000954sec (BI) \nFirst prime factor of 2305843009213693981 is 31 in 0.000004sec (long) and 0.000914sec (BI) \nFirst prime factor of 2305843009213693983 is 3 in 0.000003sec (long) and 0.000876sec (BI) \nFirst prime factor of 2305843009213693985 is 5 in 0.000003sec (long) and 0.000950sec (BI) \nFirst prime factor of 2305843009213693987 is 7014691 in 0.036126sec (long) and 0.313198sec (BI) \nFirst prime factor of 2305843009213693989 is 3 in 0.000007sec (long) and 0.000870sec (BI) \nFirst prime factor of 2305843009213693991 is 41 in 0.000004sec (long) and 0.000836sec (BI) \nFirst prime factor of 2305843009213693993 is 131 in 0.000005sec (long) and 0.000867sec (BI) \nFirst prime factor of 2305843009213693995 is 3 in 0.000003sec (long) and 0.000866sec (BI) \nFirst prime factor of 2305843009213693997 is 128053 in 0.000718sec (long) and 0.006650sec (BI) \nFirst prime factor of 2305843009213693999 is 7 in 0.000017sec (long) and 0.000849sec (BI) \nFirst prime factor of 2305843009213694001 is 3 in 0.000003sec (long) and 0.000845sec (BI) \nFirst prime factor of 2305843009213694003 is 23 in 0.000003sec (long) and 0.000848sec (BI) \nFirst prime factor of 2305843009213694005 is 5 in 0.000002sec (long) and 0.000877sec (BI) \nFirst prime factor of 2305843009213694007 is 3 in 0.000002sec (long) and 0.000862sec (BI) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T04:37:05.713",
"Id": "39039",
"ParentId": "39035",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39039",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T03:16:25.580",
"Id": "39035",
"Score": "3",
"Tags": [
"java",
"project-euler",
"primes"
],
"Title": "Smallest prime factor of a large number (using BigInteger)"
}
|
39035
|
<p>In our company we have a machine hostname as - </p>
<pre><code>dbx111.dc1.host.com
dbx112.dc2.host.com
dcx113.dc3.host.com
</code></pre>
<p>Here <code>dc1</code>, <code>dc2</code>, <code>dc3</code> are our datacenter and we will be having only three datacenter. But it might be possible that they can have more dots in between separated by another domain.</p>
<p>Now I need to find in which <code>datacenter</code> my current machine is in. I will be running below code in some machine as shown above.. And below code will tell me which datacenter my code is running in. But is there any way to modify the below code to make it more efficient? I guess we can write this much better -</p>
<pre><code>String datacenter = getCurrentDatacenter();
private String getCurrentDatacenter(){
String s_hostName = null;;
try {
s_hostName = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
s_logger.debug(LogLevel.ERROR+"\t"+e.getStackTrace().toString());
}
if (s_hostName != null && !s_hostName.isEmpty()){
s_hostName.toUpperCase();
if (s_hostName.contains(DatacenterEnum.DC1.name())){
currentDatacenter = DC1;
}
else if (s_hostName.contains(DatacenterEnum.DC2.name())){
currentDatacenter = DC2;
}
else if (s_hostName.contains(DatacenterEnum.DC3.name())){
currentDatacenter = DC3;
}
}
return currentDatacenter;
}
</code></pre>
<p>Below is my ENUM - </p>
<pre><code>public enum DatacenterEnum {
DC1, DC2, DC3;
private static final Map<Integer, DatacenterEnum> BY_CODE_MAP = new LinkedHashMap<Integer, DatacenterEnum>();
static {
for (DatacenterEnum rae : DatacenterEnum.values()) {
BY_CODE_MAP.put(rae.ordinal(), rae);
}
}
public static String forCode(int code) {
return BY_CODE_MAP.get(code).name();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few things which I think will simplify your code a lot, and it all centers around your Enum.</p>\n\n<p>Firstly, there is no need in your enum to have the <code>BY_CODE_MAP</code> system. Remove it. You can very efficiently (and with the identical results) use the method:</p>\n\n<pre><code> public static String forCode(int code) {\n return (code >= 0 && code < values().length) ? values()[code].name() : null;\n }\n</code></pre>\n\n<p>The <code>values()</code> array in an enum will always be indexed in the same order as the ORDINAL of each Enum.</p>\n\n<p>The second thing, is that you should only be calculating the Datacenter location once for each JVM. Having it as a method which is called potentially multiple times, each time interrogating the java.net.* layer for hostnames, is inefficient.</p>\n\n<p>I suggest you add a static initializer method to your Enum that 'knows'.</p>\n\n<p>Consider the following changes to your enum, and replace the logic in your code:</p>\n\n<pre><code>private String getCurrentDatacenter(){\n DatacenterEnum us = DatacenterEnum.getCurrentDatacenter();\n return us == null ? null : us.name();\n}\n</code></pre>\n\n<p>Then, your Enum will look like (I have commented out the code I think is redundant):</p>\n\n<pre><code>import java.net.InetAddress;\nimport java.net.UnknownHostException;\n\n\npublic enum DatacenterEnum {\n DC1, DC2, DC3;\n\n// private static final Map<Integer, DatacenterEnum> BY_CODE_MAP = new LinkedHashMap<Integer, DatacenterEnum>();\n\n// static {\n// for (DatacenterEnum rae : DatacenterEnum.values()) {\n// BY_CODE_MAP.put(rae.ordinal(), rae);\n// }\n// }\n\n public static String forCode(int code) {\n return (code >= 0 && code < values().length) ? values()[code].name() : null;\n// return BY_CODE_MAP.get(code).name();\n }\n\n private static final DatacenterEnum ourlocation = compareLocation();\n\n private static DatacenterEnum compareLocation() {\n String ourhost = getHostName();\n for (DatacenterEnum dc : values()) {\n String namepart = \".\" + dc.name().toLowerCase() + \".\";\n if (ourhost.indexOf(namepart) >= 0) {\n return dc;\n }\n }\n return null;\n }\n\n private static final String getHostName() {\n try {\n return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();\n } catch (UnknownHostException e) { \n // s_logger.debug(LogLevel.ERROR+\"\\t\"+e.getStackTrace().toString());\n return \"localhost\";\n }\n }\n\n public static DatacenterEnum getCurrentDatacenter() {\n return ourlocation;\n }\n\n public static void main(String[] args) {\n System.out.println(DatacenterEnum.getCurrentDatacenter());\n }\n\n}\n</code></pre>\n\n<p>If you ever have additional datacenters, you can simply add a new name to the enum and the rest will work. Also, you can add values that are not the same naming convention... for example, if you add the ENUM \"EU1\" for your first european datacenter, it will match aaa.eu1.xxx.yyy</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T01:47:45.623",
"Id": "65618",
"Score": "0",
"body": "Thanks a lot rolfl for helping me out in this question. I also have one more question [here](http://codereview.stackexchange.com/questions/39123/efficiently-way-of-having-synchronous-and-asynchronous-behavior-in-an-applicatio). You might be able to help me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T14:46:53.830",
"Id": "39053",
"ParentId": "39041",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39053",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T05:32:56.847",
"Id": "39041",
"Score": "4",
"Tags": [
"java",
"optimization"
],
"Title": "Efficiently detect datacenter based on server hostname"
}
|
39041
|
<p>I am studying Clojure and functional programming. I wrote this function to compute the centroid of a polygon specified as a vector of points, e.g. <code>[[10 20] [0 11] [50 30]]</code>).</p>
<p><a href="https://web.archive.org/web/20120722100030/http://paulbourke.net/geometry/polyarea/" rel="nofollow">Here you can read how to compute the centroid of a polygon</a>.</p>
<p>Can you give me hints and suggestions on how to improve this code from a functional coding style POV?</p>
<pre><code>(defn centroid [p]
"Calcola il centroide del poligono p"
(let [six*area (* 6 (polygon-area p))
n (count p)
first-vertex (p 0)
polygon (conj p first-vertex)
x-terms (atom [])
y-terms (atom [])]
(dotimes [i n]
(let [point_i (polygon i)
point_i+1 (polygon (inc i))
x_i (point-x point_i)
y_i (point-y point_i)
x_i+1 (point-x point_i+1)
y_i+1 (point-y point_i+1)]
(swap! x-terms conj (* (+ x_i x_i+1)
(- (* x_i y_i+1)
(* x_i+1 y_i))))
(swap! y-terms conj (* (+ y_i y_i+1)
(- (* x_i y_i+1)
(* x_i+1 y_i))))))
(make-point (/ (reduce + 0 @x-terms) six*area)
(/ (reduce + 0 @y-terms) six*area))))
</code></pre>
|
[] |
[
{
"body": "<p>You could replace the <code>dotimes</code>/<code>atom</code>s with more functional <code>loop</code>/<code>recur</code> recursion.</p>\n\n<pre><code>(defn centroid [p]\n (let [six*area (* 6 (polygon-area p))\n n (count p)\n first-vertex (p 0)\n polygon (conj p first-vertex)]\n (loop [i 0\n x-terms []\n y-terms []]\n (if (< i n)\n (let [point (polygon i)\n point' (polygon (inc i))\n x (point-x point)\n y (point-y point)\n x' (point-x point')\n y' (point-y point')\n dxy (- (* x y')\n (* x' y))]\n (recur (inc i)\n (conj x-terms (* (+ x x') dxy))\n (conj y-terms (* (+ y y') dxy))))\n (make-point (/ (reduce + 0 x-terms) six*area)\n (/ (reduce + 0 y-terms) six*area))))))\n</code></pre>\n\n<p>You could also do it through sequences entirely:</p>\n\n<pre><code>(defn centroid [p]\n (let [six*area (* 6 (polygon-area p))\n polygon (map (juxt point-x point-y) p) ;; turns the points in [x y] pairs\n ;; `juxt` applies each function in order and outputs the results in a list.\n\n polygon' (drop 1 (cycle polygon)) ;; circular permutation of polygon \n ;; `cycle` lazily repeats and concats the input sequence.\n\n term (fn [[[x y] [x' y']]] ;; destructuring a pair of\n ;; [x y] pairs\n (let [dxy (- (* x y')\n (* x' y))] \n [(* dxy (+ x x')) (* dxy (+ y y'))]))\n [x-terms yterms] (->> (map list polygon polygon') ;; makes the [point point'] pairs\n ;; when `polygon` is exhausted, the generated sequence stops, so the fact that\n ;; `polygon'` is infinite has no effect.\n (map term)\n (apply (partial map list)))] ;; turns the sequence of pairs\n ;; into a pair of sequences\n ;; `apply` turns the list argument in an argument list that it feeds to the function\n ;; - here, a sequence of pairs. `partial` takes a function and some of its arguments\n ;; and returns it with its first arguments set - here, `map list ...`. `map list`\n ;; applied to a list of pairs will call `list` with the first elements of all pairs,\n ;; then with the seconds.\n\n (make-point (/ (reduce + 0 x-terms) six*area)\n (/ (reduce + 0 y-terms) six*area))))\n</code></pre>\n\n<p><strong>EDIT:</strong> a(n unefficient) version with <code>map</code> galore:</p>\n\n<pre><code>(defn centroid [p]\n (let [six*area (* 6 (polygon-area p))\n polygon (map (juxt point-x point-y) p)\n polygon' (drop 1 (cycle polygon))\n x (map first polygon)\n x' (map first polygon')\n y (map second polygon)\n y' (map second polygon')\n x**x (map * x x')\n y**y (map * y y')\n x**y (map * x y')\n y**x (map * y x')\n dxy (map - x**y y**x)\n x-terms (map * x**x dxy)\n y-terms (map * y**y dxy)]\n (make-point (/ (reduce + 0 x-terms) six*area)\n (/ (reduce + 0 y-terms) six*area))))\n</code></pre>\n\n<p>A full <code>loop</code>/<code>recur</code> version:</p>\n\n<pre><code>(defn centroid [[h & t :as p]]\n (let [six*area (* 6 (polygon-area p))\n a (point-x h)\n b (point-y h)]\n (loop [x a\n y b\n t t\n x-term 0\n y-term 0]\n (if-let [[h & t] t]\n (let [x' (point-x h)\n y' (point-y h)\n dxy (- (* x y')\n (* x' y))\n x-term (+ x-term (* dxy (+ x x')))\n y-term (+ y-term (* dxy (+ y y')))]\n (recur x' y' t x-term y-term))\n (let [dxy (- (* x b)\n (* a y))\n x-term (+ x-term (* dxy (+ x a)))\n y-term (+ y-term (* dxy (+ y b)))]\n (make-point (/ x-term six*area)\n (/ y-term six*area)))))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T12:39:04.293",
"Id": "65319",
"Score": "0",
"body": "Wow, the sequences version is very compact though I will need more experience to understand it completely.\nLooking at the loop/recur version, I missed that those terms were equal, good catch.\nI could also accumulate the sum instead of the terms to sum at the end. It would consume less memory and CPU cycles but I don't know if it would be as clear as it is now.\nPS: in the first example the variable is defined as `x**y` and later referred to as `x^y`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T13:14:43.177",
"Id": "65320",
"Score": "0",
"body": "Thanks, I made the correction. I included some comments in the sequences version, I hope that helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T21:38:18.827",
"Id": "65352",
"Score": "0",
"body": "In this line from the 3rd example: `let [ ... x' (map first polygon') ...]`, being `polygon'` an infinite list, wouldn't `map` loop forever?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T22:53:41.487",
"Id": "65358",
"Score": "0",
"body": "`map` returns (immediately) a lazy sequence whose terms will be evaluated when they are iterated through. We never actually iterate over the whole length of `polygon'` (neither on those of x' or y'), but on its \"product\" with `polygon` - or one of its derivated sequences (which are finite) - through `map`. This \"product\" has the same length as the shortest of its two parameters. `reduce` provokes a cascading evaluation of these lazy sequences, and only the terms that are needed are evaluated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T08:29:53.377",
"Id": "65398",
"Score": "0",
"body": "Thanks for the explanation, now I am sure I understand well how they works. However I was referring to `y' (map second polygon')` where the only (and shortest) list is `polygon'`, an infinite list. I tried a similar code and it looped for ever.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T11:15:12.057",
"Id": "65403",
"Score": "0",
"body": "Did you try it in a REPL ? Trying to print an infinite sequence will iterate through it (for ever). If you try `(range)` in a REPL, it loops forever. But if you try `(map * (range) (range 100))`, you get the result quickly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T14:14:41.433",
"Id": "65410",
"Score": "0",
"body": "Yes, I tried it in a REPL. In the _map galore_ version, the code `map`s only over an infinite list in the 6th and 8th line of code (`(map first polygon')` and `(map second polygon')`) since `polygon'` is infinite. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T00:24:05.117",
"Id": "65457",
"Score": "0",
"body": "Yes and no. `polygon'` is potentially infinite. But applying `map` to it doesn't cause an iteration through it ; we create a lazy sequence whose first term is a function of the input sequence's first term, whose second term is a function term is a function of the input sequence's second term, etc. . None of these terms are evaluated until the lazy sequence is iterated through, which means that the input sequence isn't iterated through. In effect `polygon'`, `x'` and `y'` are finite, because they are only read up to the point where `polygon`/`x`/`y` is exhausted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:19:16.900",
"Id": "65587",
"Score": "0",
"body": "Now I got it! I forgot that `map` creates lazy sequences. I need to get used to all these esoteric tools. :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T11:52:35.690",
"Id": "39046",
"ParentId": "39045",
"Score": "4"
}
},
{
"body": "<p>A fairly concise functional version, incorporating the area calculation:</p>\n\n<pre><code>(defn centroid [p]\n (let [pairs (partition 2 1 (conj p (first p)))\n xp (mapv (fn [[[x1 y1] [x2 y2]]] (- (* x1 y2) (* x2 y1))) pairs)\n twice-area (apply + xp)\n\n dot-xp (fn [xs] (apply + (map * xs xp)))\n transpose (fn [vv] (apply mapv vector vv))\n\n pair-sums (mapv #(map (partial reduce +) (transpose %)) pairs)]\n (mapv (comp #(/ % (* 3 twice-area)) dot-xp) (transpose pair-sums))))\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>(centroid [[10 20] [0 11] [50 30]])\n</code></pre>\n\n<p>... produces</p>\n\n<pre><code>[20 61/3]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-30T14:27:16.140",
"Id": "64274",
"ParentId": "39045",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39046",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T10:59:09.087",
"Id": "39045",
"Score": "4",
"Tags": [
"functional-programming",
"clojure",
"computational-geometry"
],
"Title": "Centroid of a polygon in Clojure"
}
|
39045
|
<p>I am building a <a href="http://en.wikipedia.org/wiki/Webhook" rel="nofollow">Webhook</a> model so users can receive data from a messaging app.
I have never created such a system before, and I'd like to get some feedback on my attempt.</p>
<pre><code>$url = 'https://www.example.com/user-webhook-request.php';
$handshakeKey = "1234abcd";
$data = array('title' => 'Hello',
'message' => 'World',
'url' => 'http://example.com/#check',
'image' => 'http://www.example.com/pics/file.jpg',
'handshakekey' => $handshakeKey);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
curl_close($curl);
</code></pre>
<p>Is there anything I should change to meet best or common practices?</p>
|
[] |
[
{
"body": "<p>I'm not familiar with that pattern, but I'll see what I can comment on.</p>\n\n<ul>\n<li><code>$url</code> is not a good name. What kind of URL is it? What importantance does the page have?</li>\n<li>Is <code>$handshakeKey</code> an API key, or just some string that's checked on both ends? I'm assuming the latter, however, you should always check if the site you're working with has an official API. If it's all your project, I suggest you make an API.</li>\n<li>What kind of <code>$data</code> is it? (Bad naming again)</li>\n<li><p>Fix the indentation of <code>$data</code>. If you're using a version of PHP greater than 5.4, I suggest you use the square bracket notation. I think many find it easier to read.</p>\n\n<pre><code>$data = [\n 'title' => 'Hello',\n 'message' => 'World',\n 'url' => 'http://example.com/#check',\n 'image' => 'http://www.example.com/pics/file.jpg',\n 'handshakekey' => $handshakeKey\n];\n</code></pre></li>\n<li><p>What kind of <code>$content</code> is it? Again, give these variables some meaning.</p></li>\n</ul>\n\n<p>I don't see anything wrong with your cURL commands. Nice :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T00:09:24.780",
"Id": "57139",
"ParentId": "39047",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T12:01:55.150",
"Id": "39047",
"Score": "2",
"Tags": [
"php",
"json",
"curl"
],
"Title": "Webhook Structuring"
}
|
39047
|
<p>I have attempted the GUI controls creation in a prompt based on data from dictionary. Is this the best way of implementing this?</p>
<pre><code>import sys
from PyQt4 import QtCore, QtGui
class MessageBox(QtGui.QDialog):
"""docstring for MessageBox"""
def __init__(self, data=None, parent=None):
super(MessageBox, self).__init__(parent)
self._data = data
self.buildUi()
def buildUi(self):
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setSpacing(10)
for index, (key, values) in enumerate(self._data.iteritems()):
getLbl = QtGui.QLabel("Get", self)
label = QtGui.QLabel(key, self)
chkBox = QtGui.QCheckBox(self._data[key][0], self)
chkBox.setToolTip("Click here to get the book")
version = QtGui.QSpinBox( self)
version.setValue(self._data[key][-1])
version.setRange(self._data[key][-1], 12)
self.gridLayout.addWidget(getLbl, index, 0)
self.gridLayout.addWidget(label, index, 1)
self.gridLayout.addWidget(chkBox, index, 2)
self.gridLayout.addWidget(version, index, 3)
self.layout = QtGui.QVBoxLayout()
self.okBtn = QtGui.QPushButton("OK")
self.layout.addLayout(self.gridLayout)
self.horLayout = QtGui.QHBoxLayout()
self.horLayout.addStretch(1)
self.horLayout.addWidget(self.okBtn)
self.layout.addLayout(self.horLayout)
self.setLayout(self.layout)
class MainWindow(QtGui.QMainWindow):
"""docstring for MainWindow"""
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# self.widget = FormWidget()
self._data = {
'Contact':['Carl Sagan', 2],
'End of Faith':['Sam Harris', 7],
'On Mars':['Patrick Moore', 1],
}
self.btn = QtGui.QPushButton("Hello", self)
self.btn.clicked.connect(self._launchMessageBox)
self.show()
def _launchMessageBox(self):
dlg = MessageBox(self._data)
dlg.exec_()
def main():
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
# window.raise_()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>This will work, but it may be hard to scale. At a minimum, I'd create a separate class for the work you're doing in the enumerate loop so that the dialog class is only concerned with populating a widget list and the details of what the widgets look like internally are handled in a class that just pops out book widgets - that will make for cleaner code and easier maintenance.</p>\n\n<p>The more 'modern' way to do this is some variant on the MVC (Model-View-Controller) or MVVM (Model -view - viewmodel) patterns. The basic idea is the same - create a factory which produces display widgets for the items in a list of some kind. The main difference its that the MVVM pattern encourages you to split out the different aspects of the problem -- managing the contents of the list, displaying parts of the list, and interactng with the list items -- into distinct parts of the code (the 'model', the 'view' and the 'viewmodel' or 'controller') respectively. (There's a whole lot of programmer-on-programmer controversy about MVC vs MVVM - background <a href=\"http://joel.inpointform.net/software-development/mvvm-vs-mvp-vs-mvc/\" rel=\"nofollow\">here</a>.)</p>\n\n<p>In this example, going with an MV* pattern offers facilities like filtering a list ('show only books from 2013'), enabling/disabling list items ('gray out the books over $50') without lots of tedious looping codes. Plus you could potentially do things like design your widgets in the QT designer for better layout, etc without touching the code directly.</p>\n\n<p>All this lets you decouple the UI functionality (views, filters, appearance) from the data. As your lists get bigger, and the need to manage their contents gets more complex, this is a big help in staying sane.</p>\n\n<p>Yasin from TAO has nice, detailed <a href=\"http://www.youtube.com/watch?v=mCHVI8OXDxw\" rel=\"nofollow\">Youtube tutorial on this</a> approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T23:34:44.753",
"Id": "39065",
"ParentId": "39048",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T12:29:31.713",
"Id": "39048",
"Score": "3",
"Tags": [
"python",
"gui",
"pyqt"
],
"Title": "Dynamically generated controls based on data from dictionary"
}
|
39048
|
<p>I would like to share a part of some code written several years ago (I have changed from mysql to mysqli); this code works perfectly. I am new to my company, and our senior programmers wrote some extra lines to optimize branch predictions. My question is: is it necessary to follow this code? Does it improve performance?</p>
<p>We are hosting our files on Linux VPS CentOS 64Bit, 4GM RAM</p>
<pre><code> $gq = array(); //to hold global ques
$gq = array_merge($m1_array,$m2_array,$m3_array,$m4_array,$m5_array,$mp5_array) ;
unset ($m1_array,$m2_array,$m3_array,$m4_array,$m5_array,$mp5_array);
shuffle($gq);
// collect answers
//preparing list of question ids to get the answer
$qnolist ='';
foreach ($gq as $qm)
{$qnolist = $qnolist.','.$qm['qid'];}
$qnolist=substr_replace($qnolist ,'',0,1);
//sorted list qry always good performance (branch predictor)
$qnoarray =explode(",",$qnolist);
sort($qnoarray);
$qnolist=implode(",",$qnoarray);
$sql = "SELECT some fields where `qid` in ({$qnolist}) order by `qid`,`aid`;";
$result = mysqli_query ($dbcon, $sql) or die("Server connection error...");
$ga = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($ga, $row);
}
mysqli_free_result($result);
</code></pre>
|
[] |
[
{
"body": "<p>Performance tuning can be a strange thing sometimes. My instinct is to say that the explosion/implosion of the data will cost more than any branch-prediction benefits.</p>\n\n<p>Also, the only use of the sorted in clause is in the database itself... which should be efficient regardless of the order of the values in the <code>IN</code> clause.</p>\n\n<p>Finally, performance characteristics of big datasets can be very different to small data sets.</p>\n\n<p>When people go out of their way to do a 'hack' for performance, it is normally only with a very good reason. Normally there is a 'good' comment as to why something is done.</p>\n\n<p>In this case, I can't seem to find any reference on Google why a sorted <code>in</code> clause is beneficial.</p>\n\n<p>So, you should do the following:</p>\n\n<ol>\n<li>identify how large the list normally are.</li>\n<li>benchmark the code as it is. focus first on the PHP. How much time is taken sorting the data for the in clause.</li>\n<li>benchmark the SQL query using <code>in</code> values that are randomly sorted, and compare it to queries with ordered values.</li>\n</ol>\n\n<p>My instinct is that you do not have enough values in your data to make the processing worthwhile. But, this is also an occasion where there may be some odd, esoteric issue which is solved nicely.... Your only logical choices are:</p>\n\n<ol>\n<li>leave the code as is, and assume it does something good, or, at least does nothing bad</li>\n<li>benchmark the code yourself, and confirm the benefits and then fix it, or move on (satisfy your curiosity)</li>\n<li>speak with the programmer who added the code, and see if there is something you are missing.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T15:08:45.443",
"Id": "65326",
"Score": "1",
"body": "thanks, I am preparing for benchmark ...let I update this post with result..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T15:59:34.797",
"Id": "65328",
"Score": "0",
"body": "with out sorting query take some extra time, so I would like to choose \"leave the code as is, and assume **it does something good**, or, at least does nothing bad\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T12:53:38.787",
"Id": "65775",
"Score": "1",
"body": "the IN() clause in mysql is expensive/slow you're better off doing joins / group bys / distincts instead of doing an IN() and filtering/grouping in php outside of the actual query. I assume you have correctly built an index on the qid column too ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T08:57:52.063",
"Id": "67335",
"Score": "0",
"body": "@@dave thanks sir, yes all the columns in where clause are indexed... I agree \"in\" clause are expensive, but I don't have any alternative for using in clause, because of its random collection... please help me or give tip to use alternative for \"in\" clause for my situation ..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T13:51:09.027",
"Id": "39050",
"ParentId": "39049",
"Score": "3"
}
},
{
"body": "<p>@rolfl's answer covers the major points very well. In addition, I would recommend that you change the comment, removing the phrase \"branch predictor.\" A <a href=\"http://en.wikipedia.org/wiki/Branch_predictor\" rel=\"nofollow\">branch predictor</a> is a part of the CPU which attempts to predict the result of a branch so that the CPU can speculatively execute the predicted branch. A programmer can write code that optimizes branch prediction in assembly, or C, or other compiled languages for which the programmer can reliably predict the machine code that the compiler will emit. In an interpreted language such as PHP or SQL, there is so much code between your source and the machine that optimizing for the branch predictor at the level of your PHP or SQL source no longer makes any sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T12:48:06.277",
"Id": "39089",
"ParentId": "39049",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T12:50:36.877",
"Id": "39049",
"Score": "3",
"Tags": [
"php",
"optimization",
"mysql"
],
"Title": "Is code optimization for branch predictor necessary now?"
}
|
39049
|
<p>Grails is a <a href="http://en.wikipedia.org/wiki/Convention_over_configuration" rel="nofollow">coding-by-convention</a> framework that leverages well-established <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a> frameworks (<a href="/questions/tagged/spring" class="post-tag" title="show questions tagged 'spring'" rel="tag">spring</a>, <a href="/questions/tagged/hibernate" class="post-tag" title="show questions tagged 'hibernate'" rel="tag">hibernate</a>, SiteMesh) to allow programmers to quickly develop web applications. </p>
<p>It touts features such as a zero-XML configuration and a typical web-application <a href="/questions/tagged/mvc" class="post-tag" title="show questions tagged 'mvc'" rel="tag">mvc</a> architecture.</p>
<p>Grails applications are mainly written in <a href="/questions/tagged/groovy" class="post-tag" title="show questions tagged 'groovy'" rel="tag">groovy</a>, a dynamic language with strong interoperability with Java and features similar to other languages <a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged 'ruby'" rel="tag">ruby</a>, <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a> and <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged 'perl'" rel="tag">perl</a></p>
<p>Along with its core, Grails has a plugin architecture and library that can provide developers with common web application features like <a href="/questions/tagged/security" class="post-tag" title="show questions tagged 'security'" rel="tag">security</a> and dynamic UI tools.</p>
<p>Recent release (as of September 2013) of Grails (v 2.3.0) includes various features:</p>
<ul>
<li>Complete REST support</li>
<li>Async Programming APIs</li>
<li>Dependency Management with Aether</li>
<li>Forked Execution Everywhere</li>
<li>XSS Prevention</li>
<li>Rewritten Data Binding</li>
<li>Hibernate 4 Support</li>
<li>Loads of smaller, useful features!</li>
</ul>
<p><strong>Version History:</strong></p>
<ul>
<li><strong>Grails 0.3</strong> - November 2006</li>
<li><strong>Grails 0.4</strong> - Januray 2007</li>
<li><a href="http://grails.org/0.5+Release+Notes" rel="nofollow">Grails 0.5</a> - May 2007</li>
<li><a href="http://grails.org/0.6+Release+Notes" rel="nofollow">Grails 0.6</a> - August 2007 </li>
<li><a href="http://grails.org/1.0+Release+Notes" rel="nofollow">Grails 1.0</a> - February 2008 </li>
<li><em>SpringSource acquires G2One, the inventors of Grails in November 2008</em></li>
<li><a href="http://grails.org/1.1+Release+Notes" rel="nofollow">Grails 1.1</a> - March 2009</li>
<li><a href="http://grails.org/1.2+Release+Notes" rel="nofollow">Grails 1.2</a> - December 2009</li>
<li><em>VMWare acquires SpringSource in August 2009</em></li>
<li><a href="http://grails.org/1.3+Release+Notes" rel="nofollow">Grails 1.3</a> - May 2010</li>
<li><a href="http://grails.org/2.0.0+Release+Notes" rel="nofollow">Grails 2.0</a> - December 2011</li>
<li><a href="http://grails.org/2.1.0+Release+Notes" rel="nofollow">Grails 2.1</a> - July 2012</li>
<li><a href="http://grails.org/2.2.0+Release+Notes" rel="nofollow">Grails 2.2</a> - December 2012</li>
<li><a href="http://grails.org/2.3.0%20Release%20Notes" rel="nofollow">Grails 2.3</a> - September 2013 (released in SpringOne2GX 2013)</li>
</ul>
<p><strong>Related tags:</strong></p>
<ul>
<li><a href="http://stackoverflow.com/tags/gorm/info">GORM</a> - Grails object relational mapping implementation, backed by <a href="http://stackoverflow.com/tags/hibernate/info">Hibernate</a></li>
<li><a href="http://stackoverflow.com/tags/gsp/info">GSP</a> - <em>Groovy Server Pages</em>, the Grails template mechanism</li>
<li><a href="http://groovy.codehaus.org/" rel="nofollow">Groovy</a> - The programming language Grails uses</li>
</ul>
<p><strong>Online resources:</strong></p>
<ul>
<li><a href="http://www.grails.org/" rel="nofollow">Grails Home</a></li>
<li><a href="http://www.grails.org/plugin/home" rel="nofollow">Grails Plugin Library</a></li>
<li><a href="http://www.grails.org/doc/latest/" rel="nofollow">Grails Reference Documentation</a></li>
<li><a href="http://en.wikipedia.org/wiki/Grails_%28framework%29" rel="nofollow">Wikipedia on Grails</a></li>
<li><a href="http://groovy.codehaus.org/Getting+Started+Guide" rel="nofollow">Groovy - Getting Started Guide</a></li>
<li><a href="http://www.infoq.com/minibooks/grails-getting-started" rel="nofollow">Getting Started with Grails</a> - <em>free ebook</em></li>
<li><a href="http://www.springsource.com/" rel="nofollow">SpringSource</a> - company that sponsor Grails development</li>
<li><a href="https://github.com/grails-samples" rel="nofollow">Sample Applications</a> - some simple examples</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T14:25:23.933",
"Id": "39051",
"Score": "0",
"Tags": null,
"Title": null
}
|
39051
|
Web framework using the Groovy programming language. Groovy should also be tagged.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T14:25:23.933",
"Id": "39052",
"Score": "0",
"Tags": null,
"Title": null
}
|
39052
|
<p>I'm doing a clock in javascript and I am not sure this way is the best way to rotate the pointers. </p>
<p>Is this ok, or is there a better way?</p>
<pre><code>// browser vendors
var browsers = [
'webkit',
'Moz',
'ms',
'O',
''];
// function to move the pointers
function moveMe(el, unit) {
var deg = unit * 360 / 60;
browsers.each(function (b) {
el.style[b + 'Transform'] = 'rotate(' + deg + 'deg)';
});
}
// function to check the time
function checkTime() {
var date = new Date();
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hours = date.getHours();
moveMe(sPointer, seconds);
!seconds && moveMe(mPointer, minutes);
!minutes && moveMe(hPointer, hours);
}
</code></pre>
<p>The fiddle I'm playing with is <a href="http://jsfiddle.net/9ZY6u/" rel="nofollow"><strong>here</strong></a>.</p>
|
[] |
[
{
"body": "<p>First of all, your code use <code>Array.each()</code> method, which is a non-standard Javascript method, added by Mootools. I would rather use a standard loop, in order to keep a <em>vanilla</em> JS code.</p>\n\n<p>Then, instead of setting all properties every time, you should test which properties are supported by the browser and set them accordingly.</p>\n\n<p>Finally, since you are moving minutes only when <code>!seconds</code> (i.e. <code>seconds == 0</code>), the clock initialization is a bit weird. On page load, you should always move minutes and hours.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T18:46:57.533",
"Id": "65339",
"Score": "0",
"body": "Thanks for feedback! I do initialization on __[my fiddle](http://jsfiddle.net/9ZY6u/)__. About the `.each()` I have more mootools but sure, a vanilla loop is better. Good idea to detect browser... About the rotation itself, is that the best way to do it? By setting style on the image?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T18:50:23.377",
"Id": "65340",
"Score": "0",
"body": "That's indeed the most straightforward solution. Otherwise, you'll need to use HTML5 Canvas API."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T06:51:10.900",
"Id": "65397",
"Score": "0",
"body": "For reference, there is an [`Array.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method that is standard JavaScript (ES 5.1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T23:35:33.600",
"Id": "70798",
"Score": "0",
"body": "I disagree with the `.each` comment. If you're using a framework you can write code for the framework"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T18:43:46.060",
"Id": "39058",
"ParentId": "39057",
"Score": "2"
}
},
{
"body": "<p>In GCC, if you write <code>!seconds && moveMe(mPointer, minutes);</code> and compile with <code>-Wall</code> you get this warning:</p>\n\n<pre><code>[Warning] value computed is not used [-Wunused-value]\n</code></pre>\n\n<p>I know this is not C, but the problem is the same and I can't see why you don't explicitly write <code>if</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T22:34:56.713",
"Id": "65601",
"Score": "0",
"body": "+1 for pointing out a possible bug. Is this also the case if the first value is not negated with `!`? Because this is a common practise in javascript"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:38:46.373",
"Id": "39136",
"ParentId": "39057",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T18:22:30.233",
"Id": "39057",
"Score": "2",
"Tags": [
"javascript",
"css"
],
"Title": "Rotate image via javascript using CSS"
}
|
39057
|
<p>I wrote a simple emacs module that generates standard templates that I use for my blog's static site generator.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun hakyll-site-location ()
"Return the location of the Hakyll files."
"~/Sites/hblog/")
(defun hakyll-new-post (title tags)
"Create a new Hakyll post for today with TITLE and TAGS."
(interactive "sTitle: \nsTags: ")
(let ((file-name (hakyll-post-title title)))
(set-buffer (get-buffer-create file-name))
(markdown-mode)
(insert
(format "---\ntitle: %s\ntags: %s\ndescription: \n---\n\n" title tags))
(write-file
(expand-file-name file-name (concat (hakyll-site-location) "posts")))
(switch-to-buffer file-name)))
(defun hakyll-new-note (title)
"Create a new Note with TITLE."
(interactive "sTitle: ")
(let ((file-name (hakyll-note-title title)))
(set-buffer (get-buffer-create file-name))
(markdown-mode)
(insert (format "---\ntitle: %s\ndescription: \n---\n\n" title))
(write-file
(expand-file-name file-name (concat (hakyll-site-location) "notes")))
(switch-to-buffer file-name)))
(defun hakyll-post-title (title)
"Return a file name based on TITLE for the post."
(concat
(format-time-string "%Y-%m-%d")
"-"
(replace-regexp-in-string " " "-" (downcase title))
".markdown"))
(defun hakyll-note-title (title)
"Return a file name based on TITLE for the note."
(concat
(replace-regexp-in-string " " "-" (downcase title))
".markdown"))
</code></pre>
<p>Now, this works, but it could do with DRYing up a little bit, but I don't know enough elisp to do it myself.</p>
<ul>
<li><code>hakyll-new-post</code> and <code>hakyll-new-note</code> are very similar and could do with DRYing up, but I'm not sure how to pass the correct parameter to any refactored function</li>
<li>I'm hard coding <code>hakyll-site-location</code>. Is there any way that I can request for and store a configuration in my emacs dotfiles?</li>
</ul>
<p>Any help or pointers to documentation are welcome.</p>
|
[] |
[
{
"body": "<h2>DRY-ing it up:</h2>\n\n<p>It looks like variation is in:</p>\n\n<ul>\n<li>how the filename is obtained</li>\n<li>the contents of the inserted text</li>\n<li>the name of the file to write to.</li>\n</ul>\n\n<p>Also note that if <code>format</code> is given extra arguments not needed by its format-spec that <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/Formatting-Strings.html\" rel=\"nofollow\">they are ignored</a>.</p>\n\n<p>So you could define a function which takes 3 arguments: the function to call to get the filename to read from, the file-name to write to, and a the format-spec string.</p>\n\n<p>In order to pass a named function to a method you need to quote it as in the example:</p>\n\n<pre><code>(mapcar '1+ '(1 2 3))\n</code></pre>\n\n<p>If you want to pass an anonymous function to a function you defined it with <code>#'(lambda ...)</code>. For example:</p>\n\n<pre><code>(mapcar #'(lambda (x) (1+ x)) '(1 2 3))\n</code></pre>\n\n<h2>Making a configuration setting</h2>\n\n<p>I'd suggest changing your <code>hakyll-site-location</code> function into a variable. Use <code>defvar</code> to define it and then you can simply <code>setq</code> it in your emacs dotfiles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T22:30:40.300",
"Id": "39063",
"ParentId": "39059",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T19:17:30.750",
"Id": "39059",
"Score": "5",
"Tags": [
"template",
"elisp"
],
"Title": "Emacs module that generates templates for my blog's static site generator"
}
|
39059
|
<p>I have tried to design a class for a <a href="http://en.wikipedia.org/wiki/Complete_graph" rel="nofollow">complete graph</a>.</p>
<p>Needless to say, disadvantages of my current solution are very visible:</p>
<ul>
<li><p>dependent inputs have led to verification headaches.</p>
<p>In this code we rely on 2 inputs <code>set of nodes</code> and <code>edge map</code>. This creates the need to add a special verification function called <code>addEdgeVerification</code> to ensure both these
data structures are in sync.how to avoid this complexity of <code>inter-parameter dependency</code> at the same not burdening the client with headache of providing a complex data structure as input to our code ?</p></li>
<li><p>forces illegal states when some functions are invoked out of sequence.</p>
<p>This code returns illegal state if <code>getAdj</code> is called before complete graph has been constructed. How can this <code>illegal state issues</code> be avoided, without the need to force user to provide a complete graph ? Note the name of code is <code>CompleteGraphConstructor</code>. This means users will make use of our code to construct a complete graph. We dont users to take any effort to construct graph themselves. We want them to provide tiny inputs such as edges and nodes, and we should take the pain to join pieces.</p></li>
</ul>
<p>But alternatives are also not free from handicaps:</p>
<ul>
<li><p>dumping everything in constructor would make it a god constructor</p>
<p>A constructor can help us reduce/eliminate <code>illegal state</code>. But it would result in god constructors. It does not look like a good option, either.</p></li>
</ul>
<p>I am looking for recommendations on code architecture.
</p>
<pre><code>public class CompleteGraphConstructor<T> {
private final Map<T, HashMap<T, Double>> graph;
private Set<T> nodes;
public CompleteGraphConstructor() {
graph = new HashMap<T, HashMap<T, Double>>();
}
/**
* Add the nodes needed to be part of a graph.
*
* @param nodes the set nodes to add in the graph.
* @return true if nodes list is set, and false if it is not.
*/
public boolean addNodes (Set<T> nodes) {
// prevent overriting the nodes.
if (this.nodes != null) {
/**
* Should exception check be performed inside or outside?
*/
if (nodes == null) throw new NullPointerException("The node cannot be null.");
if (nodes.size() == 0) throw new NullPointerException("The size of node cannot be zero.");
this.nodes = nodes;
return true;
}
return false;
}
/**
* Add all edges of the graph.
*
* @param nodeId if nodeId is not null.
* @param allEdges all the edges of input node
*/
public void addEdges (T nodeId, Map<T, Double> allEdges) {
addEdgeVerification(nodeId, allEdges);
graph.put(nodeId, (HashMap<T, Double>) allEdges);
}
private void addEdgeVerification(T nodeId, Map<T, Double> allEdges) {
if (!nodes.contains(nodeId)) throw new NoSuchElementException("The source node: " + nodeId + " does not exist.");
// making sure that edges include nodes provided in the node Set.
for (T node : allEdges.keySet()) {
if (!nodes.contains(node)) throw new NoSuchElementException("The target node: " + nodeId + " not exist.");
}
// make sure that all the nodes in the edge set are included in allEdges
for (T node : nodes) {
if (node != nodeId) {
if (!allEdges.containsKey(nodeId)) throw new IllegalArgumentException("The input map does not contain all edges. ");
}
}
}
public Map<T, Double> getAdj (T nodeId) {
if (!nodes.contains(nodeId)) throw new NoSuchElementException("The node " + nodeId + " does not exist.");
if (!graph.containsKey(nodeId)) throw new IllegalStateException("The graph is not populated with " + nodeId);
return graph.get(nodeId);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T01:39:07.090",
"Id": "65373",
"Score": "0",
"body": "Why was this code marked negative ? I am looking for suggestions is this out of place ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T04:30:13.227",
"Id": "65389",
"Score": "1",
"body": "Maybe is because you are asking \"for recommendations on code architecture.\". If you take a look in the [help center](http://codereview.stackexchange.com/help/on-topic), you will realize that your question is off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T06:18:27.643",
"Id": "65395",
"Score": "0",
"body": "apologies and agreed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T06:23:24.783",
"Id": "65396",
"Score": "0",
"body": "Just for the record, I did not down voted your question. You don't need to apologize. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T12:50:12.023",
"Id": "65405",
"Score": "1",
"body": "I downvoted it because I didn't understand the question: I didn't understand what the program was supposed to do, until I realized that \"complete graph\" is a technical term with a precise meaning (after which I added a hyperlink to a definition of \"complete graph\", and reversed my downvote)."
}
] |
[
{
"body": "<p>I think you expect addNodes to be called exactly once, and expect it to be called before any other method.</p>\n\n<p>Therefore, remove the addNodes method, and move the <code>Set<T> nodes</code> parameter to the constructor.</p>\n\n<p>The next thing you want to do is define all edges. To do that you expect the user to call addEdges repeatedly (one for each node).</p>\n\n<p>A simpler way to do that might be to pass in a list of all edges. If you do the following then you only need to call the method once (because the List can contain all edges for all nodes):</p>\n\n<pre><code>public class Edge<T>\n{\n T node1;\n T node2;\n Double d;\n}\n\npublic void addEdges(Iterable<Edge> allEdges) {\n for (Edge edge : allEdges) {\n addEdge(edge.node1, edge.node2, edge.value);\n addEdge(edge.node2, edge.node1, edge.value);\n }\n}\n\nprivate void addEdge(T node1, T node2, Double value) {\n if (!graph.containsKey(node1))\n graph.put(node1, new HashMap<T, Double>());\n HashMap<T, Double> map = graph.get(node1);\n if (map.containsKey(node2))\n throw new DuplicateEdgeException(\"Duplicate \" + node1 + \" to \" + node2);\n map.put(node2, value);\n}\n</code></pre>\n\n<p>Your <code>Set<T> nodes</code> is only used for assertions. I'm not sure how useful that is.</p>\n\n<p>Also I don't understand your comment about a \"<a href=\"http://c2.com/cgi/wiki?GodMethod\" rel=\"nofollow\">god constructor</a>\". A constructor initializes the object using input data: that is something to love.</p>\n\n<p>In summary, perhaps a class like the following. This constructs an arbitrary graph, using only a collection of edges as its input; it supports an <code>isComplete</code> method to test whether the resulting graph is complete (which, you could call as an assertion in the constructor):</p>\n\n<pre><code>class Graph\n{\n public class Edge<T>\n {\n T node1;\n T node2;\n Double d;\n }\n\n private final Map<T, HashMap<T, Double>> graph;\n\n public Graph(Iterable<Edge> allEdges) {\n graph = new HashMap<T, HashMap<T, Double>>();\n for (Edge edge : allEdges) {\n addEdge(edge.node1, edge.node2, edge.value);\n addEdge(edge.node2, edge.node1, edge.value);\n }\n }\n\n private void addEdge(T node1, T node2, Double value) {\n if (!graph.containsKey(node1))\n graph.put(node1, new HashMap<T, Double>());\n HashMap<T, Double> map = graph.get(node1);\n if (map.containsKey(node2))\n throw new DuplicateEdgeException(\"Duplicate \" + node1 + \" to \" + node2);\n map.put(node2, value);\n }\n\n public bool isComplete()\n {\n int count = graph.size();\n for (HashMap<T, Double> map : graph.values())\n if (count != (map.size() + 1))\n return false;\n return true;\n }\n\n public Map<T, Double> getAdj (T nodeId) {\n if (!graph.containsKey(nodeId)) throw new IllegalStateException(\"The graph is not populated with \" + nodeId); \n return graph.get(nodeId);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:13:44.747",
"Id": "65439",
"Score": "0",
"body": "maybe god constructor was a wrong term to refer to but here is the article I was referring to - http://stackoverflow.com/questions/18049710/constructor-best-practices"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:20:05.437",
"Id": "65441",
"Score": "0",
"body": "@JavaDeveloper I see. In my opinion, both those answers are wrong, and I don't understand their reasoning. I think that an API should be easy to use, as simple as possible, and difficult to use incorrectly: therefore having a single constructor is better than 'multi-stage' construction, which would requires the user/client to make several methods calls in the right sequence in order to 'construct' the final object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T12:48:37.330",
"Id": "39090",
"ParentId": "39064",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39090",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T22:51:35.717",
"Id": "39064",
"Score": "6",
"Tags": [
"java",
"exception-handling",
"graph"
],
"Title": "Code to construct a complete graph"
}
|
39064
|
<p>I'm very new to C, so pointing out better ways of doing things, errors, bad practices, etc would be optimal at this stage.</p>
<p><a href="https://github.com/brandonwamboldt/projects/blob/master/fibonacci/fib.c">Code on GitHub</a></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int *calculateFibonacciSequence(int n, int start)
{
int i;
// Allocate memory for our fibonacci sequence from the heap
int *numbers = malloc(sizeof(int) * n);
// Need to calculate at least one number
if (n <= 0) {
return 0;
}
// Can't start with a number under zero
if (start != 0 && start != 1) {
return 0;
}
// Get the seed values
if (start == 0) {
numbers[0] = 0;
numbers[1] = 1;
} else {
numbers[0] = 1;
numbers[1] = 1;
}
// Calculate the sequence
for (i = 1; i < n; i++) {
numbers[i + 1] = numbers[i] + numbers[i - 1];
}
return numbers;
}
int main(int argc, char *argv[])
{
int i, n;
int start = 0;
int *sequence;
// Check to see how many arguments we got
if (argc <= 1) {
puts("Please pass the number of iterations to run.");
return 1;
}
// Get the number of iterations to run
n = atoi(argv[1]);
// Did they specify a start value
if (argc > 2) {
start = atoi(argv[2]);
}
// Calculate the sequence
sequence = calculateFibonacciSequence(n, start);
// Output the sequence
if (sequence) {
printf("%d", sequence[0]);
for (i = 1; i <= n; i++) {
printf(",%d", sequence[i]);
}
// Newline
puts("");
} else {
puts("Error processing fibonacci sequence");
}
// Free memory
free(sequence);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:26:33.143",
"Id": "65615",
"Score": "0",
"body": "Since you're just printing the numbers, what is your original task: to print them or to compute them in an array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:28:31.550",
"Id": "67619",
"Score": "0",
"body": "@syb0rg I accepted your answer just now. Originally I was giving people time to post/edit and then I forgot to accept an answer. While your recursive example doesn't really do what I want, your post is very informative. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:30:27.773",
"Id": "67620",
"Score": "0",
"body": "@BrandonWamboldt Thanks! I did add a faster iterative solution in case you did not want recursion."
}
] |
[
{
"body": "<p>You C is very good. Just a few comments:</p>\n\n<p>The <code>start</code> parameter is pointless. Just print the whole sequence.</p>\n\n<p>Don't allocate memory until you know your parameters are valid. Else you have\na memory leak.</p>\n\n<p>You don't check that the <code>numbers[]</code> array was allocated successfully and you\nhave overflowed the array by one place.</p>\n\n<p>Define loop variables in the loop where possible:</p>\n\n<pre><code>for (int i = 1; i < n; i++) {...}\n</code></pre>\n\n<p>Many of your comments are not useful. They might be required by your\nsupervisor (if you have one) but in normal code would be considered 'noise'. Comments should add something that the reader can't see for himself. Usually 'why' is a better question to answer than 'what', as for good code, what you are doing should be self-evident. </p>\n\n<p>Defining variables where they are needed, not at the beginning of functions, is\noften considered best practice.</p>\n\n<p>EDIT: Also, to add a new line, <code>putchar('\\n');</code> would be more normal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:18:12.870",
"Id": "65367",
"Score": "1",
"body": "Hmm, I may have re-iterated some points you had. My answer was in the works when you posted this and didn't notice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T02:44:06.107",
"Id": "65378",
"Score": "1",
"body": "No problem - if we both thought the same things, there's perhaps more chance of them being true :-) BTW your recursive solution is notationally neat but horribly inefficient. Do a Fibonacci of 46 and it calls `fibonacci` 9615053904 times (and takes correspondingly long)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T04:11:26.037",
"Id": "65384",
"Score": "0",
"body": "Yeah, I think I had a [Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm). I have edited in a solution that uses [memoization](https://en.wikipedia.org/wiki/Memoization) now, which is much faster."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:02:09.287",
"Id": "39067",
"ParentId": "39066",
"Score": "12"
}
},
{
"body": "<h2>What you did well on:</h2>\n\n<ul>\n<li><p>Your program is easy to read.</p></li>\n<li><p>You are allocating memory, even though it is unsafe in certain cases (other answers have addressed this, so I won't cover it).</p></li>\n<li><p>You prepare for some corner cases.</p></li>\n</ul>\n\n<hr>\n\n<h2>Things you could improve:</h2>\n\n<ul>\n<li><p>You are returning <code>0</code> when your program runs into a problem (except\nin one spot where there are too many parameters being entered).</p>\n\n<pre><code>return 0;\n</code></pre>\n\n<p><code>0</code> is typically the return code for a exiting successfully. If we\nrun into a problem in our program, we should return something to\nindicate we ran into a problem. I prefer to return negative numbers.</p>\n\n<pre><code>return -1;\n</code></pre>\n\n<p>Also, you should return different numbers for different errors. A user generated error such as malformed input should not return the same error code as an internal error. This makes debugging a lot easier when you are trying to determine the cause of an error.</p>\n\n<p>However, since you are returning an <code>int*</code>, it would be better to return <code>NULL</code> instead. This is what you are doing right now, in a somewhat abnormal way by returning 0. Just return <code>NULL</code>.</p>\n\n<pre><code>return NULL;\n</code></pre></li>\n<li><p>You should mark <code>int</code>s as <code>unsigned</code> if they are never going to be negative.</p>\n\n<pre><code>unsigned int start;\n</code></pre></li>\n<li><p>You are not maximizing how many Fibonacci you can produce using only an <code>int</code>, or even an <code>unsigned int</code>. An <code>unsigned int</code> has a maximum value of 2147483647, where a <code>long long unsigned int</code> has a maximum value of 18446744073709551615. That's 8589934562 times larger!</p></li>\n<li><p>Declare <code>i</code> inside of your <code>for</code> loops. This is part of the <a href=\"https://en.wikipedia.org/wiki/C99\" rel=\"nofollow\">C99 standard</a>, so you may have to adjust how you compile your program.</p>\n\n<pre><code>for (unsigned int i = 1; i <= n; i++)\n</code></pre></li>\n<li><p>I don't see the point of the <code>start</code> variable. Unless this is part of some problem you are trying to solve, I would just print the whole sequence. It would cut down on your lines of code a lot as well.</p></li>\n<li><p>The Fibonacci series is a great place to practice recursion.</p>\n\n<pre><code>long long unsigned int fibonacci(long long unsigned int n)\n{\n if (n < 2) return n;\n else return (fibonacci(n-1) + fibonacci(n-2));\n}\n</code></pre>\n\n<p>This algorithm here is short, and gets the job done just has you did in less lines of code. We could even shorten it a bit further if we wanted to (with ternary operators).</p>\n\n<pre><code>long long unsigned int fibonacci(long long unsigned int n)\n{\n return (n < 2)? n : fibonacci(n-1) + fibonacci(n-2);\n}\n</code></pre>\n\n<p>We have to be careful though to <a href=\"https://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm\" rel=\"nofollow\">avoid repeating the calculation of results for previously processed inputs</a>; to do this we should use <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoization</a>. I've implemented this in my final program.</p></li>\n<li><p>Keep in mind that sometimes recursion will make your algorithm a bit\nslower with time-complexity, which can be the case here (depending on your implementation of an iterative solution). Here is the fastest iterative algorithm I could work up (this may still be a bit slower with the <code>pow()</code> function).</p>\n\n<pre><code>long long unsigned int fibonacci(long long unsigned int n)\n{\n return (1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n));\n}\n</code></pre>\n\n<p>However, using this method requires the use of <code>double</code>s, and the <code>return</code> will make an implicit cast that could cause some rounding problems. Therefore, we will <code>round()</code> the result in our final code.</p></li>\n<li><p>You should test if you input is a number, and not some malformed input.</p>\n\n<pre><code>if (scanf(\"%i\", &num) <= 0)\n{\n puts(\"Invalid input.\");\n return -1;\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h2>Final code:</h2>\n\n<ul>\n<li><h3>Iterative: O(1)</h3>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nlong long unsigned int fibonacci(long long unsigned int n)\n{\n return round((1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)));\n}\n\nint main(void)\n{\n unsigned int num = 0;\n\n printf(\"Enter how far to calculate the series: \");\n if (scanf(\"%i\", &num) <= 0)\n {\n puts(\"Invalid input.\");\n return -1;\n }\n\n for(unsigned int n = 1; n < num + 1; ++n) printf(\"%llu\\n\", fibonacci(n));\n}\n</code></pre></li>\n<li><h3>Recursion: O(n)</h3>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n#define ARRAYLENGTH 100 // keep in mind the result must fit in an llu int (fibonacci values grow rapidly)\n // you will run into issues after 93, so set the length at 100\nlong long int memoization[ARRAYLENGTH];\n\nlong long unsigned int fibonacci(long long unsigned int n)\n{\n if (memoization[n] != -1) return memoization[n];\n\n return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));\n}\n\nint main(void)\n{\n unsigned int num = 0;\n\n for(unsigned int i = 0; i < ARRAYLENGTH; i++) memoization[i] = -1; // preset array\n\n printf(\"Enter how far to calculate the series: \");\n if (scanf(\"%i\", &num) <= 0)\n {\n puts(\"Invalid input.\");\n return -1;\n }\n if (num < ARRAYLENGTH)\n {\n for(unsigned int n = 1; n < num + 1; ++n) printf(\"%llu\\n\", fibonacci(n));\n }\n else\n {\n puts(\"Input number is larger than the array length.\");\n return -2;\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:26:28.930",
"Id": "65368",
"Score": "0",
"body": "Isn't declaring the loop counter inside the loop statement a syntax error in C? Or does the OP have C99?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:33:14.863",
"Id": "65369",
"Score": "0",
"body": "@Jamal It was an error, so I kept that part how it was"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:37:53.220",
"Id": "65370",
"Score": "0",
"body": "@Jamal Yes, in older standards. But C99 is the \"lowest\" standard that should be used (in my opinion)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:40:29.733",
"Id": "65371",
"Score": "0",
"body": "Okay. For the short time I've written C (mostly in just one class), I was always used to declaring it outside since C99 wasn't in use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:34:04.660",
"Id": "66282",
"Score": "0",
"body": "I think you got confused by the trap that I pointed out in my answer: that's a `NULL` pointer being returned, not a number 0. Returning `-1` as a pointer to indicate an error condition would be really weird."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:38:34.113",
"Id": "66284",
"Score": "0",
"body": "According to @Loki, current thinking in the C/C++ world is that `unsigned` types are more trouble than they are worth, especially when you won't be going anywhere near the maximum value (like `start`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:44:15.903",
"Id": "66287",
"Score": "2",
"body": "I'd consider the global array, with a fixed size limit, and recursion not an improvement, but rather three steps back."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T09:56:02.853",
"Id": "67246",
"Score": "0",
"body": "@syb0rg: You \"final code\" is broken: In `main()` you have a `char temp` and `scanf(\"%s\", &temp)`. That's asking for a buffer overflow. Also, it can calculate at most the ninth Fibonacci number due to the single digit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T21:24:21.943",
"Id": "67428",
"Score": "0",
"body": "@EOF I would be interested to talk to you more about that in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T00:52:36.990",
"Id": "67440",
"Score": "0",
"body": "@200_success I said Fibonacci was a great place to practice recursion, it may not be the most efficient. I have now included an iterative example as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:50:43.670",
"Id": "67621",
"Score": "0",
"body": "The double precision formula should be rounded, or you may get wrong results (x.99999999 -> x when it should be x+1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T00:52:24.600",
"Id": "67623",
"Score": "0",
"body": "@VedranŠego You should visit me in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) so we can talk more about this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T12:14:15.007",
"Id": "67695",
"Score": "0",
"body": "Sorry, I wasn't here. My reasoning is simple: the result of the above expression is, in theory, an integer. Due to rounding errors, it is possible that the obtained result is non-integer. Conversion to `int` is a truncation, so if the computed result is smaller than the exact one (even by as little as the machine precision), this will get truncated and will give the wrong result. I don't have the example when it actually happens. Maybe never, but it depends on various factors which you cannot test all (i.e., all possible processors), so I go with the \"better safe than sorry\" approach."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:17:15.287",
"Id": "39068",
"ParentId": "39066",
"Score": "16"
}
},
{
"body": "<p>Your code is rather unsafe.</p>\n\n<p>You allocate memory using <code>malloc()</code>, based on a user-submitted number that is never checked. If the user supplies <strong>-1</strong> in <code>argv[1]</code>, <code>malloc()</code> will try to allocate <strong>0xFFFFFFFC</strong> bytes on a 32- or <strong>0xFFFFFFFFFFFFFFFC</strong> bytes on a 64-bit two's-complement architecture. This may fail.</p>\n\n<p>The return value of <code>malloc()</code> is never checked, which may lead to a segmentation-fault if <code>malloc()</code> failed and the resulting null-pointer is subsequently dereferenced.</p>\n\n<p>After you allocate your buffer, you check for input validity, and if the check fails, the function returns <strong>0</strong>. <code>main()</code> treats this return value as a pointer and <code>free()</code>'s it, but if an error occurred in the function, <strong>0</strong> is passed to <code>free()</code> instead of the pointer to the allocation and the allocated memory is leaked.</p>\n\n<p>In this case it doesn't matter, because the program exits and all memory is automatically freed on program exit, but for a bigger project this would not work.</p>\n\n<p>The code should be rewritten.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T02:15:44.410",
"Id": "65620",
"Score": "0",
"body": "Makes sense, thanks. Never had to do memory management manually before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:35:23.367",
"Id": "39179",
"ParentId": "39066",
"Score": "10"
}
},
{
"body": "<p>Welcome to the world of C and its pitfalls.</p>\n\n<p>In particular, you have a memory leak if the parameters to <code>calculateFibonacciSequence()</code> fail validation. That is, you call <code>malloc()</code>, but the <code>numbers</code> pointer will be lost forever once you <code>return 0</code>. The solution would be to postpone <code>malloc()</code> until after the parameters pass validation.</p>\n\n<p>Also in <code>calculateFibonacciSequence()</code>, you wrote <code>return 0</code>, but you are actually returning a null pointer, not a number 0. It would be clearer to write <code>return NULL</code>.</p>\n\n<p>As a nitpick, I think two spaces for indentation is too stingy for readability. Small indentation also encourages excessive nesting, which is poor programming practice. Try four spaces instead.</p>\n\n<p>Overall, though, not bad!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:31:46.633",
"Id": "39547",
"ParentId": "39066",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39068",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-11T23:45:43.960",
"Id": "39066",
"Score": "13",
"Tags": [
"c",
"beginner",
"fibonacci-sequence"
],
"Title": "Fibonacci sequence in C"
}
|
39066
|
<p>I have a naming problem: lists with un-named elements. I wish to get the names of the elements in the list, without going back upstream to where the list was created. An example is <code>modelList</code> below:</p>
<pre><code>## naming problem
lmNms <- c( "mod1", "mod2", "mod3", "mod4", "mod5", "mod6")
lapply(lmNms,
function(N) assign(N, lm(runif(10) ~ rnorm(10)), env = .GlobalEnv))
modelList <- list(mod1, mod2, mod3, mod4, mod5, mod6)
</code></pre>
<p>I have written the below function which takes the list and the <code>environment</code> as arguments (as well as an argument to return names only), looks for a matching object in the target environment, and then attaches that name to the element and returns the list. </p>
<pre><code>nameListObjects <- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {
if(is.null(ENV)) ENV <- .GlobalEnv
for(i in seq_along(LIST)){
# check the class of all objects in the target environment
classMatches <- sapply(ls(ENV),
function(N) class(get(N)) == class(LIST[[i]]))
# see which objects of matching class are all.equal to the subject
TF <- sapply(names(classMatches[classMatches]),
function(N) is.logical(all.equal(LIST[[i]], get(N))))
names(LIST)[i] <- names(classMatches[classMatches])[TF]
}
if(NAMES.ONLY) names(LIST) else LIST
}
R>nameListObjects(modelList, NAMES.ONLY=TRUE)
[1] "mod1" "mod2" "mod3" "mod4" "mod5" "mod6"
</code></pre>
<p>This took me to the edge of my R ability. </p>
<p>I'm interested in better ways to do this (i presume there are multiple better ways), problems with this approach, and any other comments. </p>
|
[] |
[
{
"body": "<p>You could have used <code>identical</code> to compare objects. However, I would recommend representing all objects by their MD5 digests, so you can then use <code>match</code> to find the matches:</p>\n\n<pre><code>nameListObjects <- function(LIST, ENV = NULL, NAMES.ONLY = FALSE) {\n\n if(is.null(ENV)) ENV <- .GlobalEnv\n require(digest)\n list.md5 <- sapply(LIST, digest)\n env.names <- ls(envir = ENV)\n env.md5 <- sapply(env.names, function(x)digest(get(x, envir = ENV)))\n list.names <- env.names[match(list.md5, env.md5)]\n\n if(NAMES.ONLY) list.names else setNames(LIST, list.names)\n}\n\nnameListObjects(modelList, NAMES.ONLY=TRUE)\n[1] \"mod1\" \"mod2\" \"mod3\" \"mod4\" \"mod5\" \"mod6\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T02:50:00.103",
"Id": "65380",
"Score": "0",
"body": "+1, thanks. I don't know what an MD5 digest is -- can you please explain a little?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T02:55:34.270",
"Id": "65381",
"Score": "0",
"body": "I'd recommend you google it for a better explanation, but the idea is that a fast algorithm reads and converts an object's contents into a character string e.g. `digest(mod1)` is `f7c95caf2caafd8603977ac967f0ebe2`. As you can guess from the length and complexity of the string, the probability of two distinct objects sharing the same digest is very, very small. It's like a fingerprint in a sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T02:38:13.507",
"Id": "39072",
"ParentId": "39069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T00:47:05.547",
"Id": "39069",
"Score": "2",
"Tags": [
"r"
],
"Title": "finding names of un-named list elements"
}
|
39069
|
<p>Not long ago, I posted <a href="https://codereview.stackexchange.com/questions/38085/dynamic-stack-implementation">this dynamic stack</a> for review. Now I wrote a new version, which is hopefully a better one.</p>
<p>Please take a look and let me know how I could improve performance and increase code quality.</p>
<p>It works by storing pointers to the content. If there's not enough memory, it will try to increase the allocated space.</p>
<p><strong>header</strong></p>
<pre><code>#ifndef DYNAMIC_STACK
#define DYNAMIC_STACK
#define DSTACK_SUCCESS 1
#define DSTACK_ERROR 0
//The stack just stores pointers
typedef struct Dynamic_Stack Dynamic_Stack;
struct Dynamic_Stack {
void **start; //Array of pointer to void
void **position;
void **end;
};
//Set up stack
int dstack_init(Dynamic_Stack *stack, size_t slots);
void dstack_free(Dynamic_Stack *stack);
void dstack_clear(Dynamic_Stack *stack);
int dstack_push(Dynamic_Stack *stack, void *new_element);
void *dstack_pop(Dynamic_Stack *stack);
//0 is the top of the stack
void *dstack_peek(Dynamic_Stack *stack, size_t levels);
int dstack_increase_capacity(Dynamic_Stack *stack, size_t new_slots);
int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total);
void dstack_shrink_to_fit(Dynamic_Stack *stack);
#endif
</code></pre>
<p><strong>c file</strong></p>
<pre><code>#include <stdlib.h>
#include "dynamic_stack.h"
#define MULTIPLIER 1.00 //Increase by 100% on every expansion
#define FIXED_EXPANSION 0 //Overrides multiplier
//Internal
//Must keep at least 1 slot or it will break
static int dstack_resize(Dynamic_Stack *stack, size_t new_slot_capacity)
{
size_t position = stack->position - stack->start;
void *temp = realloc(stack->start, new_slot_capacity * sizeof(void *));
if(temp == NULL)
return DSTACK_ERROR;
stack->start = temp;
stack->end = stack->start + new_slot_capacity;
//Put position back if needed
stack->position = (position < new_slot_capacity)
? stack->start + position
: stack->end;
return DSTACK_SUCCESS;
}
#if FIXED_EXPANSION >= 1
static int expand(Dynamic_Stack *stack)
{
return dstack_resize(stack, stack->end - stack->start + FIXED_EXPANSION);
}
#else
static int expand(Dynamic_Stack *stack)
{
//Check if multiplier is producing at least 1 new slot
size_t old_slots = stack->end - stack->start;
size_t new_slots = old_slots * MULTIPLIER;
if(new_slots == 0)
return DSTACK_ERROR;
return dstack_resize(stack, old_slots + new_slots);
}
#endif
//Public
//Set up stack
int dstack_init(Dynamic_Stack *stack, size_t slots)
{
if((stack->start = malloc(sizeof(void *) * slots)) == NULL)
return DSTACK_ERROR;
stack->position = stack->start;
stack->end = stack->start + slots;
return DSTACK_SUCCESS;
}
void dstack_free(Dynamic_Stack *stack)
{
free(stack->start);
}
void dstack_clear(Dynamic_Stack *stack)
{
stack->position = stack->start;
}
int dstack_push(Dynamic_Stack *stack, void *new_element)
{
if(stack->position == stack->end && expand(stack) == DSTACK_ERROR)
return DSTACK_ERROR;
*stack->position = new_element;
++stack->position;
return DSTACK_SUCCESS;
}
void *dstack_pop(Dynamic_Stack *stack)
{
if(stack->position == stack->start)
return NULL;
return *--stack->position;
}
//0 is the top of the stack
void *dstack_peek(Dynamic_Stack *stack, size_t levels)
{
if(levels >= stack->position - stack->start)
return NULL;
return *(stack->position - 1 - levels);
}
int dstack_increase_capacity(Dynamic_Stack *stack, size_t new_slots)
{
return dstack_resize(stack, stack->end - stack->start + new_slots);
}
int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total)
{
if(remove_total >= stack->end - stack->start)
return DSTACK_ERROR;
return dstack_resize(stack, stack->end - stack->start - remove_total);
}
//Always leave 1 extra slot so there's no risk of resizing to 0
void dstack_shrink_to_fit(Dynamic_Stack *stack)
{
dstack_resize(stack, stack->position - stack->start + 1);
}
</code></pre>
<p><strong>example</strong></p>
<pre><code> #include <stdio.h>
#include "dynamic_stack.h"
int main(void)
{
char *words[] = {
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
""
};
Dynamic_Stack stack;
if(!dstack_init(&stack, 12))
return 1;
for(char **ite = words; **ite != '\0'; ++ite){
dstack_push(&stack, *ite);
}
size_t i = 0;
for(char **ite = words; **ite != '\0'; ++ite)
puts(dstack_peek(&stack, i++));
dstack_increase_capacity(&stack, 8);
dstack_shrink_to_fit(&stack);
for(char *ite; (ite = dstack_pop(&stack)) != NULL; ++ite)
puts(ite);
dstack_free(&stack);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Sorry, but I really don't like the use of raw <code>void*</code> and pointer arithmetic\neverywhere. The whole code would be simpler if you added a <code>typedef</code>:</p>\n\n<pre><code>typedef void* Slot;\n</code></pre>\n\n<p>and globally replace <code>void *</code> with <code>Slot</code></p>\n\n<p>I don't normally like hiding pointer types behind a <code>typedef</code> but in this case\nthe <code>void*</code> is not really a pointer - it is just storage space.</p>\n\n<p>Having done that, redefine the stack as follows:</p>\n\n<pre><code>struct Dynamic_Stack {\n Slot *slots;\n size_t position;\n size_t size;\n};\n</code></pre>\n\n<p>So the current insertion point and the stack size are both just integers, not\npointers. You can now replace all of your pointer arithmetic (each of which\ngives a compilation warning with <code>-Wsign-conversion</code> and <code>-Wsign-compare</code>) with\nsimple indices. You must also replace accesses to the slots with array\naccess:</p>\n\n<pre><code>int dstack_push(Dynamic_Stack *stack, Slot new_element)\n{\n ...\n stack->slots[stack->position++] = new_element;\n</code></pre>\n\n<p><hr>\nSome other issues:</p>\n\n<p>The expansion mechanism is odd. Using a floating point size multiplier\nand then returning a <strong>runtime error</strong> when the compile-time multiplier turns\nout to have the wrong value (produces a zero expansion) in some circumstance\nis wrong. I'd suggest you keep it simple and just double the size of the\nstack when expanding unless it turns out that this is bad for your application\n(I can't see why it should be - you have facilities for shrinking the stack\nafter all). You have made it more complicated than it needs to be.</p>\n\n<p>In your <code>dstack_pop</code> and <code>dstack_peep</code> you have wrongly mixed the data and\nerror return values. It is quite valid for me to push zero onto the stack and\nI expect to be able to pop zero too, but these two functions return zero on\nerror. You need to separate the error return from the data:</p>\n\n<pre><code>Slot dstack_pop(Dynamic_Stack *stack, int *status);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int dstack_pop(Dynamic_Stack *stack, Slot *slot);\n</code></pre>\n\n<p>Also, the stack parameter to <code>dstack_peek</code> should be <code>const</code></p>\n\n<hr>\n\n<p>Minor point, in the code before my renaming etc, <code>dstack_resize</code> has the\nfollowing line: </p>\n\n<pre><code>size_t position = stack->position - stack->start;\n</code></pre>\n\n<p>I would not reuse the name <code>position</code> for the index when <code>stack->position</code> is a\npointer in the structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:50:25.397",
"Id": "39317",
"ParentId": "39075",
"Score": "1"
}
},
{
"body": "<p>Regarding performance: as the major operations (push and pop) are O(1) and you wrote them in a straightforward way, it is hard to optimize them in a way which would not be annulled (or even reversed in effect) by compiler or CPU optimizations.\nOTOH, it is also hard to envision a situation where program performance would even be remotely depending on your stack code - as you are (in most cases) dealing with \"something bigger than an int\", every push/pop is accompanied by an operation on the data item which will very likely outweigh the stack operations by a factor. </p>\n\n<p>(minor nitpick: in the pop-function you could and should use two operations to decrease the stackpointer and return the value a) to be symmetric to the code in push b) to save the programmer coming after you from needing to remember what *-- means exactly) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:03:26.927",
"Id": "39368",
"ParentId": "39075",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39317",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T04:34:25.220",
"Id": "39075",
"Score": "3",
"Tags": [
"c",
"performance",
"stack"
],
"Title": "Dynamic stack in C - new version"
}
|
39075
|
<p>I am new to C++ and would like to know the most efficient way of forcing a user to enter an integer. Here is my function that I have created. Please show me the best way and explain why it's better than this.</p>
<pre><code>int getInt(){
int x;
while (true){
cout << "Enter an int." << endl;
cin.clear();
while(cin.get() != '\n');
cin >> x;
if (!cin.fail()){
return x;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your method isn't safe. If it receives a floating-point-number as an input or strings like <code>4vfdrefd</code>, it will not leave the buffer empty.</p>\n\n<p>It's pretty elegant to use <code>std::getline</code> to get the input, specially if you want to read some other types as an integer.</p>\n\n<p>A good way to grab an integer from <code>std::cin</code> is to use <code>std::stringstream</code>, as it is totally type-safe and does all the work we would have to do. => we can be lazy and laziness is always a good thing! ------- So for example we could do this to get a safe and short way of grabbing an integer from <code>std::cin</code>:</p>\n\n<pre><code>#include <sstream>\n#include <string>\n#include <iostream>\n\nint getInt()\n{\n int x=0;\n bool loop=true;\n while(loop)\n {\n std::cout << \"Enter an int.\" << std::endl;\n std::string s;\n std::getline(std::cin, s);\n\n std::stringstream stream(s);\n if(stream >> x)\n {\n loop=false;\n continue;\n }\n std::cout << \"Invalid!\" << std::endl;\n }\n return x;\n}\n\nint main(){std::cout << getInt();}\n</code></pre>\n\n<p>Hope this helped!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:05:48.983",
"Id": "65466",
"Score": "2",
"body": "Instead of `loop=false; continue;`, why not just `break`, or better yet, `return x`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T16:20:45.917",
"Id": "135916",
"Score": "0",
"body": "I consider it as ugly"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T00:04:27.617",
"Id": "39112",
"ParentId": "39076",
"Score": "1"
}
},
{
"body": "<p>I don't like while loops without a body. They are hard to read.</p>\n\n<pre><code>while(cin.get() != '\\n');\n\n// Even if the body is just a comment.\nwhile(cin.get() != '\\n')\n{ /* Empty Body */ }\n</code></pre>\n\n<p>But what you are doing is basically ignoring the current line. It would be easier to do this with <code>ignore()</code></p>\n\n<pre><code>std::cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n</code></pre>\n\n<p>But now that we have looked at it I don't really think you want to ignore the current line of input. Getting input screwed up (especially when working with interactive user input) is that you are mixing <code>std::getline</code> and <code>operator>></code>. User input is line based so always read a line of input from the user then parse the input. Then you will not get screwed up by unread end of line markers.</p>\n\n<p>Looping <code>while(true)</code> is dangerous when working with streams. Things have a tendency of becoming infinite. If your stream becomes bad (ie bad bit is set), then you will go into infinite loop. Clearing the bad bit and retrying is unlikely to make it better.</p>\n\n<p>So I would re-write like this:</p>\n\n<p>How about:</p>\n\n<pre><code>int getInt(std::istream& stream)\n{\n // Only loop as long as the input is stream is usable.\n // Otherwise you enter an infinite loop.\n while (stream)\n {\n cout << \"Enter an int.\" << endl;\n\n // Read a line of user input.\n std::string line;\n std::getline(stream, line);\n\n // Now convert user input to value.\n std::stringstream linestream(line);\n int value;\n\n if (!(linestream >> value)) {\n continue; // The input was not an integer.\n } // So retry the loop.\n\n // You got a good value.\n // Do you care if there is stuff on the end of the line?\n // i.e. If the user entered 56 f<enter> is that bad?\n // If it is then you check to see if there is more valid input on the line.\n char x;\n\n if (linestream >> x) {\n continue; // There was good input (thus the input was bad).\n }\n return value;\n }\n // If you get here,\n // this means you ran out of input.\n // What do you do?\n // You could return a default value.\n // or throw an exception.\n return 0;\n\n // The trouble with either of these methods is that its hard to detect\n // the error situation. You need to explicitly check. That is why `operator>>`\n // works well. The stream goes bad when things get out of sync and the natural\n // operations cause the current operation to fail.\n}\n</code></pre>\n\n<p>So an alternative to <code>getInt()</code> would be to extend <code>operator>></code> for reading a line and getting an integer out of it.</p>\n\n<pre><code> struct GetInt\n {\n int& val;\n GetInt(int& v): val(v) {}\n\n friend std::istream& operator>>(std::istream& str, GetInt& data)\n {\n data.val = getInt(str);\n return str;\n }\n };\n</code></pre>\n\n<p>Now you can use your line getting in a normal stream like operation.</p>\n\n<pre><code> int val;\n if (std::cin >> GetInt(val))\n {\n // We correctly retrieved a value from the user.\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:46:16.890",
"Id": "66245",
"Score": "0",
"body": "Note that `getInt` is potentially dangerous as you're performing extraction `getline(stream, line)` without checking if it worked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:48:41.773",
"Id": "66246",
"Score": "0",
"body": "@David. Thats fine. Because of `getline()` fails then `line` is left empty and thus the following attempt to read a value from the stringstream fails. This hits the continue which takes you back to the `while(stream)` which checks that the stream is OK (if it failed it is not) and does not enter the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:55:57.487",
"Id": "66248",
"Score": "0",
"body": "Touché my friend... touché. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T00:31:21.323",
"Id": "39113",
"ParentId": "39076",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T05:26:06.983",
"Id": "39076",
"Score": "4",
"Tags": [
"c++",
"beginner",
"stream"
],
"Title": "Forcing user to enter an integer"
}
|
39076
|
<p>I wrote this function for <a href="http://projecteuler.net/problem=1" rel="nofollow">Project Euler Problem 1</a>. </p>
<pre><code>prob001 :: (Integral a) => [a] -> [a] -> a
prob001 a b = sum [x | x <- a, product ( map (x `rem`) b ) == 0]
</code></pre>
<p>The use is like this</p>
<pre><code>GHCi> prob001 [1..999] [3, 5]
233168
</code></pre>
<p>But I am not at all satisfied with it. The list comprehension looks like something I have taken from Python. But I think the predicate can be much more efficient if it were written as a short-circuiting function. Currently it will have to evaluate each of these.</p>
<p>I am not able to think how to write that part in a short-circuiting way without a variable to hold the values. Am I correct in thinking that or not? Anything other that I can improve here?</p>
|
[] |
[
{
"body": "<p>I think that <code>any</code> is your friend here.</p>\n\n<pre><code>aMultipleOf factors x = any (\\f -> x `rem` f == 0) factors\nprob001 :: (Integral a) => [a] -> [a] -> a\nprob001 nums factors = sum $ filter (aMultipleOf factors) nums\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:26:05.837",
"Id": "39101",
"ParentId": "39079",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39101",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T07:44:57.877",
"Id": "39079",
"Score": "4",
"Tags": [
"beginner",
"haskell",
"project-euler"
],
"Title": "Project Euler Problem 1 - Multiples of 3 and 5"
}
|
39079
|
<p>I know that there is one more topic about the exercise 4-11, but the difference is that I solved this exercise and i just need some feedback on my solution. So, I'll explain how it works on an output like "3 4 +\n", for example. The static variable c is initialized with the value ' ' so the condition of the first if statement evaluates to true, the while loop within the if statement will run until c reaches the value '3'. Because it is a number, the function will return the NUMBER signal and the variable c will get the value ' ' - the value that breaks the loop within the 3rd if statement. </p>
<p>Now we are, again, on the first if statement and, again, c has the value ' '. The condition is evaluated to true and the loop within the if statement will run until c reaches the value '4'.
Again, because '4' is a "number" the function will return the NUMBER signal and c will get the value '+' - the value that breaks the loop within the 3rd if statement.</p>
<p>This time c is equal to '+' and the condition of the first if statement is evaluated to false, so the value '+' will be returned. I saved the value of the variable c in a temporary variable tmp, and initialize tmp with the value of c before changing it to ' '.</p>
<p>Without this movement I'll get an infinite loop.</p>
<p>The program is made of 5 parts:</p>
<p>main.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
#define MAXOP 1001
int main() {
char entry;
char s[MAXOP];
double op2;
while((entry = getop(s)) != EOF) {
switch(entry) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() +pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if(op2) {
push(pop() / op2);
}
else {
printf("can't divide by 0");
}
break;
case '\n':
printf("The value is: %f \n", pop());
break;
default:
printf("Unrecognized command %s\n", s);
break;
}
}
return 0;
}
</code></pre>
<p>getch.c</p>
<pre><code>#include <stdio.h>
#define MAXBUF 100
static char buf[MAXBUF];
static int bufp = 0; /* next free position in buffer */
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if(bufp < MAXBUF) {
printf("ungetch has been called\n");
buf[bufp++] = c;
}
else {
printf("the buffer is full\n");
}
}
</code></pre>
<p>stack.c</p>
<pre><code>#include <stdio.h>
#define MAXSTACK 100
static double stack[MAXSTACK];
static int sp = 0; /* next free position in stack */
void push(double f) {
if(sp < MAXSTACK) {
printf("\t--> the value %f has been pushed\n", f);
stack[sp++] = f;
}
else {
printf("error: the stac is full\n");
}
}
double pop(void) {
if(sp > 0) {
return stack[--sp];
}
else {
printf("error: the stack is empty!\n");
return 0.0;
}
}
</code></pre>
<p>calc.h</p>
<pre><code>#define NUMBER '0'
#define MAXLINE 1000
/*stack related functions */
void push(double f);
double pop(void);
/* output */
int getch(void);
void ungetch(int c);
/* filtration fuctions */
int getop(char s[]);
</code></pre>
<p>and getop.c</p>
<pre><code>#include <stdio.h>
#include <ctype.h>
#include "calc.h"
int getop(char s[]) {
int i, tmp;
static int c = ' ';
if((s[0] = c) == ' ' || c == '\t') {
while((s[0] = c = getch()) == ' ' || c == '\t')
;
}
s[1] = '\0';
if(!isdigit(c) && c != '.') {
tmp = c;
c = ' ';
return tmp;
}
i = 0;
if(isdigit(c)) {
while(isdigit((s[++i] = c = getch())))
;
}
if(c == '.') {
while(isdigit((s[++i] = c = getch())))
;
}
s[i] = '\0';
return NUMBER;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T12:56:10.043",
"Id": "65406",
"Score": "2",
"body": "In case anyone else is wondering, getop is being used to collect the next character or numeric operand. Here's the exercise: Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T15:00:51.823",
"Id": "65414",
"Score": "0",
"body": "I realized that I actually don't need the last if statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:03:04.057",
"Id": "65504",
"Score": "0",
"body": "The rest of code was added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T07:37:36.933",
"Id": "66495",
"Score": "0",
"body": "Whenever you see something obscure like `s[0] = c = getch()) ==` in code, you know that someone has been reading too much K&R. _Never_ use assignment inside if statements. It is dangerous practice and also makes the code less readable. There does not exist a single case where you ever need to do this."
}
] |
[
{
"body": "<p>Comments on <code>getop()</code> only:</p>\n\n<p>Your initial loop repeats the exit condition twice. It (and subsequent code)\nalso contains double assignments, which are unnecessary and generally better\navoided:</p>\n\n<pre><code>if((s[0] = c) == ' ' || c == '\\t') {\n while((s[0] = c = getch()) == ' ' || c == '\\t')\n ;\n}\n</code></pre>\n\n<p>Here is a simpler version:</p>\n\n<pre><code>while (c == ' ' || c == '\\t') {\n c = getch();\n}\ns[0] = c;\n</code></pre>\n\n<p>Your loop to read a number is repeated and repetition is normally undesirable.\nThe loop could be extracted into a function and called twice:</p>\n\n<pre><code>static int get_number(char *s)\n{\n int c = getch();\n for (; isdigit(c); c = getch()) {\n *s++ = c;\n }\n *s = '\\0';\n return c;\n}\n</code></pre>\n\n<p>On end of file, this returns EOF.</p>\n\n<p>Note that you should probably handle invalid input such as \"1.2.3\"</p>\n\n<p>In <code>main</code></p>\n\n<pre><code>char entry;\n...\nwhile((entry = getop(s)) != EOF) {\n</code></pre>\n\n<p><code>entry</code> should really be an <code>int</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T22:50:38.800",
"Id": "39248",
"ParentId": "39081",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39248",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T08:26:53.513",
"Id": "39081",
"Score": "3",
"Tags": [
"c",
"parsing",
"static"
],
"Title": "feedback for exercise 4-11 in K&R"
}
|
39081
|
<p>In several places, I have some code that looks like the following, the only difference is in the type of listener.</p>
<pre><code>public class CustomFragment extends android.app.Fragment {
SomeListener listener;
@Override
public void onAttach(android.app.Activity activity) {
super.onAttach(activity);
// duplication
// ||
// \||/
// \/
try {
listener = (SomeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SomeListener");
}
}
}
</code></pre>
<p>To avoid duplication, I wrote this simple class:</p>
<pre><code>public class TypeConvertor {
private final Object whatNeedToCast;
public static TypeConvertor cast(Object whatNeedToCast) {
return new TypeConvertor(whatNeedToCast);
}
private TypeConvertor(Object whatNeedToCast) {
this.whatNeedToCast = whatNeedToCast;
}
public <OtherType> OtherType to(Class<OtherType> toWhichToCast) {
try {
return (OtherType) whatNeedToCast;
} catch (ClassCastException e) {
throw new ClassCastException(
whatNeedToCast.toString() + " must implement " + toWhichToCast.getName()
);
}
}
}
</code></pre>
<p>And the previous code is simplified to the following:</p>
<pre><code>public class CustomFragment extends android.app.Fragment {
SomeListener listener;
@Override
public void onAttach(android.app.Activity activity) {
super.onAttach(activity);
listener = TypeConvertor.cast(activity).to(SomeListener.class);
}
}
</code></pre>
<p>But I do not like name <code>TypeConvertor</code>. Help me pick a better name (and help refactor this simple class if needed).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T14:15:26.663",
"Id": "65411",
"Score": "0",
"body": "I don't understand yourproblem but, instead of having a type converter, should CustomerFragment be a Generic class, whose type variable is the type of SomeListener (so that a specific CustomerFragment type supports a specific type of SomeListener/Activity)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T14:20:33.497",
"Id": "65412",
"Score": "0",
"body": "Activity can implement several interfaces."
}
] |
[
{
"body": "<p>It seems to me like what you have done here is to create an entire class to avoid duplicating one line. (Or OK, 5 lines if counting the try-catch statement)</p>\n<p>I don't agree with the need to create a class for this. Especially not a generic one, since this line of code:</p>\n<pre><code>return (OtherType) whatNeedToCast;\n</code></pre>\n<p>Does the same thing as:</p>\n<pre><code>return OtherType.class.cast(whatNeedToCast);\n</code></pre>\n<p>So all you are doing additionally is to wrap it in another exception which is explained just slightly better. But personally, I think this message...</p>\n<blockquote>\n<p>com.yourpackage.YourActivity@1df59a42 must implement com.yourpackage.SomeListener</p>\n</blockquote>\n<p>...actually says just as much as the default one, if you would not catch the exception in the first place:</p>\n<blockquote>\n<p>java.lang.ClassCastException: Cannot cast com.yourpackage.YourActivity to com.yourpackage.SomeListener</p>\n</blockquote>\n<p>Actually, <code>Cannot cast (class) to (class)</code> would say <strong>even more</strong> if you would override the <code>toString</code> method in <code>YourActivity</code>.</p>\n<p>If you are writing these classes to be used as a library by many other people, then it could be good practice to explain that the activity must implement some interface. Otherwise, I don't see the point of it. But either way, there's no need to create an entire class for this.</p>\n<h1>Summary:</h1>\n<p>Get rid of your additional class, just cast your <code>activity</code> to <code>SomeListener</code> and don't catch the exception to throw your own.</p>\n<p>So in the end, all that remains is this one line:</p>\n<pre><code>listener = (SomeListener) activity;\n</code></pre>\n<p>And it's perfectly OK to duplicate that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T18:57:09.843",
"Id": "39096",
"ParentId": "39091",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39096",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T12:55:44.713",
"Id": "39091",
"Score": "7",
"Tags": [
"java"
],
"Title": "Class for typecasting an Activity to an interface"
}
|
39091
|
<p>I'm a Java/C coder getting started with some Python for a side-project. I've written some unit tests for a recent side-project I'm working on, but I have a sinking suspicion I'm just writing Java-code, translated into Python.</p>
<p>I've posted a small sample of some unit-tests I wrote. I'd really appreciate any advice in how to make the code more Pythonic (best-practices, conventions, etc).</p>
<pre><code>import unittest
import urllib2
from connectionstate import ConnectionState
class Test(unittest.TestCase):
"""Unit tests for the ConnectionState"""
def test_connectionstate_reports_bad_network_connection(self):
"""ConnectionState reports a failure when currently disconnected"""
#Set up ConnectionState around mock
always_disconnected = mock_connection_check_func_always_disconnected
connstate_with_mock = ConnectionState(always_disconnected)
actual_state = connstate_with_mock.is_connected()
self.assertEqual(actual_state, False)
def test_connectionstate_detects_good_network_connection(self):
"""ConnectionState should report success when we can connect"""
#Set up ConnectionState around mock
always_connected = mock_connection_check_func_always_connected
connstate_with_mock = ConnectionState(always_connected)
actual_state = connstate_with_mock.is_connected()
self.assertEqual(actual_state, True)
def test_connectionstate_remembers_disconnections(self):
"""If the internet connection drops and then comes back, ConnectionState
can remember that the connection dropped temporarily
"""
#Set up ConnectionState around mock
sometimes_connected = mock_conn_every_other_conn_succeeds
connstate_with_mock = ConnectionState(sometimes_connected)
#Call is_connected a few times so get an unsuccessful connection
for count in range(0, 3):
connstate_with_mock.is_connected()
actual_result = connstate_with_mock.has_connection_dropped()
self.assertEqual(actual_result, True)
def test_connectionstate_doesnt_bring_up_ancient_history(self):
"""has_connection_dropped only reports failures that have happened
since the last call to has_connection_dropped. Calling
"""
#Set up ConnectionState around mock
sometimes_connected = mock_conn_every_other_conn_succeeds
connstate_with_mock = ConnectionState(sometimes_connected)
#Call is connected a few times so an unsuccessful connection is reported
for count in range(0, 3):
connstate_with_mock.is_connected()
#Call once to clear failures
connstate_with_mock.has_connection_dropped()
actual_result = connstate_with_mock.has_connection_dropped()
self.assertEqual(actual_result, False)
#Begin mock-connection functions
def mock_connection_check_func_always_disconnected(request=None, timeout=1):
raise urllib2.URLError("Unable to connect to network")
def mock_connection_check_func_always_connected(request=None, timeout=1):
pass
def mock_conn_every_other_conn_succeeds(request=None, timeout=1):
#Initialize 'static' call-counter variable
if "call_counter" not in mock_conn_every_other_conn_succeeds.__dict__:
mock_conn_every_other_conn_succeeds.call_counter = 0;
mock_conn_every_other_conn_succeeds.call_counter += 1
if mock_conn_every_other_conn_succeeds.call_counter % 2 == 0:
mock_connection_check_func_always_disconnected(request, timeout)
else:
mock_connection_check_func_always_connected(request, timeout)
#End mock-connection functions
if __name__ == "__main__":
unittest.main()
</code></pre>
|
[] |
[
{
"body": "<p>I have a few nitpicks:</p>\n\n<ul>\n<li>If you use <code>assertFalse</code> and <code>assertTrue</code> instead of <code>assertEquals(something, True/False)</code> where appropriate, the output of your unit tests will make more sense when they fail. (<a href=\"http://docs.python.org/2/library/unittest.html#assert-methods\" rel=\"noreferrer\">http://docs.python.org/2/library/unittest.html#assert-methods</a>)</li>\n<li>The argument order of <code>assertEquals</code> is <code>expected</code>, <code>actual</code>. Again, if you use the correct order the error messages will work as intended.</li>\n<li>A more common style for when you want a block of code to execute a fixed number of times (like in <code>for count in range(0, 3):</code>) is: <code>for _ in xrange(3):</code>. The <code>_</code> tells the reader that the value is unimportant, and <code>xrange</code> uses less memory since it doesn't create a list.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:08:23.743",
"Id": "65960",
"Score": "2",
"body": "`count()` is compatible with Python 3. For small counts, compatibility might be more important than the memory savings from `xrange()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-31T17:20:51.257",
"Id": "187592",
"Score": "6",
"body": "There is no indication in the docs, or in the error messages, that `assertEqual(expected, actual)` is the _correct_ signature."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-17T16:14:29.097",
"Id": "328673",
"Score": "0",
"body": "I agree with @K3---rnc Even in the official docs it's the oposite: `assertEqual(actual, expected)`: https://docs.python.org/3/library/unittest.html#basic-example For me this way makes more sense because in an `if` condition you also do it that way: `if result == 1:`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T16:01:26.307",
"Id": "39226",
"ParentId": "39092",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T15:17:10.107",
"Id": "39092",
"Score": "12",
"Tags": [
"python",
"unit-testing"
],
"Title": "Unit test best-practices in Python"
}
|
39092
|
<p>I think my code works pretty well, although I'm biased: <a href="http://jsfiddle.net/AHKb4/2/" rel="nofollow noreferrer">http://jsfiddle.net/AHKb4/2/</a></p>
<p><em><strong>Basic Overview:</strong> I'm working on building a math skill game, where the objective is to drag and drop div's to a container. Each div will have a value, likely set with classes. Each container must equal <code>theSumNum</code> to pass the level. Just giving this info so you can possibly understand better what I'm trying to achieve.</em></p>
<ol>
<li><p>Most importantly I think I've got my main function <code>pickNumbers()</code> ready to go. But I'd really appreciate any opinions and advice that you have for that function.</p>
</li>
<li><p>I've made two classes so far, <code>three</code> and <code>five</code>. I'm planning though to have classes from two through ten. I'm thinking each class will have an amount of arrays equal to that class number. Likewise there will be x number of container divs for x number of arrays.</p>
<p>So I think I could obviously improve how I do my classes by creating a for loop to generate the classes when needed, and use like <code>myArray1</code> instead of <code>myArrayOne</code>. I'm just looking for a <code>True</code> or <code>False</code> answer for this question.</p>
</li>
<li><p>Lastly, please take a look at the function <code>pickFive()</code>. So again I'm assuming I could just use a for loop for that as well? Just looking for a <code>True</code> or <code>False</code> here too, but if there's anything to look out for or be careful of in doing it that way, please let me know.</p>
</li>
</ol>
<pre><code>$(document).ready(function() {
var three = {
myArrayOne: [],
myArrayTwo: [],
myArrayThree: [],
myArraysCombined: []
}
var five = {
myArrayOne: [],
myArrayTwo: [],
myArrayThree: [],
myArrayFour: [],
myArrayFive: [],
myArraysCombined: []
}
// theArray is the array to push to ~ ex(three.myArrayTwo)
// theNum is the amount of numbers that will be in the array ~ ex(3)
// theSumNum is what the sum of all the numbers in the array will equal ~ ex(20)
// theMaxNum is the largest number that can appear in the array, except the last number may be larger since its not random ~ ex(10)
// theMinNum is the smallest number that can appear in the array ~ ex(1)
// aRandNum is a temporary var for each number in the array, except for the last number in the array
// thePreSumNum is the sum of all the numbers in the array except for the last number
// theLastNum is the last number that will be pushed to the array, this number is not random
function pickNumbers(theArray, theNum, theSumNum, theMaxNum, theMinNum) {
for (var x=0; x < theNum;) {
var aRandNum = Math.floor(Math.random()*theMaxNum + theMinNum);
if (theArray.indexOf(aRandNum) === -1) {
if (theArray.length < (theNum - 1)) {
theArray.push(aRandNum);
x += 1;
}
if (theArray.length === (theNum -1)) {
var thePreSumNum = 0;
for (var e = 0; e < theArray.length; e += 1) { thePreSumNum += theArray[e]; }
var theLastNum = theSumNum - thePreSumNum;
if (theArray.indexOf(theLastNum) > -1 || theLastNum < 1) {
theArray.length = 0;
x = theNum;
pickNumbers(theArray, theNum, theSumNum, theMaxNum, theMinNum);
}
else {
theArray.push(theLastNum);
x += 1;
}
}
}
}
}
function pickThree() {
pickNumbers(three.myArrayOne, 3, 20, 10, 1);
pickNumbers(three.myArrayTwo, 3, 20, 10, 1);
pickNumbers(three.myArrayThree, 3, 20, 10, 1);
three.myArraysCombined = three.myArrayOne.concat(three.myArrayTwo, three.myArrayThree);
}
function pickFive() {
pickNumbers(five.myArrayOne, 5, 40, 20, 1);
pickNumbers(five.myArrayTwo, 5, 40, 20, 1);
pickNumbers(five.myArrayThree, 5, 40, 20, 1);
pickNumbers(five.myArrayFour, 5, 40, 20, 1);
pickNumbers(five.myArrayFive, 5, 40, 20, 1);
five.myArraysCombined = five.myArrayOne.concat(five.myArrayTwo, five.myArrayThree, five.myArrayFour, five.myArrayFive);
}
pickThree();
pickFive();
});
</code></pre>
|
[] |
[
{
"body": "<p>Assumptions I made:</p>\n\n<ul>\n<li>The <code>3</code> object will have 3 arrays, just as the <code>67</code> object will have 67 arrays</li>\n<li>The \"combined\" array can be computed on demand</li>\n<li>Each call to <code>pickNumbers</code> for a certain object will always have the same parameters</li>\n</ul>\n\n<p>Firstly for your objects, I think they belong in a namespace and also a way to define which numbers you want to be in the game:</p>\n\n<pre><code>var Game = {}\nGame.NUMBERS = [3, 5];\n</code></pre>\n\n<p>Next instantiate all the classes:</p>\n\n<pre><code>for (var i = Game.NUMBERS.length; i --) {\n Game[Game.NUMBERS[i]] = new GameNumber(Game.NUMBERS[i]);\n}\n</code></pre>\n\n<p>Let's define what your class would look like:</p>\n\n<pre><code>var GameNumber = function(number) {\n this.number = number;\n this.arrays = [];\n for (var i = number; i --) {\n this.arrays.push([])\n }\n}\nGameNumber.prototype.combined = function() {\n Array.prototype.concat.apply([], this.arrays)\n}\nGameNumber.prototype.pick = function(arrayLength, sum, max, min) {\n for (var i = this.number; i --) {\n pickNumbers(this.arrays[i], arrayLength, sum, max, min);\n }\n}\n</code></pre>\n\n<p>Cool, so now you can create your objects in a sufficiently general way and call <code>pick</code> or <code>combined</code> on any of them.</p>\n\n<pre><code>Game[3].pick(5, 40, 20, 1);\nGame[3].combined() // Output: [...]\n</code></pre>\n\n<p>As for the <code>pickNumbers</code> function, I didn't look at the logic too heavily, I'm sure that's working how you want it to. The variable names I would simplify to <code>array</code>, <code>arrayLength</code>, <code>sum</code>, <code>max</code>, <code>min</code> for readability. You may also want to attach it to the <code>Game</code> object so you have less globals (ie <code>Game.pickNumbers = function(...)</code>). I'd also try and abstract the html from it so as to separate logic from presentation.</p>\n\n<p>Note: I haven't tested this code, it's only to give you an idea of how to structure it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T19:52:18.087",
"Id": "39099",
"ParentId": "39093",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T15:29:43.543",
"Id": "39093",
"Score": "4",
"Tags": [
"javascript",
"game"
],
"Title": "Math Skills Game Advice"
}
|
39093
|
<p>For the code sample that I am asked to submit with most of my job applications (usually Gameplay Programmer), I created this console application in which I attempt to figure out what is the best loadout for a mech to win a match within the simple turn-based combat system that I came up with. Since I will submit this as a code sample, it is important to me that it works and looks the best, and I would really appreciate all the input that you could give me.</p>
<p>I would like to mention that I already posted <a href="https://codereview.stackexchange.com/questions/26600/how-can-i-improve-this-c-genetic-algorithm-implementation">this</a> sometime last summer, but since then I reworked it considerably (mostly because I studied up on C++11), so I hope it's OK to resubmit.</p>
<p>What I'm interested in is really everything that comes to your mind when you see this — about the design, implementation, presentation, naming, or really anything that you think is important. </p>
<p>In particular, am I really taking advantage of all the C+11 concepts that I can, and am I using them in a correct manner? </p>
<p>The code as well as the rules are available online: <a href="http://www.mz1net.com/code-sample" rel="nofollow noreferrer">http://www.mz1net.com/code-sample</a></p>
<p>(UPDATE: I've updated the online version with the edits that I made based on Jamal's response.)</p>
<p>This is Main.cpp - please see the 'MechArena.cpp' and 'MechArena.h' online:</p>
<pre><code>#include <conio.h>
#include <iostream>
#include <sstream>
#include <time.h>
#include "MechArena.h"
// ======================================================================================
void init()
{
srand((int)time(0));
std::cout << "=== MECH ARENA ============================" << std::endl;
std::cout << "===========================================" << std::endl;
std::cout << std::endl;
}
// ======================================================================================
int promptPopulationSize()
{
std::cout << "Enter the population size (10K recommended): ";
// Loop until we have a valid result:
while (true)
{
std::string input;
getline(std::cin, input);
int size;
std::stringstream parser (input);
if (parser >> size)
{
if (size % 2 > 0)
{
std::cout << "Population size was rounded up to an even number: " << size+1 << std::endl;
size++;
}
std::cout << std::endl;
return size;
}
else
{
std::cout << "Please enter a valid number: ";
}
}
}
// ======================================================================================
void run()
{
init();
int populationSize = promptPopulationSize();
std::cout << "Random population seed... " << std::endl;
Population population (populationSize);
std::cout << "Population created." << std::endl;
std::cout << std::endl;
// This is the main application loop.
// Repeatedly, we prompt the user to choose a command, and than we act on his or her decision.
// We break the loop when the user chooses the 'exit' command.
while (true)
{
std::cout << "Instructions:" << std::endl;
std::cout << "-------------" << std::endl;
std::cout << "[Q/W/E/R]: Run 50/25/5/1 evolution steps." << std::endl;
std::cout << "[A/S/D]: Display the 10/5/1 best loadouts in the current population." << std::endl;
std::cout << "[X]: Exit." << std::endl;
char command = _getch();
std::cout << std::endl;
// NEXT GENERATION
int evolutionSteps = 0;
if (command == 'q') evolutionSteps = 50;
if (command == 'w') evolutionSteps = 25;
if (command == 'e') evolutionSteps = 5;
if (command == 'r') evolutionSteps = 1;
// Run the evolution steps:
for (int m = 0; m < evolutionSteps; m++)
{
std::cout << "Generation " << m+1 << "/" << evolutionSteps << ": ";
population.createNextGeneration();
std::cout << "Done." << std::endl;
}
// DISPLAY WINNERS
size_t displayWinners = 0;
if (command == 'a') displayWinners = 10;
if (command == 's') displayWinners = 5;
if (command == 'd') displayWinners = 1;
if (displayWinners > 0)
{
// Make sure that we were not asked to display more
// mechs than how many there are in the entire population.
size_t populationSize = population.getSize();
if (displayWinners > populationSize)
{
std::cout << "There are not that many mechs in the entire population - only " << populationSize << " will be shown.";
std::cout << std::endl;
displayWinners = populationSize;
}
std::cout << "TOP " << displayWinners << ((displayWinners > 1)? " MECHS" : " MECH") << " IN THE POPULATION: " << std::endl;
std::cout << "--------------------------------------" << std::endl;
std::cout << std::endl;
for (size_t m = 0; m < displayWinners; m++)
{
// Retrieve the mech to show.
const Mech& mech = population.getMech(m);
// Print out the mech's position and its score in the last match round.
std::cout << "TOP #" << m+1 << " (Last score: " << mech.getScore() << ")" << std::endl;
// Print out the mech's component setup.
std::cout << mech;
}
}
// EXIT
// Break the main application loop.
if (command == 'x')
break;
// CLEAR
std::cout << std::endl;
}
}
// ======================================================================================
int main (int argc, char* argv[])
{
try
{
run();
}
catch (const std::exception& e)
{
std::cout << std::endl;
std::cout << "[!] RUNTIME EXCEPTION ==============================" << std::endl;
std::cout << e.what() << std::endl;
std::cout << "Press any key to exit." << std::endl;
std::cin.ignore();
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong><code>#include</code>s:</strong></p>\n\n<ul>\n<li><s><code><time.h></code> is a C library; use <code><ctime></code> instead.</s></li>\n<li>Consider omitting <code><conio.h></code> as there could be some portability issues. It's also not widely used in C++, especially since you have <code><iostream></code>.</li>\n<li><s>Add <code><cstdlib></code> for <code>std::srand()</code>/<code>std::rand()</code>.</s></li>\n<li>Add <code><exception></code> for <code>std::exception</code>.</li>\n</ul>\n\n<p><strong>Everything else:</strong></p>\n\n<ul>\n<li><p><s><em>Only call <code>std::srand()</code> once in an application, preferably in <code>main()</code></em>. Even if <code>init()</code> will be called only once, keeping it in <code>main()</code> will help with maintainability.</p>\n\n<p>In addition, prefer to <code>static cast</code> cast to an <code>unsigned int</code> and, especially in C++11, <strong>use <code>nullptr</code></strong> instead of <code>NULL</code> or <code>0</code> for this use.</p>\n\n<p>So, you'll have this:</p>\n\n<pre><code>std::srand(static_cast<unsigned int>(std::time(nullptr)));\n</code></pre>\n\n<p>As you're not really using any random number generation here (no calls to <code>std::rand()</code>), just omit the relevant headers and the call to <code>std::srand()</code>.</s></p>\n\n<p><strong>You should refrain from using <code>rand</code> altogether in C++11 as it is <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow noreferrer\">considered harmful</a>. Instead, utilize C++11's <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code><random></code></a> library.</strong></p>\n\n<p>You also no longer need <code><ctime></code> and should use C++11's <a href=\"http://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\"><code><chrono></code></a>. From this library, you can obtain a seed for a PRNG with this:</p>\n\n<pre><code>auto chrono_seed = std::chrono::system_clock::now().time_since_epoch().count();\n</code></pre></li>\n<li><p><code>init()</code> is needless as it's primarily outputting hard-coded text, which shouldn't be any function's primary task. Just move all the output to <code>main()</code> and remove the function.</p>\n\n<p>Also, use <code>\"\\n\"</code> for that output instead of <code>std::endl</code>. You don't need all that flushing there.</p>\n\n<pre><code>std::cout << \"=== MECH ARENA ============================\\n\";\nstd::cout << \"===========================================\\n\\n\";\n</code></pre></li>\n<li><p>Be careful with catching exceptions here. Make sure you know which exception you're expecting to catch while knowing how to handle it. It appears you're trying to catch a runtime error, so you should catch an <a href=\"http://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"nofollow noreferrer\"><code>std::runtime_error</code></a> instead.</p></li>\n<li><p>Anything modular 2 is either 0 or 1, so just compare inequality to 0 (or equality to 1) if you're determining if <code>size</code> is an odd number:</p>\n\n<pre><code>if (size % 2 != 0)\n</code></pre>\n\n<p></p>\n\n<pre><code>if (size % 2 == 1)\n</code></pre>\n\n<p>Another (<a href=\"https://stackoverflow.com/a/160942/1950231\">possibly faster</a>) alternative is to use the bitwise AND operator:</p>\n\n<pre><code>if ((size & 1) == 0)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T20:47:59.453",
"Id": "65424",
"Score": "0",
"body": "Good points, thanks a lot. I'll update the online version in a minute: it now uses <ctime>, includes <exception> (it was included via <iostream>), has all the `std::endl` replaced with '\\n', has the entire `init()` moved into `main()`, supplies `nullptr` as the parameter to `std::srand`, and I rewrote the `size % 2` line. Fair point with the `<conio.h>`, but I think I'll probably keep it, because being able to read the control character from the console without Enter makes the application so much easier to use, and I think that pretty much all the studios that will receive this are on Windows."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T20:48:41.307",
"Id": "65425",
"Score": "0",
"body": "@electroLux: I'm making some additional corrections now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T20:49:40.607",
"Id": "65426",
"Score": "0",
"body": "If you're talking about pausing the console, there are alternatives that do not use `<conio.h>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T20:53:55.850",
"Id": "65427",
"Score": "0",
"body": "What I want is for the user not to have to press Enter when I prompt him to press a key to choose an an action to take. When I show something like \"[W]: Evolve / [X]: Show\", I want the to react immediately to the 'W' key press, and not having to wait for user to press 'W' and then Enter. [This answer](http://stackoverflow.com/a/7461203/1549314) makes me think that I need to use `<conio.h>` in order to do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:29:44.950",
"Id": "65430",
"Score": "1",
"body": "@electroLux: That's fine, then. I just wanted to at least make you aware of the portability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:26:38.317",
"Id": "81795",
"Score": "1",
"body": "Both `srand` and `rand` are ugly and [harmful](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) as well. We have got C++11. Leave that C-style stuff and move on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:46:38.043",
"Id": "81798",
"Score": "0",
"body": "@Jamal I'd add `<chrono>` which will generate the seed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:47:52.147",
"Id": "81799",
"Score": "0",
"body": "@no1: As a replacement of `<ctime>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:54:04.287",
"Id": "81800",
"Score": "0",
"body": "@Jamal Yes. You might want:\n`auto chrono_seed = std::chrono::system_clock::now().time_since_epoch().count();` \n rather than\n`auto time_seed = time(nullptr);` \nAlso the first one generates bigger seeds than the second one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:57:36.203",
"Id": "81801",
"Score": "0",
"body": "@no1: Okay. Is this just for `srand` or any of the `<random>` functions? C++11 already has `std::random_device`. By the way, I'm asking all of this because I've never used `<chrono>` before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T19:04:03.780",
"Id": "81802",
"Score": "0",
"body": "@Jamal You're welcome. If you need a PRNG such as `mt19937`/`mt19937_64`, it needs a seed.\n`std::random_device` doesn't, instead. (it isn't a PRNG) \n \nSTL talks about that as well in his talk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T19:09:22.187",
"Id": "81804",
"Score": "0",
"body": "@no1: I see. I'll mention the first seed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T19:17:32.743",
"Id": "81805",
"Score": "0",
"body": "I'd like to point out that there's a much faster way to determine whether a number is odd:\n`if (number & 1) // odd else //even`"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T19:43:18.100",
"Id": "39098",
"ParentId": "39097",
"Score": "6"
}
},
{
"body": "<p>There's something which worries me about using this as a sample for a job application: which is that it contains no <code>virtual</code> methods and no subclasses.</p>\n\n<p>No matter how clearly-written your code may be, it doesn't demonstrate an understanding of inheritance: which (I don't know) might be an important criterion in a job application.</p>\n\n<p>If this is valid criticism, perhaps change the game design so as to use inheritance in a natural way.</p>\n\n<p>One (advanced) way to do this might be to have the type of weapon have a different effect depending on the type of armour (as in a game or \"rock, paper, sissors\", the effect of the weapon varies depending on the target). I'm thinking of this as an example, because a \"implementing a video game\" is the canonical example used to teach an 'advanced' technique called <a href=\"http://en.wikipedia.org/wiki/Double_dispatch\">double-dispatch</a>. Working that implementation (if game-rule have a natural need for that implementation technique) into your sample might impress someone reviewing resumes/samples.</p>\n\n<p>People might also like to see a knowledge of (i.e. appropriate use of some) common <a href=\"http://en.wikipedia.org/wiki/Software_design_pattern\">design patterns</a>.</p>\n\n<p>My apologies for this advice: it's based on a cynical guess at the type of code which some interviewers may be looking for.</p>\n\n<p>Again based on experience with interview questions, they might also like to know:</p>\n\n<ul>\n<li>How do/did you test this?</li>\n<li>Have you thought about how to extend/maintain it various ways? I mean, add new types of feature: a GUI; playing it over the network; persisting (saving and restoring) game-state; making it a 0-player, 1-player, 2-player, or many-player game; etc.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:42:15.527",
"Id": "65431",
"Score": "0",
"body": "My answer is based on a review of the code posted at http://www.mz1net.com/code-sample (not of the code quoted above which Jamal was already inspecting)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:56:12.207",
"Id": "65432",
"Score": "0",
"body": "If relevant to this answer at all, consider including some snippets from that linked code in case the link dies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:21:47.193",
"Id": "65433",
"Score": "0",
"body": "Good point. Fortunately, I am asked to deliver several code samples, so besides the two that I already have, I'll probably prepare another one where I will use some polymorphism. I have an idea about a simple Visitor example, so that would also address the design patterns aspect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:24:31.810",
"Id": "65434",
"Score": "0",
"body": "@electroLux Some knowledge of multi-threading / thread-safety is another popular topic, at least in the C++ jobs I apply for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:37:58.120",
"Id": "65435",
"Score": "0",
"body": "@ChrisW For sure. I think that the issue with the code samples is that I would obviously like them to represent all that I can do, but they are supposed to be quite short, so ultimately I will inevitably only demonstrate only a subset of the skills that the studios would me like me to have."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:25:40.980",
"Id": "39100",
"ParentId": "39097",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "39098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T19:22:52.543",
"Id": "39097",
"Score": "7",
"Tags": [
"c++",
"c++11",
"ai"
],
"Title": "'Evolutionary AI' implementation"
}
|
39097
|
<p>I have just started learning how to build websites, and I have been experimenting by creating a contact form.</p>
<p>Here is what I currently have - can anyone suggest and recommend ways enhance my current contact form system? </p>
<p><strong>JavaScript:</strong></p>
<pre><code>$("#contactForm").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$submit = $form.find('button[type="submit"]'),
name_value = $form.find('input[id="name"]').val(),
email_value = $form.find('input[id="email"]').val(),
message_value = $form.find('textarea[id="message"]').val(),
url = $form.attr('action');
/* send the data using post */
var posting = $.post(url, {
name: name_value,
email: email_value,
message: message_value,
ajax: 1
});
posting.done(function (data) {
$form.find('span.error').remove();
if (data == "1") {
/*Change the button text.*/
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
} else {
$submit.after('<span style="display: inline-block; padding: 20px 5px; color: #bd3d3d" class="error">Failed to send the message, please check your entries and try again.</span>');
/*Change the button text.*/
$submit.text('Try Again');
}
});
});
</code></pre>
<p><strong>PHP</strong></p>
<pre><code><?php
if(isset($_POST['name']) && $_POST['email'] && $_POST['message']) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "email@website.com";
$subject = "New Message From: $name";
$message .= "$messege";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))
$response = ($mailed) ? "1" : "0";
else
$response = ($mailed) ? "<h2>Success!</h2>" : "<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
else
{
echo "Form data error!";
}
?>
</code></pre>
<p><strong>HTML:</strong> </p>
<pre><code><form id="contactForm" action="email.php" method="post" name="contactForm">
<div class="name">
<label>Your Name</label>
<input id="name" type="text" placeholder="Enter Name" required>
</div>
<div class="email">
<label>Email Address</label>
<input id="email" type="email" placeholder="Enter Email" required>
</div>
<div class="message">
<label>Message</label>
<textarea id="message" required></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-08T17:43:25.237",
"Id": "233539",
"Score": "0",
"body": "[Follow up Question](http://codereview.stackexchange.com/questions/39455/is-this-contact-form-secure)"
}
] |
[
{
"body": "<h1>Php</h1>\n\n<p>I'm not a big Php guy so I can't be too thorough in this section. The biggest thing is that you seem to be writing ... well ... a php script. While that absolutely works it's incredibly old-school and doesn't do anything as far as guiding you into the pit of success. So first bit of advice: use a framework. At time of writing, the two I've been hearing most buzz about are <a href=\"http://laravel.com/\">Laravel</a> and <a href=\"http://ellislab.com/codeigniter\">Codeigniter</a>. This is constantly changing but just pick one which you've heard about and use it, that will help you learn enough concepts to make an educated choice next time you need to select one.</p>\n\n<p>Second, at the bottom you seem to have some invalid php. You have some missing braces in that if statement toward the bottom and it has two <code>else</code> clauses in a row. I'm not sure if that will cause an error but it will definitely never run the third clause.</p>\n\n<p>Finally, your design leaves open a huge security hole if the site is ever opened to the public. You accept the message as an input parameter, much worse, you accept the email. Think of what happens when someone does a query to <code>yoursite.com/yourpage.php?email=yourgrandma&message=Send%20me%20all%20the%20money</code>and again, and again. Spammers love finding unsecured services like this! </p>\n\n<p>A much better approach is to have the emails (and maybe message) stored on the server already in the database or a text file. Then you could supply parameters like <code>email=1</code> indicating \"email the person with id=1\". </p>\n\n<p>Having this behind a login page is not a (good) defense either. Someone could easily put the above url in the src of an <code><img></code> element and every time someone who had recently logged into your site visits a page they put that on (like a comment or forum page) you will be sending spam! To defend against this make sure that page does not accept the Http GET verb (in this situation POST would be appropriate). This is exactly the kind of error that a framework shoudl help defend you from. </p>\n\n<p>Finally, I see what you're doing with the ajax flag but that's not the typical thing to do. Whether the operation succeeded or not should be determined by the returned Http code (200 for success and maybe 400 for error). Whether you should be returning json or html should be determined by a concept called <em>content negotiation</em>. This is again, something that your framework should be handling for you.</p>\n\n<h1>Html</h1>\n\n<p><code>name</code> is not a valid attribute for the <code><form></code> element. But also don't put ids on things unless you absolutely know there will be only one of these elements on the page. The spec says ids must be unique across the page and lots of javascript libraries cause errors when the assumption is broken. In this case can you guarantee there will not be two <code>contactForm</code> elements on the page at once? What if you have 2 offices and each one wants its own contact form? What about elements with <code>id=message</code> or <code>id=submit</code>? A better approach I think in this case is to use a class. That is not to say that you should never use ids but in most cases the benefit isn't worth the risk.</p>\n\n<p>Next, you don't technically need <code><button type=submit></code>, it's optional but submit is the default behavior.</p>\n\n<p>Finally, I'm not 100% sure of the spec for <code><label></code> but I don't think it works by associating the label with the following <code><input></code>. Instead you have to use the <code>for</code> attribute and <code>id</code>s (which I've already argued is bad). Or do what I recommend, something like:</p>\n\n<pre><code> <label class=\"email\">\n <span class=\"label\">Email Address</span>\n <input id=\"email\" type=\"email\" placeholder=\"Enter Email\" required>\n </label>\n</code></pre>\n\n<h1>Javascript</h1>\n\n<p>Javascript naming convention are to use <code>camelCase</code> with no underscores. It's not a big deal but it's pretty standard. The only exception is to use <code>PascalCase</code> for variables that are intended to be used with the <code>new</code> keyword (which you don't have here).</p>\n\n<p>To a lesser extent than php, but with the javascript community where it is, its probably time to start considering choosing a javascript framework (like angular, backbone, knockout, <a href=\"http://todomvc.com\">or the like</a> rather than using jquery directly.</p>\n\n<p>In my opinion you are over-specifying your selectors, no need to do <code>input[id=foo]</code> when id is already specified as unique, no need to <code>span.blah</code> when <code>span</code> holds no semantic nor structural meaning. Consider that all this stuff is indexed in the browser so by adding more selectors you might actually be slowing things down however slightly.</p>\n\n<p>You don't need to use <code>$('id=something')</code> to select, you can just say <code>$('#something')</code></p>\n\n<p>Your scope management looks pretty good, I'm happy to see you using <code>find</code> - another syntax which achieves the same purpose and you might find flows better (or not) is <code>$('[name=email]', $form)</code>.</p>\n\n<p>You've got inline styling and html. Why? Just put the element on your html page and show or hide it from javascript.</p>\n\n<p>Finally, just about everything you're doing in js is handled in a very elegant manner by the <a href=\"http://malsup.com/jquery/form/\">jquery.form</a> plugin. Just use that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T00:45:10.097",
"Id": "39115",
"ParentId": "39103",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p><strong>Use a framework.</strong> <em>As already mentioned</em></p>\n\n<ul>\n<li>Using a framework provides so much for free. It provides everything you've not provided in your code above. For example: error/exception handling, markup generation, logging, filters, validators, security...the list is long.</li>\n</ul></li>\n<li><p><strong>Completely remove the javascript.</strong></p>\n\n<ul>\n<li>There is no benefit from using ajax to submit the form. On the other hand, you've just incurred useless debt in your application by including the javascript. Let the browser simply submit the form. Don't use ajax for ajax's sake.</li>\n</ul></li>\n<li><p><strong>If you were to deploy your code as-is be sure you have a great spam filter for your email-to address, Or use some sort of \"are-you-human\" detector.</strong> </p>\n\n<ul>\n<li>I actually don't know a great way to protect contact forms...it seems the spammers keep defeating almost all efforts.</li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T01:24:59.250",
"Id": "65460",
"Score": "0",
"body": "Agreed, regular forms are underused, but see my comment about maybe using the jquery.form plugin to get the benefit at hardly any cost"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-08T18:13:06.817",
"Id": "233545",
"Score": "1",
"body": "You know, for protecting contact forms, there's this new thing called \"CAPTCHA\" that I hear works pretty decent ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T01:08:58.490",
"Id": "39118",
"ParentId": "39103",
"Score": "3"
}
},
{
"body": "<p><strong>Edit:</strong>\nyour PHP code is a little messy, I almost couldn't tell what was going on in the if statements</p>\n\n<blockquote>\n<pre><code><?php\n\n if(isset($_POST['name']) && $_POST['email'] && $_POST['message']) {\n\n $name = $_POST['name'];\n $email = $_POST['email'];\n $message = $_POST['message'];\n\n $to = \"email@website.com\";\n $subject = \"New Message From: $name\";\n $message .= \"$messege\";\n\n $headers = 'MIME-Version: 1.0' . \"\\r\\n\";\n $headers .= 'Content-type: text/html; charset=utf-8' . \"\\r\\n\";\n $headers .= 'From: '.$email . \"\\r\\n\";\n $mailed = ( mail($to, $subject, $message, $headers) );\n\n if( isset($_POST['ajax']))\n $response = ($mailed) ? \"1\" : \"0\";\n else\n $response = ($mailed) ? \"<h2>Success!</h2>\" : \"<h2>Error! There was a problem with sending.</h2>\";\n echo $response;\n }\n else\n {\n echo \"Form data error!\";\n }\n?>\n</code></pre>\n</blockquote>\n\n<p>so I would fix the indentation of your code so that it was readable, first, which would give us this</p>\n\n<pre><code><?php\n\n if(isset($_POST['name']) && $_POST['email'] && $_POST['message']) {\n\n $name = $_POST['name'];\n $email = $_POST['email'];\n $message = $_POST['message'];\n\n $to = \"email@website.com\";\n $subject = \"New Message From: $name\";\n $message .= \"$messege\";\n\n $headers = 'MIME-Version: 1.0' . \"\\r\\n\";\n $headers .= 'Content-type: text/html; charset=utf-8' . \"\\r\\n\";\n $headers .= 'From: '.$email . \"\\r\\n\";\n $mailed = ( mail($to, $subject, $message, $headers) );\n\n if( isset($_POST['ajax']))\n $response = ($mailed) ? \"1\" : \"0\";\n else\n $response = ($mailed) ? \"<h2>Success!</h2>\" : \"<h2>Error! There was a problem with sending.</h2>\";\n echo $response;\n }\n else {\n echo \"Form data error!\";\n }\n?>\n</code></pre>\n\n<p>Then I notice that you don't have any braces surrounding the nested if/else statement and almost thought that the echo was supposed to be inside of that else statement, but I knew better. I would add braces like this</p>\n\n<pre><code>if( isset($_POST['ajax'])) {\n $response = ($mailed) ? \"1\" : \"0\";\n} else {\n $response = ($mailed) ? \"<h2>Success!</h2>\" : \"<h2>Error! There was a problem with sending.</h2>\";\n}\necho $response;\n</code></pre>\n\n<p>Then we can move the echo into the if/else statement like this</p>\n\n<pre><code>if( isset($_POST['ajax'])) {\n echo ($mailed) ? \"1\" : \"0\";\n} else {\n echo ($mailed) ? \"<h2>Success!</h2>\" : \"<h2>Error! There was a problem with sending.</h2>\";\n}\n</code></pre>\n\n<p>I like returning from inside the if statements if I can.</p>\n\n<hr>\n\n<p>To obscure your E-mail from a spam bot but not from a user I use Google Captcha's, they are really cool. and you can either put a captcha on your input form, or you can put a captcha on your E-mail address</p>\n\n<p><a href=\"http://www.google.com/recaptcha/captcha\" rel=\"nofollow\">Google Recaptcha</a> is the place to go. if Google can't do it right, who can?</p>\n\n<p>it's a simple plugin, took me an hour or two, but I have ADHD and am Distracted very easily, so I don't see any reason this should take more than 30 minutes to an hour to implement into your page.</p>\n\n<p><em>Note:</em></p>\n\n<p>I just answered based off of another answer assuming what the question entailed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:43:40.760",
"Id": "39472",
"ParentId": "39103",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:47:02.530",
"Id": "39103",
"Score": "5",
"Tags": [
"javascript",
"php",
"jquery",
"html",
"ajax"
],
"Title": "PHP e-mail contact form with AJAX"
}
|
39103
|
<p>I am writing code to do some numerical task using the routines of the book <em>Numerical Recipes</em>. One of my objectives is to calculate the second derivative of a function and have a routine that calculates the first derivative of a function in a nice manner within a specified accuracy. However, I would like to generalize this method and use this function recursively to find the second derivatives or higher order derivatives if needed. I have made some changes in my code and defined a reduced function which takes one argument and achieved my aim more or less. The function that calculates the first derivatives are declared as follows:</p>
<pre><code>float dfridr(float (*func)(float), float x, float h, float *err);
</code></pre>
<p>My aim is to set the <code>h</code> value by calling another function for both of the nested <code>dfridr</code> functions at once. For clarity I have enclosed my code. I would appreciate it if you could comment on my method and provide suggestions for improvement and general feedback. As far as I've checked, it works better than the finite difference algorithms, but I think it may be refined.</p>
<pre><code>// The compilation command used is given below
// gcc Q3.c nrutil.c DFRIDR.c -lm -o Q3
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "nr.h"
#define LIM1 20.0
#define a -5.0
#define b 5.0
#define pre 100.0 // This defines the precision
/* This file calculates the func at given points, makes a
* plot. It also calculates the maximum and minimum of the func
* at given points and its first and second numerical derivative.
*/
float func(float x)
{
return exp(x / 2) / pow(x, 2);
}
// We define the following functions to aid in the calculation of the
// second derivative
float reddfridr(float x)
{
float err;
return dfridr(func, x, 0.1, &err);
}
float dfridr2(float x, float h)
{
float err;
return dfridr(reddfridr, x, h, &err);
}
int main(void)
{
FILE *fp = fopen("Q3data.dat", "w+"), *fp2 = fopen("Q3results.dat", "w+");
int i; // Declaring our loop variable
float min, max, err, nd1, nd2, x, y;
// Define the initial value of the func to be the minimum
min = func(0);
// Initialize x
x = 0;
for(i = 0; x < LIM1 ; i++)
{
x = i / pre; // There is a singularity at x = 0
y = func(x);
if(y < min)
min = y;
fprintf(fp, "%f \t %f \n", x, y);
}
fprintf(fp, "\n\n");
max = 0;
// Never forget to initialize x again
x = a;
// Since i is incremented at the end of the loop
for(i = 0; x < b ; i++)
{
x = a + i / pre;
y = func(x);
nd1 = dfridr(func, x, 0.1, &err);
nd2 = dfridr2(x, 0.1);
fprintf(fp, "%f \t %f \t %f \t %f\n", x, y, nd1, nd2);
if(y > max)
max = y;
}
fprintf(fp2, "The minimum value of f(x) is %f when x is between 0 and 20. \n", min);
fprintf(fp2, "The maximum value of f(x) is %f when x is between -5 and 5. \n", max);
fclose(fp);
fclose(fp2);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:36:00.390",
"Id": "65445",
"Score": "0",
"body": "What is `h`? This seems like an important piece of information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T01:45:50.050",
"Id": "65465",
"Score": "0",
"body": "Just a note, but numerical recipes has a very strict [copyright](http://www.nr.com/com/info-copyright.html) rule."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:09:26.673",
"Id": "65467",
"Score": "0",
"body": "@Yuushi, probably that's why we miss `dfridr` function here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:33:23.520",
"Id": "68633",
"Score": "0",
"body": "Where is `dfridr` function defined?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:35:55.287",
"Id": "68634",
"Score": "0",
"body": "@haccks It is defined in another file called DFRIDR.c and the declaration follows from the header file \"nr.h\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T21:57:12.143",
"Id": "68635",
"Score": "0",
"body": "What's the question? I think this should be in code review"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:07:17.883",
"Id": "68636",
"Score": "0",
"body": "@APerson The question is if refinement of the above code is possible so that the second numerical derivative is evaluated more accurately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:07:50.000",
"Id": "68637",
"Score": "0",
"body": "***Refinement***, the code already works, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:16:03.597",
"Id": "68638",
"Score": "0",
"body": "@APerson Yes, the code works as it is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:39:18.283",
"Id": "68639",
"Score": "1",
"body": "http://math.stackexchange.com/questions/130192/method-for-estimating-the-nth-derivative : recursion may not be the nor the fastest nor the most accurate method !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:49:48.377",
"Id": "68640",
"Score": "0",
"body": "@APerson Okay I will post it there. Sorry for the inconvenience this might have caused."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:52:03.793",
"Id": "68641",
"Score": "0",
"body": "@francis Unfortunately the finite difference methods I have used cause much lower accuracies and I have no time to write another algorithm and there is no preexisting code for finding higher order derivatives in the references I have consulted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-12T20:46:39.987",
"Id": "239783",
"Score": "0",
"body": "I think the question already exhibits an attitude problem. Numeric derivatives vs. analytic derivatives are like sprintf() vs. std::string: Writing code which does not care about buffer overflows. This is the next heartbleed waiting to happen."
}
] |
[
{
"body": "<p>If you need compile-time controlled order of derivation you probably should play with C++ templates.<br>\nIf you need run-time (i.e. write own calculator) you'll need to extend that <code>dfridr</code> function (use same approximation of derivation).</p>\n\n<p>Naive implementation and modification can look like:\n</p>\n\n<pre><code>float dfridr(float (*f)(float), float x, float h)\n{\n return f(x+h) - f(x);\n}\n\n/* changed */\nfloat dfridr(float (*f)(float), float x, float h, size_t order)\n{\n if (order == 0) return f(x);\n else if (order == 1) return f(x+h) - f(x);\n /* extend same algorithm for second derivative */\n else return dfridr(f, x+h, h, order-1) - dfridr(f, x, h, order-1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-12T20:28:53.697",
"Id": "239777",
"Score": "0",
"body": "creating the derivatives of user-entered expressions is trivial and thus there is also no need for numerical derivatives."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:34:54.997",
"Id": "39120",
"ParentId": "39106",
"Score": "2"
}
},
{
"body": "<p>Recommendations:</p>\n\n<ol>\n<li>Your output files are delimited by both spaces and tabs, which is weird. You probably want to use tabs only.</li>\n<li><p>There are a couple of points related to floating-point handling that I think deserve commenting:</p>\n\n<ul>\n<li>Evaluating <code>func(0.0)</code> has a side effect of setting some floating-point error flags.</li>\n<li>You actually intend to step <em>x</em> by <em>Δx</em>=0.01 between some lower bound and upper bound. However, repeated addition of 0.01 would result in accumulation of round-off errors, so a workaround is used.</li>\n</ul></li>\n<li><code>pow(x, 2)</code> could be simplified to <code>x * x</code>.</li>\n<li><p>Naming could be better. I suggest:</p>\n\n<ul>\n<li><code>pre</code> → <code>inv_delta_x</code> (to emphasize its relationship to <code>x</code>)</li>\n<li><code>fp</code> → <code>table</code>, and <code>fp2</code> → <code>extrema</code> (to explain the contents of the files)</li>\n</ul></li>\n<li>Since you are already using C99-style comments, you should also take advantage of C99-style variable declarations, which allow you to declare variables closer to the point of use to enhance readability.</li>\n</ol>\n\n<p>I've defined a <code>FOR_RANGE()</code> macro to make the loops in <code>main()</code> more readable, but that may be a controversial improvement. I've also initialized <code>min</code> and <code>max</code> to <code>INFINITY</code> and <code>-INFINITY</code>, respectively, as a personal preference.</p>\n\n<p>I agree that using recursion will probably yield unsatisfactory results, though I am unable to advise you further. One of the comments above links to a <a href=\"https://math.stackexchange.com/q/130192/77144\">related math question</a>. You will probably get a better answer about numerical methods on <a href=\"https://scicomp.stackexchange.com/\">Computational Science SE</a>.</p>\n\n<pre><code>#include <math.h>\n#include <stdio.h>\n\n// Singularity at x=0.0 raises exception FE_DIVBYZERO and/or sets errno to EDOM\nfloat func(float x)\n{\n return exp(x / 2) / (x * x);\n}\n\n#define FOR_RANGE(type, var, lower_bound, upper_bound, inv_delta) \\\n for (type iteration_dummy = (lower_bound) * (inv_delta), var; \\\n (var = iteration_dummy / (inv_delta)) <= (upper_bound); \\\n iteration_dummy++)\n\nint main(void)\n{\n // We want to increment x in steps of 0.01, but repeatedly adding 0.01\n // would cause round-off errors to accumulate. Therefore, we will divide\n // successive floating-point integers by 100 instead.\n const float inv_delta_x = 100.0;\n\n FILE *table = fopen(\"Q3data.dat\", \"w+\"),\n *extrema = fopen(\"Q3results.dat\", \"w+\");\n\n float min = INFINITY;\n FOR_RANGE(float, x, 0.0, 20.0, inv_delta_x)\n {\n float y = func(x);\n if (y < min) min = y;\n fprintf(table, \"%f\\t%f\\n\", x, y);\n }\n\n fprintf(table, \"\\n\\n\");\n\n float max = -INFINITY;\n FOR_RANGE(float, x, -5.0, 5.0, inv_delta_x)\n {\n float y = func(x);\n float err;\n float nd1 = dfridr(func, x, 0.1, &err); \n float nd2 = dfridr2(x, 0.1);\n if (y > max) max = y;\n fprintf(table, \"%f\\t%f\\t%f\\t%f\\n\", x, y, nd1, nd2);\n }\n\n fprintf(extrema, \"The minimum value of f(x) is %f when x is between 0 and 20.\\n\", min);\n fprintf(extrema, \"The maximum value of f(x) is %f when x is between -5 and 5.\\n\", max);\n fclose(table);\n fclose(extrema);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T00:57:59.413",
"Id": "68843",
"Score": "2",
"body": "I would recommend parenthesizing the parameters in the body of the macro, just in case the caller passes `x + 1` for `lower_bound` or whatever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:00:40.750",
"Id": "68844",
"Score": "1",
"body": "@GarethRees Yes, of course! Incorporated in [Rev 2](http://codereview.stackexchange.com/revisions/40795/2)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T23:20:37.090",
"Id": "40795",
"ParentId": "39106",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39120",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T22:51:09.477",
"Id": "39106",
"Score": "4",
"Tags": [
"c",
"recursion",
"numerical-methods"
],
"Title": "Recursive calculation of second order derivative"
}
|
39106
|
<p>Two integers <em>a</em> and <em>b</em> are relatively prime if and only if there are no integers:</p>
<blockquote>
<p>x > 1, y > 0, z > 0 such that a = xy and b = xz.</p>
</blockquote>
<p>I wrote a program that determines how many positive integers less than <code>n</code> are relatively prime to <code>n</code>. But my program works too slowly because the number is sometimes too big.</p>
<p>My program should work for <code>n <= 1000000000</code>.</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
long long int n;
int cntr = 0, cntr2 = 0;
cin >> n;
if (!n) return 0;
vector <int> num;
for (int i = 2; i < n; i++)
{
if (n % i != 0)
{
if (num.size()>0)
{
for (int j = 0; j < num.size(); j++)
{
if (i % num[j] != 0)
cntr2++;
}
if (cntr2 == num.size())
cntr++;
cntr2 = 0;
}
else
cntr++;
}
else
num.push_back(i);
}
cout << cntr + 1 << endl;
}
</code></pre>
|
[] |
[
{
"body": "<p>In order to determine whether two numbers are co-prime (relatively prime), you can check whether their <em>gcd</em> (greatest common divisor) is greater than 1.\nThe <em>gcd</em> can be calculated by Euclid's algorithm:</p>\n\n<pre><code>unsigned int gcd (unsigned int a, unsigned int b)\n {\n unsigned int x;\n while (b)\n {\n x = a % b;\n a = b;\n b = x;\n }\n return a;\n }\n</code></pre>\n\n<p>if gcd(x,y) > 1: the numbers are not co-prime.</p>\n\n<p>If the code is supposed to run on a platform with slow integer division, you can use the so called <em>binary gcd</em> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:19:56.397",
"Id": "65484",
"Score": "0",
"body": "Original sultion might be a bit better because it takes into account the fact that we need to find set of co-primes rather than check one particular pair."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:54:44.837",
"Id": "39110",
"ParentId": "39109",
"Score": "5"
}
},
{
"body": "<p>Your code can be simplified by eliminating a special case. This…</p>\n\n<pre><code>if (n % i != 0)\n{\n if (num.size()>0)\n {\n for (int j = 0; j < num.size(); j++)\n {\n if (i % num[j] != 0)\n cntr2++;\n }\n if (cntr2 == num.size())\n cntr++;\n cntr2 = 0;\n }\n else\n cntr++;\n}\n</code></pre>\n\n<p>… can be written as:</p>\n\n<pre><code>if (n % i != 0)\n{\n int cntr2 = 0;\n for (int j = 0; j < num.size(); j++)\n {\n if (i % num[j] != 0)\n cntr2++;\n }\n if (cntr2 == num.size())\n cntr++;\n}\n</code></pre>\n\n<p>Furthermore, you could eliminate <code>cntr2</code>. Breaking from the loop earlier saves work and should improve performance.</p>\n\n<pre><code>if (n % i != 0)\n{\n for (int j = 0; j < num.size(); j++)\n {\n if (i % num[j] == 0)\n {\n cntr--;\n break;\n }\n }\n cntr++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:15:04.140",
"Id": "65476",
"Score": "0",
"body": "Didn't you've lost populating `num` vector?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:23:31.290",
"Id": "39119",
"ParentId": "39109",
"Score": "0"
}
},
{
"body": "<p>Suggestions from @200_success will bring you speedup like from ~28.1s to ~11.8s (gcc 4.8.2 with -O3).\nReplacing all with <code>gcd</code> as suggested @EOF will give you ~11.4s and will save some memory.</p>\n\n<p>Overall idea is somewhat correct. You collect factors of <code>n</code> and check that there is no factors within other numbers (that are not already factors of <code>n</code>).</p>\n\n<p>But I guess you can improve solution by factoring with primes and avoid populating <code>num</code> with numbers like 4, 6, 8, 9 etc. That brings time to ~1.3s.</p>\n\n<pre><code>for (int i = 2; i < n; i++)\n{\n if (n % i == 0)\n {\n bool foundFactor = false;\n for (int j = 0; j < num.size(); ++j)\n {\n if (i % num[j] == 0)\n {\n foundFactor = true;\n break;\n }\n }\n if (!foundFactor) num.push_back(i);\n continue;\n }\n bool foundFactor = false;\n for (int j = 0; j < num.size(); ++j)\n {\n if (i % num[j] == 0)\n {\n foundFactor = true;\n break;\n }\n }\n if (!foundFactor)\n cntr++;\n}\n</code></pre>\n\n<p>For your <code>n = 1000000000</code> I've got ~13.6s</p>\n\n<p>Note that there is a linear relation beetween numbers of co-primes in 1000000000 and 1000. That's because the only difference between them is <code>(2*5)**k</code>. That leads us to another optimization based on <a href=\"http://en.wikipedia.org/wiki/Wheel_factorization\" rel=\"nofollow\">the wheel factorization</a>:</p>\n\n<pre><code>long long wheel = 1;\n\n// factorization of n\nfor (long long i = 2, m = n; i <= m; i++)\n{\n if (m % i == 0)\n {\n num.push_back(i);\n wheel *= i; // re-size wheel\n // remove powers of i from m\n do { m /= i; } while (m % i == 0);\n }\n}\n\nfor (int i = 2; i < wheel; i++)\n{\n if (n % i == 0)\n {\n continue;\n }\n bool foundFactor = false;\n for (int j = 0; j < num.size() && num[j] < i; ++j)\n {\n if (i % num[j] == 0)\n {\n foundFactor = true;\n break;\n }\n }\n if (!foundFactor)\n cntr++;\n}\ncout << cntr+1 << endl;\ncout << (cntr+1)*n/wheel << endl;\n</code></pre>\n\n<p>That gives ~0s for almost any <code>10**k</code></p>\n\n<p>P.S. It sound pretty much as Project Euler problem I've met once. I used a bit different approach. I already had a pretty good framework for working with primes and I just simply generated all numbers out of primes that have no factors of <code>n</code> initially. I.e. built up sequence of combinations <code>3**k * 7**k ...</code> until they've reached <code>n</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:56:04.613",
"Id": "39130",
"ParentId": "39109",
"Score": "0"
}
},
{
"body": "<p>Gs_'s answer starts off by essentially finding all the prime factors of <code>n</code>. If you're going to do that, then you might as well use the following well-known formula that calculates the Euler function from the prime factorisation:</p>\n\n<pre><code>phi(p1 ^ a1 * ... * pk ^ ak) =\n (p1 ^ a1 - p1 ^ (a1 - 1))\n * ...\n * (pk ^ ak - pk ^ (ak - 1))\n</code></pre>\n\n<p>The code would look something like this:</p>\n\n<pre><code>long long phi = 1;\n\n// factorization of n\nfor (long long i = 2, m = n; m > 1; i++)\n{\n // Now phi(n/m) == phi\n if (m % i == 0)\n {\n // i is the smallest prime factor of m, and is not a factor of n/m\n m /= i;\n phi *= (i - 1);\n while (m % i == 0) {\n m /= i;\n phi *= i;\n }\n }\n}\n\nreturn phi;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:07:55.453",
"Id": "65496",
"Score": "0",
"body": "What's `wheel`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:34:59.077",
"Id": "65498",
"Score": "0",
"body": "@200_success That was in ony's code. I forgot to delete it. It's removed now. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-13T11:22:22.090",
"Id": "39140",
"ParentId": "39109",
"Score": "0"
}
},
{
"body": "<p>I don't know if you still need this, since it is a very old question. I wrote it for anybody else who might be looking for the answer.</p>\n\n<p>This counts every N's \"relatively prime number\" (less then N). It is called Eulers' totient function.</p>\n\n<pre><code>#include <cstdio>\ntypedef long long lld;\n\nlld f(lld num)\n{\n lld ans = num;\n for (lld i = 2; i*i <= num; i++)\n {\n if (num%i==0)\n {\n while (num%i==0) num /= i;\n ans -= ans / i;\n }\n }\n if (num > 1)\n ans -= ans / num;\n return ans;\n}\n\nint main()\n{\n lld N;\n scanf(\"%lld\", &N);\n printf(\"%lld\", f(N));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-07T13:16:24.057",
"Id": "314356",
"Score": "0",
"body": "Euler's totient function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-07T13:36:28.317",
"Id": "314363",
"Score": "2",
"body": "This is basically a code dump answer (even after moving the explanatory text to the top). Every answer must make at least one insightful observation about the code in the question and not just offer an alternative implementation without at least explaining what it does better or how. See the [help-center](https://codereview.stackexchange.com/help/how-to-answer) for more information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-07T13:11:22.813",
"Id": "165161",
"ParentId": "39109",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:31:22.490",
"Id": "39109",
"Score": "3",
"Tags": [
"c++",
"performance",
"primes"
],
"Title": "Relative prime numbers"
}
|
39109
|
<p>I've been coding in a vacuum for several years and am trying to get up to speed on best practices, in anticipation of my eventual return to employment. I'm hoping this is the best forum in which to ask these types of questions. If not, please let me know.</p>
<p>My first question regards assigning the initial values of a <code>UIViewController</code>'s properties. In general, is it better to do this in <code>viewDidLoad</code> or in the property's getter?</p>
<p>For example, I have a <code>UIViewController</code> with graphics that are based on the user's chosen graphics Theme. The first thing that needs to happen is to load an <code>NSDictionary</code> for the chosen theme, based on the current setting in <code>NSUserDefaults</code>.</p>
<p>So to start, I have:</p>
<pre><code>#import "MainViewController.h"
@interface MainViewController ()
@property NSString *currentTheme;
@end
@implementation MainViewController
@synthesize currentTheme = _currentTheme;
</code></pre>
<p>My preferred method is to use lazy instantiation:</p>
<pre><code>- (void)setCurrentTheme:(NSString *)currentTheme {
_currentTheme = currentTheme;
}
- (NSString *)currentTheme {
if (!_currentTheme) {
_currentTheme = [[NSUserDefaults standardUserDefaults] objectForKey:@"currenttheme"];
}
return _currentTheme;
}
</code></pre>
<p>But since this is the first thing that needs to happen, anyway, I don't think there's any real difference in performance or utility from assigning this in viewDidLoad:</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
self.currentTheme = [[NSUserDefaults standardUserDefaults] objectForKey:@"currenttheme"];
}
</code></pre>
<p>Is there a preferred way of doing this?</p>
|
[] |
[
{
"body": "<p>I would recommend to use one common method for initialization of all the variables, constants, <code>NSUserDefault</code>s, etc.. </p>\n\n<p><code>viewDidLoad</code> should not be messy, it should mostly have calls to the methods.\nI believe you are all aware with code reusability and code optimization techniques.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T05:48:36.083",
"Id": "41624",
"ParentId": "39111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T23:57:47.177",
"Id": "39111",
"Score": "5",
"Tags": [
"objective-c",
"ios"
],
"Title": "Assigning initial value via getter or viewDidLoad"
}
|
39111
|
<p>When a button is pressed, an animation loop is triggered. At the start of the loop, I create a new time object.</p>
<p>I also have a pause button. A problem was created when paused and then started as the <code>Date</code> object would be recreated each time.</p>
<p>The variable is global and not defined to be anything. I could set it to 0 and run the conditional test on that instead, but either way there has to be a cleaner way of doing this. Apologies, I'm quite new to JS. </p>
<p>The code works, but it's ugly (in my opinion):</p>
<pre><code>var t;//not defined
//for starting the animation
startSim.onclick = function(){
if(t == undefined){
//get time object
t = new Date();
}
//other code...
}
</code></pre>
<p>EDIT: In case the question is unclear - I'm checking to see if the Date object has been created by finding out if the variable is undefined or not. What I'm asking is simply Is there a way to find out if the Date object already exists that doesn't rely on checking if the var is undefined.
There is little code as the above is the only relevant part, I can post the rest but it's pointless as not required. (I've added a little more to show structure but I don't think it's required to understand the question)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:12:20.997",
"Id": "65468",
"Score": "0",
"body": "You want us to review 2 lines of code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T02:24:38.107",
"Id": "65469",
"Score": "0",
"body": "@GeorgeMauer - was the question unclear?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T03:13:09.727",
"Id": "65470",
"Score": "0",
"body": "Yes it is, I can't tell what you're asking. Generally this is for code review meaning that you need code to be reviewed. I'm not against asking for design review but you've got to give me a design to review - a chart, some pseudocode, *something*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:06:36.570",
"Id": "65482",
"Score": "0",
"body": "@GeorgeMauer - apologies, I thought the question was clear, edited to try and clarify further..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:40:35.650",
"Id": "65541",
"Score": "0",
"body": "For the code as is raba's suggestion will work. I have a strong suspicion that there is a very elegant recursive solution to your problem but I can't get into specifics without seeing more code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:27:01.820",
"Id": "65552",
"Score": "0",
"body": "@GeorgeMauer - Thanks for your help. There's no need to post any more code, a function gets called when a button is pressed, that's essentially it, what happens in the function has no bearing at all upon the time object. The solution as posted was useful in detailing the error of == over === and included a solution that was far more elegant than my own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:18:00.113",
"Id": "65586",
"Score": "1",
"body": "Consider `t = t || new Date()` which either keeps `t` if it is defined or assigns the `new Date()` value"
}
] |
[
{
"body": "<p>I can think of the following improvements:</p>\n\n<ol>\n<li>Hide <code>t</code>. If you're running other JS modules, you can't really be sure that no-one else writes to the same variable.</li>\n<li>If you want to be sure that your code doesn't mix up an uninitialized timer with a \"cleared\" timer, you might want to pre-initialize the variable to <code>null</code> instead.</li>\n<li>Use <code>===</code> when comparing <code>null</code>, <code>undefined</code>, etc. In JavaScript, <code>null == undefined</code>, but only <code>null === null</code>.</li>\n</ol>\n\n<p>You might want to do something like this:</p>\n\n<pre><code>var timer = (function () {\n var t = null,\n\n start = function () {\n if (t === null) {\n t = new Date();\n }\n },\n\n stop = function () {\n var time = new Date() - t;\n t = null;\n return time;\n };\n\n return {\n start: start,\n stop: stop\n };\n})();\n\ntimer.start();\n\nvar timePassed = timer.stop();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:03:52.510",
"Id": "65495",
"Score": "0",
"body": "thank you for the suggestions and advice, it's much better than what I had, thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T19:36:28.283",
"Id": "71817",
"Score": "0",
"body": "Hi again, I'm just trying to implement a pause feature into the timer function and can't seem to get it right, would you mind lending a hand please? I've added a pause function such as: pause = function(){\n pause = true;\n pausedTime = t;\n return pausedTime;\n\n }, But it's not working as expected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T11:12:34.897",
"Id": "39137",
"ParentId": "39117",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39137",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T00:51:43.910",
"Id": "39117",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"html5",
"datetime"
],
"Title": "Better way to check if Javascript Date object exists"
}
|
39117
|
<p>I'm moderately new to programming in C and I'm not sure about programming practices with code; suddenly I have had fears that my code is messy and disorganized. I can read it when I come back a month later yet I'm still nervous if I'm doing anything that's considered taboo.</p>
<p>This isn't all the code that I've done with this project, I think my other code is fine.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include "functions.h"
#include "errh.h"
#include "mysqlerr.h"
void FIRST_TIME_HANDLER(MYSQL *conn)
{
printw("[+] Doing initialization checks...\n");
SEND_MYSQL_QUERY(conn, "create table IF NOT EXISTS user_2(username varchar(25) not null, passwd varchar(25) not null)");
printw("[+] Handler has checked tables.\n");
refresh();
}
void INThandler(int sig)
{
signal(sig, SIG_IGN);
printw("Closing server...\n");
refresh();
sleep(5);
endwin();
exit(0);
}
MYSQL_INFO *CONNECTION_INIT()
{
MYSQL_INFO *info = malloc(sizeof(*info));
info->IP = "IPADDRGOHERE"; info->user = "Hello";
info->pass = "World"; info->DB = "DBGOHERE";
return info;
}
int EXIT_SERVER(MYSQL *connection)
{
mysql_close(connection);
printw("MySQL session has now closed.\n");
refresh();
return KILL_SIGNAL;
}
MYSQL *MYSQL_CONNECT_DB(MYSQL_INFO *info)
{
MYSQL *connection;
const char *server = info->IP;
const char *user = info->user;
const char *password = info->pass;
const char *database = info->DB;
connection = mysql_init(NULL);
if(!mysql_real_connect(connection, server, user, password, database, 0,
NULL, 0))
{
//printw("[-] Error: %s\n", mysql_error(connection));
MYSQL *f = KILL_SIGNAL;
refresh();
return f;
}
printw("[+] Connected to MySQL server.\n");
FIRST_TIME_HANDLER(connection);
return connection;
}
void SEND_MYSQL_QUERY(MYSQL *conn, const char *query)
{
refresh();
if(mysql_query(conn, query))
{
ERROR err;
throw_error_init(err, 0, 1, NONFATAL, "MySQL QUERY ERROR",
"ERROR IN THE PROCESS OF QUERY.", MySQL_query_error);
}
else
{
printw("Query sent.\n");
}
}
int init_connection()
{
MYSQL *conn;
MYSQL_INFO *info = CONNECTION_INIT();
if((conn = MYSQL_CONNECT_DB(info)) == (MYSQL *) 0)
{
ERROR err;
throw_error_init(err, 1, 1, FATAL, "INIT CONNECTION ERROR",
"Failed to connect to server.", MySQL_init_failure);
}
else {
int key;
nodelay(stdscr,TRUE);
signal(SIGINT, INThandler);
while(1)
{
if((key = getch()) == ERR)
{
if(mysql_ping(conn) == 1)
{
printw("Error!\n");
refresh();
return 1;
}
}
else
{
if(key == EOF) break;
}
}
free(info);
EXIT_SERVER(conn);
return 0;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:22:56.613",
"Id": "65477",
"Score": "0",
"body": "Could you also include the corresponding header file?"
}
] |
[
{
"body": "<ol>\n<li><p>In C the naming conventions typically are <code>lower_case_with_underscore</code> for function names and types (although for types some people also use <code>PascalCase</code>). <code>UPPERCASE</code> is only really used for macro definitions.</p></li>\n<li><p>In <code>CONNECTION_INIT</code> you have a bunch of hard-coded settings. These should come from a config file or via command line arguments.</p></li>\n<li><p>In <code>init_connection</code> you write:</p>\n\n<pre><code>if((conn = MYSQL_CONNECT_DB(info)) == (MYSQL *) 0)\n</code></pre>\n\n<ul>\n<li>There is no reason to cast in order to compare it to <code>NULL</code>, simply <code>== NULL</code> works and is more idiomatic.</li>\n<li><p>There is no reason to do the assignment and compare in one statement. Splitting it up makes the if statement less crammed:</p>\n\n<pre><code>conn = MYSQL_CONNECT_DB(info);\nif (conn == NULL)\n{\n ...\n</code></pre></li>\n</ul></li>\n<li><p>I assume <code>printw</code> is some kind of way to print debug/info/tracing messages. If so then this is not a good name for the function. Better would <code>log_info</code> or similar (depending on the exact purpose).</p></li>\n<li><p>There is this magic <code>refresh</code> method called everywhere but it doesn't seem to follow any particular pattern. Seems suspicious to me.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:53:48.060",
"Id": "65481",
"Score": "0",
"body": "Just got home. printw and refresh are a part of the ncurses library. Ignore those. Thanks for the advice, I'll fix those up."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T08:36:51.653",
"Id": "39129",
"ParentId": "39122",
"Score": "4"
}
},
{
"body": "<p>All of what @ChrisWue is saying in his answer, plus:</p>\n\n<ul>\n<li>Avoid putting multiple statements on a single line (your <code>CONNECTION_INIT</code> method)</li>\n<li>To increase readability, decrease your indent level : in your <code>SEND_MYSQL_QUERY</code> and <code>init_connection</code> methods, just add a <code>return</code> statement to your error management \"ifs\", and get rid of the <code>else</code>, as you do in your <code>MYSQL_CONNECT_DB</code></li>\n<li>I don't see the <code>ERROR err</code> variable utility, as it seems only to be used inside the <code>throw_error_init</code> method</li>\n<li>In your <code>MYSQL_CONNECT_DB</code>, you return a <code>KILL_SIGNAL</code> constant if something went wrong, but when you call this method, you test for a <code>(MYSQL *) 0</code> value (or <code>NULL</code> as @ChrisWue suggested). Be coherent: either return a NULL value if something goes wrong, or test for a <code>KILL_SIGNAL</code> constant.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T03:28:42.410",
"Id": "65622",
"Score": "0",
"body": "Thank you very much for your help, the ERROR err variable is needed for another function. Already the code is looking a lot nicer. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:09:20.360",
"Id": "39132",
"ParentId": "39122",
"Score": "4"
}
},
{
"body": "<p>You should generally avoid <code>while(1)</code> loops. Maybe rewrite that piece of code like this:</p>\n\n<pre><code> while((key = getch()) != EOF)\n {\n if(key == ERR && mysql_ping(conn) == 1)\n { \n printw(\"Error!\\n\");\n refresh(); \n return 1;\n } \n }\n</code></pre>\n\n<p><code>while(1)</code> is conceptually \"go on and on forever\", but this is not your case. This way you don't even need to call a <code>break</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T04:46:30.853",
"Id": "65623",
"Score": "0",
"body": "Wow it looks a lot neater already!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:22:31.377",
"Id": "39134",
"ParentId": "39122",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39134",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T06:00:13.067",
"Id": "39122",
"Score": "6",
"Tags": [
"c",
"mysql"
],
"Title": "Is my MySQL library wrapper neat? How can I do better?"
}
|
39122
|
<p>I am working on a project in which I am supposed to make synchronous and asynchronous behavior of my client.</p>
<p>The customer will call our client with a <code>userId</code> and we will construct a URL from that <code>userId</code> and make an HTTP call to that URL and we will get a JSON string back after hitting the URL. And after we get the response back as a JSON string, we will send that JSON string back to our customer.</p>
<p>In this case, I need to have synchronous and asynchronous methods. Some customers will call the <code>executeSynchronous</code> method to get the same feature and some customers will call our <code>executeAsynchronous</code> method to get the data back.</p>
<p>Interface:</p>
<pre><code>public interface Client {
// for synchronous
public String executeSynchronous(final String userId);
// for asynchronous
public Future<String> executeAsynchronous(final String userId);
}
</code></pre>
<p><code>SmartClient</code> which implements the <code>Client</code> interface:</p>
<pre><code>public class SmartClient implements Client {
ExecutorService executor = Executors.newFixedThreadPool(5);
// This is for synchronous call
@Override
public String executeSynchronous(String userId) {
String response = null;
Future<String> handle = getHandle(userId);
try {
response = handle.get(500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
}
return response;
}
// This is for asynchronous call
@Override
public Future<String> executeAsynchronous(String userId) {
return getHandle(userId);
}
private Future<String> getHandle(String userId) {
Future<String> future = null;
Task task = new Task(userId);
future = executor.submit(task);
return future;
}
}
</code></pre>
<p>Simple class which will perform the actual task:</p>
<pre><code>class Task implements Callable<String> {
private final String userId;
public Task(String userId) {
this.userId = userId;
}
public String call() throws Exception {
String url = createURL(userId);
// make a HTTP call to the URL
RestTemplate restTemplate = new RestTemplate();
String jsonResponse = restTemplate.getForObject(url, String.class);
return jsonResponse;
}
// create a URL
private String createURL(String userId) {
String generateURL = somecode;
return generateURL;
}
}
</code></pre>
<ol>
<li>Is this the correct and efficient way of doing this problem?</li>
<li>How about the exception handling?</li>
<li>Do I need any other <code>catch</code> blocks at any places?</li>
</ol>
|
[] |
[
{
"body": "<p>This looks good. A synchronous call is always an async call plus a wait for the result. To make that clear, <code>execute()</code> should probably call <code>executeAsync()</code> instead of <code>getHandle()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:35:04.257",
"Id": "39492",
"ParentId": "39123",
"Score": "1"
}
},
{
"body": "<p>Late answer to this question.....</p>\n\n<p>There are a few things which should be considered when implementing a solution like this, and best-practice comes in to play here.</p>\n\n<blockquote>\n <p>One nit-pick ... before we go further, your interface the methods\n <code>executeAsynchronous</code> and <code>executeSynchronous</code>, whereas your\n implementation has <code>executeAsync</code> and <code>execute</code>. This is a carelessly\n posted question?</p>\n</blockquote>\n\n<p>What you have, at the moment, works, but is it the best way? I don't think so.</p>\n\n<p>You code has a few features that are important:</p>\n\n<ul>\n<li><code>executeSynchronous()</code> - waits until you have a result, returns the result.</li>\n<li><code>executeAsynchronous()</code> - returns a Future immediately which can be processed after other things are done, if needed.</li>\n<li>it has a private <code>getHandle()</code> method which does the hard work of creating a Callable, and returning a future.</li>\n</ul>\n\n<p>Now, I have tried to list why there are problems with this, but, it's easier to actually show you a different approach, and explain why it is better.... so, here's a different approach, which reverses the logic.</p>\n\n<p>First thing, we are going to make the interface a generic interface... why does it always have to return a String value for each URL? Also, why is it a <code>Client</code>? It is not really a client, but it is a <code>RemoteCall</code>. This is not the full Client, but a part of what it does when it talks to the server.... so, let's rename the <code>Client</code> interface, and make it generic.... Also, while we are at it, you need to declare that you throw some form of exception... my preference is for a new checked exception type, but maybe you can borrow an existing exception. What you have is not best-practice. Here's a decent exception to throw:</p>\n\n<pre><code>class RemoteCallException extends Exception {\n\n private static final long serialVersionUID = 1L;\n\n public RemoteCallException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public RemoteCallException(String message) {\n super(message);\n }\n\n}\n</code></pre>\n\n<p>Then, with that exception, we can complete the interface:</p>\n\n<pre><code>public interface RemoteCall<T> {\n\n // for synchronous\n public T executeSynchronous(final String action) throws RemoteCallException;\n\n // for asynchronous\n public Future<T> executeAsynchronous(final String action);\n}\n</code></pre>\n\n<p>Right, this interface is now a better representation of the work it is supposed to do.</p>\n\n<p>Now, here's a key feature I want you to consider.... at the moment, you may only have one 'action' you need to execute on the server, the part of translating a userid in to a JSOM response. But, I expect there is, or will be, more. Having to build a new implementation for your <code>Client</code> interface for every type of operation is a real PITA, especially when it requires building a new <code>Callable</code> / <code>Task</code> instance.... so, what we do is we create a convenient abstract class, which will do all the synchronous/asynchronous work for us.... </p>\n\n<p>Note, it does not implement executeSynchronous(), and it is still fully generic. It uses an executor service that is passed in.</p>\n\n<p>One of the <strong><em>really huge</em></strong> advantages of reversing the logic (there is no Callable involved in the synchronous call) is that the work is done on the calling thread. In your implementation, you have two threads fully occupied, the calling thread waits for work to be done, and a thread in the ExecutorService is actually doing the work. By making the <code>executeSynchronous()</code> call the way I suggest, only one thread is occupied, and the thread that is busy is the same thread that calls <code>executeSynchronous()</code></p>\n\n<pre><code>public abstract class AbstractRemoteCall<T> implements RemoteCall<T> {\n\n private final ExecutorService executor;\n\n public AbstractRemoteCall(ExecutorService executor) {\n this.executor = executor;\n }\n\n // note, final so it cannot be overridden in a sub class.\n // note, action is final so it can be passed to the callable.\n public final Future<T> executeAsynchronous(final String action) {\n\n Callable<T> task = new Callable<T>() {\n\n @Override\n public T call() throws RemoteCallException {\n return executeSynchronous(action);\n }\n\n };\n\n return executor.submit(task);\n }\n}\n</code></pre>\n\n<p>OK, so, the above class deals with any asynchronous method calls, and delegates the synchronous calls to the actual implementations.</p>\n\n<p>Now we get to your actual implementation you want to do, the <code>userid</code> -> <code>JSON</code> transformation. It is now as easy as:</p>\n\n<pre><code>public class SmartClient extends AbstractRemoteCall<String> {\n\n public SmartClient() {\n super(Executors.newFixedThreadPool(5));\n }\n\n @Override\n public String executeSynchronous(String userId) throws RemoteCallException {\n\n String url = createURL(userId);\n\n // make a HTTP call to the URL\n RestTemplate restTemplate = new RestTemplate();\n\n return restTemplate.getForObject(url, String.class);\n\n }\n\n // create a URL\n private String createURL(String userId) {\n String generateURL = somecode;\n\n return generateURL;\n }\n}\n</code></pre>\n\n<p>The advantages of all these changes are:</p>\n\n<ul>\n<li>the abstract class is the only place you need to worry about threading</li>\n<li>in a synchronous call, the work is done on the calling thread</li>\n<li>there is a better mechanism for error handling with the new RemoteCallException.</li>\n<li>you can now have many different implementations of the abstract class, each implementation does their own type of restful work, and you don't need to worry about the threading in any of them.</li>\n<li>the actual working classes (like <code>SmartClient</code>) do one thing, and one thing only.</li>\n</ul>\n\n<p>There are other advantages.... but, what you have now, though it works, is not nearly as maintainable, extensible, and reliable as what it could be.</p>\n\n<p><strong>EDIT:</strong> Some use-cases</p>\n\n<p>How would the code I recommend be used? Two situations.... Synchronous</p>\n\n<pre><code>// set up some system, need the JSON data\nSmartClient sc = new SmartClient();\nString json = sc.executeSynchronous(userid);\n</code></pre>\n\n<p>Collecting data asynchronous:</p>\n\n<pre><code>// Set up a number of things, timing can be in parallel.\ntry {\n SmartClient sc = new SmartClient();\n Future<String> jsonfut = sc.executeAsynchronous(userid);\n // set up some other things.\n // perhaps some thing that gets other data....\n // this is a different class just like the SmartClient that can be asynchronous\n DataCLient dc = new DataClient();\n Future<String> defautsfut = dc.executeAsynchronous(\"getdefaults\");\n Future<String> messagesfut = dc.executeAsyncrhonous(\"messages\");\n String json = jsonfut.get(500, TimeUnit.MILLISECONDS); \n String defaults = defaultsfut.get(); // no timeout\n String messages = messagesfut.get(); // no timeout\n} catch (TimeoutException te) {\n // handle appropriately\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:50:38.650",
"Id": "70890",
"Score": "0",
"body": "Thanks a lot `rolfl`.. Appreciated your help on this.. And now it really makes sense what is the benefit with your approach as compared to mine.. But in my use case, some customers would like to take advantage of `executeAsynchronous` method as well which means that some customers will call `executeAsynchronous` method directly from there application which will return the future and they can use it in the way they want to use and sometimes they will call `executeSynchronous` method as well. But in your example I guess customers can only call `executeSynchronous` method directly..?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:51:23.683",
"Id": "70891",
"Score": "0",
"body": "... Or might be I am missing something. Can you show me an example how customers will call `executeSynchronous` and `executeAsynchronous` method.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T04:58:24.680",
"Id": "70894",
"Score": "0",
"body": "@user2809564 I think you are missing that the executeAsynchronous calls the executeSynchronous as a Callable/Future"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:00:06.073",
"Id": "70896",
"Score": "0",
"body": "Aah.. I just saw that but I don't see any future.get call in the synchronous method. And how do I timeout the synchronous call if it is taking time greater than we have specified?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:01:30.283",
"Id": "70898",
"Score": "0",
"body": "And this is slightly new approach for me so I am trying to understand how would I make a call to synchronous and asynchronous method from the outside application? So if you can provide an example then it will be of great help to me.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:03:55.810",
"Id": "70899",
"Score": "0",
"body": "@user2809564 - good question. I saw the timeout in your original code and thought 'huh, that does not belong there'. If you are going to have an asynchronous call, then you should let the client manage the timeout.... which they can do with the Future's `get(long, TimeUnit)` call. If you add the timeout yourself, you are no longer asynchronous"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:06:26.197",
"Id": "70900",
"Score": "0",
"body": "Yeah.. that's a good point but I was told that I should implement both synchronous and asynchronous method and customer can use whatever method they want to use in there application depending on there requirement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T05:08:00.377",
"Id": "70901",
"Score": "0",
"body": "In general I am wondering how would external customer will make a call if I go with your suggestion? Can you provide an example if possible?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T23:28:53.860",
"Id": "41299",
"ParentId": "39123",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "41299",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T06:11:48.850",
"Id": "39123",
"Score": "9",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Synchronous and asynchronous behavior for client"
}
|
39123
|
<p>I was not sure if I should post about 200 lines here. I want to make this ant simulation faster. The bottleneck is at <code>Ant.checkdistancebetweenantsandfood()</code>.</p>
<p>It would be great if you have some hints for some cleaner or more efficient code. I hope this is the right place to show this code.</p>
<pre><code>import random
import time
import datetime
# TODO
# food - 100 portions okay
# bring food to the hill okay
# bring food to the hill - direct way
# use food over time
# die if food is out
# bear if enough food is there
# trail okay
# trail disolves over time
# opponent - different properties
# new food
# inside ant hill ?
# make calculations faster
#############################
# PLOT - BEGIN
#############################
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
# field size
size = 30
# black ants
x1 = [0]
y1 = [0]
points, = ax.plot(x1, y1, marker='o', linestyle='None', alpha=0.3,
markersize=5, c='black')
# ant hill
x2 = [0]
y2 = [0]
points2, = ax.plot(x2, y2, marker='o', linestyle='None', alpha=0.6,
markersize=30, c='brown')
# food
foodamount = 220
foodposx = []
foodposy = []
for i in range(foodamount):
foodposx.append(random.randint(0, 2*size)-size)
foodposy.append(random.randint(0, 2*size)-size)
points3, = ax.plot(foodposx, foodposy, marker='o', linestyle='None',
alpha=0.6, markersize=5, c='green')
foundenoughfood = 20
anthillfood = 0
# movement
speed = .4
# trail
trailx = [0]
traily = [0]
trail, = ax.plot(trailx, traily, marker='o', linestyle='None', alpha=0.6,
markersize=5, c='orange')
#trailduration = []
bearingspeed = 100 # higher value = slower bearing
# red ants
#...
ax.set_xlim(-size, size)
ax.set_ylim(-size, size)
new_x = np.random.randint(10, size=1)
new_y = np.random.randint(10, size=1)
points.set_data(new_x, new_y)
plt.pause(.0000000000001)
#############################
# PLOT - END
#############################
class Antqueen:
counter = 2
def __init__(self, name):
"""Initializes the data."""
self.name = name
print("(Initializing {0})".format(self.name))
def bear(self):
# print Antqueen.counter, 'ants born'
self.name = 'ant_' + str(Antqueen.counter)
Antqueen.counter = Antqueen.counter + 1
ants[self.name] = None
globals()[self.name] = Ant(self.name)
class Ant:
population = 0
def __init__(self, name):
"""Initializes the data."""
self.name = name
self.food = 10
self.posx = 0.0
self.posy = 0.0
#print("(Initializing {0})".format(self.name))
Ant.population += 1
def die(self):
"""I am dying."""
print("{0} is dead!".format(self.name))
Ant.population -= 1
if Ant.population == 0:
print("{0} was the last one.".format(self.name))
else:
print("There are still {0:d} ants working.".format(Ant.population))
def sayHi(self):
print("Hello, call me {0}.".format(self.name))
# move + trail
def move(self):
if globals()[name].food < foundenoughfood:
self.posx = self.posx + speed*(random.random()-random.random())
self.posy = self.posy + speed*(random.random()-random.random())
# found enough food
# go back to home
else:
# close to the ant hill
# lay down some food to the ant hill
if abs(self.posx) < .5:
if abs(self.posy) < .5:
global anthillfood
anthillfood = anthillfood + globals()[name].food - 10
#print "anthillfood: ", anthillfood
# lay down everything but 10
globals()[name].food = 10
# far away from the ant hill
# set trail
trailx.append(self.posx)
traily.append(self.posy)
# draw the trail ###
trail.set_data(trailx, traily)
# move towards the ant hill
vecx = -self.posx
vecy = -self.posy
len_vec = np.sqrt(vecx**2+vecy**2)
self.posx = self.posx + vecx*1.0/len_vec/3 + speed*(random.random()-random.random())/1.5
self.posy = self.posy + vecy*1.0/len_vec/3 + speed*(random.random()-random.random())/1.5
def eat(self, name, foodnumber, foodposx, foodposy):
if foodtable[foodnumber][1] > 0:
# food on ground decreases
foodtable[foodnumber][1] = foodtable[foodnumber][1] - 1
# food in ant increases
globals()[name].food = globals()[name].food + 1
#print name, globals()[name].food, "food"
# food is empty
if foodtable[foodnumber][1] == 0:
#print "foodposx: ", foodposx
del foodposx[foodnumber]
del foodposy[foodnumber]
points3.set_data(foodposx, foodposy)
@classmethod
def howMany(cls):
"""Prints the current population."""
print("We have {0:d} ants.".format(cls.population))
def checkdistancebetweenantsandfood(self):
for name in ants.keys():
for i in range(len(foodposx)-1):
# measure distance between ant and food
if -1 < globals()[name].posx - foodposx[i] < 1:
if -1 < globals()[name].posy - foodposy[i] < 1:
globals()[name].eat(name, i, foodposx, foodposy)
# slower
#distance = np.sqrt((globals()[name].posx - foodposx[i])**2 + (globals()[name].posy - foodposy[i])**2)
#if distance < 1:
# globals()[name].eat(name, i, foodposx, foodposy)
# generate ant queen
antqueen = Antqueen("antqueen")
# generate some ants
ants = {'ant_1': None}
for name in ants.keys():
globals()[name] = Ant(name)
# amount of food
foodtable = []
for i in range(foodamount):
foodtable.append([i, 10])
#############################
# start simulation
#############################
for i in range(100000):
# move all ants
for name in ants.keys():
globals()[name].move()
# generate more ants
if (i % bearingspeed == 0):
antqueen.bear()
# plot ants
allposx = []
allposy = []
for name in ants.keys():
allposx.append(globals()[name].posx)
allposy.append(globals()[name].posy)
points.set_data(allposx, allposy)
plt.draw()
#plt.pause(0.000000000001) # draw is faster
# ants find food
for name in ants.keys():
globals()[name].checkdistancebetweenantsandfood()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:43:51.693",
"Id": "65488",
"Score": "1",
"body": "Have you tried the \"slower\" code without calling `np.sqrt()`? (In other words, work using the square of the distance.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:47:15.333",
"Id": "65489",
"Score": "0",
"body": "The square of the distance? Do you mean distance**(0.5)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:50:33.083",
"Id": "65490",
"Score": "1",
"body": "`dist_sq = (globals()[name].posx - foodposx[i])**2 + (globals()[name].posy - foodposy[i])**2; if dist_sq < 1 * 1: eat(…)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:29:26.560",
"Id": "65497",
"Score": "1",
"body": "`globals()` is meant for special uses only. Why don't you simply store the `Ant` objects in the `ants` dictionary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T14:16:54.703",
"Id": "66394",
"Score": "1",
"body": "This could be a fun week-end CR challenge"
}
] |
[
{
"body": "<p>It looks like you're looping through the ants twice, once inside checkdistancebetweenantsandfood() and once when you call it. That seems like it's probably wrong.</p>\n\n<p>Method:</p>\n\n<pre><code> def checkdistancebetweenantsandfood(self):\n for name in ants.keys():\n for i in range(len(foodposx)-1):\n # measure distance between ant and food\n if -1 < globals()[name].posx - foodposx[i] < 1:\n if -1 < globals()[name].posy - foodposy[i] < 1:\n globals()[name].eat(name, i, foodposx, foodposy)\n</code></pre>\n\n<p>Call:</p>\n\n<pre><code> # ants find food\n for name in ants.keys():\n globals()[name].checkdistancebetweenantsandfood()\n</code></pre>\n\n<p><strong>Other optimizations</strong></p>\n\n<p>Another possible optimization is to exit the loop if a food source is found. Presumably the ants can only eat from one food source at a time.</p>\n\n<p>Example:</p>\n\n<pre><code> def checkdistancebetweenantsandfood(self):\n for name in ants.keys():\n for i in range(len(foodposx)-1):\n # measure distance between ant and food\n if -1 < globals()[name].posx - foodposx[i] < 1:\n if -1 < globals()[name].posy - foodposy[i] < 1:\n globals()[name].eat(name, i, foodposx, foodposy)\n break\n</code></pre>\n\n<p>If there are many food sources, you might try putting the food sources into a grid based on their position. That way the ants only need to check the for food sources in adjacent cells instead of having to loop through all of the food sources.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T19:07:01.820",
"Id": "39555",
"ParentId": "39124",
"Score": "2"
}
},
{
"body": "<p><a href=\"http://www.python.org/dev/peps/pep-0008/#function-names\" rel=\"nofollow\">PEP-8 suggest the following about function names</a>:</p>\n\n<blockquote>\n <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>\n</blockquote>\n\n<p><code>check_distance_between_ants_and_food</code> would follow this guidance and would be easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T23:28:18.737",
"Id": "40065",
"ParentId": "39124",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T06:42:47.927",
"Id": "39124",
"Score": "3",
"Tags": [
"python",
"performance",
"numpy",
"simulation"
],
"Title": "How can I make my ant simulation faster?"
}
|
39124
|
<p>I have issues with dynamically typed languages, and I tend to worry about type a lot.</p>
<p>Numpy has different behaviour depending on if something is a matrix or a plain ndarray, or a list. I didn't originally have all these asserts, but I inserted them while trying to debug a type error.</p>
<pre><code>from numpy import *
sigmoid = vectorize(lambda(x): 1.0/(1.0+exp(-x)))
def prob_hOn_givenV (v,b,w):
assert isinstance(v,matrix)
assert isinstance(w,matrix)
assert isinstance(b,matrix)
assert shape(v)[1]==shape(w)[0]
#print("|v|="+str(shape(v)) +"|w|="+str(shape(w)) )
return sigmoid(b+v*w) #sum up rows (v is a column vector)
def prob_vOn_givenH (h,a,w):
assert isinstance(h,matrix)
assert isinstance(a,matrix)
assert isinstance(w,matrix)
assert shape(h)[1]==shape(w.T)[0]
return sigmoid(a+h*w.T) #sum up columns. (h is a row vector)
</code></pre>
<p>Is there a better way? Perhaps a defensive programming toolkit? There is also duplication in the code, but I can't see a nice way of removing it while maintaining meaning. People familiar with Restricted Boltzman Machines will recognise the conditional formula used for Gibbs sampling for contrastive divergence. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:23:20.240",
"Id": "65509",
"Score": "0",
"body": "The key point is that a compiler's static type checking is a kind of test, but an incomplete one (otherwise statically typed languages would have no bugs). In a dynamically typed languages, unit tests take the place of the compiler's type checks, _and_ add some degree of assurance that the code is correct (something the compiler can never do for you, whether statically or dynamically typed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:48:54.897",
"Id": "65522",
"Score": "1",
"body": "Aside: `from numpy import *` -- don't do this. This will replace some common Python builtins, like `any` and `all`, with `numpy` versions which can silently return exactly the opposite values."
}
] |
[
{
"body": "<p>First, I recommend avoiding the <code>matrix</code> type altogether. The problems it causes outweighs the minor syntactical convenience it provides, in my (and quite a few others') opinion.</p>\n\n<p>Second, the idiomatic way to do this kind of thing in numpy is not to assert that the inputs are particular types, but to coerce them to an <code>ndarray</code>. <code>np.asarray()</code> does this efficiently; if the input is an <code>ndarray</code>, the input passes through untouched; if it is an <code>ndarray</code> subclass, then a new <code>ndarray</code> will be created but only as a view on the original data so no data will be copied.</p>\n\n<pre><code>import numpy as np\n\ndef sigmoid(x):\n # No need to use vectorize() for this. It's already vectorized.\n return 1.0 / (1.0 + np.exp(-x))\n\ndef prob_hOn_givenV(v, b, w):\n v = np.asarray(v)\n b = np.asarray(b)\n w = np.asarray(w)\n # Don't bother checking the shape. `np.dot()` will do that for us.\n # Strictly speaking, the `asarray(v)` and `asarray(w)` aren't necessary\n # since `np.dot(v, w)` already does that internally. But it does no harm.\n return sigmoid(b + np.dot(v, w))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:15:10.943",
"Id": "65507",
"Score": "0",
"body": "my issue wit ndarray was that it isn't nice for checking shape. Because ndarray doesn't differentiate between shape of (1,N),(N,1) and (N). \nand that gives me headaches trying to ensure I have the formula right (esp when w is square)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T11:17:48.860",
"Id": "39138",
"ParentId": "39125",
"Score": "2"
}
},
{
"body": "<p>These are the best links to pythonic ways of doing various checks:</p>\n\n<p><a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary#Pre-.2FPost-Conditions\" rel=\"nofollow\" title=\"pre- and post-conditions\">Pre- and Post-conditions</a> and <a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29\" rel=\"nofollow\" title=\"Type Enforcement\">Type Enforcement</a></p>\n\n<p>You can use particular sets of asserts (or any other piece of code for more complicated checks, for example checking if an list of ints truly contains all ints)\nas a function, and then use that function as a parameter to the decorator, making a very clean description of what you're checking.</p>\n\n<p>The accept/returns decorator is a quick and clean way of checking your inputs.\nThe pre- and post-condition checking decorator is more suited for larger or more complicated sets of checks, whether it's type enforcement, or parameter range, or any other relationship between the data, like if an array's elements are sorted.</p>\n\n<p>I used to include all these checks in the function alone, but with some functions it makes the code rather unreadable, as the real functionality gets lost in all the checks. This is a fairly simple way to organize your checks, and make your code easier to read.</p>\n\n<p>+1 for not trusting duck typing ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:13:59.887",
"Id": "39154",
"ParentId": "39125",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T07:51:32.283",
"Id": "39125",
"Score": "5",
"Tags": [
"python",
"numpy",
"matrix",
"machine-learning",
"assertions"
],
"Title": "Defensive programming type-checking"
}
|
39125
|
<p>Is there any way to reduce total execution time for the function <code>getSilhouetteIndex</code>? P.S. I am using <code>weka SimpleKMeans</code> for getting kmeans and <code>ceval</code>.</p>
<pre><code>private double getSilhouetteIndex(List<ITSPoI> _POIs, SimpleKMeans kmeans, ClusterEvaluation ceval)
{
double si_index = 0;
double[] ca = ceval.getClusterAssignments();
double[] d_arr = new double[ca.length];
List<Double> si_indexes = new ArrayList<Double>();
for (int i=0; i<ca.length; i++)
{
// STEP 1. Compute the average distance between the i-th PoI and all other points of a given cluster
double a = averageDist(_POIs,ca,i,1);
// STEP 2. Compute the average distance between the i-th PoI and all PoIs of other clusters
for (int j=0; j<ca.length; j++)
{
double d = averageDist(_POIs,ca,j,2);
d_arr[j] = d;
}
// STEP 3. Compute the the distance from the i-th PoI to its nearest cluster to which it does not belong
double b = d_arr[0];
for (Double _d : d_arr)
{
if (_d < b)
b = _d;
}
// STEP 4. Compute the Silhouette index for the i-th PoI
double si = (b - a)/Math.max(a,b);
si_indexes.add(si);
}
// STEP 5. Compute the average index over all observations
double sum = 0;
for(Double _si : si_indexes)
{
sum += _si;
}
si_index = sum/si_indexes.size();
return si_index;
}
private double averageDist(List<ITSPoI> _POIs, double[] ca, int id, int calc)
{
double avgDist = 0;
List<ITSPoI> clusterPOIs = new ArrayList<ITSPoI>();
// Distances inside the cluster
if (calc == 1)
{
for (int i = 0; i<ca.length; i++)
{
if (ca[i] == ca[id])
clusterPOIs.add(_POIs.get(i));
}
}
// Distances outside the cluster
else
{
for (int i = 0; i<ca.length; i++)
{
if (ca[i] != ca[id])
clusterPOIs.add(_POIs.get(i));
}
}
double latx, lonx, laty, lony;
double[] dist = new double[clusterPOIs.size()];
latx = _POIs.get(id).getLat();
lonx = _POIs.get(id).getLon();
for (int i=0; i<clusterPOIs.size(); i++)
{
laty = clusterPOIs.get(i).getLat();
lony = clusterPOIs.get(i).getLon();
dist[i] = distanceGeo(latx,lonx,laty,lony);
}
double sum = 0;
for(Double d : dist)
{
sum += d;
}
avgDist = sum/dist.length;
return avgDist;
}
private double distanceGeo(double lat1, double lon1, double lat2, double lon2)
{
if (lat1 == lat2 && lon1 == lon2)
{
return 0;
}
else
{
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
return dist;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:49:36.407",
"Id": "65560",
"Score": "0",
"body": "I might be stupid but what **does** this method? What is a `ITSPoI`, what is `SimpleKMeans` and what is `ClusterEvaluation`. To me, you haven't provided much [context](http://meta.codereview.stackexchange.com/questions/1226/code-should-include-a-description-of-what-the-code-does) on this question."
}
] |
[
{
"body": "<p>There are <a href=\"http://www.movable-type.co.uk/scripts/latlong.html\" rel=\"nofollow\">three methods</a> for computing a great circle distance between two points that are specified by latitude and longitude:</p>\n\n<ol>\n<li>You used the <a href=\"http://en.wikipedia.org/wiki/Spherical_law_of_cosines\" rel=\"nofollow\">spherical law of cosines</a>, which is the most straightforward method based on mathematical principles.</li>\n<li>The <a href=\"http://en.wikipedia.org/wiki/Haversine_formula\" rel=\"nofollow\">haversine formula</a> yields better accuracy for small distances, though at a greater computational cost.</li>\n<li>An approximation can be obtained by using the Pythagorean theorem on an equirectangular projection.</li>\n</ol>\n\n<p>For the purposes of clustering, an approximation of the great circle distance might be good enough. I would also declare this function <code>private static final</code> as a very strong hint that it can be inlined — as it should, since it's a pure mathematical function.</p>\n\n<pre><code>private static final double approxDistanceGeo(double lat1, double lon1, double lat2, double lon2)\n{\n if (lat1 == lat2 && lon1 == lon2)\n {\n return 0;\n }\n else\n {\n double x = deg2rad(lon1 - lon2) * Math.cos(deg2rad((lat1 + lat2) / 2));\n double y = deg2rad(lat1 - lat2);\n double dist = Math.sqrt(x * x + y * y);\n dist = dist * 60 * 1.1515 * 1.609344;\n return dist;\n }\n}\n</code></pre>\n\n<p>Working directly in radians could save a few <code>deg2rad()</code> conversions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:59:56.460",
"Id": "65500",
"Score": "0",
"body": "private static double deg2rad(double deg) \n {\n return (deg * Math.PI / 180.0);\n }"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T11:51:43.010",
"Id": "39142",
"ParentId": "39133",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39142",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T10:19:15.350",
"Id": "39133",
"Score": "2",
"Tags": [
"java",
"performance",
"mathematics",
"computational-geometry",
"floating-point"
],
"Title": "How to reduce execution time for this clustering computation?"
}
|
39133
|
<p>Based on the advice provided in <a href="https://codereview.stackexchange.com/questions/39097/how-can-i-improve-this-c-evolutionary-ai-implementation">my previous question</a>, I would like to post the other source file that actually implements all the combat mechanics and also the actual evolution process. </p>
<p>As with the previous question, I am interested in all kinds of feedback — regarding design, implementation, algorithms, presentation, style, cleanliness, correct C++11 usage, or anything that you think that could make this work better as an impressive code sample submitted to support a job application.</p>
<p>The entire code as well as the rules can be seen at <a href="http://www.mz1net.com/code-sample" rel="nofollow noreferrer">http://www.mz1net.com/code-sample</a> — that is also where the 'MechArena.h' that declares the classes and describes them a little better is available.</p>
<pre><code>#include <algorithm>
#include <exception>
#include "MechArena.h"
// COMPONENT SET ========================================================================
// ======================================================================================
// The no-param constructor initialises the component list with random components.
template<typename T>
Components<T>::Components (size_t size)
{
for (size_t m = 0; m < size; m++)
{
T component = Components<T>::randomComponent();
this->components.push_back(component);
}
}
// ======================================================================================
// The 'crossover' constructor creates a new Components instance that randomly mixes the
// components used by the two provided parents component sets. Some components will also
// be randomly switched to a random component due to mutation.
template<typename T>
Components<T>::Components (const Components<T>& c1, const Components<T>& c2)
{
size_t c1Size = c1.components.size();
size_t c2Size = c2.components.size();
if (c1Size != c2Size)
{
throw std::exception("Crossover is impossible between component sets that do not have the same size.");
}
// For each component in the set, decide randomly which parent's component the new
// component set will inherit. For optimisation, we request one random number and use
// its bits to decide on the respective component slots.
int r = rand();
for (size_t m = 0; m < c1Size; m++)
{
int mask = 1 << m;
this->components.push_back( (r & mask) ? c1.components.at(m) : c2.components.at(m) );
}
// Mutation:
for (T& component : this->components)
{
if (rand()%1000 <= 50)
{
component = Components::randomComponent();
}
}
}
// ======================================================================================
template<typename T>
const std::vector<T>& Components<T>::getList() const
{
return this->components;
}
// ======================================================================================
template<typename T>
std::ostream& operator<< (std::ostream& os, const Components<T>& c)
{
for (T component : c.getList())
{
os << componentName(component) << '\n';
}
return os;
}
// ======================================================================================
// For each component type (armor/weapon/reactor/aux), we specialise the
// 'randomComponent' method so that it works with the correct enumeration:
ArmorComponent Components<ArmorComponent>::randomComponent()
{
int r = rand() % COMP_ARMOR_LAST;
return static_cast<ArmorComponent>(r);
}
// ======================================================================================
WeaponComponent Components<WeaponComponent>::randomComponent()
{
int r = rand() % COMP_WEAPON_LAST;
return static_cast<WeaponComponent>(r);
}
// ======================================================================================
ReactorComponent Components<ReactorComponent>::randomComponent()
{
int r = rand() % COMP_REACTOR_LAST;
return static_cast<ReactorComponent>(r);
}
// ======================================================================================
AuxComponent Components<AuxComponent>::randomComponent()
{
int r = rand() % COMP_AUX_LAST;
return static_cast<AuxComponent>(r);
}
// WEAPON ===============================================================================
// ======================================================================================
Weapon::Weapon (Mech& owner, WeaponComponent component) :
owner(owner),
component(component)
{
switch (component)
{
case COMP_WEAPON_LASER_HEAVY:
this->hits = 30;
this->cooldown = 5;
this->hitType = HT_PULSE;
break;
case COMP_WEAPON_LASER_FAST:
this->hits = 10;
this->cooldown = 2;
this->hitType = HT_PULSE;
break;
case COMP_WEAPON_MISSILE_LAUNCHER:
this->hits = 50;
this->cooldown = 4;
this->hitType = HT_BLAST;
break;
default:
throw std::exception("Cannot setup a Weapon - there are no data related to the provided component.");
}
this->readyIn = this->cooldown;
this->calibration = false;
}
// ======================================================================================
// Applies a reactor component to the weapon, so that the weapon can alter
// its values (cooldown, hit amount, etc.) based on the particular component.
void Weapon::applyReactorComponent (ReactorComponent component)
{
// Heavy Laser: Reduce cooldown with Heat Sink.
if (this->component == COMP_WEAPON_LASER_HEAVY && component == COMP_REACTOR_HEAT_SINK)
{
this->cooldown--;
}
// Missile Launcher: Reduce cooldown with Advanced Lock-On System.
if (this->component == COMP_WEAPON_MISSILE_LAUNCHER && component == COMP_REACTOR_LOCK_ON)
{
this->cooldown--;
}
// Fast Laser: Increase hit amount with Predictive Scanners.
if (this->component == COMP_WEAPON_LASER_FAST && component == COMP_REACTOR_SCANNERS)
{
this->hits = int (this->hits * 1.5);
}
}
// ======================================================================================
// Makes the weapon act in the mech's combat turn. Reduces the weapon's cooldown, and in
// case that this makes the weapon able to attack this turn, it attacks the provided opponent.
void Weapon::act (Mech& opponent)
{
this->readyIn--;
if (this->readyIn > 0) return;
// For missile-based weapons, check that the mech can spend a missile:
if (!this->requiresMissile() || this->owner.spendMissile())
{
opponent.receiveHit(this->hitType, this->hits, this->calibration);
this->readyIn = this->cooldown;
}
}
// ======================================================================================
bool Weapon::requiresMissile()
{
return (this->component == COMP_WEAPON_MISSILE_LAUNCHER);
}
// ======================================================================================
void Weapon::reset() {
this->readyIn = this->cooldown;
}
// MECH =================================================================================
// ======================================================================================
// The no-param constructor creates a new mech with a random component setup.
Mech::Mech() :
armorComponents(3),
weaponComponents(4),
reactorComponents(3),
auxComponents(2)
{
this->initID();
this->initCombatValues();
}
// ======================================================================================
// The crossover constructor creates a new crossover mech that is based on the two provided
// parents. The new mech randomly mixes components of its parents, and some components can
// also be randomly switched to another due to mutation.
Mech::Mech (const Mech& m1, const Mech& m2) :
armorComponents (m1.armorComponents, m2.armorComponents),
weaponComponents (m1.weaponComponents, m2.weaponComponents),
reactorComponents (m1.reactorComponents, m2.reactorComponents),
auxComponents (m1.auxComponents, m2.auxComponents)
{
this->initID();
this->initCombatValues();
}
// ======================================================================================
// Provides the mech with a unique ID.
// This needs to be called by all the constructors.
void Mech::initID()
{
static int ID = 0;
this->ID = ++ID;
}
// ======================================================================================
// Calculates all the mech's combat values based on its component setup.
// This needs to be called by all the constructors.
void Mech::initCombatValues()
{
this->maxArmor = 100;
this->armorAutoRepair = 0;
this->pulseAbsorb = 0;
this->interceptor = false;
this->repairBots = false;
this->maxMissiles = 0;
this->maxCountermeasures = 0;
this->maxNanobots = 0;
this->score = 0;
// Armor:
for (ArmorComponent component : this->armorComponents.getList())
{
switch (component)
{
case COMP_ARMOR_BONUS:
this->maxArmor += 35;
break;
case COMP_ARMOR_REPAIR_AUTO:
this->armorAutoRepair += 5;
break;
case COMP_ARMOR_REPAIR_BOTS:
this->repairBots = true;
this->nanobots += 1;
break;
case COMP_ARMOR_MISSILE_INTERCEPTOR:
this->interceptor = true;
this->countermeasures += 1;
break;
case COMP_ARMOR_LASER_ABSORB:
this->pulseAbsorb += 2;
break;
default:
throw std::exception("Cannot setup the mech with the provided armor component.");
}
}
// Weapons:
for (WeaponComponent component : this->weaponComponents.getList())
{
this->weapons.push_back( Weapon(*this, component) );
}
// Reactor:
for (ReactorComponent component : this->reactorComponents.getList())
{
// Let all the weapons update their internal values based on the reactor component:
for (std::vector<Weapon>::iterator weaponIt = this->weapons.begin(); weaponIt != this->weapons.end(); weaponIt++)
{
weaponIt->applyReactorComponent(component);
}
}
// Auxiliary:
for (AuxComponent component : this->auxComponents.getList())
{
switch (component)
{
case COMP_AUX_MISSILES:
this->maxMissiles += 4;
break;
case COMP_AUX_COUNTERMEASURES:
this->maxCountermeasures += 2;
break;
case COMP_AUX_NANOBOTS:
this->maxNanobots += 3;
break;
default:
throw std::exception("Cannot setup the mech with the provided auxiliary component.");
}
}
}
// ======================================================================================
// Executes a match between the two provided mechs and returns the match result.
// This is a static method that expects both the match participants as parameters.
MatchResult Mech::match (Mech& m1, Mech& m2)
{
m1.resetCombatValues();
m2.resetCombatValues();
int turn = 0;
static const int turnLimit = 25;
// Each turn:
while (turn < turnLimit)
{
m1.actCombatTurn(m2);
m2.actCombatTurn(m1);
bool mech1Dead = !m1.isAlive();
bool mech2Dead = !m2.isAlive();
if (mech1Dead && mech2Dead) return MATCH_RESULT_DRAW;
if (mech1Dead) return MATCH_RESULT_MECH_2_WINS;
if (mech2Dead) return MATCH_RESULT_MECH_1_WINS;
turn++;
}
return MATCH_RESULT_DRAW;
}
// ======================================================================================
// Allows the mech to take all the actions that it can take in its combat turn:
// use or cool down its weapons, auto-repair, use nanobots to repair, etc.
void Mech::actCombatTurn (Mech& opponent)
{
this->autoRepair();
this->botRepair();
this->attack(opponent);
}
// ======================================================================================
// Executes the mech's auto-repairs.
void Mech::autoRepair()
{
this->armor = std::min(this->armor + this->armorAutoRepair, this->maxArmor);
}
// ======================================================================================
// Makes the mech use its nanobot repair module in its combat turn, when appropriate.
void Mech::botRepair()
{
// Check that the mech has the repair
// module and also a nanobot to spare.
if (!this->repairBots) return;
if (this->nanobots <= 0) return;
// Do not repair unless needed.
const int nanobotRepairAmount = 20;
if (this->armor > this->maxArmor - nanobotRepairAmount) return;
// Repair and spend the nanobot.
this->armor += nanobotRepairAmount;
this->nanobots--;
}
// ======================================================================================
// Makes the mech act with all its weapons in its combat turn.
void Mech::attack (Mech& opponent)
{
for (Weapon& weapon : this->weapons)
{
weapon.act(opponent);
}
}
// ======================================================================================
// Makes the mech receive a combat hit. This reduces the mech's armor.
// The mech is allowed to use all its protection mechanisms (countermeasures, laser absorbs).
// For calibrated hits, the hit destroys a missile, a countermeasure, or a nanobot.
void Mech::receiveHit (HitType hitType, int hits, bool calibration)
{
// Pulse hits: Reduce the hit amount by our 'laser absorb' value.
if (hitType == HT_PULSE)
{
this->armor -= (hits - this->pulseAbsorb);
}
// Blast hits: Counter them with a countermeasure, if available.
if (hitType == HT_BLAST)
{
if (this->interceptor && this->countermeasures > 0)
{
this->countermeasures--;
}
else
{
this->armor -= hits;
}
}
// For calibrated hits, destroy a
// missile/countermeasure/nanobot.
if (calibration)
{
if (this->missiles > 0)
{
this->missiles--;
}
else if (this->countermeasures > 0)
{
this->countermeasures--;
}
else if (this->nanobots > 0)
{
this->nanobots--;
}
}
}
// ======================================================================================
bool Mech::isAlive() const
{
return (this->armor > 0);
}
// ======================================================================================
// Makes the mech spend a missile. Returns 'true' when the mech had a missile to spare.
// Returns 'false' when the mech was out of missiles.
bool Mech::spendMissile()
{
if (this->missiles > 0)
{
this->missiles--;
return true;
}
return false;
}
// ======================================================================================
// Restores all the mech's combat status values (armor, weapon cooldowns, missiles, etc.)
// to their initial values, so that it can start a new combat match.
void Mech::resetCombatValues()
{
this->armor = this->maxArmor;
this->missiles = this->maxMissiles;
this->countermeasures = this->maxCountermeasures;
this->nanobots = this->maxNanobots;
for (Weapon& weapon : this->weapons)
{
weapon.reset();
}
}
// ======================================================================================
void Mech::addScore (int point)
{
this->score += point;
}
// ======================================================================================
void Mech::resetScore()
{
this->score = 0;
}
// ======================================================================================
int Mech::getScore() const
{
return this->score;
}
// ======================================================================================
std::ostream& operator<< (std::ostream& os, const Mech& m)
{
os << "MECH #" << m.ID << " SPECIFICATIONS:\n";
os << "=========================\n";
os << " [ARMOR]:\n";
os << m.armorComponents << '\n';
os << " [WEAPON]:\n";
os << m.weaponComponents << '\n';
os << " [REACTOR]:\n";
os << m.reactorComponents << '\n';
os << " [AUX]:\n" ;
os << m.auxComponents << '\n';
return os;
}
// POPULATION ===========================================================================
// ======================================================================================
Population::Population (size_t size)
: size(size)
{
// The population size has to be an even number, so that we will later
// be able to pair up all the mechs with an opponent in a combat round.
if (size % 2 > 0) {
throw std::exception("The population size has to be an even number.");
}
// Fill the population with random mechs.
this->mechs.reserve(size);
for (size_t m = 0; m < size; m++)
{
this->mechs.push_back( std::unique_ptr<Mech> ( new Mech() ) );
}
this->sorted = true;
}
// ======================================================================================
void Population::createNextGeneration()
{
this->runMatches();
this->prune();
this->procreate();
}
// ======================================================================================
// Resets the all the mechs' scores and executes several match rounds.
void Population::runMatches()
{
for (auto& mech : this->mechs)
{
mech->resetScore();
}
const static int rounds = 40;
for (int m = 0; m < rounds; m++)
{
this->runMatchRound();
}
}
// ======================================================================================
// Randomly pairs all the mechs up with an opponent and makes the pairs execute a match.
void Population::runMatchRound()
{
// Create an index queue that will contain indices [0 .. size] into the mech vector in
// a randomised order, then use this queue to pair up the mechs into their matches.
std::vector<size_t> queue;
for (size_t m = 0; m < this->mechs.size(); m++)
{
queue.push_back(m);
}
std::random_shuffle(queue.begin(), queue.end());
while (!queue.empty())
{
size_t index1 = *queue.rbegin(); queue.pop_back();
size_t index2 = *queue.rbegin(); queue.pop_back();
Mech& mech1 = *this->mechs[index1];
Mech& mech2 = *this->mechs[index2];
// Execute the match:
MatchResult matchResult = Mech::match(mech1, mech2);
switch (matchResult)
{
case MATCH_RESULT_MECH_1_WINS:
mech1.addScore(5);
break;
case MATCH_RESULT_MECH_2_WINS:
mech2.addScore(5);
break;
case MATCH_RESULT_DRAW:
mech1.addScore(1);
mech2.addScore(1);
break;
}
}
this->sorted = false;
}
// ======================================================================================
// Calculates a score threshold based on the arithmetic mean between all the
// scores the population, and releases all the mechs that scored below this limit.
void Population::prune()
{
int scoreTotal = 0;
for (auto& mech : this->mechs) {
scoreTotal += mech->getScore();
}
int scoreThreshold = scoreTotal / this->mechs.size();
// For all the mechs below the score threshold, release the mech and reset its pointer in the
// population to indicate that it needs to be replaced with a new mech in the procreation step.
for (auto& mech : this->mechs)
{
if (mech->getScore() < scoreThreshold)
{
mech.reset();
}
}
}
// ======================================================================================
// Replaces all the mechs that were released in the 'prune' step with new mechs. Each survivor's
// score is used as the relative chance that it will be selected as a parent to a new mech.
void Population::procreate()
{
// Build up the parent pool – a container that we will use to randomly select
// parents. The parents are represented by their indices into the mech list.
WeightedSet<size_t> parents;
for (size_t index = 0; index < this->mechs.size(); index++)
{
if (this->mechs[index] != nullptr)
{
parents.insert(index, this->mechs[index]->getScore());
}
}
// For each mech that was released:
for (auto& mech : this->mechs)
{
if (mech != nullptr) continue;
Mech& parent1 = *this->mechs[ parents.random() ];
Mech& parent2 = *this->mechs[ parents.random() ];
mech = std::unique_ptr<Mech> ( new Mech (parent1, parent2) );
}
}
// ======================================================================================
// Returns the mech with the N-th best score.
const Mech& Population::getMech (size_t index)
{
if (index >= this->mechs.size())
{
throw std::exception("The provided mech index is out of bounds.");
}
this->sort();
return *this->mechs.at(index);
}
// ======================================================================================
// Sorts the mechs, winners to losers.
void Population::sort()
{
if (this->sorted) return;
std::sort(this->mechs.begin(), this->mechs.end(),
[](const std::unique_ptr<Mech>& m1, const std::unique_ptr<Mech>& m2)
{
return m1->getScore() > m2->getScore();
}
);
this->sorted = true;
}
// ======================================================================================
size_t Population::getSize() const
{
return this->size;
}
// WEIGHTED SET =========================================================================
// ======================================================================================
template<typename T>
void WeightedSet<T>::insert (T val, int w)
{
this->values[ this->maxValue() + w ] = val;
}
// ======================================================================================
// Returns a random element from the set, with the elements' weights
// serving as relative probabilities that the element will be selected.
template<typename T>
T WeightedSet<T>::random()
{
if (this->values.empty())
{
throw std::exception("An empty set cannot be queried for a random value");
}
// Generate a random number and use the cumulative weights map to
// locate the first element with its cumulative weight greater than the number.
int r = rand() % this->maxValue();
std::map<int, T>::iterator it = this->values.upper_bound(r);
if (it == this->values.end())
{
throw std::exception("WeightedSet integrity failure.");
}
return it->second;
}
// ======================================================================================
template<typename T>
int WeightedSet<T>::maxValue() const
{
return (this->values.empty()) ? 0 : this->values.crbegin()->first;
}
// COMPONENT NAMES ======================================================================
// ======================================================================================
// Functions that provides translations between the Armor/Weapon/Reactor/AuxComponent
// enumeration values and their human-readable component names.
template<>
std::string componentName (ArmorComponent ac)
{
switch (ac)
{
case COMP_ARMOR_BONUS: return "Thermo-Carbon-60 Armor Plates";
case COMP_ARMOR_REPAIR_AUTO: return "Auto-Replicative Fibres";
case COMP_ARMOR_REPAIR_BOTS: return "Nanobot Repair Module";
case COMP_ARMOR_MISSILE_INTERCEPTOR: return "AIMS: Anti-Missile System";
case COMP_ARMOR_LASER_ABSORB: return "Inverse EM Field";
default:
throw std::exception("The provided ArmorComponent does not have a textual description.");
}
}
// ======================================================================================
template<>
std::string componentName (WeaponComponent wc)
{
switch (wc)
{
case COMP_WEAPON_LASER_FAST: return "Black Adder: Fast Laser";
case COMP_WEAPON_LASER_HEAVY: return "Obliterator: Heavy Laser";
case COMP_WEAPON_MISSILE_LAUNCHER: return "Trebuchet: Missile Launcher";
default:
throw std::exception("The provided WeaponComponent does not have a textual description.");
}
}
// ======================================================================================
template<>
std::string componentName (ReactorComponent rc)
{
switch (rc)
{
case COMP_REACTOR_HEAT_SINK: return "White Noise Heat Sink";
case COMP_REACTOR_LOCK_ON: return "Advanced Missile Lock-on System";
case COMP_REACTOR_SCANNERS: return "Predictive Scanners";
case COMP_REACTOR_CALIBRATION: return "Explosive Laser Calibration Module";
default:
throw std::exception("The provided ReactorComponent does not have a textual description.");
}
}
// ======================================================================================
template<>
std::string componentName (AuxComponent ac)
{
switch (ac) {
case COMP_AUX_MISSILES: return "Ammo: Missiles";
case COMP_AUX_COUNTERMEASURES: return "Ammo: Countermeasures";
case COMP_AUX_NANOBOTS: return "Extra: Nanobots";
default:
throw std::exception("The provided AuxComponent does not have a textual description.");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Don't like all the switches (I suppose you are doing it for speed (doubt it makes a difference)).</p>\n\n<p>I would a couple of tests to see if using switches actually does make a significant difference, compared to virtual functions in terms of speed in your use case scenarios.</p>\n\n<p>But it (switches) makes the code a mess and hard to compartmentalize (maintain/fix), I would use classes to encapsulate meaning and prevent bugs. It also makes bugs more likely.</p>\n\n<p>Prefer to throw <code>std::runtime_error</code> rather than <code>std::exception</code>. It narrows down the type you need to catch at runtime. PS if you are really going for speed then exceptions can be more costly than virtual function calls (but measure).</p>\n\n<p>I prefer putting const on the right (there is one corner case where it matters). But the community is still split over this so you take it or leave it:</p>\n\n<pre><code>std::ostream& operator<< (std::ostream& os, const Components<T>& c) \n\nI prefer:\n\nstd::ostream& operator<< (std::ostream& os, Components<T> const& c) \n // ^^^^^^\n\n// Its a const ref.\n</code></pre>\n\n<p>It also makes reading types easier. As you read types from right to left and const always binds to the left (unless it is the first item then in binds right).</p>\n\n<pre><code>// Components<T> const&\n// ^ Reference to\n// ^^^^^ const\n// ^^^^^^^^^^^^^ Components<T>\n\n char const * const data = \"Plop\";\n char const * const& data1 = data;\n// ^ Reference to\n// ^^^^^ Const\n// ^ Pointer to\n// ^^^^^ Const\n// ^^^^ char\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:33:09.347",
"Id": "65588",
"Score": "0",
"body": "Thanks. The reason I use switches is that I think that in this case the code actually reads more easily this way than with a polymorphic approach; the combat system here is trivial, and to represent it with virtual methods would imho be an overkill. Good point about the `std::runtime_error`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T02:46:42.197",
"Id": "65621",
"Score": "0",
"body": "@electroLux: [Do polymorphism or conditionals promote better design?](http://stackoverflow.com/q/234458/14065)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:36:52.937",
"Id": "65963",
"Score": "0",
"body": "I had to sleep on your advice, but in the end I took it and rewrote the code. For instance, Weapon is now an abstract class that is derived into LaserWeapon and MissileWeapon. The code does look better."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:58:38.057",
"Id": "39169",
"ParentId": "39141",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T11:24:34.200",
"Id": "39141",
"Score": "7",
"Tags": [
"c++",
"c++11",
"ai"
],
"Title": "Follow-up: C++ 'evolutionary AI' implementation"
}
|
39141
|
<p>The exercise is explained in the comments. Do you have any suggestion? </p>
<pre><code>package com.atreceno.it.javanese.attic;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Imagine you have several copies of the same page of text. Someone rips each
* page up into fragments. Write a program to reassemble a given set of text
* fragments into their original sequence. The program should have a main method
* accepting the path to a text file containing text fragments separated by a
* semicolon. Each line in the file is a different test case.
*
* @author atreceno
*
*/
public class Defragmenter {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(reassemble(line));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Assemble the fragments in the correct order.
*
* @param line
* String containing the fragments of the document.
* @return the line in the correct order.
*/
private static String reassemble(String line) {
// Each line contains text fragments separated by a semicolon.
String[] fragments = line.split(";");
List<String> list = new ArrayList<String>(Arrays.asList(fragments));
// Sort the fragments by size
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
// Pick up the first fragment
String text = list.get(0);
list.remove(0);
// Start the algorithm
for (int i = list.size() - 1; i >= 0; i--) {
int max = 0;
int idx = 0;
int match = 0;
int m = 0;
int n = 0;
for (int j = list.size() - 1; j >= 0; j--) {
String findMe = list.get(j);
m = text.length();
n = findMe.length();
for (int k = 1 - findMe.length(); k < text.length(); k++) {
if (k < 0) { // Prefix
int l = n + k;
if (text.regionMatches(0, findMe, -k, l)) {
if (l > max) {
idx = k;
max = l;
match = j;
}
}
} else { // Suffix
int l = k + n <= m ? n : m - k;
if (text.regionMatches(k, findMe, 0, l)) {
if (l > max) {
idx = k;
max = l;
match = j;
}
}
}
}
}
if (idx < 0) { // Prefix
text = list.get(match).substring(0, -idx) + text;
} else if (idx > m - list.get(match).length()) { // Suffix
text = text + list.get(match).substring(m - idx);
}
list.remove(match);
}
return text;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T15:39:46.837",
"Id": "129631",
"Score": "0",
"body": "[What you can and cannot do after receiving answers.](http://meta.codereview.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c/1765#1765)"
}
] |
[
{
"body": "<p>Your code is really good and very well written. I think that's why you haven't received a response; not much to critique! You have good comments, good style, pretty much good everything. I wish I saw code like this in my production environment.</p>\n\n<p>The only thing I noticed that you might clean your code up a bit is this part:</p>\n\n<pre><code>int max = 0;\nint idx = 0;\nint match = 0;\nint m = 0;\nint n = 0;\n</code></pre>\n\n<p>You can shorten this long block of variable declarations as the following. Makes the code look a bit cleaner.</p>\n\n<pre><code>int max = 0, idx = 0, match = 0, m = 0, n = 0;\n</code></pre>\n\n<p>Also, if possible, could you give the variables better names? The first three are fairly self-explanatory, but once you get into all your random letters, it gets pretty hard to follow what you're trying to do in your code. For example:</p>\n\n<pre><code>int l = k + n <= m ? n : m - k;\n</code></pre>\n\n<p>Without having written the code, this statement takes awhile to figure out. It would go a long way to have meaningful variable names rather than random letters. Java is supposed to be verbose, so don't be afraid to make it so.</p>\n\n<p>I won't say I understand what your code is doing with 100% certainty, but you can see how something like this is a bit more understandable, hopefully:</p>\n\n<pre><code>int length = lookBack + findMeLength <= trueLength ? findMeLength : trueLength - lookBack\n</code></pre>\n\n<p>But seriously, very high quality code!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:46:55.173",
"Id": "65685",
"Score": "0",
"body": "If you figured out their meaning, could you suggest better names for them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T15:08:56.477",
"Id": "65688",
"Score": "0",
"body": "Thanks for adding names. It's the fact I couldn't understand it (because of the variable names) that made me not want to review it, and it's the reason I can't call it \"high quality code\". IMO source code should be written for humans to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T15:09:50.047",
"Id": "65689",
"Score": "1",
"body": "@ChrisW Haha, yeah. But if the names of variables in those tightly-nested loops is the only thing to critique, still not very bad. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:43:32.523",
"Id": "39223",
"ParentId": "39143",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:25:56.747",
"Id": "39143",
"Score": "7",
"Tags": [
"java"
],
"Title": "Fragments of paper"
}
|
39143
|
<p>Asserts work differently in different langauges, and there are different variants of them in testing libraries. But the commonality of them all is that if the predicate passed to it evaluates as false then the user will be notified of this fact, sometimes by program termination.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:38:47.480",
"Id": "39145",
"Score": "0",
"Tags": null,
"Title": null
}
|
39145
|
An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:38:47.480",
"Id": "39146",
"Score": "0",
"Tags": null,
"Title": null
}
|
39146
|
<p>I am practicing my recursion skills as I think I am really weak in this area.</p>
<p>I have written the following Java class whose purpose is to reverse a string but to do it 'in-place' - i.e. no additional arrays. I have two implementations - one iterative and one recursive. Why would I choose one implementation over the other?</p>
<p>Also, does my recursive solution use tail call optimization? </p>
<pre><code>public class TestRecursion {
public static void reverseIter(char[] in) {
int start = 0;
int end = in.length - 1;
while(start < end) {
swap(start, end, in);
start ++;
end--;
}
System.out.println("iteration result: "+in);
}
public static char[] reverseRecur(char[] in, int start, int end) {
if (end < start) return in;
else {
swap(start, end, in);
return reverseRecur(in, ++start, --end);
}
}
private static void swap(int start, int end, char[] input) {
char c1 = input[start];
char c2 = input[end];
input[start] = c2;
input[end] = c1;
}
public static void main(String[] args) {
char[] input = "testy".toCharArray();
reverseIter(input);
char[] input2 = "testy".toCharArray();
char[] out = reverseRecur(input2, 0, input2.length-1);
System.out.println("recursive result: "+out);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:57:19.127",
"Id": "65523",
"Score": "0",
"body": "The JVM doesn't support full TCO and javac doesn't even attempt the partial TCO simulation that Scala uses. Java is not a good language to use recursion in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:31:43.977",
"Id": "65582",
"Score": "0",
"body": "Move your `S.o.println()` out of `reverseIter()` into `main()`, not just for consistency with `reverseRecur()`, but also because it is a good habit to write functions without side effects whenever possible."
}
] |
[
{
"body": "<p>In this case Iteration is preferable.</p>\n\n<p>If your input string would cause StackOverflowError exceptions.\nBesides, iteration would be much faster because it does not require the overhead of creating a stack frame with the parameters, calling the function, and returning the value. Since Java does not support tail recursion, the function call cannot be optimized away.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T13:30:57.637",
"Id": "39149",
"ParentId": "39147",
"Score": "2"
}
},
{
"body": "<p>First some clean-up is needed on your code. The iterative method first:</p>\n\n<ul>\n<li>do not call <code>System.out.println(\"iteration result: \"+in);</code> as this will do a <code>toString()</code> on <code>in</code> and you will get something like <code>iteration result [C@b312fca6</code>. Use the following instead: <code>System.out.println(\"iteration result: \" + Arrays.toString(in));</code></li>\n<li><code>start</code> and <code>end</code> are not great names because, after the first loop, they no longer represent the start and end positions. Consider <code>left</code> and <code>right</code> as alternatives.</li>\n<li><p>In this case, a double-value <code>for</code> loop is a good candidate for readability:</p>\n\n<pre><code>for (int left = 0, right=in.length - 1; left < right; left++, right--) {\n swap(left, right, in);\n}\n</code></pre></li>\n<li><p>alternatively, a single value iteration could be useful:</p>\n\n<pre><code>for (int i = (in.length - 1) / 2; i >= 0; i--) {\n swap(i, in.length - 1 - i, in);\n}\n</code></pre></li>\n</ul>\n\n<p>in the recursive call, you have some other problems:</p>\n\n<ul>\n<li>The character array is passed in, and modified in place. There is no reason to return it as well. The method should return <code>void</code>.</li>\n<li>you should simplify the condtitional statement to make the tail-recursion obvious... since the <code>true</code> part of the <code>if</code> condition returns from the method, there is no need for an else block</li>\n<li>you should not be modifying the actual start and end values 'in place' as this requires some extra work. In the recursive call you can simply do <code>start + 1</code> instead of <code>++start</code>.</li>\n<li>I prefer using the <code>final</code> keyword on recursive components to make sure you only modify what you should be....</li>\n</ul>\n\n<p>Consider the recursive method:</p>\n\n<pre><code> public static void reverseRecur(final char[] in, final int left, final int right) {\n if (left >= right) {\n return;\n }\n swap(left, right, in);\n reverseRecur(in, left + 1, right - 1);\n }\n</code></pre>\n\n<p>Now the 'tail' part is obvious.</p>\n\n<p>As for whether tail-call optimization is performed, I don't know. I expect that the compiler may completely re-write this recursive function as an iteration..... which leads on to the next question: Which one is better?</p>\n\n<p>In this case, the iterative solution is best. It has the least impact on resources (stack space), and will be fastest. It is also the most intuitive (readable).</p>\n\n<p>Your iterative solution would be preferable </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:01:33.580",
"Id": "65545",
"Score": "0",
"body": "I actually think the while is more readable than the double-value for (I guess I'm just used to for-loops having *one* iteration variable). Besides this, nice review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:25:31.427",
"Id": "65581",
"Score": "0",
"body": "Strings don't read left-to-right in some languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:39:23.423",
"Id": "65583",
"Score": "0",
"body": "@200_success true, but, left and right refer to the array indices, and will work equally well for character arrays that contain right-to-left text."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:00:45.843",
"Id": "65585",
"Score": "0",
"body": "Programmers who work with right-to-left text might not think of arrays as being laid out left-to-right either. ☺︎"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:12:42.787",
"Id": "39153",
"ParentId": "39147",
"Score": "5"
}
},
{
"body": "<p>Some nitpicks about your <code>reverseRecur()</code>.</p>\n\n<p>I would name the parameters <code>beginIndex</code> and <code>endIndex</code>. The alternative pair would be <code>start</code> – <code>finish</code>, but C++ chooses <code>begin</code> – <code>end</code>, so I think it would be more conventional.</p>\n\n<p>Another convention in Java (and most languages with 0-based arrays) is to use inclusive-exclusive intervals. That is, <code>begin</code> would be the index of the first character to be included in the reversal, and <code>end</code> would be one greater than the index of the last character to be included in the reversal. This convention is used, for example, with <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)\" rel=\"nofollow\"><code>String.substring(int beginIndex, int endIndex)</code></a>. It's also nice to remove the <code>-1</code> from <code>main()</code>.</p>\n\n<pre><code>public static char[] reverseRecur(char[] in, int beginIndex, int endIndex) {\n if (endIndex <= beginIndex) return in;\n swap(in, beginIndex, endIndex);\n return reverseRecur(in, ++beginIndex, --endIndex);\n}\n</code></pre>\n\n<p>As for <code>swap()</code>, I would put the arguments in the same order for consistency, but rename the parameters. There is no sense of \"beginning\" or \"ending\" when swapping two elements. By connotation, <code>i</code> and <code>j</code> are array indexes. You can get away with just one temporary variable.</p>\n\n<pre><code>private static void swap(char[] in, int i, int j) {\n char tmp = in[i];\n in[i] = in[j];\n in[j] = tmp;\n}\n</code></pre>\n\n<p>For consistency, also offer</p>\n\n<pre><code>public static void reverseIter(char[] in, int beginIndex, int endIndex) { ... }\n</code></pre>\n\n<p>(Alternatively, declare <code>reverseRecur(char[], int, int)</code> to be a <code>private</code> helper to <code>public reverseRecur(char[])</code>.)</p>\n\n<hr>\n\n<p>As for the question of whether iteration or recursion is more appropriate… iteration is almost always preferable in Java (and other languages of the C family). Since there is no support for tail call optimization, recursion will fail for large inputs with a stack overflow. There are some situations where recursion is appropriate: when you have an algorithm that explores a tree and requires backtracking, and you know that the tree depth will be reasonable, and the problem is too complex to convert into an iterative solution.</p>\n\n<p>String reversal isn't one of those situations, but it's good to get some practice with recursion for when you eventually encounter such a situation. ☺︎</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:23:39.827",
"Id": "39178",
"ParentId": "39147",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:44:23.447",
"Id": "39147",
"Score": "8",
"Tags": [
"java",
"optimization",
"recursion",
"iteration"
],
"Title": "Reversing a string in-place - recursion or iteration?"
}
|
39147
|
<p>Visual Studio somehow optimizes the below code to be 20 times faster (release with optimization vs. release with no optimization). What could it be doing?</p>
<pre><code>for (unsigned n = 1; n != units.size(); n++)
for (unsigned j = 0; j != (units.size() - n); j++)
{
unsigned sizesMap[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (auto it = units.begin() + n; it != (units.begin() + (n + j + 1)); it++)
{
for (unsigned k = 1; k != 11; k++)
{
sizesMap[k] += (*it).sizes[k];
}
}
//do something with sizesmap
}
</code></pre>
<p>Unit class has a sizes array (10 members). The first two loops give all the possible sequences of "unit" in the vector. (1-2, 1-3, 1-100, 2-3, 2-4, 2-100, etc), which I then compare with one another using the sizesmap. I tried unrolling the inner loop and just adding sizesmap 10 times, that gave about 2% performance improvement. I compiled with Visual Studio 2013. Could it be vectorization (adds the (*it).sizes to sizesmap in one go)? Or are the loops ineffective somehow?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:04:46.673",
"Id": "65505",
"Score": "0",
"body": "is it intentional that `sizesMap[0]` is untouched in the inner loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:40:07.213",
"Id": "65519",
"Score": "0",
"body": "The logic of the data has an order from 1 to 10 therefore I left the 0 member out. It's just for my own convenience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:07:33.890",
"Id": "65548",
"Score": "2",
"body": "Please add the type (declaration) of your `units` variable, or `Unit` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:31:38.313",
"Id": "65554",
"Score": "0",
"body": "There are so many optimizations that can be done on loops. Unrolling/code-hoisting/loop-reversal/array-remapping/predictive branching marks etc. the list is long and you really need to look at a compiler optimizing book. http://www.amazon.com/Optimizing-Compilers-Modern-Architectures-Dependence-based/dp/1558602860"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:11:55.280",
"Id": "65566",
"Score": "0",
"body": "When you do \"something\" with `sizesMap`, do you modify the entries of `sizesMap` or not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:26:01.543",
"Id": "65614",
"Score": "0",
"body": "I store the sizesMap in a separate vector along with the numbers of the first and last unit for each sequence I analyze."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T01:53:04.827",
"Id": "65619",
"Score": "0",
"body": "It may help to turn on Auto-Vectorizer Reporting. The compiler can output informational message for loops that are vectorized. See: [this MSDN documentation](http://msdn.microsoft.com/en-us/library/jj614596.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:45:27.043",
"Id": "65645",
"Score": "0",
"body": "I added that flag and no, it doesn't vectorize nor parallelize. But I parallelized it myself (parallel_for) and I got a 4-times speed increase, that will have to do, I guess."
}
] |
[
{
"body": "<p>Educated guesses are: in this case, <a href=\"http://en.wikipedia.org/wiki/Loop_unwinding\" rel=\"nofollow noreferrer\">loop unrolling</a> will probably feature in a big way, and may account for most of the 20X improvement. Additionally, with the loop unroll it may make other things like <a href=\"http://en.wikipedia.org/wiki/Instruction-level_parallelism\" rel=\"nofollow noreferrer\">instruction-level-parallelism</a> more effective, and even <a href=\"http://en.wikipedia.org/wiki/Cache-line\" rel=\"nofollow noreferrer\">cache-line management</a>.</p>\n<p>There are essentially only two comments to make on your situation:</p>\n<ol>\n<li>non-optimized code is going to be slower.... you pay money for the compiler for a reason, lots of smart people make it 'go fast'.</li>\n<li>you need to inspect the instruction-level code (asm) generated by the compiler in order to understand the main differences between the two versions ... anything else is just educated guessing.</li>\n</ol>\n<h2>Edit</h2>\n<p>FWIW, Purely for interest sake.... , you may want to try to manually unroll your inner-most loop, and see if this makes a significant difference:</p>\n<pre><code> for (auto it = units.begin() + n; it != (units.begin() + (n + j + 1)); it++)\n {\n sizesMap[1] += (*it).sizes[1];\n sizesMap[2] += (*it).sizes[2];\n sizesMap[3] += (*it).sizes[3];\n sizesMap[4] += (*it).sizes[4];\n sizesMap[5] += (*it).sizes[5];\n sizesMap[6] += (*it).sizes[6];\n sizesMap[7] += (*it).sizes[7];\n sizesMap[8] += (*it).sizes[8];\n sizesMap[9] += (*it).sizes[9];\n sizesMap[10] += (*it).sizes[10];\n sizesMap[11] += (*it).sizes[11];\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:03:10.953",
"Id": "65526",
"Score": "0",
"body": "The problem is that I intend to frequently use this basic algorithm in different forms and I will need to debug it A LOT, and the long waits for the non-optimized builds could get really annoying. I really wish I could figure this one out thoroughly, unfortunately I can't read assembler. I understand that adding \"register\" is not really going to help anything, so I'll probably have to look into multithreading options."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:14:20.407",
"Id": "65549",
"Score": "0",
"body": "You can try to manually unroll the innermost loop, and see what that gets you.... I will edit my answer...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:34:00.387",
"Id": "65556",
"Score": "1",
"body": "@user34888: Don't try and write code to be optimized. Write code to be readable. The compiler has so many techniques that if you try to do something tricky then you may hit one but cause the compiler to reject a couple of others. Write clean simple code; the compiler are very sophisticated and will do the rest and apply a whole bunch of techniques."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:50:50.763",
"Id": "65610",
"Score": "0",
"body": "I did the unrolling already, I mentioned that - only 2% improvement. Of course, the compiler might be unrolling the outer loops as well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T13:53:40.207",
"Id": "39151",
"ParentId": "39148",
"Score": "3"
}
},
{
"body": "<p>You declared <code>sizesMap[11]</code>, but initialized it with 13 entries. If that works at all, it might be overwriting some neighbouring memory. You could simply write <a href=\"https://stackoverflow.com/q/629017/1157100\"><code>sizesMap[11] = { 0 }</code></a>.</p>\n\n<p>Your code would be easier to understand if you universally added <code>n</code> to <code>j</code>:</p>\n\n<pre><code>for (unsigned n = 1; n != units.size(); n++)\n for (unsigned j = n; j != units.size(); j++)\n {\n unsigned sizesMap[11] = { 0 };\n\n for (auto it = units.begin() + n; it != units.begin() + (j + 1); it++)\n {\n for (unsigned k = 1; k != 11; k++)\n {\n sizesMap[k] += (*it).sizes[k];\n\n }\n }\n //do something with sizesmap\n }\n</code></pre>\n\n<p>It's also more idiomatic C++ to write:</p>\n\n<pre><code>for (auto i = units.begin() + 1; i != units.end(); ++i) {\n for (auto j = i; j != units.end(); ++j) {\n unsigned sizesMap[11] = { 0 };\n for (auto it = i; it != j + 1; ++it) {\n for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {\n sizesMap[k] += it->sizes[k];\n }\n }\n //do something with sizesMap\n }\n }\n</code></pre>\n\n<p>Assuming that when you \"do something with <code>sizesMap</code>\", you don't overwrite any of its entries, you can build on top of the <code>sizesMap</code> you previously constructed.</p>\n\n<pre><code> for (auto i = units.begin() + 1; i != units.end(); ++i) {\n unsigned sizesMap[11] = { 0 };\n for (auto j = i; j != units.end(); ++j) {\n for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {\n sizesMap[k] += j->sizes[k];\n }\n //do something non-destructive with sizesMap\n }\n }\n</code></pre>\n\n<p>I think you could even go further:</p>\n\n<pre><code> unsigned sizesMap[11] = { 0 };\n for (auto i = units.begin() + 1; i != units.end(); ++i) {\n for (auto j = i; j != units.end(); ++j) {\n for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {\n sizesMap[k] += j->sizes[k];\n }\n //do something non-destructive with sizesMap\n }\n for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {\n sizesMap[k] -= i->sizes[k];\n }\n }\n</code></pre>\n\n<p>Is the compiler doing all that for you automatically? It seems a bit freaky that it could be smart enough to do so. The only way to tell what the optimizer is doing is to inspect its assembler output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:48:55.833",
"Id": "65609",
"Score": "0",
"body": "I don't think you correctly understood what I was trying to do. I'm calculating this sizesmap for each separate sequential sequence of these \"units\" that it is possible to have and then I store it in a vector of sizemaps so that I can compare them to each other. The point is to find a sequence of units where these \"sizes\" change the least. Like nr. 23 to nr. 47. The vector of the sizemaps is not relevant here because the profiler shows that all the time is spent in these few lines. (the 13 members is a mistake that I made in adapting the code for reviewing it here.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:21:58.030",
"Id": "65613",
"Score": "0",
"body": "I corrected the (n+j) as you suggested in the first example, but I'm unsure about the iterators in the outer loops. Is the \"iterator arithmetic\" faster? I also need the integers because I store them for reference (the sizesmap vector also contains the beginning and end unit for each sequence analyzed). I could change that but I doubt that I would get a speed increase because I initially had it != units.begin() + n + j + 1 and I got a big speed boost just from putting the parentheses around. So adding the integers was a lot faster than adding iterators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:37:32.623",
"Id": "65640",
"Score": "0",
"body": "Redefining `j` to include `n` wouldn't make it significantly faster, nor does would changing it to use the iterator syntax. With those moves, I was mainly aiming for readability so that I could understand what was going on. What _could_ make a significant performance difference is changing the code to avoid rebuilding `sizesMap` from scratch every single iteration. Consider: how does one `sizesMap` differ from the `sizesMap` of the previous round? Then change your code to do the minimum necessary to get there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:43:56.550",
"Id": "65644",
"Score": "0",
"body": "I don't think I can do that. Right now sizesmap doesn't change that much, but in the future I will be adding weighed calculations, with every new added unit having a lot more weight so that I could precisely catch the break line where the statistical unit.sizes pattern changes suddenly (example: 100 units with a regular sizes pattern, then suddenly 1 with irregular - doesn't change the overall picture enough to be \"caught\", so it has to be multiplied to be worth at least a third of the previous units put together). So each sizesmap is basically unique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:32:21.463",
"Id": "65651",
"Score": "0",
"body": "But you're right - at this point, the compiler could possibly optimize that way: the sizesmap for units 1-21 can be obtained by just adding unit 21 to sizesmap for units 1-20. That would actually be a cheat because it won't work when I add the weighing algorithm."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:36:01.190",
"Id": "39173",
"ParentId": "39148",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T12:56:17.910",
"Id": "39148",
"Score": "2",
"Tags": [
"c++",
"performance",
"vectors",
"iteration"
],
"Title": "Optimizing a vector loop"
}
|
39148
|
<p>I've a application which runs with two threads. The main thread runs in one infinity-while-loop:</p>
<pre><code>while (true) {
try {
ArrayList<Info> infoList = zabbixHandler.APIRequest();
handleInfo.handleInformation(infoList);
Thread.sleep(5000);
}
}
</code></pre>
<p>The second thread, which uses more than 50% of my CPU, must be able to stop and run again, which I asked already with <a href="https://stackoverflow.com/questions/20638617/how-can-i-stop-and-start-again-a-thread-correctly">this question on Stack Overflow</a>.</p>
<p>The solution works perfectly, but as I already said, it uses >50% of the CPU. Here are the two loops of the solution: </p>
<pre><code>private volatile boolean finished = true;
public void run() {
Process p;
while (true) {
// loop until the thread is finished
while (!finished) {
try {
// let every lamp shine...
p = Runtime.getRuntime().exec(onCommand + "-green");
p.waitFor();
// ... for 0.5 seconds ...
Thread.sleep(500);
// ... then turn it off again ...
p = Runtime.getRuntime().exec(offCommand + "-green");
p.waitFor();
// ... and let the next lamp shine
p = Runtime.getRuntime().exec(onCommand + "-yellow");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-yellow");
p.waitFor();
p = Runtime.getRuntime().exec(onCommand + "-red");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-red");
p.waitFor();
p = Runtime.getRuntime().exec(onCommand + "-blue");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-blue");
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>How could I reduce the use of CPU while retaining the functionality? </p>
<p><strong>EDIT</strong>:<br>
The <code>finish</code> element will be changed by a getter and setter. Because it is volaitle, it shouldn't get complications.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:25:41.403",
"Id": "65510",
"Score": "0",
"body": "please provide the actual code inside the second code block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:07:03.120",
"Id": "65514",
"Score": "0",
"body": "Are you aware that `Thread.sleep(milliseconds)` is a rough estimation only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T15:28:51.280",
"Id": "65517",
"Score": "2",
"body": "where does `finished` change to `true`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:04:13.020",
"Id": "65527",
"Score": "0",
"body": "How are you measuring that the second thread takes `> 50%` of the time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:10:15.290",
"Id": "65530",
"Score": "0",
"body": "-1 vote because you are not showing us the most important part of the code: how does the variable `finished` get declared, and how is it modified. Will remove -1 when question is corrected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T12:24:44.397",
"Id": "65661",
"Score": "0",
"body": "@rolfl: The declaration is already postet in the top of the second code block. With my edit now I added, that I change the boolean with a simple getter and setter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T12:25:31.887",
"Id": "65662",
"Score": "0",
"body": "@Malachi: I though this isn't an important part sorry. I edited the question. I change it with a simple getter and setter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T15:08:06.267",
"Id": "65687",
"Score": "0",
"body": "@LongJohn that isn't telling us how you are getting or setting `finish` and how the loop will be escaped. somewhere in your loop you have to have an \"escape clause\""
}
] |
[
{
"body": "<p>don't use a busy wait but instead use a wait condition (here using the built-in monitor in Object):</p>\n\n<pre><code>public void run() {\n while(true){\n while(!finished){\n // do stuff\n }\n try{\n synchronized(this){\n while(finished)\n wait();//wait until notify gets called in startThread\n }\n }catch(InterruptedException e){}\n }\n\n}\n\npublic synchronized void startThread() {\n finished = false;\n notify();//wake up the wait\n}\n</code></pre>\n\n<p>I note that <code>finished</code> should remain volatile. </p>\n\n<p>I put the <code>wait()</code> in the <code>synchronized</code> block in a while loop to avoid the race where the thread has just tested the first while condition and is about to enter the <code>synchronized</code> block but <code>startThread()</code> then gets called; putting <code>finished</code> back to <code>false</code> and the thread waiting anyway. This can lead to the thread blocking while waiting on a <code>notify()</code> that never happens.</p>\n\n<p>To help any more I need to see what exactly happens inside that while loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:01:34.677",
"Id": "65525",
"Score": "0",
"body": "This answer makes no sense to me.... where is there a **spin lock**?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:04:43.703",
"Id": "65528",
"Score": "1",
"body": "@rolfl when `finished` is true the thread keeps spinning in the outer while but never getting in the inner while, this is equivalent to `while(true){while(finished){}/*do stuff*/}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:07:09.803",
"Id": "65529",
"Score": "2",
"body": "Ahh, that makes sense, but why didn't you say that in your answer? ... ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:12:31.583",
"Id": "65531",
"Score": "0",
"body": "Assuming you are right about the finished variable (which I suspect you are), then the better/right/modern solution would be using Reentrant-lock and conditions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:17:00.907",
"Id": "65533",
"Score": "0",
"body": "@rolfl maybe but I think that's a bit overkill in this case"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T12:28:15.273",
"Id": "65663",
"Score": "0",
"body": "Thank you for your answer. Not it really working well, the cpu usage is reduced. Sadly i'm unable to +1 you, but the accepted answer you will get."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:28:45.627",
"Id": "39155",
"ParentId": "39152",
"Score": "9"
}
},
{
"body": "<p>The right tool for this job in Java6 and newer is the combination of a <code>ReentrantLock</code> and a <code>Condition</code></p>\n\n<p><strong>EDIT:</strong> You should also consider changing your Process-running code.... consider creating a function:</p>\n\n<pre><code>private static void runAndWaitFor(String command) {\n Process p = Runtime.getRuntime().exec(command);\n p.waitFor();\n}\n</code></pre>\n\n<p>Then, in your blinking loop, you can reduce your code duplication with:</p>\n\n<pre><code> // let every lamp shine...\n runAndWaitFor(onCommand + \"-green\");\n\n // ... for 0.5 seconds ...\n Thread.sleep(500);\n\n // ... then turn it off again ...\n runAndWaitFor(offCommand + \"-green\");\n // ... and let the next lamp shine\n runAndWaitFor(onCommand + \"-yellow\");\n\n ...... etc. .....\n</code></pre>\n\n<p>Now, even with the simpler code, you still have the two threads, one needs to wait until a condition is met, and when the condition is met, it needs to execute some work until the condition is reverted.</p>\n\n<p>In your 'working' thread you want a method to call <code>workStarted()</code> which will start the lights blinking, and then <code>workCompleted()</code> which will stop the lights.</p>\n\n<p>The pattern to use is:</p>\n\n<pre><code>import java.util.concurrent.locks.Condition;\nimport java.util.concurrent.locks.ReentrantLock;\n\n\npublic class ThreadBlocker implements Runnable {\n\n private final ReentrantLock mylock = new ReentrantLock();\n private final Condition workready = mylock.newCondition();\n private boolean finished = true;\n\n public void workStarted() {\n mylock.lock();\n try {\n finished = false;\n workready.signalAll();\n } finally {\n mylock.unlock();\n }\n }\n\n public void workCompleted() {\n mylock.lock();\n try {\n finished = true;\n } finally {\n mylock.unlock();\n }\n }\n\n private void waitForWork() throws InterruptedException {\n mylock.lock();\n try {\n while (finished) {\n workready.await();\n }\n } finally {\n mylock.unlock();\n }\n }\n\n public void run () {\n try {\n while (true) {\n // the following method will block unless there is work to do.\n waitForWork();\n\n // change your lights in here.\n\n }\n } catch (InterruptedException ie) {\n // do some handling for the thread.\n ie.printStackTrace();\n Thread.currentThread().interrupt();\n }\n }\n\n\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:48:55.507",
"Id": "65535",
"Score": "0",
"body": "you don't need to `signalAll` in `workCompleted()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:59:39.937",
"Id": "65537",
"Score": "0",
"body": "is this sort of like having two objects where one goes and when it's done it starts (calls) the other, and when the other is done it starts (calls) the first? creating it's own loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:06:42.173",
"Id": "65538",
"Score": "0",
"body": "Not really, this is like a motion-sensitive security light. If there is motion, it turns the light on for a few seconds. At the end of that time, if there is ongoing motion, it stays on for a few more seconds. If there is no motion, it turns off."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:34:30.850",
"Id": "39160",
"ParentId": "39152",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39155",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:04:27.307",
"Id": "39152",
"Score": "4",
"Tags": [
"java",
"performance",
"multithreading"
],
"Title": "Decrease CPU usage in while loop"
}
|
39152
|
<p>I am working on a haskell exercise where I have to compute the amount of people riding a rollercoaster in a day. I have the following data: the number of rides in a day, the number of seats, and the composition of the queue.</p>
<p>The queue is a list of groups. During each ride, the first few groups of the list enter the ride. A group always rides together. The total number of people cannot exceed the number of seat during one ride.</p>
<p>After the ride, the groups go to the end of the queue (in the same order).</p>
<p>So the exercise is not really hard. But when numbers get big, my haskell implementation becomes quite slow. I have used the profiler to improve some parts, but I wasn't able to spot a bottleneck.</p>
<p>The first time I ran the profiler, the part that was parsing the groups was slow. Here is my second version (1st one was <code>replicateM n $ read <$> getLine</code>):</p>
<pre><code>getGroups :: IO [Int]
getGroups = do
c <- TIO.getContents
return $ readInts c
readInts :: T.Text -> [Int]
readInts s
| T.null s = []
| otherwise = val : rest where
(Right (val, s')) = TR.decimal s
rest = if T.null s'
then []
else (readInts $ T.tail s')
</code></pre>
<p>Another cost center is the actual computing function:</p>
<pre><code>type Queue = Seq.Seq Int
data Roller = Roller Int Int Queue
compEarn :: Roller -> Int
compEarn (Roller placeNbr rideNbr groups) = go rideNbr groups 0
where
go turnsLeft queue accum
| turnsLeft == 0 = accum
| otherwise = let
(riding, waiting) = breakQueue placeNbr queue
newQueue = waiting Seq.>< riding
newAccum = accum + (F.sum riding)
in go (turnsLeft - 1) newQueue newAccum
breakQueue :: Int -> Queue -> (Queue, Queue)
breakQueue placeNbr queue = go Seq.empty queue placeNbr where
go riding waiting spaceLeft = case Seq.viewl waiting of
Seq.EmptyL -> (riding, waiting)
group Seq.:< rest -> if spaceLeft' < 0
then (riding, waiting)
else go (riding Seq.|> group) rest spaceLeft'
where
spaceLeft' = spaceLeft - group
</code></pre>
<p>Am I missing something obvious regarding performances with this program?</p>
|
[] |
[
{
"body": "<p>So I found a few improvements which solve my problem. First, I used a vector to represent the queue, and a rolling index to store the head of the queue:</p>\n\n<pre><code>type Queue = V.Vector Int\ndata RollingQ = RollingQ Queue Int\n\ncurrentVal :: RollingQ -> Int\ncurrentVal (RollingQ v i) = v V.! i\n\nnextVal :: RollingQ -> RollingQ\nnextVal (RollingQ v i)\n | i == V.length v = RollingQ v 0\n | otherwise = RollingQ v (i + 1)\n</code></pre>\n\n<p>This led me to realize that there might be a cycle in the computation: if the number of rides is bigger than the number of groups in the queue, the state of the queue loops. I used a Map to remember information about the computation to detect the loop and compute a shortcut to get the result almost immediately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:55:48.067",
"Id": "39301",
"ParentId": "39157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39301",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:31:05.620",
"Id": "39157",
"Score": "2",
"Tags": [
"optimization",
"haskell"
],
"Title": "optimizing a rollercoaster queue"
}
|
39157
|
<p>I would like to test the following garbage collector code on a database of sessions.
It should be following the conditions below:</p>
<ul>
<li>if 'remember me' is enabled by the user, then it should delete all rows which are not active within 2 weeks.</li>
<li>if 'remember me' is disabled by the user, then it should delete all rows which are not active within 30 minutes.</li>
</ul>
<p>I have times inserted in the <code>LAST_ACTIVITY</code> column, with the <code>UNIX_TIMESTAMP()</code> format.</p>
<pre><code>public function gc( $maxlifetime )
{
$this->conn->SQL( 'DELETE FROM session WHERE (LAST_ACTIVITY < ? AND REMEMBERUSER = ?) OR (LAST_ACTIVITY < ? AND REMEMBERUSER = ?)' ,
[ strtotime('-30 minutes'), 'N' , strtotime('-2 weeks'), 'Y']);
return true;
}
</code></pre>
<p>Are the <code>AND</code> or <code>OR</code> operators working properly? I would only like to test the SQL query, and not the gc method.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T19:48:55.440",
"Id": "72645",
"Score": "0",
"body": "This probably belongs on StackOverflow."
}
] |
[
{
"body": "<h3>Observations</h3>\n\n<ul>\n<li>Your <code>$maxlifetime</code> parameter is unused.</li>\n<li>One of the conditions is redundant: any session older than two weeks should be discarded unconditionally.</li>\n<li>The capitalization of your column names is unconventional. Usually, identifiers are <code>lowercase</code>, and SQL keywords are <code>ALL CAPS</code>. (Note: identifiers in MySQL are <a href=\"https://stackoverflow.com/q/2009005/1157100\">case-sensitive on Unix, but not Windows</a>.)</li>\n</ul>\n\n<h3>Proposal</h3>\n\n<pre><code>DELETE FROM session\n WHERE last_activity < CURRENT_TIMESTAMP() - INTERVAL 2 WEEK\n OR (rememberuser = 'N' AND last_activity < CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE);\n</code></pre>\n\n<h3>Advantages</h3>\n\n<ul>\n<li>This is a fixed query with no parameters, which keeps things simple.</li>\n<li>It's almost English-like in readability.</li>\n</ul>\n\n<h3>Caveats</h3>\n\n<ul>\n<li><p>This requires your <code>last_activity</code> column to be of the <code>DATETIME</code> or <code>TIMESTAMP</code> type. You could also make it work with integer Unix timestamps instead, using</p>\n\n<pre><code>DELETE FROM session\n WHERE last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 2 WEEK)\n OR (rememberuser = 'N' AND last_activity < UNIX_TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 30 MINUTE));\n</code></pre></li>\n<li><p>This assumes that the <code>last_activity</code> times were set according to the database server's clock, not the application server's clock. Otherwise, if they are running on separate machines, or if you are careless with your treatment of timezones, you could end up with clock skew. Therefore, it's best to pick one clock and stick with it consistently. I prefer to use the database server's clock, for several reasons:</p>\n\n<ol>\n<li>If your application runs on multiple application servers, all connecting to a central database, then the database clock is the natural official time source.</li>\n<li>Your queries can be simpler, as illustrated above.</li>\n<li>Storing the timestamps in a <code>DATETIME</code> column is more meaningful than storing them as integers.</li>\n</ol>\n\n<p>So, to make this work, the <code>last_activity</code> times have to be inserted or updated using <code>CURRENT_TIMESTAMP()</code> or <code>NOW()</code>, or established by default when a <code>TIMEZONE</code> column has no specified value.</p></li>\n<li>Admittedly, this formulation uses MySQL-specific date / time functions, so it is less portable. Similar solutions exist for other database systems, though.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:10:47.087",
"Id": "42258",
"ParentId": "39161",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:39:05.827",
"Id": "39161",
"Score": "2",
"Tags": [
"php",
"mysql",
"datetime",
"session"
],
"Title": "Update SQL query using UNIX time"
}
|
39161
|
<p>I've been playing around with inheritance in JavaScript and I'm wondering if there are any drawbacks to this method which tries to emulate classical inheritance from C-based languages.</p>
<pre><code>Function.prototype.extends = function (parentClass) {
function temp () { this.constructor = this; };
temp.prototype = new parentClass();
this.prototype = new temp();
};
var Animal = function() {
function Animal() {};
Animal.prototype.walk = function () {
return this.name + ' walks';
};
return Animal;
}();
var Cat = function () {
function Cat (name) {
this.name = name;
};
Cat.extends(Animal);
Cat.prototype.meow = function() {
return this.name + ' meows';
};
return Cat;
}();
var Chester = new Cat('Chester');
console.log(Chester.meow()); // Chester meows
console.log(Chester.walk()); // Chester walks
</code></pre>
<p>This is a crude example, but can anyone point out any glaring problems?</p>
|
[] |
[
{
"body": "<p>Observations:</p>\n\n<ul>\n<li>You changed the Function prototype, which is generally considered bad practice.</li>\n<li>The inheritance does work, <code>instanceof</code> checks work fine</li>\n<li><p>I do not see how it emulates classical inheritance better than this:</p>\n\n<pre><code>var Cat = function () {\n\n function Cat (name) {\n Animal.call(this); //This takes care of inheritance, classic JS\n this.name = name;\n };\n //Fix prototype\n Cat.prototype = new Animal();\n Cat.prototype.constructor = Cat;\n\n Cat.prototype.meow = function() {\n return this.name + ' meows';\n };\n\n return Cat;\n}();\n</code></pre></li>\n</ul>\n\n<p>Except that you are more explicit and less verbose in declaring the inheritance.\nI guess it is a matter of style at this point, I would stick with the old school.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:15:07.277",
"Id": "65567",
"Score": "0",
"body": "This is not a complete example and it doesn't establish inheritance. Try `Chester.walk()` for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:23:16.653",
"Id": "65568",
"Score": "0",
"body": "Fixed, so I guess the question is, is that function saving three lines worth it? I would guess not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:33:05.490",
"Id": "65658",
"Score": "0",
"body": "@tomdemuyt Thanks for your answer. I appreciate that extending the `Function` prototype may be frowned upon, but I do feel that this method feels a lot more intuitive when writing. My only concern really was that it might cause havoc with the prototype chain."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:11:10.653",
"Id": "39171",
"ParentId": "39162",
"Score": "1"
}
},
{
"body": "<p>Hang on a tick... there <em>is</em> a problem here that, weirdly nobody has noticed. I will admit that this is hardly ever used, but still: <br>\nIn a normal JS prototypal inheritance scenario, you would be able to pull stunts like these:</p>\n\n<pre><code>var Animal = (function()\n{\n function Animal()\n {\n this.name = this.constructor.name;\n };\n Animal.prototype.walk = function()\n {\n return this.name + ' is walking';\n };\n return Animal;\n}()):\nvar Cat = (function(parent)\n{\n function Cat(name)\n {\n this.name = name || this.constructor.name;\n };\n Cat.prototype = new Animal;\n Cat.prototype.constructor = Cat;\n Cat.prototype.sleep = function()\n {\n return this.name + ' is sleeping';\n };\n return Cat;\n}(Animal));\nvar garfield = new Cat('Garfield');\n//code\nvar newSameClass = new garfield.constructor();\n</code></pre>\n\n<p>Whereas the <code>extends</code> method you have written causes infinite constructor recursion: you're declaring a new function, that uses the <code>this</code> keyword... but <em>because</em> it's being used with the <code>new</code> keyword, it creates a new instance of itself (<code>temp</code>).<br>\nIn the constructor of <code>temp</code>, all it does is equate its prototype to its own instance... <strong><em>you create an object that is its own prototype</em></strong> and therefore effectively is not part of any chain (it keeps on pointing to itself) and for some bizarre reason, you expect this to keep track of the <em>constructor</em>? I think what you ought to write is this:</p>\n\n<pre><code>Function.prototype.extends = function(parentClass)\n{\n var temp = this.prototype.constructor;\n this.prototype = new ParentClass;\n this.prototype.constructor = temp;\n};\n</code></pre>\n\n<p>Which works just fine, and doesn't require some temp constructor/object at any point.\nJust try it with this simple example:</p>\n\n<pre><code>function Animal(){};\nfunction Cow(){};\nCow.extends(Animal);\nfunction Bird(){};\nfunction Chicken(){};\nBird.extends(Animal);\nChicken.extends(Bird);\nvar dinner = new Chicken();\nconsole.log(dinner instanceof Animal);//true -- sorry vegetarians\nconsole.log(dinner instanceof Cow);//false -- no beef tonight\nconsole.log(dinner instanceof Bird);//true -- mmm, poultry\nconsole.log(dinner instanceof Chicken);//true -- roasted, probably\n</code></pre>\n\n<p>Which is, I take it, what you wanted.<br>\nPS: I would strongly advise you <em>not</em> to augment prototypes you don't <em>own</em>. By that I mean <code>Object</code>, <code>Array</code>, <code>Function</code>, <code>Date</code> and the like... Save for a few cases where the <code>String</code> prototype poses X-browser issues (<code>String.trim</code> wasn't implemented in IE8, for example).<br>\nYou might encounter issues with other toolkits/libs, future updates, issues depending on the implementation (IE, FF and V8 deal with native prototypes differently in some cases)</p>\n\n<p>All in all, it's best to leave them be... I see no reason why you shouldn't simply write a function, and <em>not</em> attach it to the prototype. Or, if needs must, do what ECMA is doing: all these <code>createObject</code>-like thingies go into one big bin: <code>Object</code> as in <code>Object.getOwnPropertyNames()</code> and <code>Object.getPrototypeOf()</code>. What's so difficult about:</p>\n\n<pre><code>function extend(child, parent)\n{\n var prto, Object.getPrototypeOf(child),\n tmp = prto.constructor;\n prto = new parent;\n prto.constructor = tmp;\n return child;//<-- this might be handy\n}\n//usage:\nvar garfield = new (extends(Cat, Animal))('garfield');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:42:39.143",
"Id": "66139",
"Score": "0",
"body": "Thanks again! Weirdly I had picked up on infinite constructor recursion and the solution is a carbon copy of your suggestion. The original method was also exactly the same as your `extend(child, parent)` method. This was just an experiment to emulate the syntactical sugar of C-based languages, or rather, a more intuitive way of writing this extends that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T10:55:20.320",
"Id": "66385",
"Score": "1",
"body": "@IanBrindley: You're welcome... if you don't mind my asking: since stack-exchange sites aim to be a reference for future users, googling a specific problem, you might want to reconsider which answer is up-voted/accepted here. Since I mention the infinite recursion, and suggest a different approach that, by your own admission, is what you've ended up using, then perhaps this answer should be the one marked as accepted? (PS: as for the answer to your other, PHP, question: I know I'm a bit of a rep-whore, but an up-vote for my efforts would be greatly appreciated ;-P)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:29:25.637",
"Id": "39480",
"ParentId": "39162",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39480",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:08:41.393",
"Id": "39162",
"Score": "2",
"Tags": [
"javascript",
"inheritance"
],
"Title": "Classical inheritance in JavaScript"
}
|
39162
|
<p>I have the following code to load an enumeration into a bound combo box, but am not quite happy with it. </p>
<p>I would prefer to store the actual <code>enum</code> value in the combo box and bind directly to it.
However, I can't quite figure out how to do so.</p>
<pre><code> public enum HemEnum
{
HemNone = -1,
Hemsew = 0,
HemWeld = 1,
Hemdoublefold = 2
}
public static void LoadHemCombo(ComboBox cbo)
{
var values = from Enum e in Enum.GetValues(typeof(HemEnum))
select new { ID = e, Name = e.ToString() };
foreach (var value in values)
{
var s = GetHemTypeDescription((HemEnum)value.ID );
cbo.Items.Add(s);
}
}
public static string GetHemTypeDescription(HemEnum hemType)
{
string s = null;
switch (hemType)
{
case HemEnum.HemNone:
s = "none";
break;
case HemEnum.Hemsew:
s = "sewn";
break;
case HemEnum.HemWeld:
s = "welded";
break;
case HemEnum.hemdoublefold:
s = "double folded";
break;
default:
s = "not known";
break;
}
return s;
}
</code></pre>
<p>Inside the form load event I load the combo and bind to it.</p>
<pre><code> LoadHemCombo(cboHem)
cboHem.DataBindings.Add("Text", myBindingSource, "HemTypeDescription");
class myObject
{
public string HemTypeDescription
{
get
{
return GetHemTypeDescription(this.HemType);
}
set
{
this.HemType = GetHemTypeFromDescription(value);
}
}
public static vHemEnum GetHemTypeFromDescription(string description)
{
int r =0;
for (var i = (int)HemEnum.HemNone; i <= (int)HemEnum.Hemdoublefold; i++)
{
var s = GetHemTypeDescription((HemEnum)i);
if (description == s)
{
r = i;
break;
}
}
return (HemEnum)r;
}
}
</code></pre>
<p>in the designer I set </p>
<pre><code>myBindingSource.DataSource = myObject
</code></pre>
<p>and before loading the form I create an instance of <code>myObject</code> and add it to <code>myBindingSource</code> using </p>
<pre><code>myBindingSource.Add(myObject)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T22:32:24.447",
"Id": "65600",
"Score": "0",
"body": "I've got a custom class devoted to solving this [over here](http://stackoverflow.com/questions/15557999/binding-to-enums/15558108#15558108). All the advice below is good advice, but this class also addresses pulling the data back out as the right type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:31:56.467",
"Id": "65608",
"Score": "0",
"body": "Thanks every one.\nI also made it generic.\nSo now I just have\n'public void LoadCombo<T>(ComboBox cbo)'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-27T15:09:43.833",
"Id": "239841",
"Score": "0",
"body": "You can use `ObjectDataProvider` to get all enum values in XAML and then bind it to `ItemsSource`. [Here](http://druss.info/2015/01/wpf-binding-itemssource-to-enum/) is a full example."
}
] |
[
{
"body": "<p>The easiest way to accomplish what you want is to create a list of the possible enum values and data bind that list to the combo box. You can do this through the designer (under Data) or with the following code:</p>\n\n<pre><code>cboHem.DataSource = enumList;\n</code></pre>\n\n<p>With an enum, it should automatically use the individual enum values as the selected value and display the enum values' .ToString result in the control.</p>\n\n<p>If you use localization strings, it's a little (but not much) more complicated. Instead of binding enum values directly, you will want to bind a list of objects with the enum value and your localized string representation for the value, and then set the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember%28v=vs.110%29.aspx\" rel=\"nofollow\">DisplayMember</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.valuemember%28v=vs.110%29.aspx\" rel=\"nofollow\">ValueMember</a> properties to the appropriate fields on your bound objects.</p>\n\n<p>Once again, that can be done through the designer (under Data again) or through code, as follows:</p>\n\n<pre><code>cboHem.DisplayMember = \"DisplayValue\";\ncboHem.ValueMember = \"EnumValue\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:33:46.283",
"Id": "65555",
"Score": "1",
"body": "How do I create enumList? \nI cant use `Enum.GetValues(typeof(HemType));` because the description is different to HemType.ToString()"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:18:59.870",
"Id": "39165",
"ParentId": "39163",
"Score": "3"
}
},
{
"body": "<h3>Naming</h3>\n<p><code>HemEnum</code>, or any enum name that ends with the word <code>Enum</code>, is a bad name for an enum. Enum types should not contain the word "enum" in their names.</p>\n<p>Similarly, <code>HemEnum</code> values should not contain "Hem" in their names either. Your <code>HemEnum</code> should therefore read something like this:</p>\n<pre><code>public enum HemType\n{\n None = -1,\n Sewn = 0,\n Weld = 1,\n DoubleFold = 2\n}\n</code></pre>\n<p><code>myObject</code> is a bad name for a class - should be <code>MyObject</code>. Kidding (although not really - types should be named following a PascalCasing convention). Anything that ends with "Object" should be banned from being a class name. <strong>Note that <code>myObject</code> doesn't compile as provided.</strong> (where's <code>this.HemType</code>?)</p>\n<p>The pseudo-Hungarian notation is ok in <a href=\"/questions/tagged/winforms\" class=\"post-tag\" title=\"show questions tagged 'winforms'\" rel=\"tag\">winforms</a> for naming controls (i.e. the "cbo" prefix for ComboBoxes, "txt" for TextBoxes, etc.) - had you been using current technology (WPF) I would have strongly advised against such naming though.</p>\n<h3>Nitpicks</h3>\n<p>You seem to make <code>static</code> anything that <em>can</em> be made <code>static</code>. Don't. Just because a method doesn't use instance members <em>now</em> doesn't mean it <em>never</em> will, and changing a <code>public static void</code> method to be <code>public void</code>, is a <em>breaking change</em>.</p>\n<p><code>vHemEnum</code> doesn't seem to be a type defined anywhere. Typo?</p>\n<p>I'll assume the out-of-whack indentation is a <kbd>Copy</kbd>+<kbd>Paste</kbd> glitch.</p>\n<h3>Binding?</h3>\n<p>You say you want databinding, and yet you're doing this:</p>\n<pre><code>foreach (var value in values)\n{\n var s = GetHemTypeDescription((HemEnum)value.ID );\n cbo.Items.Add(s);\n}\n</code></pre>\n<p>Create a type that exposes <code>DisplayValue</code> and <code>EnumValue</code> properties, and use @DanLyons' or @JesseCSlicer's answer to bind your combobox items.</p>\n<h3>Captions</h3>\n<p>A more extensible way (vs. attributes) of providing captions for your enums, would be to use a resource file (.resx) - call the strings per the enum's names, and then retrieve the caption from the resource strings:</p>\n<pre><code>var description = resx.ResourceManager.GetString(hemType.ToString());\n</code></pre>\n<hr />\n<p>Bottom line, I've seen worse WinForms code (and WPF for that matter), but it could be improved.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:31:51.047",
"Id": "39167",
"ParentId": "39163",
"Score": "13"
}
},
{
"body": "<p>Here may be an decent way of doing what you want:</p>\n\n<pre><code>public enum HemEnum\n{\n [Description(\"none\")]\n HemNone = -1,\n [Description(\"sewn\")]\n Hemsew = 0,\n [Description(\"welded\")]\n HemWeld = 1,\n [Description(\"double folded\")]\n Hemdoublefold = 2\n}\n\n\npublic static void LoadHemCombo(ComboBox cbo)\n{\n cbo.DataSource = Enum.GetValues(typeof(HemEnum))\n .Cast<Enum>()\n .Select(value => new\n {\n (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,\n value\n })\n .OrderBy(item => item.value)\n .ToList();\n cbo.DisplayMember = \"Description\";\n cbo.ValueMember = \"value\";\n}\n</code></pre>\n\n<p>Do note, this method requires a <code>[Description]</code> on every <code>enum</code> member. If one isn't there, you'll get a <code>NullReferenceException</code>. This requirement keeps the code simple by not needing a nullity check.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T22:27:47.593",
"Id": "65599",
"Score": "0",
"body": "This is very similar to what I use, but I've extended it a bit further so that the `[Description]` attribute doesn't have to be there. See the code [here](https://gist.github.com/gabehesse/1002735) for an example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T22:55:05.263",
"Id": "65603",
"Score": "0",
"body": "@Bobson I just commented on your code bits with one of my own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:00:05.373",
"Id": "65604",
"Score": "0",
"body": "Sorry, I phrased that rather misleadingly (too much editing). My code is a slight modification of the linked code, which itself supported missing `[Description]` attributes. I didn't intend to take credit for writing the initial `EnumLabel` that I linked. I do like your modifications, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:07:21.450",
"Id": "65605",
"Score": "1",
"body": "Cool, heh. I hope whomever wrote the linked code doesn't take any offense. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:15:35.950",
"Id": "65606",
"Score": "0",
"body": "Wonderful. I changed the binding to ' cboHem.DataBindings.Add(\"SelectedValue\", myBindingSource, 'HemType\") so I could use it;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T10:15:01.417",
"Id": "84271",
"Score": "0",
"body": "I load combo using your code, great. How can I set value in combo ? For example, selectedItem is Hemdoublefold = 2 - \"double folded\""
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:40:51.503",
"Id": "39168",
"ParentId": "39163",
"Score": "13"
}
},
{
"body": "<p>I did a quick mock up using the following and it works well.</p>\n\n<p>Enumerated Values</p>\n\n<pre><code> public enum HemEnum\n {\n [Description(\"None\")]\n None = -1,\n [Description(\"Item will be sewn\")]\n Sew = 0,\n [Description(\"Item will be welded\")]\n Weld = 1,\n [Description(\"Item will be double folded\")]\n Doublefold = 2\n }\n</code></pre>\n\n<p>A name value binder used to populate a binding source, this is the class that will be bound as an item to the combobox. Mapping the cboEnum.ValueMember to the NameValueBinder.Value etc..</p>\n\n<pre><code>public class NameValueBinder\n{\n public NameValueBinder()\n {\n }\n\n public NameValueBinder(object value, string name)\n {\n this.Value = value;\n this.Name = name;\n }\n\n public object Value { get; set; }\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>Method in your form or class to pull the items into a list. This function takes an enum type as the parameter and retrieves a list of all enumeration values in the enum and converts each one to a NameValueBinder item and returns the list of all items. The type being passed as a parameter allows one function to retrieve a bindable list for any enum in the application, no need to write one function per enumeration.</p>\n\n<pre><code>public List<NameValueBinder> GetValues(Type type)\n{\n List<NameValueBinder> binders = new List<NameValueBinder>();\n\n if (type.BaseType != typeof(Enum))\n return binders;\n\n var items = Enum.GetValues(type);\n\n foreach (var item in items)\n {\n binders.Add((item as Enum).ToListItem());\n }\n\n return binders;\n }\n</code></pre>\n\n<p>Extension class to convert from enum to binder item. The first function ToListItem converts the enum value (i.e. HemEnum.Weld) to a NameValueBinder class by mapping the enum value to the Value property and the DescriptionAttribute value the name property.\nThe binder will be added to a list or collection for databainding to the ui element. The second function retrieves the value of the DescriptionAttribute for the enum value. If the enum value does not have an associated DescriptionAttribute, the name of the enum is returned in it's place.</p>\n\n<pre><code>public static class EnumExtensions\n{\n public static NameValueBinder ToListItem(this Enum value)\n {\n string description = value.GetDescription();\n return new NameValueBinder(value, description);\n }\n\n public static string GetDescription(this Enum enumVal)\n {\n var type = enumVal.GetType();\n var memInfo = type.GetMember(enumVal.ToString());\n var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);\n\n foreach (var attribute in attributes)\n {\n if(attribute .GetType() == typeof(DescriptionAttribute))\n return (attribute as DescriptionAttribute).Description;\n }\n\n // no description attribute found, just return the name\n return enumVal.ToString(); }\n}\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>// create a binding source and populates it with the enum values/descriptions\nBindingSource cboLookupBinding = new BindingSource();\ncboLookupBinding.DataSource = typeof(NameValueBinder);\ncboLookupBinding.DataSource = GetValues(typeof(HemEnum));\n\n// bind the combobox to the bindingsource\ncboHem.ValueMember = \"Value\";\ncboHem.DisplayMember = \"Name\";\ncboHem.DataSource = cboLookupBinding;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T23:24:14.463",
"Id": "148911",
"Score": "0",
"body": "Good code review answers typically have more plain-English than actual source code. There's nothing wrong with posting code to show what you mean, but we really like good explanations of why your code is better and what mistakes were made and what warrants the original code being replaced with your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T23:25:43.577",
"Id": "148912",
"Score": "0",
"body": "Could you explain why you made these changes a little more?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T23:01:13.007",
"Id": "82782",
"ParentId": "39163",
"Score": "1"
}
},
{
"body": "<p>All of the answers I found on the internet seem pretty complex. I found that you can get an array from an enum and convert the array to a list, which can be used as a datasource for your combobox. It's extremely simple and seems to be working in my project.</p>\n\n<pre><code>public enum Status\n{\n Open = 1,\n Closed,\n OnHold\n}\n\nList<Status> lstStatus = Enum.GetValues(typeof(Status)).OfType<Status>().ToList();\nddlStatus.DataSource = lstStatus;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-12T19:40:37.720",
"Id": "128210",
"ParentId": "39163",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39168",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T17:50:27.860",
"Id": "39163",
"Score": "13",
"Tags": [
"c#",
"algorithm",
"winforms",
"enum"
],
"Title": "Loading a combobox with an enum and binding to it"
}
|
39163
|
<p>I have a class <code>Creator</code> which will execute a block code for a number of times. I'm not sure how to write this in a more elegant way in Ruby.</p>
<pre><code>class Creator
attr_accessor :block
def self.create(&block)
@block = block
return self
end
def self.for(number)
0.upto(number) {
block.call
}
end
end
</code></pre>
<p>And this is how I call it which I want to stay like this.</p>
<pre><code>Creator.create{
SomeModel.create!(@attr)
}.for(30)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:16:23.990",
"Id": "65655",
"Score": "1",
"body": "I am sure you have your reasons, but what about `30.times { SomeModel.create!(@attr) }`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:25:49.760",
"Id": "65657",
"Score": "0",
"body": "Yeah, that's one option that I was looking at as well. But I'm trying to learn code/block in ruby and I'm planning to do some more in this class as well."
}
] |
[
{
"body": "<p>With <code>attr_accessor :block</code> you define a accessor for an instance.</p>\n\n<p>You may use the variable <code>@block</code> directly:</p>\n\n<pre><code>class Creator\n def self.create(&block)\n @block = block\n return self\n end\n\n def self.for(number)\n 0.upto(number) {\n @block.call\n }\n end\nend\n\n\nCreator.create{ \n p 'here' #your SomeModel.create!(@attr)\n}.for(30)\n</code></pre>\n\n<p>Or if you think you need an accessor:</p>\n\n<pre><code>class Creator\n class << self\n attr_accessor :block\n def create(&block)\n self.block = block\n return self\n end\n\n def for(number)\n 0.upto(number) {\n block.call\n }\n end\n end\nend\n\n\nCreator.create{ \n p 'here' #your SomeModel.create!(@attr)\n}.for(30)\n</code></pre>\n\n<p>But there is no need of for and create. I would define only one method that accepts the number of executions:</p>\n\n<pre><code>class Creator\n def self.create(number, &block)\n number.times{\n block.call\n }\n end\nend\n\nCreator.create(30){ \n p 'here' #your SomeModel.create!(@attr)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:52:40.447",
"Id": "39176",
"ParentId": "39166",
"Score": "1"
}
},
{
"body": "<p>This can be done simply enough inline that I don't think the creator class is worth the trouble:</p>\n\n<pre><code>30.times.map { SomeModel.create!(@attr) }\n</code></pre>\n\n<p><code>30.times</code> creates an Enumerator that yields 30 times, then <code>map</code> turns each yield into a new instance of <code>SomeModel</code>.</p>\n\n<p>or, if you don't need the actual instances:</p>\n\n<pre><code>30.times { SomeModel.create!(@attr) }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:20:55.763",
"Id": "65656",
"Score": "1",
"body": "apparently the OP wants the code to work by side-effects (not a great idea) and the `map` is not necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:24:42.320",
"Id": "65664",
"Score": "0",
"body": "@tokland, Thanks. Edited. When dealing with the database, it's all about side-effects. What the OP wants done doesn't seem bad to me (although the heavyweight machinery to do it does)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:42:53.100",
"Id": "39181",
"ParentId": "39166",
"Score": "2"
}
},
{
"body": "<p>You want instance methods, not class methods. With the current code, you would get:</p>\n\n<pre><code>hello = Creator.create { puts \"Hello\" }\ngoodbye = Creator.create { puts \"Goodbye\" }\nhello.for(1) # Prints \"Goodbye\"\n</code></pre>\n\n<p>Assuming you don't want <code>block</code> to be changed afterwards, I would change <code>attr_accessor</code> to <code>attr_reader</code>. I don't see much reason to even expose a reader, though — it seems that doing so would only lead to mischief.</p>\n\n<pre><code>class Creator\n # For compatibility with the old API\n def self.create(&block)\n return self.new(&block)\n end\n\n def initialize(&block)\n @block = block\n end\n\n def for(number)\n number.times { @block.call }\n end\nend\n</code></pre>\n\n<p>This is just a syntactic sugar wrapper for blocks. Perhaps a more generic name than <code>Creator</code> might be appropriate. It might also be simpler to call <code>number.times { block.call }</code> directly.</p>\n\n<p>Standard indentation for Ruby is two spaces.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:48:55.240",
"Id": "39182",
"ParentId": "39166",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39182",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T18:30:59.123",
"Id": "39166",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "How to write save block code like this more elegant in Ruby?"
}
|
39166
|
<p>I've written a small <a href="https://github.com/r-darwish/gameoflife" rel="nofollow">Game of Life</a> module in Haskell, as well as a small testing application. I'm relatively new to the language, so any kind of comment about the code is welcome. The most important comments for me are comments about efficiency of the code, and of course bugs. I would also be happy to accept comments about:</p>
<ul>
<li>Coding Style</li>
<li>"Reinventing the wheel"</li>
<li>Misuse of features</li>
<li>Show instance efficiency</li>
</ul>
<p></p>
<pre><code>module GameOfLife
( State(..)
, Board
, evolve
, initBoard
, setStates
, nextGen ) where
import Data.List
import Data.Maybe
import qualified Data.Map as Map
data State = Alive | Dead deriving (Eq, Show)
type Coord = (Int,Int)
data Cell = Cell { cellState :: State
, cellCoord :: Coord } deriving Show
data Board = Board { boardGrid :: (Map.Map Coord Cell)
, boardWidth :: Int
, boardHeight :: Int}
initBoard :: Int -> Int -> Board
initBoard width height =
let grid = Map.fromList $ [(c, Cell Dead c) | x <- [0..width - 1], y <- [0..height - 1], let c = (x,y)]
in Board grid width height
setState :: Board -> State -> Coord -> Board
setState (Board grid width height) state (x,y)
| y >= height || y < 0 = error "Height is off bounds"
| x >= width || x < 0 = error "Width is off bounds"
| otherwise =
let c = (x,y)
newGrid = Map.insert c (Cell state c) grid
in Board newGrid width height
setStates :: Board -> State -> [Coord] -> Board
setStates board state = foldl (\board coord -> setState board state coord) board
neighbours :: Board -> Coord -> [Cell]
neighbours (Board grid width height) c@(x,y)
| not (inBounds c) = error "Coordinate off bounds"
| otherwise =
let neighboursCoords = filter (/= c) $ filter inBounds [(x',y') | x' <- [x - 1..x + 1], y' <- [y - 1..y + 1]]
in map getCell neighboursCoords
where
inBounds (x,y) = x >= 0 && y >= 0 && x < width && y < height
getCell (x,y) = fromJust $ Map.lookup (x,y) grid
nextGen :: Board -> Board
nextGen board =
let
livingNeighbours c = length $ filter (==Alive) $ map cellState (neighbours board c)
takeState state = map cellCoord $ filter (\c -> cellState c == state) $ Map.elems $ boardGrid board
underPop = filter (\coords -> (livingNeighbours coords) < 2) $ takeState Alive
overPop = filter (\coords -> (livingNeighbours coords) > 3) $ takeState Alive
newBorn = filter (\coords -> (livingNeighbours coords) == 3) $ takeState Dead
revive b = setStates b Alive newBorn
kill b = setStates b Dead (overPop ++ underPop)
in kill $ revive board
evolve :: Board -> [Board]
evolve board =
let next = nextGen board
in next:evolve next
-- Show instances --
instance Show Board where
show (Board grid width height) =
intercalate "\n" $ map gridLine [0..height - 1]
where gridLine l =
concat $ map (charState . cellState . fromJust) [Map.lookup (x,l) grid | x <- [0..width -1]]
charState state
| state == Dead = " "
| state == Alive = "@"
</code></pre>
<p><strong>EDIT:</strong> New version with Array:</p>
<pre><code>module GameOfLife
( State(..)
, Board
, evolve
, initBoard
, setStates
, nextGen
, toText
) where
import Data.List
import Data.Array
import System.IO
import qualified Data.Text as T
data State = Alive | Dead deriving (Eq, Show)
type Coord = (Int,Int)
type Board = Array Coord State
initBoard :: Coord -> Board
initBoard (width,height) =
let bounds = ((0,0),(width - 1,height - 1))
in array bounds $ zip (range bounds) (repeat Dead)
setStates :: Board -> [(Coord,State)] -> Board
setStates = (//)
getStates :: Board -> [Coord] -> [State]
getStates board coords = map (board!) coords
neighbours :: Board -> Coord -> [Coord]
neighbours board c@(x,y) =
filter (/= c) $ filter (inRange (bounds board)) [(x',y') | x' <- [x - 1..x + 1], y' <- [y - 1..y + 1]]
nextGen :: Board -> Board
nextGen board =
let
allCells = range (bounds board)
takeState state coords = map fst . filter (\(_,s) -> s == state) $ zip coords (getStates board coords)
livingNeighbours = length . takeState Alive . neighbours board
zipState state coords = zip coords (repeat state)
underPop = zipState Dead . filter (\c -> (livingNeighbours c) < 2) $ takeState Alive allCells
overPop = zipState Dead .filter (\c -> (livingNeighbours c) > 3) $ takeState Alive allCells
newBorn = zipState Alive .filter (\c -> (livingNeighbours c) == 3) $ takeState Dead allCells
in setStates board (concat [underPop, overPop, newBorn])
evolve :: Board -> [Board]
evolve = iterate nextGen
toText :: Board -> T.Text
toText board = T.intercalate (T.singleton '\n') (rows minY)
where
((minX,minY),(maxX,maxY)) = bounds board
rows y
| y > maxY = []
| otherwise = (row y minX):rows (y + 1)
row y x
| x > maxX = T.empty
| otherwise = T.cons (stateToChar $ board!(x,y)) (row y (x + 1))
stateToChar state
| state == Alive = '@'
| otherwise = ' '
</code></pre>
<p><strong>EDIT 2:</strong> nextGen implemented using do notation:</p>
<pre><code>nextGen :: Board -> Board
nextGen board =
let
allCells = range (bounds board)
takeState dstate coords = do
coord <- coords
let state = board ! coord
guard $ state == dstate
return (coord)
theLiving = takeState Alive allCells
theDead = takeState Dead allCells
livingNeighbours = length . takeState Alive . neighbours board
underPop = do
alive <- theLiving
guard $ (livingNeighbours alive) < 2
return (alive,Dead)
overPop = do
alive <- theLiving
guard $ (livingNeighbours alive) > 3
return (alive,Dead)
newBorn = do
dead <- theDead
guard $ (livingNeighbours dead) == 3
return (dead,Alive)
in setStates board (concat [underPop, overPop, newBorn])
</code></pre>
|
[] |
[
{
"body": "\n\n<h3>First of all you should consider how you represent your board.</h3>\n\n<ul>\n<li>Using <code>Array</code> with two-dimension index (<code>Ix</code>) would be a good choice for the way you work right now. You define value for each cell individually no matter what is in that cell.</li>\n<li>Alternative way is to use <code>Map</code> to <code>()</code> or <code>Set</code> of coordinates to represent <code>Alive</code> cells while treating rest of the board as <code>Dead</code>.</li>\n<li>Yet another is to use own container without even mentioning of coordinates.<br>\nConsider the way how list (<code>[a]</code>) defined. That's actually a single-linked list. And you can create double-linked list like <code>data DList a = DList DList a DList</code>. In a same way you can define a double-linked grid (4 directions). Going further will let you define 5th dimension that represents generations.<br>\nSuch approach often used to represent lazy infinite structures that grow while you walk over them (ex. you walk around some cell and then dive into next generation and walk around again revealing how everythin were changed).<br>\nI remember some term associated with that called <a href=\"http://en.wikipedia.org/wiki/Cellular_automaton\" rel=\"nofollow\">\"cellular automaton\"</a></li>\n</ul>\n\n<h3>Next would be state (in case of <code>Array</code> and \"cellular automaton\")</h3>\n\n<p>Here you can define your own <code>State</code> just to make it clear, but you as well can use <code>Bool</code>. Note that it doesn't look like you need coordinates at all (consider dropping them from <code>Cell</code>).</p>\n\n<h3>Producing of new <code>Map</code>, <code>Set</code>, <code>Array</code> should be considered carefully I guess</h3>\n\n<p>One of the important thing is that its better to avoid producing of new board on each intermediate step (killing and reviving). I'd suggest to build up delta and then apply to original board. That should guard you from building almost similar copies of board.</p>\n\n<h3>Signatures</h3>\n\n<ul>\n<li>It's a very common practice for update functions to take input as a last argument. I.e. <code>setState :: State -> [Coord] -> Board -> Board</code>. That allows to write something like: <code>killTopLeft = setStates Dead [(0,0)]</code></li>\n</ul>\n\n<h3>Using high-order functions</h3>\n\n<pre><code>evolve = iterate nextGen\n</code></pre>\n\n<p>And</p>\n\n<pre><code>setStates board state coords = Map.union updates board where\n updates = Map.fromList $ map (\\c -> (c, Cell state c)) coords\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:57:42.390",
"Id": "65584",
"Score": "0",
"body": "Thank you. I'm not sure I understand what you said about deltas. As far as I understand every object in Haskell is immutable, so even \"applying deltas\" productes a new copy of the object, doesn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T06:04:04.723",
"Id": "65629",
"Score": "1",
"body": "@darwish, yes there is no variables in the way as they present in other languages. But you can accumulate deltas in list which built a bit easier than `Map` and then update your original board with that list. Since you'll do build/modification from list library will be able to optimize somehow those operation to do them inplace (ex. convert list to array, sort it and rise a delta-`Map` from it)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:16:51.910",
"Id": "39177",
"ParentId": "39170",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T19:00:17.627",
"Id": "39170",
"Score": "7",
"Tags": [
"beginner",
"haskell",
"game-of-life"
],
"Title": "Game of Life implementation in Haskell"
}
|
39170
|
<p>As <code>xts</code> objects are arrays, getting apply functions to work is a little tricky if you want to preserve the dates. For example, take the <code>xts</code> object <code>xx</code> below: </p>
<pre><code>xx <- xts(replicate(6, sample(c(1:10), 10, rep = T)),
order.by = Sys.Date() + 1:10)
</code></pre>
<p>Say we wish to apply a function to each column (to keep it simple say i wish to add 100 to each element of each column). </p>
<pre><code>sapply(xx, function(col) col + 100)
</code></pre>
<p>Doing with with <code>sapply</code> loses the row names. </p>
<p>Using <code>apply</code> works -- but it is slow (see below). </p>
<pre><code>apply(xx, 2, function(col) col + 100)
</code></pre>
<p>To address this, I wrote the following helper:</p>
<pre><code>mapXts <- function(Xts, cFUN) {
if(!is.xts(Xts)) stop("Must supply function with xts object")
Z <- Xts
for (j in 1:ncol(Xts)) {
Z[,j] <- do.call(cFUN, list(Xts[,j]))
}
Z
}
</code></pre>
<p>The obligatory horse race: </p>
<pre><code>set.seed(1)
xz <- xts(replicate(6, sample(c(1:100), 1000, rep = T)),
order.by = Sys.Date() + 1:1000)
apFun <- function() apply(xz, 2, function(col) col + 100)
sapFun <- function() sapply(xz, function(col) col + 100)
mapXf <- function() mapXts(xz, function(col) col + 100)
op <- microbenchmark(
app = apFun(),
sap = sapFun(),
mXf = mapXf(),
times = 1000L)
</code></pre>
<p>This results in speedups of about 5x over <code>apply</code> and is about 3x faster than <code>sapply</code> (and it gives me back the data in the formate i most value). </p>
<pre><code>Unit: microseconds
expr min lq median uq max neval
app 3083.425 3206.0295 3287.1725 3496.9720 30678.90 1000
sap 1669.384 1763.7945 1827.0265 1952.7490 24173.88 1000
mXf 615.279 677.0005 709.4725 787.1635 24390.62 1000
</code></pre>
<p>Are there any further tricks i might use to speed things up? Also, any dark corners in the case that i've missed? </p>
|
[] |
[
{
"body": "<p>You can use the function <code>vapply</code>. The help page of <code>?vapply</code> says:</p>\n\n<blockquote>\n <p>vapply is similar to sapply, but has a pre-specified type of return\n value, so it can be safer (and sometimes faster) to use.</p>\n</blockquote>\n\n<p>You can use</p>\n\n<pre><code>vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))\n</code></pre>\n\n<p>The argument <code>FUN.VALUE</code> is used to tell the <code>vapply</code> what the function returns. Since all columns are numeric, the function returns a numeric vector of length <code>nrow(xz)</code> for each column of <code>xz</code>. Unfortunately, <code>vapply</code> does not preserve the dates of the <code>xts</code> object.</p>\n\n<p>You can use the following command to generate a new object based on <code>xz</code> and replace all values with the matrix returned by <code>vapply</code>. This is very easy with the following command:</p>\n\n<pre><code>\"[<-\"(xz, , vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))))\n</code></pre>\n\n<p>The function <code>\"[<-\"</code> copies the <code>xz</code> object and replaces all its values.</p>\n\n<p>Alternatively, you can create a new <code>xts</code> object based on the matrix returned by <code>vapply</code> and the <code>time</code> information in your original <code>xts</code> object.</p>\n\n<pre><code>xts(vapply(xz, function(col) col + 100, FUN.VALUE = numeric(nrow(xz))),\n order.by = time(xz))\n</code></pre>\n\n<hr>\n\n<p>Now, we test the approaches:</p>\n\n<pre><code>vapFun <- function() \"[<-\"(xz, , vapply(xz, function(col) col + 100, \n FUN.VALUE = numeric(nrow(xz))))\n\nvapFun2 <- function() xts(vapply(xz, function(col) col + 100, \n FUN.VALUE = numeric(nrow(xz))),\n order.by = time(xz))\n\n\nlibrary(microbenchmark)\n\nop <- microbenchmark(\n app = apFun(),\n sap = sapFun(), \n mXf = mapXf(),\n vap = vapFun(),\n vap2 = vapFun2(),\n times = 1000L)\n\nUnit: microseconds\n expr min lq median uq max neval\n app 4066.612 4117.860 4167.324 4270.200 364484.879 1000\n sap 3337.001 3428.798 3463.680 3532.317 4310.336 1000\n mXf 1232.070 1263.531 1275.663 1295.014 2320.361 1000\n vap 984.732 1013.248 1022.726 1035.330 100172.130 1000\n vap2 1326.899 1368.562 1389.672 1428.608 126477.354 1000\n</code></pre>\n\n<p>As you can see, the approach with <code>vapply</code> and <code>\"[<-\"</code> is the fastest one.</p>\n\n<hr>\n\n<p>An important information: if the function you want to apply to each column is a mathematical operation, you can apply it to the whole <code>xts</code> object at once, e.g., <code>xz + 100</code>. This is considerably faster and returns an <code>xts</code> object, i.e., the dates are preserved.</p>\n\n<pre><code>simpleFun <- function() xz + 100\n\n\nop <- microbenchmark(\n app = apFun(),\n sap = sapFun(), \n mXf = mapXf(),\n vap = vapFun(),\n vap2 = vapFun2(),\n simple = simpleFun(),\n times = 1000L)\n\nUnit: microseconds\n expr min lq median uq max neval\n app 4063.972 4119.6995 4145.120 4243.7955 85454.87 1000\n sap 3347.558 3429.6725 3450.778 3515.3745 86508.52 1000\n mXf 1236.142 1267.2030 1276.455 1289.7095 84349.75 1000\n vap 992.792 1017.7425 1024.992 1033.7785 82275.26 1000\n vap2 1336.300 1372.8755 1390.553 1423.9875 83118.79 1000\n simple 92.770 98.4305 101.080 103.9995 81233.70 1000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:30:06.453",
"Id": "65713",
"Score": "0",
"body": "+1/ accepted. Thanks. I've just read up on \"[<-\", but am still a little unsure about it. Could you please explain a little? Perhaps if you name the arguments in `vapFun` it would help make it clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:42:23.797",
"Id": "65716",
"Score": "1",
"body": "@ricardo The command `\"[<-\"(x, , y)` is similar to `x[] <- y` but leaves `x` unchanged and returns a new object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T23:57:35.307",
"Id": "65725",
"Score": "0",
"body": "@SvenHehenstein Thanks; so the second argument that's left blank is the dimension argument?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:33:49.990",
"Id": "65745",
"Score": "0",
"body": "@ricardo Right!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:58:49.973",
"Id": "39212",
"ParentId": "39180",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "39212",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T20:36:37.063",
"Id": "39180",
"Score": "4",
"Tags": [
"performance",
"r"
],
"Title": "best way to apply across an xts object"
}
|
39180
|
<p>So I wrote this function to convert a given number to its interpretation in the English language as part of the <a href="http://projecteuler.net/problem=17" rel="nofollow">Project Euler exercises</a>. It works fine, but I sense that it's rather sloppy and inelegant, especially for Python where many things can be done quickly in a couple of lines. Any feedback on how to make this code more beautiful/Pythonic is appreciated!</p>
<pre><code>NUMBER_WORDS = {
1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "six",
7 : "seven",
8 : "eight",
9 : "nine",
10 : "ten",
11 : "eleven",
12 : "twelve",
13 : "thirteen",
14 : "fourteen",
15 : "fifteen",
16 : "sixteen",
17 : "seventeen",
18 : "eighteen",
19 : "nineteen",
20 : "twenty",
30 : "thirty",
40 : "forty",
50 : "fifty",
60 : "sixty",
70 : "seventy",
80 : "eighty",
90 : "ninety"
}
def convert_number_to_words(num):
#Works up to 99,999
num = str(num)
analyze = 0
postfix = remainder = None
string = ""
if len(num) > 4:
analyze = int(num[0:2])
remainder = num[2:]
postfix = " thousand "
elif len(num) > 3:
analyze = int(num[0:1])
remainder = num[1:]
postfix = " thousand "
elif len(num) > 2:
analyze = int(num[0:1])
remainder = num[1:]
postfix = " hundred "
if int(remainder) > 0:
postfix += "and "
elif int(num) in NUMBER_WORDS:
analyze = int(num)
else:
analyze = int(num[0:1] + "0")
remainder = num[1:]
postfix = "-"
string = NUMBER_WORDS[analyze]
if postfix is not None:
string += postfix
if remainder is not None and int(remainder) > 0:
return string + convert_number_to_words(remainder)
else:
return string
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:48:01.937",
"Id": "65589",
"Score": "0",
"body": "\"And\" is normally reserved for writing out fractions. 13,500 would be \"thirteen thousand and five hundred\" in your example, but would be said as \"thirteen thousand five hundred\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:55:20.713",
"Id": "65590",
"Score": "0",
"body": "@TyCobb Ah, good point. Editted. I'm with you that \"and\" shouldn't be included at all, but it's in the directions of the problem: http://projecteuler.net/problem=17"
}
] |
[
{
"body": "<p>Here's one using modulo <code>%</code> and list joining that uses your original <code>NUMBER_WORDS</code> dict:</p>\n\n<pre><code>def int_to_english(n):\n english_parts = []\n ones = n % 10\n tens = n % 100\n hundreds = math.floor(n / 100) % 10\n thousands = math.floor(n / 1000)\n\n if thousands:\n english_parts.append(int_to_english(thousands))\n english_parts.append('thousand')\n if not hundreds and tens:\n english_parts.append('and')\n if hundreds:\n english_parts.append(NUMBER_WORDS[hundreds])\n english_parts.append('hundred')\n if tens:\n english_parts.append('and')\n if tens:\n if tens < 20 or ones == 0:\n english_parts.append(NUMBER_WORDS[tens])\n else:\n english_parts.append(NUMBER_WORDS[tens - ones])\n english_parts.append(NUMBER_WORDS[ones])\n return ' '.join(english_parts)\n</code></pre>\n\n<p>It works up to 999,999, but could be extended further with a little customisation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-27T14:04:09.597",
"Id": "206747",
"Score": "0",
"body": "Your very last `else` shouldn't append 2 elements but insert them at once with a `-` as separation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T06:03:08.693",
"Id": "39201",
"ParentId": "39183",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39201",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T21:24:35.967",
"Id": "39183",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"python-3.x",
"converting"
],
"Title": "Python converter: number-to-English - Project Euler 17"
}
|
39183
|
<p>I am working on an app: a virtual sandbox of sorts, a lot like <a href="http://dan-ball.jp/en/javagame/dust/" rel="nofollow"><em>Powder Game</em></a>.</p>
<p>The problem is, when working with an app, you must deal with hardware limitations. Don't get me wrong, the speed isn't like 2 FPS or anything, but I would just like for someone to look over the code and point out any spots that could use optimization, to speed things up. I just want max performance for the first stable build, and I might learn something.</p>
<p>I am using <a href="http://pygame.renpy.org/android-packaging.html" rel="nofollow">pgs4a</a> to package it for Android.</p>
<p>This code is a bit lengthy, so if you'd like for me to post it as a zip file, just let me know.</p>
<pre><code>import pygame
from random import choice
from pygame.locals import *
try:
import android
except ImportError:
android = None
pygame.init()
end=0
if android:
android.init()
android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
menuscreen=pygame.display.set_mode((480,320))
done=0
phone=pygame.image.load('phone.bmp').convert()
tablet=pygame.image.load('tablet.bmp').convert()
prect=pygame.Rect(70,50,117,41)
trect=pygame.Rect(70,180,117,41)
stype=1
while done==0:
menuscreen.fill((0,0,0))
menuscreen.blit(phone,(70,50))
menuscreen.blit(tablet,(70,180))
if android:
if android.check_pause():
android.wait_for_resume()
for e in pygame.event.get():
if e.type==MOUSEBUTTONDOWN:
if prect.collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]):
stype=1
done=1
elif trect.collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]):
stype=2
done=1
if not android:
if e.type==QUIT:
end=1
done=1
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
end=1
done=1
pygame.display.flip()
if stype==1:
screen = pygame.display.set_mode((480,320))
partdraw=pygame.Surface((480,320))
else:
screen = pygame.display.set_mode((800,480))
partdraw=pygame.Surface((800,480))
def DrawPart(x,y,col):
pygame.draw.rect(partdraw, col, (x,y,8,8), 0)
class PlantPart(object):
def __init__(self,x,y):
self.x=x
self.y=y
self.rect=pygame.Rect(self.x,self.y,8,8)
self.color=(0,203,0)
self.gone=0
def update(self):
self.rect=pygame.Rect(self.x,self.y,8,8)
if self.y<screen.get_height()-8:
if screen.get_at((self.x,self.y+8)) == (0,0,0,255) or screen.get_at((self.x,self.y+8)) == (0,0,255,255):
self.y+=8
if self.gone==0:
if self.x>0 and self.x<screen.get_width()-8:
if screen.get_at((self.x-1,self.y)) == (255,0,0,255) or screen.get_at((self.x+8,self.y)) == (255,0,0,255):
self.gone='yes'
sand.remove(self)
if self.y>0 and self.y<screen.get_height()-8:
if screen.get_at((self.x,self.y+8)) == (255,0,0,255) or screen.get_at((self.x,self.y-1)) == (255,0,0,255):
if self.gone==0:
self.gone=1
sand.remove(self)
class SandPart(object):
def __init__(self,x,y):
self.x=x
self.y=y
self.rect=pygame.Rect(self.x,self.y,8,8)
self.color=(200,180,0)
def update(self):
self.rect=pygame.Rect(self.x,self.y,8,8)
if self.y<screen.get_height()-8:
if screen.get_at((self.x,self.y+8)) == (0,0,0,255) or screen.get_at((self.x,self.y+8)) == (0,0,255,255):
self.y+=8
class WaterPart(object):
def __init__(self,x,y):
self.x=x
self.y=y
self.rect=pygame.Rect(self.x,self.y,8,8)
self.color=(0,0,255)
self.gone=0
def update(self):
self.rect=pygame.Rect(self.x,self.y,8,8)
do=choice([1,2,1,2,1,2,2,1])
if self.x>0 and self.x<screen.get_width()-8:
if screen.get_at((self.x-1,self.y)) == (255,0,0,255) or screen.get_at((self.x+8,self.y)) == (255,0,0,255):
self.gone=1
sand.remove(self)
if screen.get_at((self.x-1,self.y)) == (0,203,0,255) or screen.get_at((self.x+8,self.y)) == (0,203,0,255):
if self.gone==0:
sand.remove(self)
self.gone=1
sand.append(PlantPart(self.x,self.y))
if self.y>0 and self.y<screen.get_height()-8:
if screen.get_at((self.x,self.y+8)) == (255,0,0,255):
if self.gone==0:
self.gone=1
sand.remove(self)
if screen.get_at((self.x,self.y+8)) == (0,203,0,255):
if self.gone==0:
sand.remove(self)
sand.append(PlantPart(self.x,self.y))
if self.gone==0:
if self.y>0:
if screen.get_at((self.x,self.y-1)) == (255,0,0,255) or screen.get_at((self.x,self.y-1)) == (200,180,0,255):
sand.remove(self)
if self.y<screen.get_height()-8:
try:
if screen.get_at((self.x+4,self.y+8)) == (0,0,0,255):
self.y+=8
else:
if do==1:
if screen.get_at((self.x+9,self.y+3)) == (0,0,0,255):
self.x+=8
elif screen.get_at((self.x-5,self.y+3)) == (0,0,0,255):
self.x-=8
except:
pass
class LavaPart(object):
def __init__(self,x,y):
self.x=x
self.y=y
self.rect=pygame.Rect(self.x,self.y,8,8)
self.color=(255,0,0)
self.gone=0
def update(self):
self.rect=pygame.Rect(self.x,self.y,8,8)
do=choice([1,2,1,2,1,2,2,1])
if self.x>0 and self.x<screen.get_width()-8:
if screen.get_at((self.x-1,self.y)) == (0,0,255,255) or screen.get_at((self.x+8,self.y)) == (0,0,255,255):
self.gone=1
sand.remove(self)
if self.y<screen.get_height()-8:
if screen.get_at((self.x,self.y+8)) == (0,0,255,255):
if self.gone==0:
sand.remove(self)
if self.gone==0:
if self.y>0:
if screen.get_at((self.x,self.y-1)) == (0,0,255,255) or screen.get_at((self.x,self.y-1)) == (200,180,0,255):
sand.remove(self)
if self.y<screen.get_height()-8:
try:
if screen.get_at((self.x+4,self.y+8)) == (0,0,0,255):
self.y+=8
else:
if do==1:
if screen.get_at((self.x+9,self.y+3)) == (0,0,0,255):
self.x+=8
elif screen.get_at((self.x-5,self.y+3)) == (0,0,0,255):
self.x-=8
except:
pass
def main():
global end
global sand
while True:
menu=0
clock=pygame.time.Clock()
sand=[]
menurect=pygame.Rect(20,15,117,41)
img='clear.bmp'
image1=pygame.image.load(img).convert()
clearrect=pygame.Rect(screen.get_width()-260,15,117,41)
img='menu.bmp'
image2=pygame.image.load(img).convert()
backrect=pygame.Rect(screen.get_width()-137,15,117,41)
img='back.bmp'
image3=pygame.image.load(img).convert()
sel='SandPart'
menuitems=[pygame.Rect(25,60,32,32),pygame.Rect(25,120,32,32),pygame.Rect(25,180,32,32),pygame.Rect(25,240,32,32)]
while end==0:
screen.fill((0,0,0))
mse=pygame.mouse.get_pos()
screen.blit(partdraw,(0,0))
partdraw.fill((0,0,0))
screen.blit(image2,(20,15))
pygame.draw.rect(screen, (0,0,0), (-480,0,480,800), 0)
eraserect=pygame.Rect(mse[0]-6,mse[1]-6,16,16)
for s in sand:
DrawPart(s.x,s.y,s.color)
s.update()
if pygame.mouse.get_pressed()==(1,0,0):
if menurect.collidepoint(mse[0],mse[1]):
if android:
android.vibrate(0.2)
menu=1
while menu==1:
screen.fill((0,0,0))
screen.blit(image3,(screen.get_width()-137,15))
screen.blit(image1,(screen.get_width()-260,15))
mse=pygame.mouse.get_pos()
if pygame.mouse.get_pressed()==(1,0,0):
if clearrect.collidepoint(mse[0],mse[1]):
sand=[]
if android:
android.vibrate(0.1)
if backrect.collidepoint(mse[0],mse[1]):
if android:
android.vibrate(0.2)
menu=0
if menu==1:
for m in menuitems:
if m==menuitems[0]:
if m.collidepoint(mse[0],mse[1]):
if pygame.mouse.get_pressed()==(1,0,0):sel='SandPart'
if android:
android.vibrate(0.1)
if sel is not 'SandPart':
pygame.draw.rect(screen, (200,180,0), m, 1)
else:
pygame.draw.rect(screen, (200,180,0), m, 0)
elif m==menuitems[1]:
if m.collidepoint(mse[0],mse[1]):
if android:
android.vibrate(0.1)
if pygame.mouse.get_pressed()==(1,0,0):sel='WaterPart'
if sel is not 'WaterPart':
pygame.draw.rect(screen, (5,5,210), m, 1)
else:
pygame.draw.rect(screen, (5,5,210), m, 0)
elif m==menuitems[2]:
if m.collidepoint(mse[0],mse[1]):
if android:
android.vibrate(0.1)
if pygame.mouse.get_pressed()==(1,0,0):sel='PlantPart'
if sel is not 'PlantPart':
pygame.draw.rect(screen, (0,203,0), m, 1)
else:
pygame.draw.rect(screen, (0,203,0), m, 0)
elif m==menuitems[3]:
if m.collidepoint(mse[0],mse[1]):
if android:
android.vibrate(0.1)
if pygame.mouse.get_pressed()==(1,0,0):sel='LavaPart'
if sel is not 'LavaPart':
pygame.draw.rect(screen, (255,0,0), m, 1)
else:
pygame.draw.rect(screen, (255,0,0), m, 0)
if not any(m.collidepoint(mse[0],mse[1]) for m in menuitems):
if pygame.mouse.get_pressed()==(1,0,0):
sel='erase'
if android:
if android.check_pause():
android.wait_for_resume()
for e in pygame.event.get():
if not android:
if e.type==QUIT:
menu=0
end=1
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
menu=0
end=1
pygame.display.flip()
else:
if screen.get_at((mse[0],mse[1]))==(0,0,0,255):
if sel is not 'erase':
sand.append(eval(sel)((mse[0]/8)*8,(mse[1]/8)*8))
if sel=='erase':
for s in sand:
if s.rect.colliderect(eraserect):
sand.remove(s)
if android:
if android.check_pause():
android.wait_for_resume()
for e in pygame.event.get():
if not android:
if e.type==QUIT:
end=1
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
end=1
clock.tick(65)
pygame.display.flip()
break
# This isn't run on Android.
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T16:58:17.313",
"Id": "65696",
"Score": "4",
"body": "The best way to optimize code is to profile it and optimize only the critical parts. Optimizing for the sake of it loses readability and does nothing for performance (I've worked on hi performance programs for 8+ years). So, if you can run a profile on the code and come like: \"This part of my code sucks processor, do you know how to make it work faster\" 'd be easier :-)"
}
] |
[
{
"body": "<p>The comment from fernando.reyes is 100% correct: if you haven't measured things, you can't tell what's slow, or if it gets faster. That said, there are two main things I see that I know from prior exposure are likely to be slow. Since I've not used python on android, much less pgs4a, even that is quite possibly not applicable or not relevant. So, again, if you don't measure, you cannot prove whether these are actually meaningful in your case, or if changing them helps.</p>\n\n<p>(By the way, seriously, clean up the code before asking for reviews. In the nearly 300 lines of code, the only comment (or docstring) is <code># This isn't run on Android.</code>, there are multiple unhelpful—such as one-character—variable names, the use of horizontal whitespace is irregular, and vertical whitespace is missing.)</p>\n\n<p><strong>Avoid eval.</strong> Its use can prevent normal optimizations that python does for local variables in a function. For example:</p>\n\n<pre><code>sel='SandPart'\n...\nif sel is not 'SandPart':\n...\nsand.append(eval(sel)((mse[0]/8)*8,(mse[1]/8)*8))\n</code></pre>\n\n<p>Prefer working with callables as actual objects.</p>\n\n<pre><code>sel = SandPart\n...\nif sel is not SandPart:\n...\nsand.append(sel((mse[0]/8)*8, (mse[1]/8)*8))\n</code></pre>\n\n<p><strong>Avoid looking up globals or deep attribute lookups in loops.</strong> For example:</p>\n\n<pre><code>if e.type==MOUSEBUTTONDOWN:\n if prect.collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]):\n</code></pre>\n\n<p>could well be this, to avoid half of the lookups:</p>\n\n<pre><code>if e.type==MOUSEBUTTONDOWN:\n if prect.collidepoint(*pygame.mouse.get_pos()):\n</code></pre>\n\n<p>or this, to avoid the other half:</p>\n\n<pre><code>if e.type==MOUSEBUTTONDOWN:\n if prect.collidepoint(*e.pos):\n</code></pre>\n\n<p>Similarly you can consider capturing the globals (or better yet their deep attribute names) as locals to avoid excess lookups:</p>\n\n<pre><code>def main():\n Rect = pygame.Rect\n get_pressed = pygame.mouse.get_pressed\n draw_rect = pygame.draw.rect\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:54:32.523",
"Id": "39239",
"ParentId": "39185",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T22:18:42.460",
"Id": "39185",
"Score": "3",
"Tags": [
"python",
"performance",
"android",
"pygame"
],
"Title": "Virtual sandbox game"
}
|
39185
|
<p>I am working on building an <code>UndoManager</code> in C#. The concept is to store events and property changes in a <code>Stack<Action<T>></code> instance. I believe it is working, but I am also looking for peer review.</p>
<p>What can I improve? Do you see any bugs? </p>
<pre><code>public abstract class UndoManager<T>
{
/// <summary>
/// Adds an Event to Stack
/// </summary>
/// <param name="undoOperation"></param>
protected abstract void Add(Action<T> undoOperation);
/// <summary>
/// Returns the size of the stack
/// </summary>
/// <returns></returns>
public abstract int Size();
/// <summary>
/// Holds all the Events in a stack
/// </summary>
protected Stack<Action<T>> MyUndoOperations { get; set; }
protected Stack<Action<T>> MyRedoOperations { get; set; }
/// <summary>
/// Preforms the undo action. Pops the last event and gets a reference to the next event
/// and fires the event
/// </summary>
public abstract void Undo();
/// <summary>
/// Preforms the Redo action.
/// </summary>
public abstract void Redo();
}
public class MyClass : UndoManager<MyClass>
{
#region Getter and Setters
private String myValue;
public String MyValue
{
get { return this.myValue; }
set
{
this.Add(x => x.myValue = value);// save the operation on the stack
this.myValue = value;
}
}
private String productName;
public String ProductName
{
get { return productName; }
set
{
this.Add(x => x.productName = value);// save the operation on the stack
productName = value;
}
}
#endregion
/// <summary>
/// Returns the size of the Action Event Stack
/// </summary>
/// <returns>Size of this.MyOperations</returns>
public override int Size()
{
return this.MyUndoOperations.Count();
}
public MyClass()
{
this.MyUndoOperations = new Stack<Action<MyClass>>();
this.MyRedoOperations = new Stack<Action<MyClass>>();
}
/// <summary>
/// Pushes the last Action event on the Stack
/// </summary>
/// <param name="undoOperation">Last Action Event</param>
protected override void Add(Action<MyClass> undoOperation)
{
//this.MyRedoOperations.Clear();
this.MyUndoOperations.Push(undoOperation);
}
/// <summary>
/// Preforms the undo action. Pops the last event and gets a reference to the next event
/// and fires the event
/// </summary>
public override void Undo()
{
if (this.MyUndoOperations != null && this.MyUndoOperations.Any())
{
Action<MyClass> topAction = this.MyUndoOperations.Pop();// remove the very last event.
this.MyRedoOperations.Push(topAction); // add to the redo stack
if (this.MyUndoOperations.Any())
{
// get a reference (peek) to the last event
Action<MyClass> lastAction = this.MyUndoOperations.Peek();
lastAction(this);// fire event
//this.Add(lastAction); // add to the undo stack
}
}
}
public override void Redo()
{
if (this.MyRedoOperations.Any())
{
Action<MyClass> lastAction = this.MyRedoOperations.Pop();
lastAction(this);// fire event
this.Add(lastAction);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Calling Add ought to clear the MyRedoOperations stack, but not when you call it from Redo.</p>\n\n<p>Secondly, <code>Action<T></code> is an uncomplicated type. It works for properties, because replaying an old action will reset the property to its previous value. However it won't work if you want a more general manager which can undo methods (not just properties), for example, the edit methods of a document. Consider a method which adds items to a list: if you replay an old method it will add the item again, not remove it. Therefore when I implemented an undo manager, instead of storing a single Action I would store a pair of actions (one for undo and one for redo), for example like the following pseudocode:</p>\n\n<pre><code>// A typical method which needs undoing\nvoid InsertItem(object item)\n{\n // this method should do:\n // this.MyList.Insert(item);\n\n // construct a pair of undo/redo actions\n EditorAction editorAction = new EditorAction() {\n Do = this.MyList.Insert(item),\n Undo = this.MyList.Remove(item)\n };\n // invoke the Do action and save it on the Undo stack\n NewAction(editorAction);\n}\n\nclass EditorAction\n{\n Action Undo;\n Action Do;\n}\n\nvoid NewAction(EditorAction editorAction)\n{\n // Perform the action for the first time\n editorAction.Do();\n // Save the action on the undo stack\n UndoStack.Push(editorAction);\n RedoStack.Clear()\n}\n\nvoid UndoAction()\n{\n EditorAction editorAction = UndoStack.Pop();\n editorAction.Undo();\n RedoStack.Push(editorAction);\n}\n\nvoid RedoAction()\n{\n EditorAction editorAction = RedoStack.Pop();\n editorAction.Do();\n UndoStack.Push(editorAction);\n}\n</code></pre>\n\n<p>Thirdly, beware of making UndoManager an abstract class. Do its Undo/Redo methods really need to be abstract and overriden, or could it be a concrete class instead? The problem with an abstract class is that C# doesn't support multiple inheritance: a class (e.g. MyClass) can only have one abstract base class; if UndoManager is an abstract class then it can't be used by any class which already has another base class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:51:22.903",
"Id": "65665",
"Score": "0",
"body": "Chris, I like this approach. I still need to review all the answers (which its great how constructive the responses are). Putting your code online for review is like asking if your baby is ugly or pretty. Nevertheless, I think @Sergey's approach along with yours will improve my code. I'll work on it and post an edit for review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:21:35.737",
"Id": "65677",
"Score": "2",
"body": "I mostly agree with everything you wrote, but I would advise against using a struct to store command delegates. It's not only mutable and passed by value, but you don't get any options for inheritance, overriding stuff, proxying commands, or basically storing any state within the command itself. As a design decision at this time, it would be much better to keep your options open by creating an interface for a command, which can also easily have a \"poor-man's\" delegate-only implementation for quick and dirty commands."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:42:26.377",
"Id": "65683",
"Score": "1",
"body": "@Groo Sorry about that. I meant it as pseudo-code for \"A class with public members\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:39:20.390",
"Id": "65964",
"Score": "0",
"body": "I've since read the answers/comments from on this post and did a major overhaul of the code. Should I start a new CR question to review the new code, of update my OP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T19:00:33.790",
"Id": "65972",
"Score": "1",
"body": "@PhilVallone See [How to deal with follow-up questions?](http://meta.codereview.stackexchange.com/questions/1065/how-to-deal-with-follow-up-questions)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:47:02.427",
"Id": "39187",
"ParentId": "39186",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>What's most important, as @ChrisW wrote, you need two separate actions for <code>Execute</code>/<code>Redo</code> and <code>Undo</code>. A common command interface would be something like:</p>\n\n<pre><code>public interface ICommand\n{\n // Executes this command.\n void Execute();\n\n // Undoes this command.\n void Undo();\n}\n</code></pre></li>\n<li><p>The <code>UndoManager</code> should not be generic nor abstract. By making it generic, you only allow it to store a limited set of commands, which is unnecessary. The manager should not know anything about the command it stores, apart from the fact that it can invoke <code>Execute</code> and <code>Undo</code> on them.</p></li>\n<li><p>There is no need to make it abstract, either. I would however extract its interface so that you can test it (mock it), or provide dummy implementations in special cases. I doubt you would have additional derived undo managers, since its behavior is well defined, so I would probably limit the interface to something like:</p>\n\n<pre><code>public interface IUndoManager\n{\n // Executes the specified commmand and adds it to the Undo stack.\n void Execute(ICommand commmand);\n\n // Undoes the last command in the Undo stack.\n void Undo();\n\n // Redoes the last command in the Redo stack.\n void Redo();\n}\n</code></pre>\n\n<p>If you want to let your callers know more about the command manager state, then you can extend the whole thing by adding properties like <code>Name</code> to the <code>ICommand</code>, or <code>CanUndo</code>/<code>CanRedo</code> to the <code>ICommandManager</code>. That will allow your callers (i.e. a menu item in your Edit menu) to know if there exists an undoable command, and what's its description. But at all costs <strong>avoid</strong> exposing \"internal\" stuff, like the size of your stack.</p></li>\n<li><p>Although I understand it's conceptual code, I would avoid prefix class names and property names with <code>My</code> (<code>MyClass</code>, <code>MyUndoOperations</code>). It doesn't provide any useful information.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:03:05.007",
"Id": "39210",
"ParentId": "39186",
"Score": "7"
}
},
{
"body": "<p>In order to undo some changes, you should either do all changes besides last one, or you can remove last change and do opposite operation. E.g. if you are inserting something to database, then opposite operation will be removing from database.</p>\n\n<p>Next, your class do to many things - it has own responsibilities, which are related to ProductName and MyValue managing. But you are also make this class managing actions stack - calculating size, adding and removing actions. I think all that behavior can and should be encapsulated in UndoManager class (btw, I don't like manager classes, because it's not clear what they do - it worth thinking about better name here).</p>\n\n<p>So, common way to encapsulate operations is a Command pattern. Basic command which allows executing some operations (both direct and opposite) looks like:</p>\n\n<pre><code>public class Command \n{\n private readonly Action _action;\n private readonly Action _undoAction; \n\n public Command(Action action, Action undoAction)\n {\n _undoAction = undoAction;\n _action = action;\n }\n\n public void Execute()\n {\n _action();\n }\n\n public void Undo()\n {\n _undoAction();\n }\n}\n</code></pre>\n\n<p>Now, when we have operations encapsulated, we can create commands manager (I'm still thinking of better name):</p>\n\n<pre><code>public class StateManager\n{\n private Stack<Command> commands = new Stack<Command>();\n\n protected void ChangeState(Command command)\n {\n command.Execute();\n commands.Push(command);\n }\n\n public void RestorePreviousState()\n {\n var command = commands.Pop();\n command.Undo();\n }\n\n // You can add Redo functionality here\n}\n</code></pre>\n\n<p>It encapsulates working with commands. It executes command when you do something and it removes last command with undoing it when you want to undo last change. Now inherit from this class:</p>\n\n<pre><code>public class MyClass : StateManager\n{\n private String myValue;\n private String productName;\n\n public String MyValue\n {\n get { return myValue; }\n set \n {\n string currentValue = myValue;\n ChangeState(new Command(() => myValue = value, \n () => myValue = currentValue)); \n }\n }\n\n public String ProductName\n {\n get { return productName; }\n set\n {\n string currentValue = productName;\n ChangeState(new Command(() => productName = value, \n () => productName = currentValue)); \n }\n }\n}\n</code></pre>\n\n<p>Now you can keep track on object state changes:</p>\n\n<pre><code>MyClass mc = new MyClass();\nmc.MyValue = \"foo\";\n// mc.MyValue is \"foo\";\nmc.MyValue = \"bar\";\n// mc.MyValue is \"bar\";\nmc.RestorePreviousState();\n// mc.MyValue is \"foo\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:12:18.860",
"Id": "65646",
"Score": "1",
"body": "I fail to see a single good reason to force inheritance in this case. As mentioned by ChrisW, this `UndoManager` can be implemented as separate and all-sufficient entity. And i think it should, otherwise its usefulness whould be quite limited. \"Favor Aggregation over Inheritance\" and blah blah :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:19:38.057",
"Id": "65648",
"Score": "0",
"body": "@Nik it's not really important here, but agree keeping instance of `StateManager` will be probably better, than inheriting from it. But that will require implementing `RestorePreviousState` method in each class which should have manageable state. Main idea here is encapsulating state changes in command, providing undo operations, executing state change in manager, and moving all state managing to manager."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:27:51.310",
"Id": "65649",
"Score": "1",
"body": "not necessary. You would still be able to implement `Undo` method on command level. Or implement undo by re-applying the command stack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:30:17.343",
"Id": "65650",
"Score": "0",
"body": "@Nik sorry, didn't get you. My command already implements Undo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:56:27.247",
"Id": "65653",
"Score": "1",
"body": "@Nik Sergey is saying that if StateManager is instance data instead of a base class, then the containing class needs to explicitly implement a visible method `void RestoreState() { this.StateManager.RestoreState(); }` instead of simply inheriting that method into its API."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T11:14:24.823",
"Id": "65654",
"Score": "0",
"body": "@ChrisW, ah, i see. I was thinking about the reverse aggregation (which, frankly, makes more sense to me). Meaning i would design `StateManager` as a container for some generic object, so i would access the actual object via `StateManger` and not vise versa."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:58:31.363",
"Id": "65666",
"Score": "1",
"body": "If you don't like 'Manager' as a name then perhaps call it 'History'; and expose it as a public property of the class which contains (not subclasses) it, so that a client can could `foo.History.Undo()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:20:29.663",
"Id": "66124",
"Score": "1",
"body": "@SergeyBerezovskiy - I have a follow up question. If `Command` holds both the undo and redo events, when a undo event takes place and is popped off the stack, you loose the associated redo event. Is is better to hold the events types in their own stack e.g. RedoStack and UndoStack?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T15:28:22.140",
"Id": "66129",
"Score": "1",
"body": "@PhilVallone yes, if you want to have redo option, you need to store command in some redo stack which should be completely cleared when you adding new command to `commands` stack. You also can use some kind of list with pointer to current command, but I think two stacks is simpler to implement."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T10:04:45.357",
"Id": "39211",
"ParentId": "39186",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39211",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T23:21:42.253",
"Id": "39186",
"Score": "9",
"Tags": [
"c#",
"delegates"
],
"Title": "A custom Undo Manager"
}
|
39186
|
<p>Looking for optimization, smart tips and verification of complexity: O (log (base 2) power).</p>
<p>NOTE: <code>System.out.println("Expected 16, Actual: " + Power.pow(2, 7));</code> is a typo. It correctly returns 128.</p>
<pre><code>/**
* Find power of a number.
*
* Complexity: O (log (base 2) power)
*/
public final class Power {
private Power() { }
/**
* Finds the power of the input number.
* @param x the number whose power needs to be found
* @param pow the power
* @return the value of the number raised to the power.
*/
public static double pow(double x, int pow) {
if (x == 0) return 1;
return pow > 0 ? getPositivePower(x, pow) : 1 / getPositivePower(x, -pow);
}
private static double getPositivePower(double x, int pow) {
assert x != 0;
if (pow == 0) return 1;
int currentPow = 1;
double value = x;
while (currentPow <= pow/2) {
value = value * value;
currentPow = currentPow * 2;
}
return value * getPositivePower(x, pow - currentPow);
}
public static void main(String[] args) {
System.out.println("Expected 6.25, Actual: " + Power.pow(2.5, 2));
System.out.println("Expected 16, Actual: " + Power.pow(2, 7));
System.out.println("Expected 0.25, Actual: " + Power.pow(2, -2));
System.out.println("Expected -27, Actual: " + Power.pow(-3, 3));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:27:40.363",
"Id": "65616",
"Score": "2",
"body": "I assume you don't want to use the built-in `java.lang.Math.pow` function."
}
] |
[
{
"body": "<p>This <strong>can</strong> get worse than \\$\\operatorname{O}(\\log \\verb~pow~)\\$. [Remark: in \\$\\operatorname{O}\\$-notation, the base of an logarithm is irrelevant, since it represents only a multiplication with a constant]</p>\n\n<p>Let \\$\\verb~pow~ = 2^n - 1\\$ for some \\$n\\$. Then you're computing the following powers:</p>\n\n<ul>\n<li><p>\\$1, 2, 4,\\dots, 2^{n-1}\\$, followed by a function call for \\$\\verb~pow~ = (2^n-1) - 2^{n-1} = 2^{n-1} - 1\\$;</p></li>\n<li><p>\\$1, 2, 4,\\dots, 2^{n-2}\\$, followed by a function call for \\$\\verb~pow~ = (2^{n-1}-1) - 2^{n-2} = 2^{n-2} - 1\\$;</p></li>\n<li><p>\\$1, 2, 4,\\dots, 2^{n-3}\\$, followed by a function call for \\$\\verb~pow~ = (2^{n-2}-1) - 2^{n-3} = 2^{n-3} - 1\\$;<br>\n...</p></li>\n</ul>\n\n<p>All in all, \\$n + (n-1) + ... + 1 = n(n+1)/2\\$ calls of the inner loop. In terms of <code>pow</code>, this is \\$\\operatorname{O}(\\log^2 \\verb~pow~)\\$.</p>\n\n<p>Instead, observe <code>pow</code> as a binary number. I don't do Java, so I'll just sketch this in C, which is quite like it.</p>\n\n<pre><code>double px = x; // current power of x\ndouble result = 1;\nwhile (pow > 0) {\n if (pow % 2) result *= px;\n pow /= 2;\n px *= px;\n}\n</code></pre>\n\n<p>So, you are observing \\$x, x^2, x^4, x^8,...\\$ and multiplying with them if the corresponding binary digit of <code>pow</code> is equal to \\$1\\$. This has \\$\\operatorname{O}(\\log \\verb~pow~)\\$ steps.</p>\n\n<p>By the way, I don't think \\$2^7\\$ is expected to be \\$16\\$. ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-03T03:14:57.690",
"Id": "256282",
"Score": "0",
"body": "I added some MathJax to this answer (the edit's in the queue right now) but I'm unsure how you want MathJax for that big code block starting with `1, 2, 4,..., 2^{n-1}`. Can you edit it the way you want to do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-03T13:13:38.503",
"Id": "256342",
"Score": "0",
"body": "@Peanut Thank you. I've TeXified it now (that was not an option when I first wrote the answer). Feel free to suggest further improvements if you think I did something wrong or unclear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:51:11.970",
"Id": "39193",
"ParentId": "39190",
"Score": "7"
}
},
{
"body": "<p>Bug #1: <em>0.0<sup>n</sup> where n > 0</em> is equal to <code>0.0</code>, and not <code>1</code> as you have in your code <code>if (x == 0) return 1;</code> (although <em>0<sup>0</sup></em> is 1, not 0, and <em>0.0<sup>n</sup> where n < 0</em> is <em>NaN</em>).</p>\n\n<p>Bug #2: You very carefully have the test method:</p>\n\n<pre><code>System.out.println(\"Expected 16, Actual: \" + Power.pow(2, 7));\n</code></pre>\n\n<p>But, <em>2<sup>7</sup></em> is actually 128.</p>\n\n<p>At this point, I figure a vote-to-close, but, FYI: </p>\n\n<p>Picking apart the core method <code>getPositivePower(double, int)</code> .... This is your code:</p>\n\n<pre><code>private static double getPositivePower(double x, int pow) {\n assert x != 0;\n if (pow == 0) return 1;\n\n int currentPow = 1;\n double value = x; \n while (currentPow <= pow/2) {\n value = value * value;\n currentPow = currentPow * 2;\n }\n\n return value * getPositivePower(x, pow - currentPow);\n}\n</code></pre>\n\n<ul>\n<li>Why do you need the <code>assert</code>? Sure, you can check the input value is correct, but, there is only one place to call the method, and it is a few lines above. There is no reason to assert <strong>everything</strong>.... you have to trust something somewhere, and in my opinion, this is overly cautious.</li>\n<li>in the last line, you are either 1, or 0 powers short of your intended result, so why do you have to do a full recursion? Simply: `return value * (pow == currentPow ? 1 : x);</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:57:09.883",
"Id": "39194",
"ParentId": "39190",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39193",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T00:06:33.917",
"Id": "39190",
"Score": "3",
"Tags": [
"java",
"mathematics",
"reinventing-the-wheel"
],
"Title": "Find power of a number"
}
|
39190
|
<p>I have a considerably large directive which is doing many things: First it renders a Google Map, then it adds a listener to check when the bounds of the map change, then it renders points on the map based where the bounds currently are, and finally it has a menu of options which allow the user to turn on and off various settings on the map. </p>
<p>The code snippet below has been heavily modified to show the most important aspects of the directive. I've also hardcoded the template rather than used a <code>templateURL</code>.</p>
<p>This directive works exactly the way I want it to, and my questions are more about best practices for Angular:</p>
<ol>
<li>Should I be pulling out the Ajax calls and placing them inside a service?</li>
<li>Should I create a Map controller and put some of this configuration logic in there?</li>
<li>When do I know if I need a new controller for that matter?</li>
</ol>
<p>I'm afraid there is too much going on inside this directive and it should be broken out.</p>
<pre><code>(function(angular) {
'use strict';
angular.module('myApp.directives').directive('myAppMap', [function() {
return {
template: '<div>A whole bunch of toggles for the map go here</div> \
<div id="map-canvas" style="width: 100%; height: 600px"></div>'
link: function(scope, element, attrs) {
var map, markers = [], currentLayer = [];
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(34.05, -118.245),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'myApp_style']
}
},
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions)
map.mapTypes.set('myApp_style', styledMap);
map.setMapTypeId('myApp_style');
google.maps.event.addListener(map, 'bounds_changed', (function() {
_getClusters();
})());
}
function _getClusters(filters) {
$.ajax({
url: "http://localhost:1625/ocpu/library/imyApp/R/gen_cluster/json",
type: 'POST',
dataType:'json',
data: {
NE_lng:map.getBounds().getNorthEast(),
SW_lng:map.getBounds().getSouthWest()
maxNumber: 100
},
success:function(data){
_setMarkers(map, JSON.parse(data));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("ajax error - arun", xhr.status, thrownError);
}
})
}
function _setMarkers(map, clusters) {
for (var i = 0; i < clusters.length; i++) {
var thisCluster = clusters[i];
var myLatLng = new google.maps.LatLng(thisCluster.lat, thisCluster.lon);
markers[i] = new MarkerWithLabel({
position: myLatLng,
map: map,
icon: "marker_01.png",
labelClass: "myAppMarker",
labelAnchor: new google.maps.Point(10, 40),
})
google.maps.event.addListener(markers[i], 'click', function() {
map.setCenter(this.getPosition())
map.setZoom(map.getZoom()+1);
})
}
}
function _toggleControls(direction) {
if (direction=="open") {
$(".mapControls").height("130");
$(".mapControls .controls").fadeIn();
}
else {
$(".mapControls .controls").fadeOut();
$(".mapControls").height("30");
}
}
$(".mapControls .open").click(function(){
if ($(".mapControls .controls").is(":visible")) {
_toggleControls("close")
}
else {
_toggleControls("open")
}
})
initialize();
}
}
}]);
})(window.angular);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:50:14.910",
"Id": "65686",
"Score": "0",
"body": "Your code does not run, your return statement seems wrong."
}
] |
[
{
"body": "<p>From a once over</p>\n\n<ul>\n<li>You seem to be missing a comma after <code></div>'</code></li>\n<li>You seem to be missing a comma after <code>SW_lng:map.getBounds().getSouthWest()</code></li>\n<li>This code is reviewable, still, next time make sure there are no syntax errors..</li>\n<li>Hard coding <code>(34.05, -118.245)</code> is wrong, get it from your Angular model/controller</li>\n<li>Why prefix all your functions with <code>_</code>, except for <code>initialize</code> ?</li>\n<li>Hard coding <code>\"http://localhost:1625/ocpu/library/imyApp/R/gen_cluster/json\"</code> is bad</li>\n<li>Production code should not have <code>console.log</code></li>\n<li>You are not using the variable <code>currentLayer</code></li>\n<li>You are not using the parameter <code>filters</code> in <code>_getClusters</code></li>\n<li>You should not create a new listener function for each marker in <code>_setMarkers</code>, you could create 1 function before the loop with a reference to <code>map</code>. This might cause performance problems</li>\n<li>You should merge <code>_toggleControls</code> and <code>$(\".mapControls .open\").click(</code>, it does not look DRY</li>\n</ul>\n\n<p>All in all, I find the Google Maps API unwieldy, and because of that I do not think this is too much. However, you do need to something with the configuration logic, right now it looks akward.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T15:19:23.133",
"Id": "39224",
"ParentId": "39196",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T01:40:07.797",
"Id": "39196",
"Score": "1",
"Tags": [
"javascript",
"angular.js",
"google-maps"
],
"Title": "Directive to create a Google map"
}
|
39196
|
<p>I am writing a program to factor stupidly large integers (5000 digits+), and performance is obviously critical. A currently TODO feature is to factor semiprimes, specifically RSA, which is why the cube root function is included. Don't tell me it's impossible. I'm trying to learn, not actually do it. Before I start on the actual factorization, I would love review on the current program. I'm not 100% on the check methods, and any help on general performance would be helpful.</p>
<pre><code>package pfactor;
import java.io.File;
import java.math.BigInteger;
import java.util.Scanner;
public class Factor {
static BigInteger number;
static BigInteger sqrt;
static BigInteger cbrt;
static boolean abbrev;
static final BigInteger TWO = new BigInteger("2");
static final BigInteger THREE = new BigInteger("3");
public static void main(String[] args) throws Exception {
System.out.println("Abbreviate Numbers?");
abbrev = ask("Do you want to abbreviate numbers? ");
number = new BigInteger(getFile());
System.out.println("Factoring: \n\n" + abbreviate(number));
sqrt = sqrt(number);
System.out.println("The square root is: " + abbreviate(sqrt));
System.out.println("Difference: " + abbreviate(number.subtract((sqrt.multiply(sqrt))).abs()));
System.out.println("Check returns: " + checksqrt());
cbrt = cbrt(number);
System.out.println("The cube root is: " + abbreviate(cbrt));
System.out.println("Difference: " + abbreviate(number.subtract((cbrt.multiply(cbrt).multiply(cbrt))).abs()));
System.out.println("Check returns: " + checksqrt());
}
public static String getFile() throws Exception {
Scanner s = new Scanner(new File("Number.dat"));
String i = "";
while (s.hasNextLine()) {
i = i + s.nextLine();
}
return i;
}
public static BigInteger sqrt(BigInteger n) {
BigInteger guess = n.divide(BigInteger.valueOf((long) n.bitLength() / 2));
boolean go = true;
int c = 0;
BigInteger test = guess;
while (go) {
BigInteger numOne = guess.divide(TWO);
BigInteger numTwo = n.divide(guess.multiply(TWO));
guess = numOne.add(numTwo);
if (numOne.equals(numTwo)) {
go = false;
}
if (guess.mod(TWO).equals(BigInteger.ONE)) {
guess = guess.add(BigInteger.ONE);
}
//System.out.println(guess.toString());
c++;
c %= 5;
if (c == 4 && (test.equals(guess))) {
return guess;
}
if (c == 2) {
test = guess;
}
}
if ((guess.multiply(guess)).equals(number)) {
return guess;
}
return guess.add(BigInteger.ONE);
}
public static BigInteger cbrt(BigInteger n) {
BigInteger guess = n.divide(BigInteger.valueOf((long) n.bitLength() / 3));
boolean go = true;
int c = 0;
BigInteger test = guess;
while (go) {
BigInteger numOne = n.divide(guess.multiply(guess));
BigInteger numTwo = guess.multiply(TWO);
guess = numOne.add(numTwo).divide(THREE);
if (numOne.equals(numTwo)) {
go = false;
}
if (guess.mod(TWO).equals(BigInteger.ONE)) {
guess = guess.add(BigInteger.ONE);
}
// System.out.println(guess.toString());
c++;
c %= 5;
if (c == 4 && (test.equals(guess))) {
return guess;
}
if (c == 2) {
test = guess;
}
}
if ((guess.multiply(guess)).equals(number)) {
return guess;
}
return guess.add(BigInteger.ONE);
}
public static int[] fac() {
//Factor method TODO, does nothing, never called
return new int[5];
}
public static boolean checksqrt() {
if ((sqrt.multiply(sqrt)).equals(number)) {
return true;
}
BigInteger margin = number.subtract((sqrt.multiply(sqrt))).abs();
BigInteger maxError = (sqrt.subtract(BigInteger.ONE)).multiply(TWO);
if (margin.compareTo(maxError) == -1) {
return true;
}
return false;
}
public static boolean checkcbrt() {
if ((cbrt.multiply(cbrt).multiply(cbrt)).equals(number)) {
return true;
}
BigInteger margin = number.subtract((cbrt.multiply(cbrt).multiply(cbrt))).abs();
BigInteger c = cbrt.subtract(BigInteger.ONE);
BigInteger maxError = ((c.multiply(c)).multiply(THREE)).add(c.multiply(THREE));
if (margin.compareTo(maxError) == -1) {
return true;
}
return false;
}
public static String abbreviate(BigInteger n) {
if (abbrev)
return n.toString().substring(0, 3) + "..." + n.mod(new BigInteger("1000")) + "(" + n.toString().length() + " digits)";
return n.toString();
}
public static boolean ask(String prompt) {
Scanner s = new Scanner(System.in);
System.out.println(prompt + "(Y/N)");
char c = s.nextLine().charAt(0);
if (c == 'N' || c == 'n') {
return false;
}
if (c == 'Y' || c == 'y') {
return true;
}
return ask("");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The following review is about the style only, I'll leave the review of the functionality to somebody who can actually do the math.</p>\n<hr />\n<blockquote>\n<p>package pfactor;</p>\n</blockquote>\n<p>Package names should associate the package with a person or organization. For testing code it is okay to omit it, but if you ever release code "into the wild" or onto a production system, the package name should be in the format:</p>\n<pre><code>package com.mycompany.mypackage;\npackage com.gmail.username.mypackage;\npackage com.github.username.mypackage;\n</code></pre>\n<hr />\n<pre><code> static BigInteger number;\n</code></pre>\n<p>Static variables that get modified? That's bad...refactor all your code into an instance-class or get rid of those (static) variables. Using static variables that get modified only begs for trouble, thread-safety is only one of the issues.</p>\n<hr />\n<pre><code>public static void main(String[] args) throws Exception {\n</code></pre>\n<p>This is evil, your <code>main</code> method should never throw exceptions, and especially not <code>Exception</code>, it's the "I really just don't care and can't be bothered" of error handling.</p>\n<p>Handle exceptions in the main method and fail gracefully.</p>\n<hr />\n<pre><code>public static String getFile() throws Exception {\n</code></pre>\n<p>Okay, here goes rule number 1 for error handling:</p>\n<blockquote>\n<p>Never, ever, for whatever reason...and let me get this straight, there is no reason, never, absolutely never, ever, you can't come up with one, to <code>throws Exception</code>.</p>\n</blockquote>\n<p>Handle exceptions where you need to handle them, rethrow or wrap them. Or <em>at the least</em> declare the exceptions <em>explicitly</em> thrown by the method.</p>\n<p>Why is this so important? Imagine that you wrote a library with some useful functions which only declare <code>throws Exception</code>. How is the client supposed to handle specific error conditions? Testing the exception for a certain instance of a class? Parsing the error message? How does the client know that all exceptional cases are handled? How can the client guarantee that the code relying on your functions does not break? The answer is, not at all...and that's unacceptable.</p>\n<hr />\n<pre><code>Scanner s = new Scanner(new File("Number.dat"));\n</code></pre>\n<p>You're only entitled to use one-letter-variable names in two situations:</p>\n<ul>\n<li><code>for</code> loops (i, j, k)</li>\n<li>Dimensions (x, y, z)</li>\n</ul>\n<p>There is not a single reason to not use a fully understandable name for your variables. So, whenever you want to use a single letter as a variable name, stop, think by yourself "what does this variable hold" and then you name it according to it.</p>\n<pre><code>Scanner scanner = new Scanner(new File("Number.dat"));\nString content = "";\nwhile (scanner.hasNextLine()) {\n content = content + scanner.nextLine();\n}\nreturn content;\n</code></pre>\n<p>You can now start reading in the middle of the function and you still know what's going on. Overall, most of your variables need better naming.</p>\n<hr />\n<pre><code>String i = "";\n</code></pre>\n<p>This is pure evil. <code>i</code> is traditionally only used for <code>for</code> counters.</p>\n<hr />\n<pre><code>i = i + s.nextLine();\n</code></pre>\n<p>The <code>+</code> operator for concatenating strings is a very bad choice. Under the hood the folllowing happens:</p>\n<ul>\n<li>Get String A</li>\n<li>Get String B</li>\n<li>Allocate new memory (C) in the size of A + B</li>\n<li>Copy A into C</li>\n<li>Copy B into C</li>\n<li>Override A with C</li>\n</ul>\n<p>This is <em>slow</em>. You should use a <code>StringBuilder</code> instead, like this:</p>\n<pre><code>StringBuilder content - new StringBuilder();\ncontent.append(line);\nreturn content.toString();\n</code></pre>\n<p>This performs roughly these operations under the hood:</p>\n<ul>\n<li>Allocate some more memory</li>\n<li>Copy B into that memory</li>\n</ul>\n<p>The speed difference between Strings <code>+</code> and <code>StringBuilder</code> is extreme, in a tight loop with many iterations, <code>+</code> might take 5 minutes, <code>StringBuilder</code> will be done in less then 30ms.</p>\n<hr />\n<pre><code>//Factor method TODO, does nothing, never called\n</code></pre>\n<p>That's not true, it does return an empty <code>int</code> array. Either remove it or make sure that it can not be called.</p>\n<hr />\n<pre><code>if (abbrev)\nreturn n.toString()\n</code></pre>\n<p>That's badly formatted, you should always use braces, even for one-line <code>if</code>s.</p>\n<pre><code>if (abbrev) {\n return n.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T16:28:54.863",
"Id": "65693",
"Score": "0",
"body": "Why is the removal of static necessary, I'm confused, and removing it breaks the code. I know I could probably fix it by writing a second class, but I'm concerned with the possibility of performance degradation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:18:57.340",
"Id": "65711",
"Score": "0",
"body": "[It is basically a global variable that gets altered at a whim, multi-threading will yield obscure results and maintainability is not that good either](http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil). If you write static methods, they should be self-contained or it should be clear *why* they need some sort of static variable to save their state. Additionally testing of these methods is complex at best. It would be best to refactor your methods so that they can stand on their own, or if you need to keep something, make it an instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T22:50:43.287",
"Id": "65722",
"Score": "0",
"body": "Well, all those variables are only written to once, but read many times in many methods across (possibly) multiple classes. Wouldn't that be what static is for? I read the link and my statics are 1: Needed for the entire length of the program, and 2: (I think) are thread safe, since they will only need to be read by later calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-14T23:26:09.570",
"Id": "94634",
"Score": "0",
"body": "@DavidGreen Static variables are practically always wrong (constants are fine). How to ged rid of them: 1. Remove all `static` modifiers. 2. Rename `main` to something else, e.g., `go`. 3. Write a trivial `main` creating an instance and calling `go` on it. 4. Be assured that this can't influence the performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T09:36:07.087",
"Id": "94678",
"Score": "0",
"body": "@maaartinus: In that case I'd argue that the class doing all the work and the class holding `main()` should not be the same. But personally I like the \"wrap an instance in static methods\" approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T17:11:51.403",
"Id": "94721",
"Score": "1",
"body": "@Bobby Agreed, there should be usually a separated class for `main` doing the boring things. But this is the next step after getting rid of `static`. And wrapping the whole process in a static method is fine, too (unless you need more flexibility later)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-13T16:20:36.150",
"Id": "133705",
"Score": "0",
"body": "\"This is evil, your main method should never throw exceptions\" - actually, all my tools do this as their purpose is to work when they can. When they can't they should tell me what's wrong so I can fix it (and the stack trace is unbeatable in this respect), either in code or in data."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:05:46.707",
"Id": "39206",
"ParentId": "39197",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T02:59:23.580",
"Id": "39197",
"Score": "5",
"Tags": [
"java",
"performance"
],
"Title": "Performance of BigInteger square root and cube root functions in Java"
}
|
39197
|
<p>This is my first relatively big program. First it shows an <code>askdirectory()</code> screen to get the path. It gets all subfolders of that path and appends them to a list. It checks every folders' items if they are wanted file types by checking extensions and puts them into a proper sqlite table. After all files written to a database file, a GUI appears to get what user wants to search. After clicking <code>search_button</code> it gets <code>my_entry</code> and checks if it's in database. If yes, appends it to a list and after all database is searched, it shows results in a listbox. </p>
<p>There are two lists because I couldn't find the way to get path while only writing file names to a list. So one of the list is shown and only have file names, the other one is hidden and contains whole path for that file. </p>
<p>My code is working relatively slow while writing to a database or reading from it but my real problem is, this program should search 3TB of data which contain <em>lots</em> of folders, files etc.. So when I try to show hundreds (sometimes it is thousands) of items in listBox, GUI freezes. I cannot scroll up/down or open folders by double clicking on their names.</p>
<ol>
<li><p>How can I handle that problem? Is there a way to do it with Tkinter or should I use something else?</p></li>
<li><p>Any tips on style?</p></li>
<li><p>Lastly, about writing to/reading from database performance, should I use threading?</p></li>
</ol>
<p></p>
<pre><code>#-*-coding: utf8-*-
import os
import sys
import time
import sqlite3
import tkinter
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from win32com.shell import shell, shellcon
class Prompt(tkinter.Frame):
def search_button(self):
reading.reader() ##to get data from database tables
self.my_entry = self.ent.get()
if self.my_entry:
for line in reading.lines:
if self.my_entry.lower() in line.split("/")[-1].lower(): ##if entry from textbox in file/path name
self.results.append(line)
self.shown_list()
self.hidden_list()
self.results.clear() #cleared because of next searches
def search_button2(self):
"""i'm destroying first button and adding 2nd one because of UI thing.
Without this UI looks worse than it is now"""
self.lst.destroy()
self.btn2.pack_forget()
self.search_button()
def on_frame_configure(self, event):
self.cvs.configure(scrollregion=self.cvs.bbox("all"))
def __init__(self, den):
self.fp = filepath
self.results = []
self.lbl1 = tkinter.Label(den, text="Select the File Type")
self.lbl2 = tkinter.Label(den, text="Enter the Keyord")
self.ent = tkinter.Entry(den)
self.btn = tkinter.Button(den, text="Search", command=self.search_button)
self.cmb = tkinter.ttk.Combobox(den)
self.cmb["values"] = ["Music","Image","Document","Other","All"]
self.cmb.current("0")
self.lbl1.pack()
self.cmb.pack()
self.lbl2.pack()
self.ent.pack()
self.btn.pack()
##needed to create a canvas to use scrollbar on my Listbox
tkinter.Frame.__init__(self,den)
self.cvs = tkinter.Canvas(den, borderwidth=0, background="#ffffff")
self.frame = tkinter.Frame(self.cvs, background="#ffffff")
self.vsb = tkinter.Scrollbar(den, orient="vertical", command=self.cvs.yview)
self.cvs.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.cvs.pack(fill="both", expand=True)
self.cvs.create_window((4,4), window=self.frame, anchor="nw",
tags="self.frame")
self.frame.bind("<Configure>", self.on_frame_configure)
def shown_list(self):
results = self.results
self.lst = tkinter.Listbox(self.frame, selectmode="SINGLE", height = len(results), width = "100")
if self.my_entry and not results:
tkinter.messagebox.showwarning(title = "Can not find",\
message = "There is no result matching with the keyword")
if not self.my_entry:
tkinter.messagebox.showwarning(title = "No keyword to Search" \
,message = "Enter a Keyword")
for index, item in enumerate(results, start=1):
self.lst.insert(index, item.split("\\")[-1][:-4])
if results:
self.lst.bind("<Double-Button-1>", self.open_folder)
self.btn.destroy()
self.btn2 = tkinter.Button(den, text="New Search", command= self.search_button2)
self.btn2.pack()
self.lst.pack(fill="both", expand=True)
def hidden_list(self):
results = self.results
self.lst2 = tkinter.Listbox(self.frame)
for index, item in enumerate(results, start=1):
self.lst2.insert(index, item)
self.lst2.pack()
self.lst2.pack_forget()
self.results = results
def open_folder(self,event): #this opens folder with selected item using shell commands
selected_name = []
self.selection = self.lst2.get(self.lst.curselection()[0])
selected_path = self.selection.split(self.selection.split("\\")[-1])[0][:-1]
selected_name.append(self.selection.split("\\")[-1])
try:
launch_file_explorer(selected_path,selected_name)
except KeyError:
tkinter.messagebox.showwarning(title = "Can not Find the File " \
,message = "Make Sure File Isn't Modified")
def launch_file_explorer(path, files):
folder_pidl = shell.SHILCreateFromPath(path,0)[0]
desktop = shell.SHGetDesktopFolder()
shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder)
name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, 0), item) for item in shell_folder])
to_show = []
for file in files:
to_show.append(name_to_item_mapping[file])
shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0)
class Reading:
def reader(self):
""" reads items from tables depending on combobox selection"""
if prompt.cmb.get() == "Music":
self.reader_music()
elif prompt.cmb.get() == "Image":
self.reader_image()
elif prompt.cmb.get() == "Document":
self.reader_document()
elif prompt.cmb.get() == "Other":
self.reader_others()
elif prompt.cmb.get() == "All":
self.reader_music()
mlines = self.lines
self.reader_image()
ilines = self.lines
self.reader_document()
dlines = self.lines
self.reader_others()
olines = self.lines
self.lines = mlines + ilines + dlines + olines
def reader_music(self):
self.lines = []
müzikler = data.execute("""select * from müzik""")
for row in müzikler:
self.lines.append(os.path.join(row[0],row[1]))
"""if only row[1] it searches only file names but since my target has lots of
images named like DSC123123 I needed to search in both file name and path."""
def reader_image(self):
self.lines = []
resimler = data.execute("""select * from resim""")
for row in resimler:
self.lines.append(os.path.join(row[0],row[1]))
def reader_document(self):
self.lines = []
dökümanlar = data.execute("""select * from döküman""")
for row in dökümanlar:
self.lines.append(os.path.join(row[0],row[1]))
def reader_others(self):
self.lines = []
diğerleri = data.execute("""select * from diğer""")
for row in diğerleri:
if not os.path.isdir(os.path.join(row[0],row[1])): #to not show folders
self.lines.append(os.path.join(row[0],row[1]))
class Searcher:
def writer(self): ##creates tables and calls the function to insert items
data.execute(""" create table if not exists müzik(path text,
filename text UNIQUE) """)
data.execute(""" create table if not exists resim(path text,
filename text UNIQUE) """)
data.execute(""" create table if not exists döküman(path text,
filename text UNIQUE) """)
data.execute(""" create table if not exists diğer(path text,
filename text UNIQUE) """)
for roots ,dirs ,files in os.walk(searchFolder):
for item in os.listdir(roots):
table_writing(item,roots)
conn.commit()
def table_writing(item,path):
"""
depending on their extensions, inserts items to corresponding tables """
if "."+item.split(".")[-1].lower() in audio_ext:
data.execute(""" INSERT OR IGNORE into müzik
(path, filename) VALUES (?,?)""",(path,item))
elif "."+item.split(".")[-1].lower() in image_ext:
data.execute(""" INSERT OR IGNORE into resim
(path, filename) VALUES (?,?)""",(path,item))
elif "."+item.split(".")[-1].lower() in document_ext:
data.execute(""" INSERT OR IGNORE into döküman
(path, filename) VALUES (?,?)""",(path,item))
else:
data.execute(""" INSERT OR IGNORE into diğer
(path, filename) VALUEs (?,?)""",(path,item))
class FolderSelect:
""" I need to monitor if there are any changes in files. So I needed to store chosen path in database """
def __init__(self):
data.execute("""CREATE TABLE if not EXISTS SearchPath(num INT, path TEXT) """)
data.execute(""" select * from SearchPath""")
b = data.fetchone()
if b is None:
self.searchPath = tkinter.filedialog.askdirectory(parent=den,initialdir="/",title='Please select a directory')
data.execute("""INSERT INTO SearchPath(num,path) VALUES(?,?)""",(1,self.searchPath))
data.execute(""" select * from SearchPath""")
self.searchPath = data.fetchone()[1]
self.searchPath = self.searchPath.replace("/","\\")
if __name__ == "__main__":
audio_ext = [".mp3",".flac",".wma",".wav",".m4a"]
image_ext = [".jpg",".png",".bmp"]
document_ext = [".doc",".txt",".pdf",".docx"] ##these ext. types will be increased
filepath = os.getcwd()
directories = []
wasItThere = True ##checks if there was a database file beforehand.
if not os.path.isfile("test.db"):
wasItThere = False
conn = sqlite3.connect("test.db")
data = conn.cursor()
den = tkinter.Tk()
folder = FolderSelect()
searchFolder = folder.searchPath
reading = Reading()
searcher = Searcher()
if not wasItThere: ##if there is, program doesn't bother to check all folders,items again and again
searcher.writer()
den.title("Arama")
prompt = Prompt(den)
den.mainloop()
conn.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:13:03.263",
"Id": "71351",
"Score": "0",
"body": "Have you considered using easygui? This is all good and well for a Tkinter practice, but at the end of the day easygui is a pretty well written, if limited, module. I could probably write this program in 1/3 of the lines with it, using perhaps two other modules. Just a thought."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T03:07:23.213",
"Id": "71742",
"Score": "0",
"body": "Never heard of EasyGui before. I will try to learn and implement it if my pageing thing won't work. Now I am -kinda- using Sam's idea and will split results in parts and try to display them in more than one list."
}
] |
[
{
"body": "<p>In looking at your code, there are a few things I would do:</p>\n\n<ol>\n<li>Subclass TK.. <code>class MainGUI(Tk):</code></li>\n<li>Attach all gui components to this class.... your frame for example.</li>\n<li>Add a queue and a polling method for GUI updates to the MainGUI class (this may help fix your freezing issue). You can use the TK.after method to ask the mainloop to do this periodically.</li>\n<li>Do the heavy lifting items such as db reads, filesystem, etc in a separate thread if they block too long, but make sure they don't update the GUI directly from that thread, you can pass a reference to the GUI to them and they should place a callback on the updateq for the main loop to execute as it runs a polling cycle.</li>\n<li>Check the code for pep8 compliance.</li>\n</ol>\n\n<p>Here is an example of how I have done GUI's using TKinter:</p>\n\n<pre><code>class MainGUI(Tk):\n \"\"\" The GUI \"\"\"\n\n def __init__(self):\n super().__init__()\n self.updateq = queue.Queue()\n\n # Build main components\n\n # Layout components\n\n # Key bindings\n\n self.poll()\n self.mainloop()\n\n def poll(self):\n \"\"\" Polls the Queue for the arrival of various callbacks \"\"\"\n # You may want to process more or less callbacks each cycle...\n # here it uses 100 as a maximum\n for i in range(100):\n if self.updateq.empty():\n break\n\n callback, args = self.updateq.get()\n if args:\n callback(args)\n else:\n callback()\n\n # Recursive call\n self.after(50, self.poll)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:32:41.753",
"Id": "47664",
"ParentId": "39198",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "47664",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T04:28:19.590",
"Id": "39198",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "Tkinter file searching program"
}
|
39198
|
<p>Not lock-free, but still only C++11 and no Boost. It also supports timeouts.</p>
<pre><code>#pragma once
#include <cstddef>
#include <chrono>
#include <memory>
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename T>
class blocking_queue {
public:
explicit blocking_queue(std::size_t max_size) :_max_size(max_size), _q()
{}
blocking_queue(const blocking_queue&) = delete;
blocking_queue& operator=(const blocking_queue&) = delete;
~blocking_queue() = default;
std::size_t size()
{
std::lock_guard<std::mutex> lock(_mutex);
return _q.size();
}
//Return false if failed to push due to full queue after the timeout have passed
bool push(const T& item, const std::chrono::milliseconds& timeout)
{
std::unique_lock<std::mutex> ul(_mutex);
if (_q.size() >= _max_size) {
if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.size() >= _max_size)
return false;
}
_q.push(item);
if (_q.size() <= 1)
_item_pushed_cond.notify_all();
return true;
}
//Return false if failed to pop due to empty queue after the timeout have passed
bool pop(T& item, const std::chrono::milliseconds& timeout)
{
std::unique_lock<std::mutex> ul(_mutex);
if (_q.empty()) {
if (_item_pushed_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.empty())
return false;
}
item = _q.front();
_q.pop();
if (_q.size() >= _max_size - 1)
_item_popped_cond.notify_all();
return true;
}
private:
std::size_t _max_size;
std::queue<T> _q;
std::mutex _mutex;
std::condition_variable _item_pushed_cond;
std::condition_variable _item_popped_cond;
};
</code></pre>
|
[] |
[
{
"body": "<p>Your size is not mutating. So should declare it const.</p>\n<pre><code>std::size_t size() const\n // ^^^^^\n</code></pre>\n<p>Still in the <code>size()</code> I don't see any in point in lock on such short term. As soon as the function exits the value can be mutated and will thus be out of date (so if you get a value as another thread is mutating it you will be in no better state).</p>\n<pre><code>// There is no point in this function.\n// It has no intrinsic value alone but can only be used within a set of commands.\n// But since you lock per call, if you make multiple calls another thread can \n// mutate the object and make this value stale.\n{\n std::lock_guard<std::mutex> lock(_mutex);\n return _q.size();\n}\n</code></pre>\n<p>Not sure your timed push will work as expected:</p>\n<pre><code>if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout || _q.size() >= _max_size)\n</code></pre>\n<p>Say you set a timeout of 10 seconds. Now another threads pops at 1 second and signals the condition variable. This can potentially release this thread (this does not guarantee your thread will require the lock before another third thread manages to call push). This means that your size would still be max (when you eventually reacquire the lock) and thus you exit with false after only one second.</p>\n<p>You need to use the other version of <code>wait_for()</code> that has a test function.</p>\n<pre><code>if (!_item_popped_cond.wait_for(ul, timeout, [&q,&_max_size](){return _q.size() < _max_size;})) {\n return false;\n}\n</code></pre>\n<p>Or put it inside a loop:</p>\n<pre><code>while(_q.size() >= _max_size) {\n if (_item_popped_cond.wait_for(ul, timeout) == std::cv_status::timeout) {\n return false;\n }\n // probably need to adjust timeout here.\n}\n</code></pre>\n<p>Don't see the need to test before notifying after a push. Also why are you notifying all threads, why not just notify one (there is only one new item available).</p>\n<pre><code>if (_q.size() <= 1) // Why test. Always notify\n _item_pushed_cond.notify_all(); // notify_one();\n</code></pre>\n<p>All the same comments apply to pop.</p>\n<p>I don't like the name of your identifier names. Technically nothing wrong with them. But there are so many situations where identifiers with an initial underscore is incorrect that I avoid them. And most C++ code follows the same rules. <a href=\"https://stackoverflow.com/q/228783/14065\">What are the rules about using an underscore in a C++ identifier?</a></p>\n<p>Note: The std lib with the compiler usually uses underscores but they are specifically allowed to (as they are part of the implementation). This is where most beginners pick up this hobbit; But as you are writing code that is not part of the implementation the same rules do not appy and thus this is not a reason to follow that convention.</p>\n<h3>Expansion of my point on locking above</h3>\n<p>The only way to use the lock is:</p>\n<pre><code>std::size_t count = que.size(); // locks getting size.\nfor(int loop = 0;loop < count; ++loop)\n{\n que.pop(); // locks while popping.\n}\n</code></pre>\n<p>I see very little use for the size() method in this context. Between the call to the size() method and other methods your object could have been mutated thus making your results stale. Any function that queries state like this is not returning you anything useful because it can immediately by out of date as soon as the lock is released.</p>\n<p>So what should you do?</p>\n<p>Where you have operations that can be combined together into a larger piece of work. What you normally do is <strong>not</strong> provide the interface directly. You provide a way to lock the object that returns an interface that you can use (because while you hold the interface object you hold the lock).</p>\n<pre><code>class blocking_queue\n{\n friend class blocking_queue_interface;\n // Private interface can not be used directly.\n std::size_t p_size() const;\n bool p_push(T& item, const std::chrono::milliseconds& timeout, std::lock_guard<std::mutex>& lock);\n bool p_pop(T& item, const std::chrono::milliseconds& timeout, std::lock_guard<std::mutex>& lock);\n\n ......\n public:\n // Public interface\n // Just gets lock and calls private interface.\n // Should only be used as a last resort.\n // Personally I would not provide this interface at all.\n std::size_t size() const\n {\n std::lock_guard<std::mutex> lock(_mutex);\n return p_size();\n }\n bool p_push(T& item, const std::chrono::milliseconds& timeout)\n {\n std::lock_guard<std::mutex> lock(_mutex);\n return p_push(item, timeout, lock);\n }\n bool p_pop(T& item, const std::chrono::milliseconds& timeout)\n {\n std::lock_guard<std::mutex> lock(_mutex);\n return p_pop(item, timeout, lock);\n }\n };\n\n // A locked interface.\n // You can acquire the lock and make multiple calls without\n // the data becoming stale between calls.\n class blocking_queue_interface\n {\n blocking_queue queue;\n std::lock_guard<std::mutex> lock;\n\n blocking_queue_interface(blocking_queue& q): queue(q), lock(queue._mutex) {}\n ~blocking_queue_interface() {}\n // delete remove all copy and assignment operators.\n\n // Calls the private version of these methods\n // as it has already aquired the lock\n std::size_t size() const {return queue.p_size());\n bool push(T& item, const std::chrono::milliseconds& timeout) {return queue.p_push(item, timeout, lock);}\n bool pop(T& item, const std::chrono::milliseconds& timeout) {return queue.p_pop(item, timeout, lock);}\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T07:16:49.180",
"Id": "65636",
"Score": "2",
"body": "Great review thanks. About locking of size() function, I think queue.size() is not defined/not correct if another thread push/pops this queue simultanously (see http://www.cplusplus.com/reference/queue/queue/size/ about race conditions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T07:57:54.800",
"Id": "65637",
"Score": "0",
"body": "@GabiMe: There is a data race. But that is not the same as defined/incorrect. But really the data race is irrelevant. As soon as the function exits another thread can change the size and thus your value is out of date. So why should you care if there is a data race. PPS. Please don't use cplusplus.com as a reference. It is good as a quick look up for syntax and stuff (most of the time) but it is know to have serious flaws. But if you are going to quote stuff use the standard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:29:22.463",
"Id": "65639",
"Score": "1",
"body": "Who can guarantee that the std's inner queue size var will not contain total garbage? If setting the size variable is not atomic, it could contain temporarily any junk, right? not just old valid value"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:45:02.813",
"Id": "65641",
"Score": "0",
"body": "wouldn't correctness of unsynchronized size be dependent on the memory model?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:47:59.027",
"Id": "65642",
"Score": "0",
"body": "@LokiAstari, consider that `size()` walks over `deque` chains and calculate their sizes. If someone will `pop()` element and that chain you've just stepped on id destroyed you may start working with freed memory. Even if you just read a number that is not aligned to CPU word size you can get number which never was there in single threaded env."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T04:23:37.240",
"Id": "66368",
"Score": "0",
"body": "+1 for suggesting that `size()` be `const`, -1 for suggesting that OP introduce undefined behavior by not taking the lock. Data races are ***by definition*** incorrect in C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T23:54:09.930",
"Id": "66584",
"Score": "0",
"body": "@Casey, GabiMe yes you are both correct. I retract my initial statement. But I still see the interface as useless because as soon as the function returns the data is stale ant the object state can be mutated. I have updated my answer with my extended reasoning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T00:04:29.073",
"Id": "66586",
"Score": "0",
"body": "I'll certainly grant that `size` is low-value. All it does is attest that at some time the queue had the given size. This could be useful for debugging output, or some kind of statistics collection, but not much else."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T06:53:45.640",
"Id": "39203",
"ParentId": "39199",
"Score": "8"
}
},
{
"body": "<p>I'd say that size limitation you've put on is more like policy rather than container limitation. If you'd have ring-buffer as underline container that <code>max_size</code> will be justified.</p>\n\n<p>I'd suggest you to split this into <code>max_size</code> policy applying adapter and unlimited multi-threaded queue. And while you have no <code>resize</code> you can mark <code>_max_size</code> as <code>const</code>.</p>\n\n<p>Note as well that C++11 provide very nice way to construct elements right in containers. You may want to forward that feature (see <a href=\"http://en.cppreference.com/w/cpp/container/queue/emplace\" rel=\"nofollow\">emplace method of std::queue</a>)</p>\n\n<p>Also don't forget about movable semantic for constructor of your queue and for elements you are pushing in (<code>bool push (T &&item /*, ...*/)</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:55:24.317",
"Id": "39205",
"ParentId": "39199",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T05:12:36.787",
"Id": "39199",
"Score": "10",
"Tags": [
"c++",
"c++11",
"queue"
],
"Title": "Multi producer/consumer queue (without Boost) in C++11"
}
|
39199
|
<p>I have a the beginnings of a class (in this case for a NeuralNet). <br>
I'm not very happy with how I am initializing self.ws, seems a bit off.
What is the pythonic way to do this?</p>
<pre><code>import numpy as np
class NeuralNet:
def __init__(self,layerSizes):
self.ws = self._generateStartingWeights(layerSizes)
def _generateStartingWeights(self,layerSizes):
def randMatrix(szThis,szNext): return np.matrix(np.random.normal(0,0.01,(szThis,szNext)))
return [randMatrix(szThis,szNext) for (szThis,szNext) in pairwise(layerSizes)]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T07:14:01.603",
"Id": "65635",
"Score": "0",
"body": "Fixed, thanks. That was not what was feeling wrong though."
}
] |
[
{
"body": "<p>I think the primary question here is one of whether <code>_generateStartingWeights</code> or <code>randMatrix</code> are reusable; the secondary question is of naming conventions.</p>\n\n<p>If <code>_generateStartingWeights</code> is not reusable, there's little reason not to write <code>__init__</code> without the layers of helpers (and that's assuming there's not some better way to use numpy for this). Oh, and if it is reusable, you can just return this from it, instead of using a locally defined helper function:</p>\n\n<pre><code>def __init__(self, layerSizes):\n self.ws = [np.matrix(np.random.normal(0, 0.01, pair)) for pair in pairwise(layerSizes)]\n</code></pre>\n\n<p>On the flip side, if <code>randMatrix</code> is reusable, it needs to be somewhere other than local to another function.</p>\n\n<p>As for naming conventions, a potentially heated subject, lots of people refer to <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP-8</a> (which I want to clarify is not a requirement for third party code unless you want to make it one). However due to its prevelance in the Python community, there seems to be a general preference for <code>underscore_separated</code> instead of <code>camelCase</code> names. Since it's not even always followed in the standard library, your project's preferences can overrule it. I only bring it up since I personally find <code>camelCase</code> names to be less in line with my view of \"pythonic.\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:10:40.153",
"Id": "39241",
"ParentId": "39202",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T06:11:40.630",
"Id": "39202",
"Score": "1",
"Tags": [
"python",
"classes"
],
"Title": "Class initialisation of fields"
}
|
39202
|
<p>Looking for code review, optimizations, good practice recommendations etc.</p>
<pre><code>/**
* This is utility class for operations on rotated one-d array.
*
* Note: a sorted array, reverse-sorted or a single element is array is not considered rotated sorted.
* Eg:
* [4, 5, 1, 2, 3] is condidered rotated.
* While.
* [1, 2, 3, 4, 5] is not considered rotated
*
*
* Complexity: O (log n)
*/
public final class RotatedOneDSortedArray {
private RotatedOneDSortedArray() { }
/**
* Searches for the value provided in the rotated sorted array.
* If found, returns the index, of provided array, else returns -1.
* If array is not rotated and sorted, then results are unpredictable
*
* Throws an exception if array is null.
*
* @param a the rotated sorted array
* @param x the element to be searched
* @returns the index at which the element is found, else returns -1
*/
public static int binarySearchForRotatedArray(int[] a, int x) {
int partitionIndex = findPartition(a, 0, a.length - 1);
if (partitionIndex == -1) return -1;
if (x >= a[0] && x <= a[partitionIndex]) {
return binarySearch(a, 0, partitionIndex, x);
} else {
return binarySearch(a, partitionIndex + 1, a.length -1, x);
}
}
private static int binarySearch (int[] a, int lb, int hb, int x) {
assert a != null;
if (lb > hb) return -1;
int mid = (lb + hb)/2;
if (a[mid] == x) return mid;
if (a[mid] < x) {
return binarySearch(a, mid + 1, hb, x);
} else {
return binarySearch(a, lb, mid - 1, x);
}
}
/**
* Returns the index of greatest element of the rotated sorted array.
* if array is not rotated sorted, results are unprodictable
*
* @param a the input array
* @param lb the lower bound
* @param hb the higher bound
* @return the index of the highest element in the array.
*/
private static int findPartition(int[] a, int lb, int hb) {
assert a!= null;
if (lb == hb) return -1;
int mid = (lb + hb)/2;
if (a[mid] > a[mid + 1]) {
return mid;
}
if (a[mid] > a[hb]) {
// go right.
return findPartition(a, mid + 1, hb);
} else {
// go left.
return findPartition(a, lb, mid); // note i cannot do mid - 1
}
}
public static void main(String[] args) {
// even length of the array.
int[] a1 = {6, 7, 8, 1, 2, 3};
System.out.println("Expected -1, Actual : " + binarySearchForRotatedArray(a1, -1));
int[] a2 = {6, 7, 8, 1, 2, 3};
System.out.println("Expected 1, Actual : " + binarySearchForRotatedArray(a2, 7));
int[] a3 = {6, 7, 8, 1, 2, 3};
System.out.println("Expected 5, Actual : " + binarySearchForRotatedArray(a3, 3));
int[] a4 = {6, 7, 8, 1, 2, 3};
System.out.println("Expected 2, Actual : " + binarySearchForRotatedArray(a4, 8));
int[] a5 = {6, 7, 8, 1, 2, 3};
System.out.println("Expected 3, Actual : " + binarySearchForRotatedArray(a5, 1));
// odd length of the array.
int[] a6 = {4, 6, 7, 8, 1, 2, 3};
System.out.println("Expected -1, Actual : " + binarySearchForRotatedArray(a6, -1));
int[] a7 = {4, 6, 7, 8, 1, 2, 3};
System.out.println("Expected 2, Actual : " + binarySearchForRotatedArray(a7, 7));
int[] a8 = {4, 6, 7, 8, 1, 2, 3};
System.out.println("Expected 6, Actual : " + binarySearchForRotatedArray(a8, 3));
int[] a9 = {4, 6, 7, 8, 1, 2, 3};
System.out.println("Expected 3, Actual : " + binarySearchForRotatedArray(a9, 8));
int[] a10 = {4, 6, 7, 8, 1, 2, 3};
System.out.println("Expected 4, Actual : " + binarySearchForRotatedArray(a10, 1));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:06:27.613",
"Id": "65643",
"Score": "2",
"body": "I think you should put just a bit more effort an make it work for a \"non-rotated\" sorted buffer, since it's basically a special case of a rotated buffer (i.e. the case where the tail of the list is empty). If I got it right, that's the case where `(partitionIndex == -1)`, and it simply means you should do a binary search of the entire array. Also, the structure you are dealing with is more commonly called a [circular buffer](http://en.wikipedia.org/wiki/Circular_buffer)."
}
] |
[
{
"body": "<p>As mentioned in my comment, the structure you are dealing with is more commonly called a <a href=\"http://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow\">circular buffer</a>. The Wikipedia link has several examples on how to efficiently provide thread safe read/write access (a producer/consumer queue), but what's more important is the idea that you can <strong>abstract the access to your circular buffer to an interface</strong>, so that callers deal with it like it's an ordinary list.</p>\n\n<p>The interface might look something like this (sorry for my poor Java skills):</p>\n\n<pre><code>public interface IReadonlyList<T>\n{\n // gets the item at the specified index\n T getItem(int index);\n\n // gets the length\n int length();\n}\n</code></pre>\n\n<p>And the circular buffer implementation would simply offset the internal index before returning the requested value:</p>\n\n<pre><code>// note that _headOffset and _actualArray aren't\n// assigned anywhere, it's just a concept\n\npublic class CircularBuffer<T> : IReadonlyList<T>\n{\n private final int _headOffset;\n private final T[] _actualArray;\n\n public T getItem(int index)\n {\n var actualIndex = (index + _headOffset) % Length;\n return _actualArray[actualIndex];\n }\n\n public int length()\n {\n return _actualArray.Length;\n }\n}\n</code></pre>\n\n<p>Wrapping the class in an interface like this allows you to use a general binary search algorithm you would use for a standard sorted list (and any other algorithm which would work on a non-circular buffer).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T06:36:08.977",
"Id": "65743",
"Score": "0",
"body": "That is a nice and clean idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:25:29.553",
"Id": "39207",
"ParentId": "39204",
"Score": "3"
}
},
{
"body": "<p>Here's what I've done :</p>\n\n<ul>\n<li>enhanced the tests</li>\n<li>support sorted array (circular array with a shift of 0)</li>\n<li>remove recursion for optimisation and clearer signature</li>\n</ul>\n\n\n\n<pre><code>/**\n * This is utility class for operations on rotated one-d array.\n *\n * Complexity: O (log n)\n */\npublic final class RotatedOneDSortedArray {\n\n private RotatedOneDSortedArray() { }\n\n /**\n * Searches for the value provided in the rotated sorted array.\n * If found, returns the index, of provided array, else returns -1.\n * If array is not rotated and sorted, then results are unpredictable\n *\n * Throws an exception if array is null.\n *\n * @param a the rotated sorted array\n * @param x the element to be searched\n * @returns the index at which the element is found, else returns -1\n */\n public static int binarySearchForRotatedArray(int[] a, int x) {\n int partitionIndex = findPartition(a);\n\n if (partitionIndex == -1) return -1;\n\n if (x >= a[0] && x <= a[partitionIndex]) {\n return binarySearch(a, 0, partitionIndex, x);\n } else {\n return binarySearch(a, partitionIndex + 1, a.length -1, x);\n }\n\n }\n\n private static int binarySearch (int[] a, int lb, int hb, int x) {\n assert a != null;\n\n while (lb <= hb)\n {\n int mid = (lb + hb)/2;\n int midv = a[mid];\n if (midv < x) {\n lb = mid + 1;\n } else if (midv > x) {\n hb = mid -1;\n } else {\n return mid;\n }\n }\n return -1;\n }\n\n /**\n * Returns the index of greatest element of the rotated sorted array.\n * if array is not rotated sorted, results are unprodictable\n *\n * @param a the input array\n * @return the index of the highest element in the array.\n */\n private static int findPartition(int[] a) {\n assert a!= null;\n\n int lb = 0;\n int hb = a.length-1;\n\n // Check if rotation is 0\n if (a[lb] < a[hb])\n return hb;\n\n while (lb != hb)\n {\n int mid = (lb + hb)/2;\n\n if (a[mid] > a[mid + 1]) {\n return mid;\n } else if (a[mid] > a[hb]) {\n // go right.\n lb = mid + 1;\n } else {\n // go left.\n hb = mid; // note i cannot do mid - 1\n }\n }\n return -1;\n }\n\n\n public static void main(String[] args) {\n // even length of the array.\n int expected = 0; int actual = 0;\n int[] a1 = {6, 7, 8, 1, 2, 3};\n expected = -1; actual = binarySearchForRotatedArray(a1, -1);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a2 = {6, 7, 8, 1, 2, 3};\n expected = 1; actual = binarySearchForRotatedArray(a2, 7);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a3 = {6, 7, 8, 1, 2, 3};\n expected = 5; actual = binarySearchForRotatedArray(a3, 3);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a4 = {6, 7, 8, 1, 2, 3};\n expected = 2; actual = binarySearchForRotatedArray(a4, 8);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a5 = {6, 7, 8, 1, 2, 3};\n expected = 3; actual = binarySearchForRotatedArray(a5, 1);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n\n // odd length of the array.\n int[] a6 = {4, 6, 7, 8, 1, 2, 3};\n expected = -1; actual = binarySearchForRotatedArray(a6, -1);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a7 = {4, 6, 7, 8, 1, 2, 3};\n expected = 2; actual = binarySearchForRotatedArray(a7, 7);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a8 = {4, 6, 7, 8, 1, 2, 3};\n expected = 6; actual = binarySearchForRotatedArray(a8, 3);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a9 = {4, 6, 7, 8, 1, 2, 3};\n expected = 3; actual = binarySearchForRotatedArray(a9, 8);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n int[] a10 = {4, 6, 7, 8, 1, 2, 3};\n expected = 4; actual = binarySearchForRotatedArray(a10, 1);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n\n // properly sorted\n int[] a11 = {1, 2, 3, 4, 5, 6, 7};\n expected = -1; actual = binarySearchForRotatedArray(a11, 0);\n expected = 0; actual = binarySearchForRotatedArray(a11, 1);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 1; actual = binarySearchForRotatedArray(a11, 2);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 2; actual = binarySearchForRotatedArray(a11, 3);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 3; actual = binarySearchForRotatedArray(a11, 4);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 4; actual = binarySearchForRotatedArray(a11, 5);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 5; actual = binarySearchForRotatedArray(a11, 6);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = 6; actual = binarySearchForRotatedArray(a11, 7);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n expected = -1; actual = binarySearchForRotatedArray(a11, 8);\n if (expected != actual) System.out.println(\"Expected \" + expected + \" , Actual : \" + actual);\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T09:39:43.643",
"Id": "39208",
"ParentId": "39204",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39207",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T08:25:12.980",
"Id": "39204",
"Score": "2",
"Tags": [
"java",
"binary-search"
],
"Title": "Binary search in rotated sorted array"
}
|
39204
|
<p>I'm using C++11 and I have the following problem (pseudo C++):</p>
<pre><code>template<typename T, R1 (*F1)(Args1...)>
class one_size_fits_them_all {};
template<typename T, typename U, typename V, R1 (*F1)(Args1...), R2 (*F2)(Args1...)>
class one_size_fits_them_all {};
template<typename T, typename U, R1 (*F1)(Args1...), R2 (*F2)(Args2...), R3 (*F3)(Args3...)>
class one_size_fits_them_all {};
</code></pre>
<p>So what I want to do is to overload the class by its template parameters <em>and</em> pass in function pointers.<br>
I came up with this fully compile- and runnable solution:</p>
<pre><code>// compile with `g++ -std=c++11 test.cpp`
#include <iostream>
#define CALLABLE(FUNCTION) callable<decltype(FUNCTION), FUNCTION>
template<typename Signature, Signature & S>
struct callable;
template<typename Return,
typename ... Args, Return (&Function)(Args ...)>
struct callable<Return(Args ...), Function> {
Return operator()(Args ... args)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl;
return Function(args ...);
}
};
template<typename ... Arguments>
class one_size_fits_them_all;
// A generic template
template<typename T, typename U, typename V,
typename F1, typename F2, typename F3>
class one_size_fits_them_all<T, U, V, F1, F2, F3>
{
public:
one_size_fits_them_all(void)
{
std::cerr << "generic one_size_fits_them_all" << std::endl
<< __PRETTY_FUNCTION__ << std::endl << std::endl;
F1()();
F2()();
F3()();
std::cerr << std::endl;
}
};
// A specialized template
template<typename T, typename Callable>
class one_size_fits_them_all<T, int, int, void, void, Callable>
{
public:
one_size_fits_them_all(void)
{
std::cerr << "specialized one_size_fits_them_all" << std::endl
<< __PRETTY_FUNCTION__ << std::endl << std::endl;
Callable()();
std::cerr << std::endl;
}
};
void f1(void)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}
void f2(void)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}
void f3(void)
{
std::cerr << __PRETTY_FUNCTION__ << std::endl << std::endl;
}
int main(int argc, char ** argv)
{
// generic template
auto generic = one_size_fits_them_all<
int, int, int, CALLABLE(f1), CALLABLE(f2), CALLABLE(f3)>();
// specialized template
auto specialized_int = one_size_fits_them_all<
int, int, int, void, void, CALLABLE(f1)>();
// specialized template
auto specialized_double = one_size_fits_them_all<
double, int, int, void, void, CALLABLE(f3)>();
return 0;
}
</code></pre>
<p>My questions are:</p>
<ol>
<li>Is this a good solution? </li>
<li>Can it be improved?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:27:13.720",
"Id": "66214",
"Score": "0",
"body": "Why function pointers? Why not use [function objects](http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:41:47.487",
"Id": "66286",
"Score": "0",
"body": "I intend to use this mainly for C functions (more specifically c style iterator function on PODs). If I got that function object thing right, I'd have to write a wrapper class for each of the C functions."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T12:00:26.673",
"Id": "39213",
"Score": "5",
"Tags": [
"c++",
"c++11",
"pointers",
"template-meta-programming"
],
"Title": "C++ class \"overload\" using variadic templates and wrapped function pointers"
}
|
39213
|
<p>I have the following code to get the ID of a <code><a href="#ID"> </ a></code> and go to their respective div <code><div id="" /></code>:</p>
<pre><code>$('a[href=#certificados]').click(function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: $('#certificados').offset().top }, 1000);
});
$('a[href=#team]').click(function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: $('#team').offset().top }, 1000);
});
$('a[href=#house]').click(function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: $('#house').offset().top }, 1000);
});
$('a[href=#contact]').click(function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: $('#contact').offset().top }, 1000);
});
</code></pre>
<p>How could I optimize the code?</p>
|
[] |
[
{
"body": "<p>If you want to make the code DRYer, you can do</p>\n\n<pre><code>['#certificados', '#team', '#house', '#contact'].forEach(function(anchor){\n $(\"a[href=\"+anchor+\"]\").click(function(e){\n e.preventDefault();\n $(\"html, body\").animate({ scrollTop: $(anchor).offset().top }, 1000);\n });\n})\n</code></pre>\n\n<p>If all internal links are to be handled this way, do</p>\n\n<pre><code>$('a[href^=\"#\"]').click(function(e){\n e.preventDefault();\n $(\"html, body\").animate({ scrollTop: $(this.hash).offset().top }, 1000);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:01:25.280",
"Id": "65668",
"Score": "0",
"body": "Why a forEach? jQuery supports multiple elements in a selector!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:01:51.790",
"Id": "65669",
"Score": "0",
"body": "@epascarello to not compute n and to be dryer on the a[href=...] thing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:04:35.200",
"Id": "65670",
"Score": "0",
"body": "Maybe rename `n` to `anchor` ?, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:14:29.920",
"Id": "65673",
"Score": "1",
"body": "`this.href` does not work"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:22:34.627",
"Id": "65678",
"Score": "1",
"body": "`this.href` returns the full URL, You would need to use `this.getAttribute(\"href\")` or `$(this).attr(\"href\");` or hash http://jsfiddle.net/7439C/1/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:24:41.917",
"Id": "65680",
"Score": "0",
"body": "@dystroy that bit me in the butt awhile back, will not forget that one. lol"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T15:30:26.743",
"Id": "65692",
"Score": "0",
"body": "@epascarello I was bitten too... and I keep forgetting ^^ And I also remember the behavior was different on IE..."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:59:59.153",
"Id": "39218",
"ParentId": "39216",
"Score": "5"
}
},
{
"body": "<p>Get the \"respective\" div in a more general way from the link's <code>href</code> attribute:</p>\n\n<pre><code>$('a[href=#certificados], a[href=#team], a[href=#house], a[href=#contact]').click(function(e){\n e.preventDefault();\n $(\"html, body\").animate({ scrollTop: $(this.hash).offset().top }, 1000);\n // this.hash would be equivalent to $(this).attr(\"href\") in your case\n});\n</code></pre>\n\n<p>Probably you also can use a much better selector now - maybe selecting those links by a common class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:25:44.703",
"Id": "65681",
"Score": "3",
"body": "Bad thing about this solution is maintaining the list of items and the slower look-up. You would be better off using a common classname."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:36:07.497",
"Id": "65682",
"Score": "3",
"body": "@epascarello: That's what I suggested in the last sentence :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:46:38.360",
"Id": "65684",
"Score": "0",
"body": "Just hoping the OP saw it. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:01:41.033",
"Id": "39220",
"ParentId": "39216",
"Score": "11"
}
},
{
"body": "<p>You can make an extension, that will let you specify what link scrolls to where, without creating a hard dependancy between the <code>href</code> attribute and the target identity:</p>\n\n<pre><code>$.fn.scrollTo = function(target){\n return this.click(function(e){\n e.preventDefault();\n $(\"html, body\").animate({ scrollTop: $(target).offset().top }, 1000);\n });\n};\n\n$('a[href=#certificados]').scrollTo('#certificados');\n$('a[href=#team]').scrollTo('#team');\n$('a[href=#house]').scrollTo('#house');\n$('a[href=#contact]').scrollTo('#contact');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T22:36:01.047",
"Id": "65721",
"Score": "0",
"body": "Nice, but this doesn't optimize it at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T23:13:56.023",
"Id": "65723",
"Score": "0",
"body": "@SilviuBurcea: Funny that you should single out this answer and point out that it won't optimise the code (and I assume that you only mean optimise for speed, not any other aspect), as neither of the previous answers does that either..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T14:01:57.880",
"Id": "39221",
"ParentId": "39216",
"Score": "3"
}
},
{
"body": "<p>Add a class to the anchors, like <code>scrollable</code>.</p>\n\n<pre><code>$('.scrollable').click(function(e){\n e.preventDefault();\n $(\"html, body\").animate({ scrollTop: $(this.hash).offset().top }, 1000);\n});\n</code></pre>\n\n<p>Each is called under the hood, no crazy functions, just KISS.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T22:40:46.270",
"Id": "39247",
"ParentId": "39216",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39220",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T13:56:22.097",
"Id": "39216",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Animated scrolling when intra-page links are clicked"
}
|
39216
|
<p>I need to parse the data coming from a URL:</p>
<pre><code>haschanged=true
version=1
timestamp=1389562122310
DATACENTER=/pr/hello/plc
TotalNumberOfServers:4
primary:{0=1, 1=2, 2=1, 3=2, 4=1, 5=2, 6=1, 7=2, 8=1, 9=2, 10=1, 11=2, 12=1, 13=2}
secondary:{0=0, 1=0, 2=0, 3=1, 4=0, 5=0, 6=0, 7=1, 8=0, 9=0, 10=0, 11=1, 12=0, 13=0}
hosttomachine:{3=plcdbx1115.plc.domain.com, 2=plcdbx1114.plc.domain.com, 1=plcdbx1113.plc.domain.com, 4=plcdbx1116.plc.domain.com}
DATACENTER=/pr/hello/pty
TotalNumberOfServers:2
primary:{0=1, 1=2, 2=1, 3=2, 4=1, 5=2, 6=1, 7=2, 8=1, 9=2, 10=1, 11=2, 12=1, 13=2, 14=1}
secondary:{0=0, 1=0, 2=0, 3=1, 4=0, 5=0, 6=0, 7=1, 8=0, 9=0, 10=0, 11=1, 12=0, 13=0, 14=0}
hosttomachine:{1=ptydbx1145.pty.domain.com, 4=ptydbx1148.pty.domain.com}
DATACENTER=/pr/hello/vgs
TotalNumberOfServers:0
primary:{}
secondary:{}
hosttomachine:{}
</code></pre>
<p>After parsing the data I need to store all datacenter data in a <code>Map</code> like this:</p>
<pre><code>ConcurrentHashMap<String, Map<Integer, String>> primaryData
</code></pre>
<p>For example, the Key of <code>primaryData</code> is <code>/pr/hello/plc</code> and value is:</p>
<pre><code>{0=1, 1=2, 2=1, 3=2, 4=1, 5=2, 6=1, 7=2, 8=1, 9=2, 10=1, 11=2, 12=1, 13=2}
</code></pre>
<p>which is for primary.</p>
<p>Similarly another <code>Map</code> for secondary for each datacenter:</p>
<pre><code>ConcurrentHashMap<String, Map<Integer, String>> secondaryData
</code></pre>
<p>For example, the Key of <code>secondaryData</code> is <code>/pr/hello/plc</code> and value is:</p>
<pre><code>{0=0, 1=0, 2=0, 3=1, 4=0, 5=0, 6=0, 7=1, 8=0, 9=0, 10=0, 11=1, 12=0, 13=0}
</code></pre>
<p>which is for secondary.</p>
<p>And lastly, one more map for hosttomachine mapping for each datacenter:</p>
<pre><code>ConcurrentHashMap<String, Map<Integer, String>> hostMachineMapping -
</code></pre>
<p>For example, the key of <code>hostMachineMapping</code> is <code>/pr/hello/plc</code> and value is:</p>
<pre><code>{3=plcdbx1115.plc.domain.com, 2=plcdbx1114.plc.domain.com, 1=plcdbx1113.plc.domain.com, 4=plcdbx1116.plc.domain.com}
</code></pre>
<p>which is for hosttomachine.</p>
<p>And all the above map will have data for its datacenter as I have three datacenter in the above example. So each each map will have three data. And also I will parse the above response only when <code>haschanged</code> is equal to <code>true</code>. If it is not true, then I won't parse anything.</p>
<p>Here is the code I have so far, but it takes more than 200 ms to parse the data and store it in its corresponding hashmap. Is there any way to parse the above data efficiently and store it in a particular <code>ConcurrentHashMap</code>?</p>
<pre><code>private void parseResponse(String response) throws Exception {
if (response != null) {
ConcurrentHashMap<String, Map<Integer, String>> primaryData = null;
ConcurrentHashMap<String, Map<Integer, String>> secondaryData = null;
ConcurrentHashMap<String, Map<Integer, String>> hostMachineMapping = null;
long version = -1;
long timestamp = 0L;
boolean changed = false;
String splitResponse[] = response.split("DATACENTER=");
boolean flag = false;
for (String sr : splitResponse) {
if (!flag) {
flag = true;
String[] header = sr.split("\n");
changed = Boolean.parseBoolean(header[0].split("=")[1]);
if (!changed) {
return;
} else {
version = Integer.parseInt(header[1].split("=")[1]);
timestamp = Long.parseLong(header[2].split("=")[1]);
primaryData = new ConcurrentHashMap<String, Map<Integer, String>>();
secondaryData = new ConcurrentHashMap<String, Map<Integer, String>>();
hostMachineMapping = new ConcurrentHashMap<String, Map<Integer, String>>();
}
} else {
generateDATACENTERMap(sr, primaryData, secondaryData, hostMachineMapping);
}
}
if (changed) {
Mapping.setPrimaryData(primaryData);
Mapping.setSecondaryData(secondaryData);
Mapping.setHostMachineMapping(hostMachineMapping);
Mapping.setTimestamp(timestamp);
Mapping.setVersion(version);
}
}
}
private void generateColoMap(String sr, ConcurrentMap<String, Map<Integer, String>> primaryData,
ConcurrentMap<String, Map<Integer, String>> secondaryData,
ConcurrentMap<String, Map<Integer, String>> hostMachineMapping) throws Exception {
String[] data = sr.split("\n\t");
String dcName = data[0];
int numOfServers = Integer.parseInt(data[1].split(":")[1]);
if (numOfServers > 0) {
primaryData.put(dcName, generateMap(data[2]));
secondaryData.put(dcName, generateMap(data[3]));
hostMachineMapping.put(dcName, generateMap(data[4]));
}
}
private ConcurrentMap<Integer, String> generateMap(String map) throws Exception {
String tableString = map.split(":")[1];
ConcurrentMap<Integer, String> table = new ConcurrentHashMap<Integer, String>();
tableString = tableString.substring(1, tableString.length() - 1);
String[] entries = tableString.split(", ");
for (String e : entries) {
String[] entryVal = e.split("=");
table.put(Integer.parseInt(entryVal[0]), entryVal[1]);
}
return table;
}
</code></pre>
|
[] |
[
{
"body": "<p>Regex to the rescue</p>\n\n<ul>\n<li><p>Regex for key: <code>(?<=DATACENTER=).*</code></p></li>\n<li><p>Regex for primary values: <code>(?<=primary:\\{).*(?=\\})</code></p></li>\n<li><p>Regex for secondary values: <code>(?<=secondary:\\{).*(?=\\})</code></p></li>\n<li><p>Regex for hostMachine Mapping: <code>(?<=hosttomachine:\\}).*(?=\\})</code></p></li>\n<li><p>Split on <code>\",\"</code> for primary, secondary, and hostMachine</p></li>\n</ul>\n\n<p>Use these as your patterns then go through each match. Each iteration should give you key with matching values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-15T00:10:05.750",
"Id": "71733",
"Score": "0",
"body": "I'm not *entirely* sure that regex is the best option here, but it seems like it's an option at least, so +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T22:32:06.950",
"Id": "41696",
"ParentId": "39231",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T18:31:31.800",
"Id": "39231",
"Score": "5",
"Tags": [
"java",
"performance",
"parsing",
"hash-map",
"url"
],
"Title": "Parsing data coming from a URL"
}
|
39231
|
<p>I have used the <a href="http://en.wikipedia.org/wiki/Newton%27s_method" rel="nofollow">Newton-Raphson method</a> to solve <a href="http://en.wikipedia.org/wiki/Cubic_function" rel="nofollow">Cubic equations</a> of the form $$ax^3+bx^2+cx+d=0$$ by first iteratively finding one solution, and then reducing the polynomial to a quadratic $$a1*x^2+b1*x+c=0$$ and solving for it using the <a href="http://en.wikipedia.org/wiki/Quadratic_equation" rel="nofollow">quadratic formula</a>. It also gives the imaginary roots.</p>
<pre><code>def deg3(a,b,c,d,g): #using newton raphson method, I designed this to solve degree3 equations
y=a*g**3+b*g**2+c*g+d
return y
def solvedeg3equation():
'''solves for cubic equations of the form ax^3+bx^2+cx+d=0 with the rough estimate of error within e'''
import math
e=float(input("e= "))
a=float(input("a= "))
b=float(input("b= "))
c=float(input("c= "))
d=float(input("d= "))
count=1
g=0.01
while abs(deg3(a,b,c,d,g))>e and count<=100 and not d==0:
count=count+1
if 3*a*g**2+2*b*g+c==0:
g=g+0.001
g=g-deg3(a,b,c,d,g)/(3*a*g**2+2*b*g+c)
if count<=100:
if d==0:
a1=a
b1=b
c1=c
g=0
else:
c1=-d/g #This is generation 3, which provides all three solutions, including imaginary solutions, if any.
a1=a
b1=(c1-c)/g #imagg=imaginary part of root, realg=real part
if b1**2-4*a1*c1<0:
realg=-b1/(2*a1)
imagg=math.sqrt(4*a1*c1-(b1**2))/(2*a1)
if a1>0:
g2=str(realg)+'+'+str(imagg)+'i'
g3=str(realg)+'-'+str(imagg)+'i'
if a1<0:
g2=str(realg)+'+'+str(-imagg)+'i'
g3=str(realg)+'-'+str(-imagg)+'i'
if abs(b1**2-4*a1*c1)<e:
g2=-b1/(2*a1)
g3=None
if b1**2-4*a1*c1>e:
g2=(-b1+math.sqrt(b1**2-4*a1*c1))/2*a1
g3=(-b1-math.sqrt(b1**2-4*a1*c1))/2*a1
print("Solved. The best guess is:",g,'and',g2,'and',g3)
print("Iterations required: ",count)
else:
print("Maximum iterations exceeded ")
print("Iterations: ",count,"Current guess: ",g)
</code></pre>
<p>I would like to know how I can make this code more efficient, both mathematically and structurally. Some places which could do with a more efficient piece of code, according to me, are:</p>
<ol>
<li><p>To avoid crashing of the program when the derivative equals zero, I have used the provision of g+0.001, to avoid the case. Is there a better way to solve this problem? Both mathematical optimizations or structural (code-related) are welcome.</p></li>
<li><p>Reducing the number of conditional statements and elementary operations (like comparisons, assignments and arithmetic operations) to reduce the computation time</p></li>
<li><p>Improve the Newton-Raphson algorithm mathematically to reduce the number of iterations required (since 3-4 digit numbers require more than 100 iterations currently). I'm incorporating the provision of better guesses. </p></li>
</ol>
<p>I am a beginner to Python (this is my second program) and programming in general, so please try to suggest as simple modifications as possible. Also, I would appreciate any tips on the general nature of my writing style.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T06:06:35.080",
"Id": "66266",
"Score": "1",
"body": "What if the first root found (`g`) is zero?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T09:44:05.537",
"Id": "66275",
"Score": "0",
"body": "@200_success Oh I missed that. Fixed by including `and not d==0` in the loop conditions, and changing the assignments in the quadratic solver to then solve the resultant quadratic. Thank you for pointing it out!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:03:30.030",
"Id": "66278",
"Score": "0",
"body": "Please refrain from editing the code in the question after reviews have been posted. (An addendum would be OK.) Our standard procedure is to roll back such edits. This time, though, I've adjusted my answer to match instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T11:44:42.577",
"Id": "66288",
"Score": "0",
"body": "@200_success I was not aware of that. I'll take care hereafter. :)"
}
] |
[
{
"body": "<h3>Handling of complex roots</h3>\n\n<p>When there are complex roots, you have two cases, for <code>a1 > 0</code> and <code>a1 < 0</code>. You could just collapse the two cases by using <code>abs(a1)</code> when defining <code>imagg</code>.</p>\n\n<p>Better yet, Python has built-in support for a <a href=\"http://docs.python.org/2/library/stdtypes.html#typesnumeric\" rel=\"nofollow\"><code>complex</code></a> type. Why not use it instead of building a string? Then you don't even have to worry about the sign of the imaginary part for the sake of a pretty printout.</p>\n\n<h3>Separation of concerns</h3>\n\n<p>Your <code>solvedeg3equation()</code> function performs input, calculation, and output. That may do the job for you, but it ensures that your code will never be reusable, other than by copying and pasting — or by piping the input to you and attempting to parse the output! Furthermore, it makes your code just as difficult to unit test. What you want is a function that accepts a polynomial (more on that shortly) and returns a 3-tuple of solutions. The caller would be responsible for input and output.</p>\n\n<h3>Notation</h3>\n\n<p>Representing a third-degree polynomial as variables <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> is unwieldy. You can't pass it around easily as one entity. The proliferation of variables imposes a mental load. Most importantly, I think that it leads to poor notation in your code.</p>\n\n<p>I propose the following notation:</p>\n\n<ul>\n<li><code>x0</code>, <code>x1</code>, <code>x2</code>: The first, second, and third roots (better than <code>g</code>, <code>g2</code>, <code>g3</code>)</li>\n<li><code>Polynomial(a, b, c, d)</code>: An object representing the polynomial <em>a x</em><sup>3</sup> + <em>b x</em><sup>2</sup> + <em>c x</em> + <em>d</em></li>\n<li><code>f</code>: The polynomial to be solved (better than <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>)</li>\n<li><code>df_dx</code>: The derivative of <code>f</code> (better than <code>3*a*g**2+2*b*g+c</code>)</li>\n<li><code>q</code>: The quadratic polynomial remaining after <code>x0</code> has been found (better than <code>c1=-d/g</code>; <code>a1=a</code>; <code>b1=(c1-c)/g</code>)</li>\n<li><code>q.discriminant()</code>: Shorthand for <code>b1**2-4*a1*c1</code></li>\n<li><code>tolerance</code>: better than <code>e</code> (which unfortunately looks like it's related to a, b, c, d)</li>\n</ul>\n\n<p>Furthermore, you shouldn't hard-code a 100-iteration limit, especially twice as a magic number in the code.</p>\n\n<h3>Polynomial class</h3>\n\n<p>As noted above, having a class for polynomials is extremely useful for your problem. In addition to the polynomial to be solved, you need its derivative, and you also have a quadratic equation to solve. A polynomial class lets you</p>\n\n<ul>\n<li>pass the polynomial into the solver function conveniently</li>\n<li>collapse several variables into one</li>\n<li>evaluate the value of the polynomial easily</li>\n<li>take its derivative</li>\n</ul>\n\n<p>Here is an implementation:</p>\n\n<pre><code>class Polynomial(object):\n def __init__(self, *coeffs):\n \"\"\"\n Polynomial(3, 5, 0, -2) represents f(x) = 3x^3 + 5x^2 - 2.\n \"\"\"\n self.coeffs = list(coeffs)[::-1]\n while self.coeffs[-1] == 0:\n self.coeffs.pop()\n\n def __call__(self, x):\n \"\"\"\n >>> f = Polynomial(3, 5, 0, -2)\n >>> f(2)\n 42\n \"\"\"\n return sum([self[n] * x ** n for n in range(len(self.coeffs))])\n\n def __getitem__(self, n):\n \"\"\"\n Gets the coefficient for x^n\n >>> f = Polynomial(3, 5, 0, -2)\n >>> f[2]\n 5\n \"\"\"\n return self.coeffs[n] if n < len(self.coeffs) else 0\n\n def __str__(self):\n \"\"\"\n >>> f = Polynomial(3, 5, 0, -2)\n >>> str(f)\n 3 x^3 + 5 x^2 + 0 x^1 + -2\n \"\"\"\n return ' + '.join([\"%d x^%d\" % (self[n], n) for n in range(len(self.coeffs))][::-1])\n\n def degree(self):\n \"\"\"\n >>> f = Polynomial(3, 5, 0, -2)\n >>> f.degree()\n 3\n \"\"\"\n return len(self.coeffs) - 1\n\n def derivative(self):\n \"\"\"\n >>> f = Polynomial(3, 5, 0, -2)\n >>> f.derivative()\n 9 x^2 + 5 x^1 + 0 x^0\n \"\"\"\n deriv = [n * self[n] for n in range(len(self.coeffs) - 1, 0, -1)]\n return Polynomial(*deriv)\n\n def discriminant(self):\n \"\"\"\n For quadratic polynomial a x^2 + b x + c, returns b^2 - 4 * a * c\n\n >>> f = Polynomial(4, -1, 2)\n >>> f.discriminant()\n -31\n \"\"\"\n if self.degree() != 2:\n raise ValueError, \"Discriminant of polynomial of degree %d not supported\" % (self.degree())\n return self[1] ** 2 - 4 * self[2] * self[0]\n</code></pre>\n\n<h3>Error handling</h3>\n\n<p>If something goes wrong, don't just print something. Raise an exception, which ensures that the caller will notice the problem!</p>\n\n<pre><code>class SolutionNotFound(ValueError):\n \"\"\"\n Raised when a root of a polynomial cannot be found.\n \"\"\"\n</code></pre>\n\n<h3>Iteration limit</h3>\n\n<p>Python has a <a href=\"http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\" rel=\"nofollow\">language feature</a> for executing an <code>else</code> clause when a loop terminates naturally through exhaustion (i.e., when its condition becomes false, rather than by an early <code>break</code>). You can use it like this:</p>\n\n<pre><code>for _ in range(max_iterations):\n if abs(f(x0)) <= tolerance:\n break\n # TODO: refine x0 here\nelse:\n # Loop exhaustion, i.e. max_iterations reached\n # TODO: raise an error\n# TODO: Calculate x1 and x2 here\n</code></pre>\n\n<h3>Pretty!</h3>\n\n<p>All of that setup lets your code look like mathematics, not like a C program. Now you can clear your head of the minutiae and focus on things that matter, like your mathematical technique.</p>\n\n<p>I've made a few remarks in the code comments as well.</p>\n\n<pre><code>from math import sqrt\n\ndef solve_degree_3_polynomial(f, tolerance=0.00000001, initial_guess=0.01, max_iterations=100):\n if f.degree() != 3:\n raise ValueError, \"Input must be a polynomial of degree 3\"\n\n # If 0 is a root, make x0 exactly 0 to trigger a special case for\n # the quadratic equation below.\n x0 = 0 if f(0) == 0 else initial_guess\n df_dx = f.derivative()\n for _ in range(max_iterations):\n if abs(f(x0)) <= tolerance:\n break\n if df_dx(x0) == 0:\n x0 += 0.001\n x0 = x0 - f(x0) / df_dx(x0)\n else:\n raise SolutionNotFound, \"Exceeded %d iterations. Current guess: f(%d) = %d\" % (max_iterations, x0, f(x0))\n\n # q = Quadratic\n q = Polynomial(f[3], f[2], f[1]) if x0 == 0 else \\\n Polynomial(f[3], (-f[0] / x0 - f[1]) / x0, -f[0] / x0)\n\n # These three cases are mutually exclusive, right? Then write them that way.\n if abs(q.discriminant()) < tolerance:\n # I think that returning a double root is better than returning\n # None for one of the roots. It's mathematically more correct,\n # and less likely to cause bugs involving NoneType.\n x1 = x2 = -q[1] / (2 * q[2])\n\n elif q.discriminant() < 0:\n # You could just let cmath.sqrt() take care of this for you instead,\n # in which case all three cases collapse down to one!\n x1 = complex(-q[1] / (2 * q[2]), +sqrt(-q.discriminant()) / (2 * q[2]))\n x2 = complex(-q[1] / (2 * q[2]), -sqrt(-q.discriminant()) / (2 * q[2]))\n\n else:\n # If you change\n # from math import sqrt\n # to\n # from cmath import sqrt\n # then the two lines below handle all three cases, regardless of\n # whether the discriminant is negative, 0, or positive.\n x1 = (-q[1] + sqrt(q.discriminant())) / (2 * q[2])\n x2 = (-q[1] - sqrt(q.discriminant())) / (2 * q[2])\n\n return x0, x1, x2\n</code></pre>\n\n<h3>Example usage</h3>\n\n<pre><code>f = Polynomial(3, -1, 6, -2)\n(x0, x1, x2) = solve_degree_3_polynomial(f)\n\nprint \"f(x) = %s\" % (f)\nprint \"f(%s) = %s\" % (x0, f(x0))\nprint \"f(%s) = %s\" % (x1, f(x1))\nprint \"f(%s) = %s\" % (x2, f(x2))\n</code></pre>\n\n<p>… prints</p>\n\n<blockquote>\n<pre><code>f(x) = 3 x^3 + -1 x^2 + 6 x^1 + -2 x^0\nf(0.333333333333) = 2.423339307e-13\nf((3.44613226844e-13+1.41421356237j)) = (-4.36495284361e-12-1.7763568394e-15j)\nf((3.44613226844e-13-1.41421356237j)) = (-4.36495284361e-12+1.7763568394e-15j)\n</code></pre>\n</blockquote>\n\n<h3>Next steps</h3>\n\n<p>As noted in the comments, I would recommend using <code>cmath.sqrt()</code> to collapse the three cases for the discriminant into one.</p>\n\n<p>It would also be a good idea to decompose the cubic equation solver into a generic Newton's method solver for any polynomial, followed by a quadratic equation solver.</p>\n\n<pre><code>def solve_degree_3_polynomial(f, ...):\n if f.degree() != 3:\n raise ValueError\n x0 = solve_polynomial_by_newton(f, ...)\n q = Polynomial(f[3], (-f[0] / x0 - f[1]) / x0, -f[0] / x0)\n x1, x2 = solve_degree_2_polynomial(q)\n return x0, x1, x2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T22:08:43.477",
"Id": "39518",
"ParentId": "39232",
"Score": "3"
}
},
{
"body": "<p>In addition, I would suggest that you can win some speed by evaluating the coefficients of the quadratic equation as:</p>\n\n<pre><code>a1= a\nb1 = a1*g + b\nc1 = b1*g + c\n</code></pre>\n\n<p>where, g is the root found out using Newton Raphson.</p>\n\n<p>In this way you avoid using the division operator (like in your method, c1 = -d/g , ...) - small but some gain at least! Besides, no fears if the denominator becomes 0.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-31T05:49:09.910",
"Id": "68471",
"ParentId": "39232",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39518",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T18:33:11.847",
"Id": "39232",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"mathematics",
"numerical-methods"
],
"Title": "Newton's method to solve cubic equations"
}
|
39232
|
<p>In the first code snippet I am creating a generic class to hold configuration details. I am currently using it as a way to pass run time configuration options to plugins in a generic manner. The second snippet is a helper class that utilizes the class to provide the public methods for use which helps guarantee type safety.</p>
<p><strong>Questions</strong></p>
<ul>
<li>How is my use of generics? I feel like there is a better way to handle this.</li>
<li>Is there a better design pattern to be used here?</li>
</ul>
<p><strong>DefaultConfiguration</strong></p>
<pre><code>import java.util.HashMap;
import java.util.Map;
public class DefaultConfiguration implements Configuration {
private final Map<String, Setting> options;
public DefaultConfiguration() {
this.options = new HashMap<String, Setting>();
}
@Override
public <T> T get(String option, Class<T> type) {
Setting setting = options.get(option);
if (setting != null) {
return type.cast(setting.getSetting(type));
}
return null;
}
@Override
public <T> void set(String option, T setting, Class<T> type) {
options.put(option, new Setting<T>(setting, type));
}
@Override
public void set(String option, Object setting) {
options.put(option, new Setting(setting, setting.getClass()));
}
class Setting<W> {
private final Class<? super W> type;
private final W setting;
public Setting(W setting, Class<? super W> type) {
this.type = type;
this.setting = setting;
}
public W getSetting(Class<? super W> type) {
if (type.isAssignableFrom(this.type)) {
return setting;
}
return null;
}
}
}
</code></pre>
<p><strong>MyConfiguration</strong></p>
<pre><code>public class MyConfiguration extends DefaultConfiguration {
public String getSettingA() {
return super.get("settingA", String.class);
}
public void setSettingA(String settingA) {
super.set("settingA", settingA, String.class);
}
public Integer getSettingB() {
return super.get("settingB", Integer.class);
}
public void setSettingB() {
super.set("settingB", settingB, Integer.class);
}
}
</code></pre>
<p><strong>Updated Classes</strong></p>
<pre><code>import java.util.HashMap;
public class Configuration
extends HashMap<String, Object>
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public <T> T get(String option, Class<T> type)
{
Object obj = get(option);
if (obj == null) {
return null;
}
try {
return type.cast(obj);
} catch (ClassCastException ex) {
throw new ConfigurationException(ex);
}
}
}
</code></pre>
<hr>
<pre><code>public class MyConfiguration
extends Configuration
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String SETTING_A = "settingA";
private static final String SETTING_B = "settingB";
public String getSettingA()
{
return get(SETTING_A, String.class);
}
public void setSettingA(String settingA)
{
put(SETTING_A, settingA);
}
public Integer getSettingB()
{
return get(SETTING_B, Integer.class);
}
public void setSettingB()
{
put(SETTING_B, settingB);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:30:56.677",
"Id": "65744",
"Score": "0",
"body": "A \"Type-safe configuration class\" is called a [Java Bean](http://en.wikipedia.org/wiki/JavaBeans)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:00:00.340",
"Id": "65812",
"Score": "0",
"body": "A Java Bean wouldn't allow the passing of arbitrary values. I want users of a framework to be able to pass any value they want to be used inside their \"plugin\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T09:40:38.357",
"Id": "65883",
"Score": "0",
"body": "\"*wouldn't allow the passing of arbitrary values*\" is pretty much the definition of type-safe."
}
] |
[
{
"body": "<p>Generics can only go so far to help you, and, this is one of those times where it just does not help all that much.</p>\n\n<p>In essence, you have the following:</p>\n\n<ul>\n<li>a configuration system where you can get values based on names (a Map).</li>\n<li>when you set a value it is for a given type (which is either specified when you set the value, or it is not, in which case it is inferred).</li>\n<li>when you get a value, it is matched against the type the getter expects, and, if it matches, it is returned.</li>\n</ul>\n\n<p>Since the getter/setter is the only place where you actually know the type of the value, there is actually zero benefit for your entire <code>Setting</code> subclass... it is redundant. You can get the same behaviour with:</p>\n\n<pre><code>private final Map<String, Object> options;\n\npublic DefaultConfiguration() {\n this.options = new HashMap<String, Object>();\n}\n\n@Override\npublic <T> T get(String option, Class<T> type) {\n Object value = options.get(option);\n if (value != null) {\n return type.cast(value);\n }\n return null;\n}\n\n@Override\npublic <T> void set(String option, T setting, Class<T> type) {\n // no point in even checking the type, the generic method will enforce that.\n // this method is essentially redundant, and could be\n // public void set(String option, Object value);\n options.put(option, setting);\n}\n\n@Override\npublic void set(String option, Object setting) {\n // this essentially a duplicate option.\n options.put(option, setting);\n}\n</code></pre>\n\n<p>here you have the exact same functionality as you did before.... if the user wants to, they can compile-time type-check their values when they set them (by ensusuring the <code>Class<T></code> parameter matches the <code>T setting</code> value</p>\n\n<p>When they retrieve the value, they can cast the result to the specified type, or return null if it is not castable.</p>\n\n<p>The functionality in <code>MyConfiguration</code> is unchanged, but, I recommend you use constants for the keys:</p>\n\n<pre><code>private static final String SETTINGA = \"settingA\";\n....\n</code></pre>\n\n<p>Finally, you may want to consider your <code>DefaultConfiguration</code> extending something like HashMap directly.... like:</p>\n\n<pre><code>public class DefaultConfiguration\n extends HashMap<String,Object>\n implements Configuration {\n</code></pre>\n\n<p>then, remove the <code>options</code> Map variable, and simply have methods like (note the direct <code>get(option)</code> instead of <code>options.get(option)</code>:</p>\n\n<pre><code>@Override\npublic <T> T get(String option, Class<T> type) {\n Setting setting = get(option);\n if (setting != null) {\n return type.cast(setting.getSetting(type));\n }\n return null;\n}\n</code></pre>\n\n<p>Now, when people use your class, they have access directly to the configuration too (with, and without your 'helper' methods).</p>\n\n<p>The bottom line though, is that your implementation does not enforce type-safety between the <code>set</code> and the <code>get</code>. The only thing it does is return null instead of throwing a ClassCastException when people use your code wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T19:58:22.693",
"Id": "65708",
"Score": "0",
"body": "Yeah after looking posting this I came to the same conclusion of it being worthless to have all of that generic junk in there. Went off the edge there. How does the design work out for as a method for implementing a configuration. Is this a lackluster design as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:07:23.833",
"Id": "65710",
"Score": "0",
"body": "Also, is there a better way to prevent people from using my code wrong? I want developers to be able to pass arbitrary details to their plugin implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:39:52.633",
"Id": "65715",
"Score": "0",
"body": "` I want developers to be able to pass arbitrary details to their plugin implementations.` I don't beleieve Generics will help you tbe that flexible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:03:37.427",
"Id": "65717",
"Score": "0",
"body": "Yeah I've removed the generics and just have a convenience method for the configuration implementations to specify their type, attempt to cast, and throw an API exception around the ClassCastException if it is thrown. I'm now mostly interested in whether using a map to provide this functionality is the most prudent design."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T19:22:35.543",
"Id": "39236",
"ParentId": "39233",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T19:01:42.793",
"Id": "39233",
"Score": "2",
"Tags": [
"java",
"api"
],
"Title": "Generic java configuration class with type safety"
}
|
39233
|
<p>Pretty printer in ABAP does not take care of all my aligning need, so I wrote a small JS script that tabulates/aligns with a custom string. It contains HTML, CSS and script in 1 file because this is a small tool.</p>
<p>Link : <a href="https://github.com/konijn/aligner" rel="nofollow">https://github.com/konijn/aligner</a></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Aligner</title>
<style>
textarea { width: 100% ; height: 200px ; font-family: monospace }
.emo { margin-top: 10px ; margin-bottom: 10px }
</style>
</head>
<body>
<h2>Aligner</h2>
<label>Editor:</label><br>
<textarea id="editor">
DATA : wa_ekpo TYPE ekpo.
DATA : wa_eket TYPE eket.
DATA : wa_decision TYPE zrms_performance_decision.
DATA : wa_receipt_item TYPE zrmt_rcpt_items.
DATA : wa_container TYPE zrmt_rcpt_hdrs_c.
</textarea><br>
<label class="emo">Align at</label>
<input type="text" id="token" class="emo" value="TYPE">
<button type="button" id= "button">Align</button><br>
<label>Output:</label><br>
<textarea id="output"></textarea><br>
<script>
//Do the DOM querying once, the DOM elements are stable
var editor = document.getElementById( 'editor' ),
output = document.getElementById( 'output' ),
token = document.getElementById( 'token' ),
button = document.getElementById( 'button' );
//What happens when we click that button
button.addEventListener( 'click' , function( e )
{
var lines = editor.value.split('\n'),
columnSizes = {};
//Collect for each line the size of each column, keep the largest column size
lines.forEach( function( line )
{
var columns = line.split( token.value );
columns.forEach( function( column , index )
{
columnSizes[index] = Math.max( column.length , columnSizes[index] || 0 );
});
});
//Build up the new text with aligned columns
output.value = lines.map( function( line )
{
var columns = line.split( token.value );
return columns.map( function( column , index )
{
return column + spaces( columnSizes[index] - column.length );
}).join( token.value );
}).join('\n');
//Make sure Firefox does not go haywire
e.preventDefault();
}, false);
//Return a string with count spaces
function spaces( count )
{
return new Array( count + 1 ).join( " " );
}
</script>
</body>
</html>
</code></pre>
<p>Please review for style and maintainability.</p>
|
[] |
[
{
"body": "<p>I'm just commenting on your HTML/CSS.</p>\n\n<ul>\n<li>I commented out some <code>br</code> tags, because they were not necessary</li>\n<li>I splitted the HTML in three parts with <code>div</code>'s</li>\n<li>Slightly adjusted the CSS rules</li>\n</ul>\n\n\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Aligner</title>\n <style>\n textarea {\n width: 100% ;\n height: 200px ;\n font-family: monospace;\n }\n .controls {\n margin-top: 10px;\n margin-bottom: 10px;\n }\n </style>\n </head>\n <body>\n <h2>Aligner</h2>\n <div class=\"editor\">\n <label>Editor:</label><!--<br>-->\n <textarea id=\"editor\">\n DATA : wa_ekpo TYPE ekpo.\n DATA : wa_eket TYPE eket.\n DATA : wa_decision TYPE zrms_performance_decision.\n DATA : wa_receipt_item TYPE zrmt_rcpt_items.\n DATA : wa_container TYPE zrmt_rcpt_hdrs_c. \n </textarea><!--<br>-->\n </div>\n <div class=\"controls\">\n <label class=\"emo\">Align at</label>\n <input type=\"text\" id=\"token\" class=\"emo\" value=\"TYPE\">\n <button type=\"button\" id= \"button\">Align</button><!--<br>-->\n </div>\n <div class=\"output\">\n <label>Output:</label><!--<br>-->\n <textarea id=\"output\"></textarea><!--<br>-->\n </div>\n <script>\n // your script\n </script>\n </body>\n</html>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T15:21:17.183",
"Id": "40041",
"ParentId": "39234",
"Score": "4"
}
},
{
"body": "<p>I recommend splitting your function into a DOM-and-event-handling function and a text-analysis function.</p>\n\n<pre><code>function alignTextColumns( text, delimiter )\n{\n …\n}\n\nbutton.addEventListener( 'click' , function( event )\n{\n output.value = alignTextColumns( editor.value, token.value );\n\n //Make sure Firefox does not go haywire \n event.preventDefault();\n}, false);\n</code></pre>\n\n<p>That way, the <code>alignTextColumns()</code> function could be reused if the more text areas are added, or if you change the user interface to want to dump the output to the same text area as the input.</p>\n\n<p>I would also bury the <code>spaces()</code> helper function inside the <code>alignTextColumns()</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T12:03:12.683",
"Id": "40091",
"ParentId": "39234",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40091",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T19:01:47.230",
"Id": "39234",
"Score": "7",
"Tags": [
"javascript",
"html",
"strings",
"css"
],
"Title": "Tabulate text with JavaScript"
}
|
39234
|
<p>I have a need to print the content of a jQueryUI Dialog to a printer, and I couldn't find anything to my liking. I developed the following simple jQuery plugin which prints one or more provided HTML elements, and am using it to print the jQueryUI Dialog DIV element. The code is below, and a live example is located <a href="http://jsfiddle.net/fyu4P/embedded/result/">here</a>.</p>
<p>It works on FF 26.0. However, after printing a couple of times, FF asks the user if popups should be disabled, which I wish not to happen. Also, it doesn't work with older IE, and likely other browsers. Don't worry because, when printing, you still need to click the operating system print dialog, so you won't waste any paper!</p>
<p>Please provide any recommendations on how this plugin could be improved.</p>
<p>Actual Plugin:</p>
<pre><code>/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
var defaults = {
elems :null, //Element to print HTML
copy_css :false,//Copy CSS from original element
external_css :null //New external css file to apply
};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options)
elems=$(settings.elems);
return this.each(function () {
$(this).click(function(e) {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
elems.each(function(){
iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
});
if(settings.copy_css) {
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}
}
if(settings.external_css) {
var style = document.createElement("link")
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = settings.external_css;
iframe.contentWindow.document.head.appendChild(style);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'window.print();';
iframe.contentWindow.document.head.appendChild(script);
$(iframe).hide();
});
});
});
},
destroy : function () {
//Anything else I should do here?
delete settings;
return this.each(function () {});
}
};
$.fn.printIt = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.printIt');
}
};
}(jQuery)
);
</code></pre>
<p>To configure:</p>
<pre><code>$(function () {
$("#openDialog").click(function () {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false
});
$('#printIt').printIt({
elems: $("#myDialog"),
copy_css: true,
external_css: 'test2.css'
});
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over: </p>\n\n<ul>\n<li>I am not a native English speaker but <code>//Element to print HTML</code> confused me. Maybe <code>//HTML elements to be printed</code>?</li>\n<li><code>delete settings;</code> is meaningless in <code>destroy</code> ( see comment )</li>\n<li><code>elems=$(settings.elems);</code> should be <code>var elems = $(settings.elems);</code> otherwise you pollute the global namespace</li>\n<li>You declare <code>var i</code> twice in a for loop</li>\n<li>You should consider removing the <code>iframe</code> in <code>destroy</code></li>\n</ul>\n\n<p>All in all very clean, maintainable code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:57:30.987",
"Id": "66107",
"Score": "1",
"body": "`delete settings` will always be meaningless as its a scope variable. He should remove that altogether"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:49:21.607",
"Id": "66119",
"Score": "0",
"body": "Thanks tomdemuyt. elems is in fact the element which will be printed, not the print button. How do you think it could be modified to be more cross browser compliant with earlier IE and even current FF (i.e. causes FF to generate popup asking whether it should prevent script from generating popups)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T21:25:44.667",
"Id": "66227",
"Score": "0",
"body": "I do not believe you can avoid the FF popups at all, I tested your plugin in Chrome, it works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:57:39.153",
"Id": "66317",
"Score": "0",
"body": "Yea, It works with recent Chrome as well is IE 9, 10, and 11. My main objective was allowing it to work with FF. The line that is causing it is `script.text = 'window.print();';`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T17:33:05.250",
"Id": "66411",
"Score": "0",
"body": "3500! Congrats!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T13:34:54.443",
"Id": "39471",
"ParentId": "39235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T19:10:40.920",
"Id": "39235",
"Score": "8",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery plugin which will print to a printer an element or a jQueryUI Dialog"
}
|
39235
|
<p>I thought this was pretty slick - maybe not, I just wanted to share and maybe get some feedback:</p>
<p>As part of a REST client class:</p>
<p>Accepts the JSON response from REST or REST-like service, searches through to find multiple errors, or return success indicator.</p>
<p>You define success and failure in a small multidimensional array broken down by resource/method, I have it set to count success/failure when it finds the properties with matching names, but could check values too:</p>
<pre><code>private $response_definitions = array(
'authenticate' => array(
'success' => array( 'accessHash' ),
'failure' => array( 'authErrorObj' ),
),
'create_order' => array(
'success' => array( 'orderSuccessObj' ),
'failure' => array( 'orderErrorObj', 'deviceErrorObj' ),
),
'cancel_order' => array(
'success' => array( 'cancelOrderObj' ),
'failure' => array( 'orderErrorObj' ),
)
);
</code></pre>
<p>You hand it your response - already decoded, in this case</p>
<pre><code>$this->checkResponse($action,json_decode($response));
</code></pre>
<p>Loops through our response. Fills a "error" property in the main class for errors, and also returns the success object, defined above, if found.</p>
<pre><code>/**
* checkForErrors
* Here we will take whatever response we have, and look for errors in it.
* sending the thrid parameter as 'false' kicks off a recursive search through the provided response()
* the search looks for both success and failure properties, defined in the class properties.
* if it finds an error value, it builds up the class' "error" property
* if it doesn't find a success, the first iteration (with the false third parameter) adds an error as well
* @param action string the action we launched so we can know what kind of errors to look for
* @param response object the full response object, converted to a php object with json_decode
* @param type string when this is false, it will begin the recursion to look for successes and failures
* @void
*/
function checkResponse( $action, $response, $type=FALSE )
{
// the first, non-recursive iteration
if( $type === FALSE ){
$this->checkResponse( $action, $response, 'failure' );
$success_result = $this->checkResponse( $action, $response, 'success' );
if( $success_result === NULL ){
$this->errors[] = (object)array(
'name' => 'TEK-00000',
'description' => 'Success Property Not Found!'
);
}
}else // the recursive iterations
{
$definitions = $this->response_definitions[$action][$type];
foreach( $response as $property => $value )
{
// if success and property is in 'success' array, then return the property
if( $type == 'success' && in_array( $property, $definitions ) ){
return $property;
}
// if failure and property is in 'failure' array, then add the error to the error property
if( $type == 'failure' && in_array( $property, $definitions ) ){
$this->errors[] = (object)array(
'name' => $value->errorCode,
'description' => $value->errorMessage
);
}
// if property is an object or an array, recursively search through it as well
if ( is_object( $value ) || is_array( $value ) ){
// if we're looking at successes, be sure to send the result up the recursion chain.
if ( $type == 'success' ){ return $this->checkResponse( $action, $value, $type ); }
elseif( $type == 'failure' ){ $this->checkResponse( $action, $value, $type ); }
}
}
}
}
</code></pre>
<p>Anyway, open to improvements I'm sure. I kind of like that you kick it off by setting one flag, then it handles are the recursion within itself and hands any success response up the chain.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T23:43:38.620",
"Id": "65852",
"Score": "0",
"body": "If you're writing your own restful service, why wouldn't you have it define whether it failed or not on its own? E.g. have every response in a format like: `{\"success\":true, \"errorMessage\":null, \"data\":\"my data\"}`,`{\"success\":false, \"errorMessage\":\"Bad Input\", \"data\":null}`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T13:28:58.603",
"Id": "102095",
"Score": "1",
"body": "Ah, I'm not writing my own service, this is just for REST client."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:03:41.940",
"Id": "39238",
"Score": "1",
"Tags": [
"php",
"recursion",
"iterator"
],
"Title": "REST Response: Checking for Success and Error"
}
|
39238
|
<p>Can I improve this markup? Is it SEO friendly?</p>
<pre><code><div class="bloc-contenu group" itemscope itemtype="http://schema.org/Hotel" itemref="logo nom-hotel">
<p><iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d89225.49873817024!2d-74.4423141!3d45.664941!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sfr!2sca!4v1389731001791" width=667 height=325 frameborder=0 style="border:0"></iframe><br>
<small><a itemprop=map href="https://www.google.ca/maps/preview#!q=Brownsburg-Chatham%2C+QC&data=!4m15!2m14!1m13!1s0x4ccedde9eac0cb83%3A0xf994ff962e761612!3m8!1m3!1d110951!2d-74.4423141!3d45.664941!3m2!1i1920!2i955!4f13.1!4m2!3d45.6608378!4d-74.4472133" target=_blank>Agrandir le plan</a></small>
<p>Pour réserver ou pour plus d'informations sur nos services&nbsp;:
<address>
<p itemprop=telephone>555&nbsp;555-5555
<p itemprop=address itemscope itemtype="http://schema.org/PostalAddress"><span itemprop=streetAddress>38, street name</span>,<br>
<span itemprop=addressLocality>City</span> (<span itemprop=addressRegion>Province</span>)<br>
<span itemprop=postalCode>XXXXXX</span>
</address>
<p><a href="https://www.facebook.com/" target=_blank><strong>Retrouvez-nous sur Facebook</strong></a>
</div>
</code></pre>
<p><code>itemref="logo nom-hotel"</code> refers to two tags at the top of the page:</p>
<pre><code><img id=logo src="/img/logo.20140104.png" alt="Name of the place" width=161 height=175 itemprop=logo>
</code></pre>
<p>and:</p>
<pre><code><h1 itemprop=name id=nom-hotel>Name of the place</h1>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:12:08.990",
"Id": "317179",
"Score": "0",
"body": "[There's a different standard microformat you could use](http://microformats.org/wiki/hcard). It's an HTML representation of [this](http://tools.ietf.org/html/rfc6350) and [this](http://tools.ietf.org/html/rfc6351). I don't know why you might prefer this one instead of the schema.org one."
}
] |
[
{
"body": "<p>From some research:</p>\n\n<ul>\n<li><p>If your code will be used on mobile, I would look into making that phone tag ( which seems to miss <code></p></code> ) into a functional phone tag : <a href=\"https://stackoverflow.com/a/11143507/7602\">https://stackoverflow.com/a/11143507/7602</a></p></li>\n<li><p>I would imagine you want your facebook link to point to your actual page.</p></li>\n<li><p>Your <code><p></code>aragraphs are not closed properly..</p></li>\n<li><p>I would leave <code><p></code>aragraphs out of <code><address></code> and would use styled <code><span></code>s</p></li>\n<li><p><code>frameborder</code> is obsolete for <code>iframe</code>, while <code>iframe</code> should have a <code>title</code></p></li>\n<li><p>Your quoting of HTML attributes is inconsistent, in my mind they should all be surrounded with double quotes.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:36:10.807",
"Id": "65719",
"Score": "0",
"body": "Thank you for the phone tag link. The Facebook link points to the actual page, I just want to keep it anonymous for now. And I'm ok with unclosed tag in this case. I don't do it in big projects, only in small websites like this. It is W3C valid and there's no bug caused by that. But why would you use `<span>`s instead of `<p>`s in `<address>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:39:05.210",
"Id": "65720",
"Score": "0",
"body": "Because semantically, those are not paragraphs ( `a distinct section of a *piece of writing*, usually dealing with a single theme and indicated by a new line, indentation, or numbering. ) but pieces of data"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:28:45.297",
"Id": "39243",
"ParentId": "39240",
"Score": "3"
}
},
{
"body": "<p>Your <strong>Microdata</strong> is fine.</p>\n\n<p>Some <strong>HTML</strong> suggestions:</p>\n\n<ul>\n<li>I wouldn’t use <code>p</code> as container for <code>iframe</code> + the map. I’d use <code>div</code> instead.</li>\n<li>Don’t use <code><br></code> after the <code>iframe</code> (<code>br</code> is <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-br-element\" rel=\"nofollow noreferrer\">for line breaks that are part of the content</a> only). Your usage of <code>br</code> in the postal address is correct.</li>\n<li>Don’t use <code>small</code> for the link to the map (as it doesn’t seem to be a <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-small-element\" rel=\"nofollow noreferrer\">side comment</a>).</li>\n<li>You could use <a href=\"https://stackoverflow.com/a/19638774/1591669\"><code>rel</code>-<code>external</code></a> for the external links to Google and Facebook.</li>\n<li><p>You could link the telephone number with the <a href=\"http://tools.ietf.org/search/rfc3966\" rel=\"nofollow noreferrer\"><code>tel</code> URI scheme</a>. But then you should include the anchor text in a <code>span</code> element, as schema.org’s <a href=\"http://schema.org/telephone\" rel=\"nofollow noreferrer\"><code>telephone</code> property</a> expects \"Text\", not \"URL\" (which would be <a href=\"https://stackoverflow.com/a/20889900/1591669\">the value for the <code>itemprop</code> if used on <code>a</code></a>).</p>\n\n<pre><code><a href=\"tel:555…\"><span itemprop=telephone>555 555-5555</span></a>\n</code></pre></li>\n<li><p>In contrast to what <a href=\"https://codereview.stackexchange.com/a/39243/16414\">tomdemuyt answered</a>, using <code>p</code> for the postal address seems to be fine (as it’s used in an <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-br-element\" rel=\"nofollow noreferrer\">example</a> in the HTML5 spec).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:45:18.283",
"Id": "39299",
"ParentId": "39240",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T20:57:26.817",
"Id": "39240",
"Score": "-1",
"Tags": [
"html",
"html5",
"microdata"
],
"Title": "Optimizing with microdata and address tag"
}
|
39240
|
<p>I have fully working code, however I'd like to make it nice. I've got these three models:</p>
<blockquote>
<ol>
<li><p>User (can have both or either one)<br>
user can have one trucker<br>
user can have one owner_trucker</p></li>
<li><p>Trucker
belongs to user</p></li>
<li><p>OwnerTrucker
belongs to user</p></li>
</ol>
</blockquote>
<p>I'm not the only one working in the app, but it starts to annoy me how everyone is solving the issue locally.</p>
<p>The problem is how to determine what the user is (a <code>trucker</code> or a <code>owner_trucker</code> or both). i.e if <code>user.trucker</code> is not nil, its a <code>trucker</code> etc.</p>
<p>So here are few examples from the application (various controllers), basically checking for the same thing but in a different way:</p>
<pre><code>helper_method :profile_type_from_user
def profile_type_from_user(user)
return profile = user.trucker ? :trucker : :owner_trucker
end
</code></pre>
<p>And then used in another controller like:</p>
<pre><code>if profile_type_from_user(profile) == :trucker
else
end
</code></pre>
<p>Another example would be:</p>
<pre><code>@profile = current_user.trucker ? current_user.trucker : current_user.owner_trucker
</code></pre>
<p>Checking if one or another:</p>
<pre><code>current_user.trucker? && current_user.owner_trucker.nil?
</code></pre>
<p>It this refactorable?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T03:13:48.277",
"Id": "65740",
"Score": "2",
"body": "Does the problem domain allow for a simplification of these roles? Are `owner_truckers` also a type of `trucker`? How is a `user` who is an `owner_trucker` different than if they were both a `trucker` and an `owner_trucker`? As it is seems like there are opportunities to remove these checks (or at least express them more meaningfully as part of the `User`) but without more understanding of the domain it's not clear what would be valid."
}
] |
[
{
"body": "<p>I think your suspicion that the code is a \"wet\" is correct. I would start moving these predicates into the model whenever they are:</p>\n\n<ul>\n<li>Used more than once, or</li>\n<li>Can make the code clearer by having a named predicate.</li>\n</ul>\n\n<p>Consider replacing this:</p>\n\n<pre><code>helper_method :profile_type_from_user\n def profile_type_from_user(user)\n return profile = user.trucker ? :trucker : :owner_trucker\n end\n</code></pre>\n\n<p>With this:</p>\n\n<pre><code>class User\n ...\n def profile_type\n trucker ? :trucker : :owner_trucker\n end\n ...\nend\n</code></pre>\n\n<p>Similarly, consider replacing this:</p>\n\n<pre><code>@profile = current_user.trucker ? current_user.trucker : current_user.owner_trucker\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>class User\n ...\n def profile\n trucker || owner_trucker\n end\n ...\nend\n\n@profile = current_user.profile\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T03:17:45.387",
"Id": "39260",
"ParentId": "39245",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39260",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T21:48:14.523",
"Id": "39245",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Supporting two kinds of user profiles"
}
|
39245
|
<p>I'm learning JavaScript and I was trying to make a custom addEvent function that would care about compatibility (I don't want to use jQuery [nor any other library] yet, in order for me to "master" the bases of JavaScript).</p>
<p>I came across this code on github (<a href="https://gist.github.com/eduardocereto/955642" rel="nofollow">https://gist.github.com/eduardocereto/955642</a>):</p>
<pre><code>/**
* Cross Browser helper to addEventListener.
*
* @param {HTMLElement} obj The Element to attach event to.
* @param {string} evt The event that will trigger the binded function.
* @param {function(event)} fnc The function to bind to the element.
* @return {boolean} true if it was successfuly binded.
*/
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
</code></pre>
<p><strong>But I was not pleased with the solution even tho it is very short and readable so I made my own (below) with a little help from the book I'm reading: "Secrets of the JavaScript Ninja"</strong></p>
<p><strong>I want to know if you guys think I have something wrong or even if you have any comments or improvements that I might not be seeing:</strong></p>
<p>I commented on that post the following (I'm pg2800 on github):</p>
<p>ORIGINAL COMMENT: 12-January-2014. UPDATED 13-January-2014. I was intrigued with your implementation and I believe I added some best practices to the code in general and also added some improvements to the "traditional" way.</p>
<p>All three implementations of the addEvent custom method below (meaning: with or without any of the addEventListener or attachEvent -- forcing the browser to test all three) worked for: CHROME: Version 32.0.1700.72 m FIREFOX: 26.0 EXPLORER: Version 10.0.9200.16750</p>
<p>Needless to say; I didn't examine all possible scenarios in my test cases, only a few... Let me know what you think.</p>
<pre><code>(function(){
// I test for features at the beginning of the declaration instead of everytime that we have to add an event.
if(document.addEventListener) {
window.addEvent = function (elem, type, handler, useCapture){
elem.addEventListener(type, handler, !!useCapture);
return handler; // for removal purposes
}
window.removeEvent = function (elem, type, handler, useCapture){
elem.removeEventListener(type, handler, !!useCapture);
return true;
}
}
else if (document.attachEvent) {
window.addEvent = function (elem, type, handler) {
type = "on" + type;
// Bounded the element as the context
// Because the attachEvent uses the window object to add the event and we don't want to polute it.
var boundedHandler = function() {
return handler.apply(elem, arguments);
};
elem.attachEvent(type, boundedHandler);
return boundedHandler; // for removal purposes
}
window.removeEvent = function(elem, type, handler){
type = "on" + type;
elem.detachEvent(type, handler);
return true;
}
}
else { // FALLBACK ( I did some test for both your code and mine, the tests are at the bottom. )
// I removed wrapping from your implementation and added closures and memoization.
// Browser don't support W3C or MSFT model, go on with traditional
window.addEvent = function(elem, type, handler){
type = "on" + type;
// Applying some memoization to save multiple handlers
elem.memoize = elem.memoize || {};
// Just in case we haven't memoize the event type yet.
// This code will be runned just one time.
if(!elem.memoize[type]){
elem.memoize[type] = { counter: 1 };
elem[type] = function(){
for(key in nameSpace){
if(nameSpace.hasOwnProperty(key)){
if(typeof nameSpace[key] == "function"){
nameSpace[key].apply(this, arguments);
};
};
};
};
};
// Thanks to hoisting we can point to nameSpace variable above.
// Thanks to closures we are going to be able to access its value when the event is triggered.
// I used closures for the nameSpace because it improved 44% in performance in my laptop.
var nameSpace = elem.memoize[type], id = nameSpace.counter++;
nameSpace[id] = handler;
// I return the id for us to be able to remove a specific function binded to the event.
return id;
};
window.removeEvent = function(elem, type, handlerID){
type = "on" + type;
// I remove the handler with the id
if(elem.memoize && elem.memoize[type] && elem.memoize[type][handlerID]) elem.memoize[type][handlerID] = undefined;
return true;
};
};
})();
</code></pre>
<p>The first two (with addEventListener or attachEvent) run as the original ones, didn't notice any differences. But for the "traditional way":</p>
<p>My original test was 150k repetitions of adding an empty function to the element's event and then run the event. But as you wrap the handlers onto each other; javascript sends the next error: "Maximum call stack size exceeded" which is only natural.</p>
<p>Then I tested for the maximum stack size allowed which was 7816 ( I made that my test size), the results of adding 7816 empty functions to the same type of event of the same element and then executing the event was:</p>
<p>Your code: minimum = 19ms, maximum = 33ms, average = 30ms. My code: minimum = 20ms, maximum = 37ms, average = 27ms.</p>
<p>There is obviously not an improvement on performance whatsoever, but we can now delete specific handlers and also we have room for more handlers, and we can use this to standarize our code with the same function to add and to remove events, so we don't have to worry about X-browser considerations.</p>
<p>If we were to have very little to none memory available, I would definitely go with your implementation.</p>
<p>--> Tests done with a Sony vaio 8GB RAM, core i7 second generation.</p>
<p>i.e.</p>
<pre><code>var div = getElementById("divID"); // returns a div element
var handler = addEvent(div, "click", function(){
/* do something */
}, false);
/* more code */
removeEvent(div, "click", handler);
</code></pre>
<p>P.S. Pardon me if I made any grammatical or orthographic mistakes, English is not my native language</p>
|
[] |
[
{
"body": "<p>Your code is clean and consistent in style and formatting. Good job.</p>\n\n<p>I've noticed two small things that are not problems but rather they were unexpected to me and might trip you coming back to this code in 6 months tie</p>\n\n<ol>\n<li><p>you end all your code blocks with <code>};</code> when you don't need to.</p>\n\n<p><strong>Your code:</strong></p>\n\n<pre><code>if(something){\n // ...\n};\n</code></pre>\n\n<p>This will not cause issues but it isn't needed. You only need it for statements<sup>1</sup> not code blocks.</p>\n\n<p><strong>statements:</strong></p>\n\n<pre><code>var something = { someProp: true, other: 'test' };\nvar somethingelse = function () { \n // ...\n};\nmyObject.someMethod();\n</code></pre>\n\n<p><strong>code blocks:</strong></p>\n\n<pre><code>if(logicalTest){\n // ...\n}\n\nwhile(count < 0){\n // ...\n}\n\nfunction myFunction(){\n // ...\n}\n</code></pre></li>\n<li><p><code>elem.memoize[type] = { counter: 1 };</code> and <code>id = nameSpace.counter++;</code> means there will never be a handler with id 0. I'm not sure that is a problem but I assumed it would start at 0 like all JavaScript lists which are 0-based list.\nIn fact I might actually use a list.</p>\n\n<pre><code>elem.memoize[type] = [];\nelem[type] = function(){\n for(var i =0; i <= elem.memoize[type].length; i++){\n if(typeof elem.memoize[type][i] == \"function\"){\n elem.memoize[type][i].apply(this, arguments);\n }\n }\n};\n\n// ...\n var nameSpaceList = elem.memoize[type], id = nameSpaceList.length;\n</code></pre></li>\n</ol>\n\n<blockquote>\n <p><sup>1</sup> You don't technically need it for statements there are ways of writing javascript without them but I am personally not a fan.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T23:26:45.797",
"Id": "39250",
"ParentId": "39246",
"Score": "1"
}
},
{
"body": "<p>As I cannot update the question. I will leave the updated code as a new answer, hope this is not forbidden also.</p>\n\n<p>UPDATEs:</p>\n\n<ol>\n<li><p>Removed the <code>return true;</code> of the <code>window.removeEvent()</code> functions because I was not validating in any way if the event was being removed.</p></li>\n<li><p>I listened to <a href=\"https://codereview.stackexchange.com/users/3472/james-khoury\">James Khoury</a> improvements and I removed the unneeded <code>;</code> on blocks and added them to statements that didn't have them. Also started the counter in 0 -> <code>elem.memoize[type] = { counter: 0 };</code></p></li>\n</ol>\n\n<p>I have used it a lot, and it does not give me any problems whatsoever yet. I hope someone finds it useful someday.</p>\n\n<pre><code>(function(){\n // I test for features at the beginning of the declaration instead of everytime that we have to add an event.\n if(document.addEventListener) {\n window.addEvent = function (elem, type, handler, useCapture){\n elem.addEventListener(type, handler, !!useCapture);\n return handler; // for removal purposes\n };\n window.removeEvent = function (elem, type, handler, useCapture){\n elem.removeEventListener(type, handler, !!useCapture);\n };\n } \n else if (document.attachEvent) {\n window.addEvent = function (elem, type, handler) {\n type = \"on\" + type;\n // Bounded the element as the context \n // Because the attachEvent uses the window object to add the event and we don't want to polute it.\n var boundedHandler = function() {\n return handler.apply(elem, arguments);\n };\n elem.attachEvent(type, boundedHandler);\n return boundedHandler; // for removal purposes\n };\n window.removeEvent = function(elem, type, handler){\n type = \"on\" + type;\n elem.detachEvent(type, handler);\n };\n } \n else { // FALLBACK ( I did some test for both your code and mine, the tests are at the bottom. )\n // I removed wrapping from your implementation and added closures and memoization.\n // Browser don't support W3C or MSFT model, go on with traditional\n window.addEvent = function(elem, type, handler){\n type = \"on\" + type;\n // Applying some memoization to save multiple handlers\n elem.memoize = elem.memoize || {};\n // Just in case we haven't memoize the event type yet.\n // This code will be runned just one time.\n if(!elem.memoize[type]){\n elem.memoize[type] = { counter: 0 };\n elem[type] = function(){\n for(key in nameSpace){\n if(nameSpace.hasOwnProperty(key)){\n if(typeof nameSpace[key] == \"function\"){\n nameSpace[key].apply(this, arguments);\n }\n }\n }\n }\n }\n // Thanks to hoisting we can point to nameSpace variable above.\n // Thanks to closures we are going to be able to access its value when the event is triggered.\n // I used closures for the nameSpace because it improved 44% in performance in my laptop.\n var nameSpace = elem.memoize[type], id = nameSpace.counter++;\n nameSpace[id] = handler;\n // I return the id for us to be able to remove a specific function binded to the event.\n return id;\n };\n window.removeEvent = function(elem, type, handlerID){\n type = \"on\" + type;\n // I remove the handler with the id\n if(elem.memoize && elem.memoize[type] && elem.memoize[type][handlerID]) elem.memoize[type][handlerID] = undefined;\n };\n\n }\n})();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T18:42:06.823",
"Id": "39553",
"ParentId": "39246",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T22:29:07.293",
"Id": "39246",
"Score": "2",
"Tags": [
"javascript",
"event-handling"
],
"Title": "JavaScript custom addEvent function to add event handlers"
}
|
39246
|
<p>I have an angle where I need to convert a 'normal' angle to an isometric angle (116 degrees), and I came up with this function. It works, but I was wondering if the math could be optimized/simplified, or if this is the way to go. It's for a mobile game. </p>
<pre><code>public static inline var ISO:Float = 0.45378560551; // (116-90) / 180 * PI=;
function convert(angle:Float):Float
{
angle -= Math.PI; // corrected angle
var randomChoosenDistance = 2.0; // could be anything, I'm only interested in final angle.
// calculate new line, using isometic angle.
var x1 = Math.cos(angle - ISO);
var x2 = Math.cos(angle - ISO) * randomChoosenDistance;
var y1 = Math.sin(angle);
var y2 = Math.sin(angle) * randomChoosenDistance;
var dx = x1 - x2;
var dy = y1 - y2;
angle = Math.atan2(dy, dx);
return angle;
}
</code></pre>
<p>Can I get the new angle, without calculating the angle between the temporary points I'm creating at the moment?</p>
|
[] |
[
{
"body": "<p>It seems to me that this is a math related question rather than code review. Let's simplified the code first,</p>\n\n<pre><code>var dx = Math.cos(a - b) - Math.cos(a - b) * r;\n</code></pre>\n\n<p>The above can be simplified to </p>\n\n<pre><code>var dx = (1 - r) * Math.cos(a - b);\n</code></pre>\n\n<p>One less Math.cos and one less multiplication is being called, which could be CPU consuming. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:20:31.627",
"Id": "65832",
"Score": "0",
"body": "Thanks, I was looking for simplified code, this helps a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T03:45:28.920",
"Id": "39262",
"ParentId": "39249",
"Score": "3"
}
},
{
"body": "<p>@neo pointed out that <code>dx</code> can be calculated as <code>(1 - r) * Math.cos(a - b)</code>. Similarly, <code>dy = (1 - r) * Math.sin(a)</code>. However, when you take <code>dy / dx</code>, which is what <code>Math.atan2(dy, dx)</code> implicitly does with its arguments, the <code>(1 - r)</code> factor cancels out. You can also see, using a geometric argument, that (<em>x</em><sub>2</sub>, <em>y</em><sub>2</sub>) is pointless (pardon the pun).</p>\n\n<p><img src=\"https://i.stack.imgur.com/XD7iw.png\" alt=\"Pointlessness of (x2, y2)\"></p>\n\n<p>Therefore, <code>Math.atan2(y1, x1)</code> would work just the same as <code>Math.atan2(dy, dx)</code>.</p>\n\n<hr>\n\n<p>So far, your function can be simplified to the following. Since you repurposed <code>angle</code> twice, I need to disambiguate them as <code>alpha</code>, <code>beta</code>, and <code>theta</code> for this discussion.</p>\n\n<pre><code>public static inline var ISO:Float = 0.45378560551; // (116-90) / 180 * PI=;\n\nfunction convert(alpha:Float):Float\n{ \n var beta = alpha - Math.PI; // corrected angle \n\n // calculate new line, using isometic angle.\n var x1 = Math.cos(beta - ISO);\n var y1 = Math.sin(beta);\n\n var theta = Math.atan2(y1, x1);\n return theta;\n}\n</code></pre>\n\n<hr>\n\n<p>But wait, there's more! There's a mysterious correction from <code>alpha</code> to <code>beta</code>, and the cosine expression is complicated.</p>\n\n<p>Let's start with <code>Math.sin(beta)</code>. That's <code>Math.sin(-alpha)</code>, or <code>-Math.sin(alpha)</code>.</p>\n\n<p>It would be nice to say <code>Math.atan2(Math.sin(alpha), something)</code> instead of <code>Math.atan2(-Math.sin(alpha), something)</code>. Let's move the negation into the denominator then, for <code>var theta = Math.atan2(Math.sin(alpha), -x1)</code>.</p>\n\n<p>Can we simplify <code>-x1</code>?</p>\n\n<pre><code>-x1 = -Math.cos(beta - ISO)\n = Math.cos(beta - ISO + 180°)\n = Math.cos(alpha - 180° - ISO + 180°)\n = Math.cos(alpha - ISO)\n</code></pre>\n\n<p>So, your function simplifies to:</p>\n\n<pre><code>public static inline var ISO:Float = 0.45378560551; // = (116-90) / 180 * PI\n\nfunction convert(angle:Float):Float\n{ \n return Math.atan2(Math.sin(angle), Math.cos(angle - ISO));\n}\n</code></pre>\n\n<p>Not only is the code more efficient, it's also less mysterious: the transformation is taking the x-coordinate of each point as if it were rotated 26° clockwise!</p>\n\n<hr>\n\n<p>I have to question the motivation behind this function, though. This isn't an angle-preserving transformation, so why are you operating on an angle? Normally, you transform points' coordinates using matrix multiplication.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T14:19:29.953",
"Id": "66516",
"Score": "0",
"body": "Thanks for taking time to this in-depth answer! It's very clear. About how I'm using this function: I have spritesheets from an old game that are drawn in isometric perspective, but my game itself runs in normal perspective (it only _looks_ isometric). I'm using this function to get the right index on the spritesheet. So yes; I have to admit this function is very project specific."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-19T20:21:06.880",
"Id": "39606",
"ParentId": "39249",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "39606",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T23:08:52.607",
"Id": "39249",
"Score": "8",
"Tags": [
"optimization",
"mathematics",
"computational-geometry",
"haxe"
],
"Title": "Calculating angle in isometric view"
}
|
39249
|
<p>Is this the best way to reverse a singly-linked list? Can it be done with two, or fewer pointers? Any other comments?</p>
<pre><code>public class ReverseLL {
Node start;
ReverseLL()
{
start=null;
}
class Node
{
Node next;
int data;
Node(int newData)
{
next=null;
data=newData;
}
public void setData(int newData)
{
data=newData;
}
public int getData()
{
return data;
}
public void setNext(Node n)
{
next=n;
}
public Node getNext()
{
return next;
}
}
public void insert(int newData)
{
Node p=new Node(newData);
if(start==null)
{
start=p;
}
else
{
Node temp=start;
while(temp.getNext()!=null)
{
temp=temp.getNext();
}
temp.setNext(p);
}
}
public void reverse()
{
Node temp=start;
Node previous=null;
Node previous1=null;
while(temp.getNext()!=null)
{
if(temp==start)
{
previous=temp;
temp=temp.getNext();
previous.setNext(null);
}
else
{
previous1=temp;
temp=temp.getNext();
previous1.setNext(previous);
previous=previous1;
}
}
temp.setNext(previous);
start=temp;
}
public void display() {
int count = 0;
if(start == null) {
System.out.println("\n List is empty !!");
} else {
Node temp = start;
while(temp.getNext() != null) {
System.out.println("count("+count+") , node value="+temp.getData());
count++;
temp = temp.getNext();
}
System.out.println("count("+count+") , node value="+temp.getData());
}
}
public static void main(String args[])
{
ReverseLL ll=new ReverseLL();
ll.insert(1);
ll.insert(2);
ll.insert(3);
ll.insert(4);
ll.insert(5);
ll.insert(6);
ll.insert(7);
ll.insert(8);
ll.display();
System.out.println();
ll.reverse();
ll.display();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T00:48:20.917",
"Id": "65728",
"Score": "0",
"body": "I have used temp, previous and previous1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T00:49:13.530",
"Id": "65729",
"Score": "0",
"body": "Why? Is this some sort of challenge that you have to restrict it this way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T00:56:54.023",
"Id": "65731",
"Score": "0",
"body": "took a lot of liberty editing and indenting your code. If you have an issue with it, feel free to roll it back. I won't take offense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-19T15:41:57.720",
"Id": "157822",
"Score": "0",
"body": "you might understand the dynamics why three pointers are necessary. It seems to be not possible in an iterative approach to do it in less pointers. I tried to explain the same here http://techieme.in/reversing-a-singly-linked-list/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T05:53:45.267",
"Id": "210940",
"Score": "0",
"body": "Nicely explained with program and stack trace: http://javabypatel.blogspot.in/2015/12/reverse-linked-list.html"
}
] |
[
{
"body": "<p>This is a nice, clean implementation of a Linked list... Generally a good job.</p>\n\n<p>You have a bug in your <code>reverse</code> method, a <code>NullPointerException</code> when the list is empty. There is an easy fix, but you should be aware.</p>\n\n<p>I also had a look at your reverse method. I cannot see a way to do it with fewer than 3 variables, while still keeping the logic readable. I am not particularly fond of your implementation... The distinct <code>if/else</code> condition makes the internal logic cumbersome. It makes things easier if you consider the process to be closer to a <em>swap</em>... we want to swap the direction of the pointer between nodes.</p>\n\n<p>So, the logic is, for three nodes A->B->C, we want to make B point to A, but, we have to remember that C comes after B <strong>before</strong> we reverse the pointer. Then we have to make C point to B, becoming A<-B<-C</p>\n\n<p>But, we have a couple of <em>loose ends</em> (pun is intended)... we have the <code>start</code> pointer which points at A, and A is pointing at B still, So, we need to remove the now-redundant A->B pointer, and also move start to point at C..... All so complicated, but it boils down to a simple loop:</p>\n\n<pre><code> public void reverse() {\n if (start == null) {\n return;\n }\n Node current = start;\n Node after = start.next;\n while (after != null) {\n Node tmp = after.next; // preserve what will come later.\n after.next = current; // reverse the pointer\n current = after; // advance the cursor\n after = tmp; // the node after is the one preserved earlier.\n }\n start.next = null; // null-out next on what was the start element \n start = current; // move the start to what was the end.\n }\n</code></pre>\n\n<p>This, to me, is much more readable than the conditional logic you had. It <strong>does</strong> use three pointers in addition to the <code>start</code>.</p>\n\n<p>If you want to, you can probably find a way to do it with one less pointer, but that is by <em>hacking</em> the <code>start</code> pointer and using it as a tracker in the loop (probably instead of <code>current</code>, but the readability, and simplicity will suffer if you do that.</p>\n\n<p>Note also that Java coding convention puts the <code>{</code> open brace at the end of the line containing the conditional block.</p>\n\n<p>Finally, at the risk of adding a little complexity to your code, most general-purpose Linked Lists in 'real' applications have an <em>O (1)</em> mechanism for getting the List size. If you have a custom purpose for the list where the size is not important, you can skip that, but, you should otherwise consider adding a size field so you can avoid doing a full iteration to get the size.</p>\n\n<p>Another Finally, The Java Iterator concept is a very common idiom. It is surprisingly complicated though to get your implementation to match the specification. I strongly recommend that you take it upon yourself to make your List iterable, and to make sure your Iterator implementation conforms to the specification (especially the conditions under which the iterator throws exceptions).</p>\n\n<p>I also extended your main method to do a few more tests than you have:</p>\n\n<pre><code> public static void main(String args[]) {\n ReverseLL ll=new ReverseLL();\n ll.reverse();\n ll.display();\n System.out.println();\n\n ll.insert(1);\n ll.reverse();\n ll.display();\n System.out.println();\n\n ll.insert(2);\n\n ll.reverse();\n ll.display();\n System.out.println();\n\n ll.reverse();\n ll.display();\n System.out.println();\n\n ll.insert(3);\n ll.insert(4);\n ll.insert(5);\n ll.insert(6);\n ll.insert(7);\n ll.insert(8);\n ll.display();\n System.out.println();\n\n ll.reverse();\n ll.display();\n System.out.println();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T03:27:42.203",
"Id": "39261",
"ParentId": "39254",
"Score": "8"
}
},
{
"body": "<p>You will have to iterate the string twice before taking it into consideration. Loop it once you are done with iteration. I think the while loop works best for this for reversing the print array by proper recursion. Hopefully if the copy array is no longer in use, then it might possibly throw an exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-07T07:50:09.357",
"Id": "356743",
"Score": "2",
"body": "What question does this answer? Specifically, what `string`, `print array`, `copy array` are you referring to?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-07T20:41:18.247",
"Id": "162782",
"ParentId": "39254",
"Score": "0"
}
},
{
"body": "<p>\"Pointer\" golfing?<br>\nContinuing <a href=\"https://codereview.stackexchange.com/a/39261/93149\">rolfl's clean-up</a>; supporting&exploiting chaining:</p>\n\n<pre><code> public Node setNext(Node n) { Node o=next; next=n; return o; }\n…\n/** Reverses the list of <code>Node</code>s sporting\n * <code>getNext()</code> and <code>setNext(futureNext)</code> */\npublic void reverse() {\n for (Node toReverse = start, inTransit = start = null ;\n null != toReverse ; start = inTransit)\n toReverse = (inTransit = toReverse).setNext(start);\n return this;\n}\n</code></pre>\n\n<p>More or less random remarks:<br>\nuse doc comments<br>\n<code>display()</code> is funny - rather override <code>toString()</code><br>\ncheck corner cases (see, again, rolfl's answer, too); consider using JUnit<br>\nconsider implementing <code>java.util.List<></code>/extending <code>java.util.AbstractList<></code><br>\nrename <code>insert()</code> to <code>append()</code> and <code>add()</code>/<code>insert()</code> at head </p>\n\n<pre><code> Node(int newData, Node n) { data = newData; next = n; }\n…\n /** Inserts <code>newData</code> in front of list. */\n public ReverseLL add(int newData) {\n start = new Node(newData, start);\n return this;\n }\n…\npublic static void main(String args[]) {\n ReverseLL ll = new ReverseLL();\n ll.reverse();\n ll.add(8);\n ll.reverse();\n for (int v = 8 ; 0 < --v ; ) // just learned _ is reserved as of 1.8\n ll.add(v);\n ll.display();\n System.out.println();\n ll.reverse();\n ll.display();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-07T08:50:32.237",
"Id": "356763",
"Score": "0",
"body": "(You may notice I don't (habitually) doc comment accessors&(Java)contructors.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-07T08:49:25.667",
"Id": "186980",
"ParentId": "39254",
"Score": "2"
}
},
{
"body": "<p><em>emphasized text</em>Without temp, this is not my code. Please see:<a href=\"https://algorithms.tutorialhorizon.com/reverse-a-linked-list/\" rel=\"nofollow noreferrer\">https://algorithms.tutorialhorizon.com/reverse-a-linked-list/</a></p>\n\n<p>//<a href=\"https://algorithms.tutorialhorizon.com/reverse-a-linked-list/\" rel=\"nofollow noreferrer\">https://algorithms.tutorialhorizon.com/reverse-a-linked-list/</a></p>\n\n<pre><code>public class ReverseLinkedList {\n\npublic static void main (String[] args) throws java.lang.Exception\n{\n LinkedListT a = new LinkedListT();\n a.addAtBegin(5);\n a.addAtBegin(10);\n a.addAtBegin(15);\n a.addAtBegin(20);\n a.addAtBegin(25);\n a.addAtBegin(30);\n// System.out.print(\"Original Link List 1 : \");\n a.display(a.head);\n a.reverseIterative(a.head);\n LinkedListT b = new LinkedListT();\n b.addAtBegin(31);\n b.addAtBegin(32);\n b.addAtBegin(33);\n b.addAtBegin(34);\n b.addAtBegin(35);\n b.addAtBegin(36);\n System.out.println(\"\");\n System.out.println(\"___________________\");\n System.out.print(\"Original Link List 2 : \");\n b.display(b.head);\n b.reverseRecursion(b.head,b.head.next,null);\n System.out.println(\"\");\n //b.display(x);\n }\n}\nclass Node{\npublic int data;\npublic Node next;\npublic Node(int data){\n this.data = data;\n this.next = null;\n}\n}\nclass LinkedListT{\npublic Node head;\npublic LinkedListT(){\n head=null;\n}\n\npublic void addAtBegin(int data){\n Node n = new Node(data);\n n.next = head;\n head = n;\n}\npublic void reverseIterative(Node head){\n Node currNode = head;\n Node nextNode = null;\n Node prevNode = null;\n\n while(currNode!=null){\n nextNode = currNode.next;\n currNode.next = prevNode;\n prevNode = currNode;\n currNode = nextNode;\n }\n head = prevNode;\n System.out.println(\"\\n Reverse Through Iteration\");\n display(head);\n}\n\npublic void reverseRecursion(Node ptrOne,Node ptrTwo, Node prevNode){\n if(ptrTwo!=null){\n if(ptrTwo.next!=null){\n Node t1 = ptrTwo;\n Node t2 = ptrTwo.next;\n ptrOne.next = prevNode;\n prevNode = ptrOne;\n reverseRecursion(t1,t2, prevNode);\n }\n else{\n ptrTwo.next = ptrOne;\n ptrOne.next = prevNode;\n System.out.println(\"\\n Reverse Through Recursion\");\n display(ptrTwo);\n }\n }\n else if(ptrOne!=null){\n System.out.println(\"\\n Reverse Through Recursion\");\n display(ptrOne);\n }\n }\n\npublic void display(Node head){\n //\n Node currNode = head;\n while(currNode!=null){\n System.out.print(\"->\" + currNode.data);\n currNode=currNode.next;\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:07:47.790",
"Id": "427966",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T19:20:19.950",
"Id": "221299",
"ParentId": "39254",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "39261",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T00:43:54.287",
"Id": "39254",
"Score": "7",
"Tags": [
"java",
"linked-list"
],
"Title": "Reversing a singly-linked List"
}
|
39254
|
<p>This feels like a simple question, but I'm wondering what the best way would be to manage the elements of a private, fixed-size array.</p>
<p>Context: I'm making a simple particle engine, and my <code>Emitter</code> class will smoothly interpolate between up to 8 colors per <code>Particle</code>, depending on the Particle's Life value. I have that part implemented and it works great. However, my question is more concerning the <code>Color[]</code> array itself.</p>
<p>Suppose I have the following code. What I would like to do is be able to alter the 8 values in a simple and logical way:</p>
<pre><code>public sealed class Emitter
{
private readonly Color[] _colors = new Color[8];
}
</code></pre>
<p>One option would be to return the whole array, but according to <a href="http://msdn.microsoft.com/en-us/library/0fss9skc.aspx">CA1819</a>, a property should not return an array, since it warns the array is mutable unless a copy is made. However, this is the behavior I want, so it <em>might</em> make sense to do it:</p>
<pre><code>public Color[] Colors
{
get { return _colors; }
}
</code></pre>
<p>Another option would be to do a simple get/set and pass a desired index as a parameter; this has the benefit of checking for success, but is more cumbersome to use because of the <code>out</code> parameter. In addition, there's nothing that explicitly states the min/max values of the color array, which means I'd have to have a <code>const byte MaxColors = 8;</code> or the like:</p>
<pre><code>public bool GetColor(int id, out Color result)
{
if (id >= 0 && id < 8)
{
// Valid index, return the color at that position
result = _colors[id];
return true;
}
// Invalid index, return the default color (R:0, G:0, B:0, A:0)
result = default(Color);
return false;
}
public void SetColor(int id, Color value)
{
if (id >= 0 && id < 8)
{
_colors[id] = value;
}
}
public void SetColor(param Color[] values)
{
// Set all 8 colors, using default values if not enough arguments are supplied
if(values != null)
for(int i = 0; i < 8; i++)
if (i > values.Length)
_colors[i] = default(Color);
else
_colors[i] = values[i];
}
</code></pre>
<p>Finally, I could do the brute force approach and make a property for each color value, and I probably don't need to explain why that's a bad idea:</p>
<pre><code>public Color Color1
{
get { return _colors[0]; }
set { _colors[0] = value; }
}
...
public Color Color8
{
get { return _colors[7]; }
set { _colors[7] = value; }
}
</code></pre>
<p>So... yeah. Based on my needs, which approach seems to make the most sense? I'm leaning towards the getter/setter pattern. Is there another way I haven't considered that would be desireable in this situation?</p>
|
[] |
[
{
"body": "<p>If you expose it via a public property then it's not a \"private\" array any more:it's part of the public interface.</p>\n\n<p>If resetting its elements is something that you want clients to do, I'd choose the first option (because it's simplest).</p>\n\n<p>Or, these ...</p>\n\n<pre><code>public void SetColor(int id, Color value) { ... }\npublic bool GetColor(int id, out Color result) { ... }\n</code></pre>\n\n<p>... could perhaps be done using <a href=\"http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx\">indexers</a> ...</p>\n\n<pre><code>public Color this[int id]\n{\n get { ... }\n set { ... }\n}\n</code></pre>\n\n<p>... but that's not very different from exposing the array (and there can be only one indexer of a given signature, which doesn't work if there's more than one array to be exposed).</p>\n\n<p>Here's a blog post on the topic: <a href=\"http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\">http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx</a></p>\n\n<p>Another possibility (I've just thought of it, haven't tested/researched this idea) might be to pass the array into the constructor:</p>\n\n<pre><code>public sealed class Emitter\n{\n private readonly Color[] _colors;\n public Emitter(Color[] colors) { _colors = colors; }\n}\n</code></pre>\n\n<p>The <strike>reason</strike> excuse for that is that so that whoever constructs Emitter has the array, can keep that array, and can (evilly) modify that array after it has used it to construct Emitter.</p>\n\n<pre><code>Color[] colors = new Color[8];\nEmitter emitter = new Emitter(colors);\ncolors[0] = Color.Red; // changes constents of array inside the Emitter\n</code></pre>\n\n<p>The official recommendation is to use a <code>List<Color></code> instead of a Color[] array, and return <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ilist%28v=vs.110%29.aspx\"><code>IList<Color></code></a> ... conceptually similar IMO, but you won't get the compiler and FxCop warnings.</p>\n\n<pre><code>public sealed class Emitter\n{\n private readonly List<Color> _colors;\n public IList<Color> Colors { get { return _colors; } }\n}\n</code></pre>\n\n<hr>\n\n<p>As @svick noted in a comment below, because arrays implement the <code>IList<T></code> interface, you can also do this:</p>\n\n<pre><code>public sealed class Emitter\n{\n private readonly Color[] _colors;\n public IList<Color> Colors { get { return _colors; } }\n}\n</code></pre>\n\n<p><code>IList<T></code> supports the API you want (i.e. an indexer property). Using <code>IList<T></code> supresses the compiler warning. It may be less intuitive to the client/user though (who may think, incorrectly, that the <code>IList<T></code> would allow them to change its size).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T01:45:22.593",
"Id": "65733",
"Score": "0",
"body": "Well, exposing it isn't a problem per se; I want to disallow changing the size, and not make it a public *variable*. But as the article link I provided indicates, properties and arrays shouldn't mix, either. I'm disinclined to use a List<> since the size is mutable, and IEnumerable types don't allow the values to be changed. The values of the colors should be changeable at any time, and the constructor would just add clutter to that (although it could simply make a default Color.White as a placeholder until something better comes along). Based on this, I think using properties is the best way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T03:05:06.097",
"Id": "65739",
"Score": "3",
"body": "Array also implements `IList<T>`, so I don't see any reason to use `List<T>` here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T01:29:54.573",
"Id": "39256",
"ParentId": "39255",
"Score": "11"
}
},
{
"body": "<p>There is a very good alternative</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Server\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n var emitter = new Emitter();\n emitter.Colors[Emitter.Color.Color1] = Color.FromArgb(255, 255, 0, 0);\n\n Console.WriteLine(emitter.Colors[Emitter.Color.Color1]);\n\n //Color[] color = ((Emitter.EmitterColor) emitter.Colors).Colors;\n //Console.WriteLine(color[0]);\n }\n }\n\n public class Emitter\n {\n public enum Color : int\n {\n Color1,\n Color2,\n Color3,\n Color4,\n Color5,\n Color6,\n Color7,\n Color8\n } \n\n readonly EmitterColor _emitterColor;\n\n public Emitter()\n {\n _emitterColor = new EmitterColor(new System.Drawing.Color[Enum.GetValues(typeof(Color)).Length]);\n }\n\n public IEmitterColor Colors\n {\n get { return _emitterColor; }\n }\n\n sealed class EmitterColor : IEmitterColor\n {\n private readonly System.Drawing.Color[] _colors;\n\n public EmitterColor(System.Drawing.Color[] colors)\n {\n _colors = colors;\n }\n\n public System.Drawing.Color this[Emitter.Color color]\n {\n get { return _colors[(int)color]; }\n set { _colors[(int)color] = value; }\n }\n\n public System.Drawing.Color[] Colors\n {\n get { return _colors; }\n }\n }\n }\n\n public interface IEmitterColor\n {\n Color this[Emitter.Color colorIndex] { get; set; }\n }\n}\n</code></pre>\n\n<p>as a bonus, by changin accessor to internal</p>\n\n<pre><code>internal sealed class EmitterColor : IEmitterColor\n{\n ...\n}\n</code></pre>\n\n<p>you can always cast as follows, to access internals:</p>\n\n<pre><code> Color[] color = ((Emitter.EmitterColor) emitter.Colors).Colors;\n Console.WriteLine(color[0]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:11:43.927",
"Id": "65783",
"Score": "1",
"body": "Why is it better? EmitterColor is similar to (but more verbose than) an array; it also doesn't support some possibly-useful interfaces, e.g. IEnumerable. Also, declaring that EmitterColor is sealed doesn't make a difference, as far as I can see: because the type-cast would still be valid even if `_emitterColor` were a subclass of EmitterColor, yet sealed doesn't ensure that EmitterColor is the only implementation of IEmitterColor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:57:06.790",
"Id": "65801",
"Score": "0",
"body": "@ChrisW: You can add IEnumerable implementation to the EmitterColor class, it is trivial. I do not get a point about type casting, please provide an example, in case you want to prevent type casting to EmitterColor class, you can declare it private. Cheers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:47:23.100",
"Id": "39287",
"ParentId": "39255",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "39256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T01:04:21.623",
"Id": "39255",
"Score": "11",
"Tags": [
"c#",
"array",
"properties"
],
"Title": "Best way to handle elements of a private array"
}
|
39255
|
<p>Looking for review, good practices, optimizations, clean code tips etc.</p>
<pre><code>/**
* Flip the columns.
*
* Complexity:
* O(row * col)
*
*/
public final class Mirror {
private Mirror () { }
/**
* Given a matrix create a mirror image,
*
* @param m the input matrix
* @throws NPE if exception occurs.
*/
public static void mirrorPatch(int[][] m) {
// for each row.
for (int i = 0; i < m.length; i++) {
// for each column
flipRow(m[i]);
}
}
private static void flipRow(int[] row) {
int length = row.length;
// simple swap of each element.
for (int i = 0; i < length/2; i++) {
int x = row[i];
row[i] = row[length -1 - i];
row[length -1 - i] = x;
}
}
public static void main(String[] args) {
// even number of columns.
int[][] m = { {1, 2, 3, 4} , {10, 20, 30, 40}};
mirrorPatch(m);
/*
* Informally verifying that output is:
* 4 3 2 1
* 40 30 20 10
*
*/
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------------------------");
// odd number of columns.
/*
* Informally verifying that output is:
* 5 4 3 2 1
* 50 40 30 20 10
*/
int[][] m1 = { {1, 2, 3, 4, 5} , {10, 20, 30, 40, 50}};
mirrorPatch(m1);
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++) {
System.out.print(m1[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------------------------");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In your top=level method <code>mirrorPatch</code> you have:</p>\n\n<pre><code> // for each row.\n for (int i = 0; i < m.length; i++) {\n // for each column\n flipRow(m[i]);\n }\n</code></pre>\n\n<p>This is unnecessarily verbose, using the iterable nature of arrays you could simply:</p>\n\n<pre><code> for (int[] row : m) {\n flipRow(row);\n }\n</code></pre>\n\n<p>This is self-documenting, and all good.</p>\n\n<p>In your <code>flipRow</code> method, you do a bit more work, and, it is pretty well structured, and readable. If you want to perhaps squeeze out some more performance, I can suggest some changes. Specifically, since you are creating the <code>length</code> variable, you may as well make it more useful by changing it to be <code>last</code> instead, which simplifies the indexing a little bit. Additionally, sometimes (when it is possible), a subtracting-loop is faster (because the condition is simpler), consider the changes as follows:</p>\n\n<pre><code>private static void flipRow(final int[] row) {\n final int last = row.length - 1;\n for (int i = last/2; i >= 0; i--) {\n int x = row[i];\n row[i] = row[last - i];\n row[last - i] = x;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T06:09:04.823",
"Id": "39266",
"ParentId": "39263",
"Score": "2"
}
},
{
"body": "<p>Since you never instantiate the <code>Mirror</code> class the private constructor <code>private Mirror () { }</code> is unnecessary. </p>\n\n<p>Another approach if your matrix is sufficiently big and you don't actually want to flip it's memory representation is to encapsulate the data in your Mirror class and expose and iterator and other methods to access the data by index which automatically show the matrix as flipped while not actually flipping the class internal representation of your data.</p>\n\n<p>You could put your test into proper <a href=\"https://stackoverflow.com/questions/8751553/how-to-write-a-unit-test\">unit tests</a>. That way you can leave the task of comparing the expected result with the result of your code to the computer.</p>\n\n<p>You should leave out comments which describe what the code does. E.g. <code>// for each row.</code> , <code>// for each column</code> or <code>// simple swap of each element.</code>. This can be understood from your code just by looking at it, especially if you use sufficiently descriptive variable and method names. Comments should be used to describe things which are not obvious to the reader of your code like why you used one approach over the other. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T06:54:21.533",
"Id": "39267",
"ParentId": "39263",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T05:49:18.593",
"Id": "39263",
"Score": "3",
"Tags": [
"java",
"matrix"
],
"Title": "Find mirror image of a matrix"
}
|
39263
|
<p>Looking for review, good practices, optimizations, clean code tips etc.</p>
<pre><code>final class Pixel {
private final int color;
public Pixel(int color) {
this.color = color;
}
public int getColor() {
return color;
}
}
/**
* Rotates an image by ninety degrees.
*
* Complexity:
* O(row * col)
*/
public final class Rotate {
private Rotate() { }
/**
* Rotes the image in anti clockwise direction.
*
* @param image the image to be rotated.
* @return the titled image.
* @throws NPE
*/
public static Pixel[][] rotateAntiClockWise(Pixel[][] image) {
int col = image.length;
int row = image[0].length;
final Pixel[][] rotatedPixel = new Pixel[row][col];
for (int i = 0; i < image.length; i++) {
for (int j = 0; j < image[0].length; j++) {
rotatedPixel[image[0].length -1 -j][i] = image[i][j];
}
}
return rotatedPixel;
}
/**
* Rotates the image in clockwise direction.
*
* @param image the image to be rotated.
* @returns the rotated image.
* @throws NPE
*/
public static Pixel[][] rotateClockWise(Pixel[][] image) {
int col = image.length;
int row = image[0].length;
final Pixel[][] rotatedPixel = new Pixel[row][col];
for (int i = 0; i < image.length; i++) {
for (int j = 0; j < image[0].length; j++) {
rotatedPixel[j][image.length -1 - i] = image[i][j];
}
}
return rotatedPixel;
}
public static void main(String[] args) {
// int[][] m = { {1, 2, 3, 4} ,
// {10, 20, 30, 40}};
Pixel[][] image = new Pixel[2][4];
image[0][0] = new Pixel(1);
image[0][1] = new Pixel(2);
image[0][2] = new Pixel(3);
image[0][3] = new Pixel(4);
image[1][0] = new Pixel(10);
image[1][1] = new Pixel(20);
image[1][2] = new Pixel(30);
image[1][3] = new Pixel(40);
Pixel[][] rotatedAntiClockNinetyDegreeImage = rotateAntiClockWise(image);
/*
* Expected:
*
* 4 40
* 3 30
* 2 20
* 1 10
*
*/
for (int i = 0; i < rotatedAntiClockNinetyDegreeImage.length; i++) {
for (int j = 0; j < rotatedAntiClockNinetyDegreeImage[0].length; j++) {
System.out.print(rotatedAntiClockNinetyDegreeImage[i][j].getColor() + " ");
}
System.out.println();
}
System.out.println("==========================================");
Pixel[][] rotatedClockWiseNinetyDegreeImage = rotateClockWise(image);
/*
* Expected:
*
* 10 1
* 20 2
* 30 3
* 40 4
*
*/
for (int i = 0; i < rotatedClockWiseNinetyDegreeImage.length; i++) {
for (int j = 0; j < rotatedClockWiseNinetyDegreeImage[0].length; j++) {
System.out.print(rotatedClockWiseNinetyDegreeImage[i][j].getColor() + " ");
}
System.out.println();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, your code is really nice looking! Below are just some basic suggestions.</p>\n\n<pre><code>final class Pixel {\n</code></pre>\n\n<p>In my opinion, you should always explicitly dictate whether classes are <code>public</code>, <code>private</code>, or <code>protected</code>.</p>\n\n<pre><code>public static Pixel[][] rotateAntiClockWise(Pixel[][] image) {\n int col = image.length;\n int row = image[0].length;\n</code></pre>\n\n<p>Here, your method assumes that every image is a rectangle of some kind. If you had an image that was, say, a triangle, your code would fail with either a <code>NullPointerException</code> or an <code>IndexOutOfBoundsException</code> at some point (depending on which end of the triangle you started at).</p>\n\n<pre><code>final Pixel[][] rotatedPixel = new Pixel[row][col];\n</code></pre>\n\n<p>Out of curiosity, is there a reason you make this two-dimensional array <code>final</code>? It doesn't affect the values stored in the arrays, and the <code>final</code> doesn't affect the reference when it's returned from the method, so there doesn't seem to be much value in having it here (unlike its use in your <code>Pixel</code> class, which makes perfect sense).</p>\n\n<pre><code>Pixel[][] rotatedAntiClockNinetyDegreeImage = rotateAntiClockWise(image);\n</code></pre>\n\n<p>This is of course pretty subjective, but this variable name is really, <em>really</em> verbose, even by Java standards. <code>rotatedAntiClockwise</code> would be sufficient, or even just <code>rotated</code> for these purposes. Just an opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:33:08.813",
"Id": "65833",
"Score": "0",
"body": "Is there any such thing as a triangle image? (A two-dimensional array of pixels that is not rectangular)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:38:35.110",
"Id": "65834",
"Score": "0",
"body": "That seems trivial to prove, does it not? Hard to type in comments without line breaks, but if the following statements are all true: `image[0].length = 1; image[1].length = 2; image[2].length = 3;` and so on. If you're asking whether or not this exists in the wild, I assume so. I suppose I could be wrong an all images are rectangular with, at best, transparent backgrounds, but such a categorical statement would seem odd to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:49:28.163",
"Id": "65835",
"Score": "0",
"body": "Well I've always assumed that all images are rectangular in the computer world. They always have a width and a height. I think that introducing non-rectangular images would cause problems in a lot of areas. Of course it's possible to create a non-rectangular two-dimensional array of pixels with code, but does it **exist**? Is such an array ever serialized to a real image that is readable by standard image viewer applications?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:50:17.767",
"Id": "65836",
"Score": "0",
"body": "Good point. No idea, truthfully."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:14:20.017",
"Id": "39321",
"ParentId": "39265",
"Score": "5"
}
},
{
"body": "<p>Assuming that you will want to do more interesting things with these images later, you should probably come up with a better OOP design. I suggest:</p>\n\n<pre><code>public interface ImageTransformation {\n public Pixel[][] transform(Pixel[][] image);\n}\n\npublic class Clockwise90Rotation implements ImageTransformation {\n ...\n}\n\npublic class AntiClockwise90Rotation implements ImageTransformation {\n ...\n}\n</code></pre>\n\n<p>It's practically no work to rearrange the code that way. In return, you gain the flexibility to do things like:</p>\n\n<pre><code>ImageTransformation[] pipeline = new ImageTransformation[] {\n new Clockwise90Rotation(),\n new ContrastEnhancer(),\n new GaussianBlur(/* radius= */ 5)\n};\nfor (ImageTransformation t : pipeline) {\n image = t.transform(image);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T20:12:41.923",
"Id": "39325",
"ParentId": "39265",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T05:59:06.780",
"Id": "39265",
"Score": "5",
"Tags": [
"java",
"matrix",
"image"
],
"Title": "Rotate an image by 90 degrees"
}
|
39265
|
<p>I have an array of <code>Item</code> objects that each have a string <code>particular</code> and a numeric <code>amount</code>. I want to put all <code>particular</code>s (separated by newlines) into a single string and the same for all <code>amount</code>s.</p>
<p>Here's what I came up with:</p>
<pre><code>particulars = []
amounts = []
items.each do |item|
particulars << item.particular
amounts << item.amount
end
particulars_string = particulars.join("\n")
amounts_string = amounts.join("\n")
</code></pre>
<p>So if</p>
<pre><code>item1.particular = "food"
item2.particular = "drink"
item1.amount = 1000
item2.amount = 2000
</code></pre>
<p>then running the code above gives</p>
<pre><code>particulars_string # "food\ndrink"
amounts_string # "1000\n2000"
</code></pre>
<p>which is correct. However, I feel that the above code can be done better. In particular, I want all the code in one loop, not the three (<code>each</code> and two <code>join</code>s) I have now. What's a better way to do this?</p>
|
[] |
[
{
"body": "<p>You can get by with just two lines:</p>\n\n<pre><code>particulars_string = items.map(&:particular).join(\"\\n\")\namounts_string = items.map(&:amount).join(\"\\n\")\n</code></pre>\n\n<p><code>Enumerable#map</code>, which is mixed into <code>Array</code>, creates a new array from an existing array by running a block on each element and storing the result. In this case though you don't need a full block, since you just need to call a single method (<code>particular</code> or <code>amount</code>). So it basically extracts those into new arrays and then joins those arrays.</p>\n\n<p>As a rule of thumb, you almost never have to \"manually\" map stuff from one array to another in Ruby using <code>each</code> and <code><<</code>. Be sure to read the docs for <a href=\"http://ruby-doc.org/core-2.0.0/Array.html\" rel=\"nofollow\"><code>Array</code></a> and <a href=\"http://ruby-doc.org/core-2.0.0/Enumerable.html\" rel=\"nofollow\"><code>Enumerable</code></a> as they're full of good stuff.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:50:48.253",
"Id": "65746",
"Score": "0",
"body": "Exactly what I was looking for!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T20:40:05.283",
"Id": "66562",
"Score": "0",
"body": "I don't really like this approach — you're still doing 4 enumerations of the length of the items array, and there's duplication on 2 local variables, 2 methods, and an argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T21:34:49.283",
"Id": "66567",
"Score": "0",
"body": "@coreyward True. Your use of `transpose` is more elegant than the duplication above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T07:29:15.340",
"Id": "66743",
"Score": "0",
"body": "@Flambino, you may be mixing me up with coreyward. I think your solution is just fine. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T10:40:06.843",
"Id": "66748",
"Score": "0",
"body": "@CarySwoveland Argh, so sorry. I was mixing you up - my mistake. But, then, _your_ use of `transpose` is more elegant :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:49:30.813",
"Id": "39269",
"ParentId": "39268",
"Score": "4"
}
},
{
"body": "<p>If you had several attributes (particular, amount, ...), you might consider doing it this way:</p>\n\n<pre><code>class Items\n attr_accessor :attributes\n def initialize(*attributes)\n @attributes = attributes\n end\nend\n\nitems = [Items.new('food', 1000), Items.new('drink', 2000)]\n\nattributes_strings = items.map(&:attributes).transpose.map {|e| e.join('\\n')}\n\nputs attribute_strings\nfood\\ndrink\n1000\\n2000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T02:55:41.760",
"Id": "65860",
"Score": "0",
"body": "Clever. I didn't know about transpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T21:44:50.017",
"Id": "66570",
"Score": "0",
"body": "As mentioned: Nicer than my answer. However, you're assuming/adding some stuff compared to the original question where the item objects; it's not given that the objects in `items` respond to, or can feasibly be made to respond to, `attributes`. Luckily, it's not necessary. I'd shorten it to simply: `particulars_string, amounts_string = items.map {|item| [item.particular, item.amount]}.transpose.map {|a|a.join(\"\\n\")}`. Same input/result as the original with no assumptions about or additions to code outside of that in the original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T07:27:49.617",
"Id": "66742",
"Score": "0",
"body": "@Flambino, I'm not sure if I understand your point about `items`. The contents of `items` is code, not data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T10:57:17.503",
"Id": "66755",
"Score": "0",
"body": "@CarySwoveland I just consider the objects in `items` \"out of scope\". All we know is that there's an array of items that each respond to `particular` and `amount`. You define your own `Item` class that responds to `attributes`, which may or may not be possible - we don't know enough about the context of OP's code. Of course you're more than welcome to suggest different approaches, but it's not necessary in this case, where it's a simple \"given this array, produce two strings\". And the core of your answer (map + transpose + map) is great for that even without assuming anything about the items"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T21:30:34.577",
"Id": "39333",
"ParentId": "39268",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39269",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:15:20.240",
"Id": "39268",
"Score": "4",
"Tags": [
"ruby",
"strings",
"array"
],
"Title": "Processing array of objects into two strings"
}
|
39268
|
<p>I have written this little tagging module to make it easier to generate small html snippets on the fly. The examples below show how this make things a bit easier. My question is about the handling of tags that contain either a single element like text or a list of other elements, like the tr element in the second example. At the moment, the code has to jump though some unpythonic loops to handle the different cases. How do I write code that handles either a single thing or a list of those things with one function in an elegant way?</p>
<pre><code>""" Supplies some utilities for creating html documents manually
>>> print(h1('test'))
<h1>
test
</h1>
>>> print(table([tr([td('d1'), td('d2')]), tr()]))
<table>
<tr>
<td>
d1
</td>
<td>
d2
</td>
</tr>
<tr />
</table>
"""
from __future__ import print_function
class tag:
""" represents an html tag - specifically used to create outputs for web pages
Basic usage - create a "test" tag:
>>> print(tag('test'))
<test />
Attributes can be specified as a dictionary
>>> print(tag('test', attributes={'prop': 'value'}))
<test prop='value' />
The real benefit - tags can be nested, allowing the python interpreter to track closing tags:
>>> print(tag('test', tag('inner')))
<test>
<inner />
</test>
"""
def __init__(self, name, contents=[], attributes={}):
self.name = name
self.contents = contents
self.attributes = attributes
def __str__(self):
tagcontents = self.name
if len(self.attributes) > 0:
attrstring = " ".join("%s='%s'" % kv for kv in self.attributes.items())
tagcontents += " " + attrstring
if self.contents:
if hasattr(self.contents, '__iter__') and not hasattr(self.contents, 'strip'):
contentstring = "\n".join(str(i) for i in self.contents)
else:
contentstring = str(self.contents)
return "<%s>\n%s\n</%s>" % (tagcontents, contentstring, self.name)
else:
return "<" + tagcontents + " />"
def __repr__(self):
return "tag(%s, contents=%s, attributes=%s)" % (self.name, self.contents, self.attributes)
def namedtag(t):
""" create a named tag class - useful for standard html tags
>>> mytag = namedtag('mytag')
>>> print(mytag())
<mytag />
"""
class n(tag):
def __init__(self, contents=[], attributes={}):
tag.__init__(self, t, contents, attributes)
return n
h1, h2, p, table, td, th, tr, a = (namedtag(t) for t in ("h1", "h2", "p", "table", "td", "th", "tr", "a"))
</code></pre>
|
[] |
[
{
"body": "<p>The solution is to have <code>contents</code> always be a list. If we don't want to impose this onto the caller of the constructor, we have to use a variable number of arguments:</p>\n\n<pre><code>def __init__(self, name, *contents, **attrs):\n ...\n</code></pre>\n\n<p>Now the functions can be called as <code>table(tr(td('d1'), td('d2')), tr())</code> or more generally:</p>\n\n<pre><code>foo(\"name\", child1, child2, ... attr1=value, attr2=value, ...)\n</code></pre>\n\n<p>Then inside the function, <code>contents</code> will be a tuple and <code>attrs</code> a dictionary.</p>\n\n<hr>\n\n<p>Otherwise, I find your inappropriate usage of OOP unnecessary. For example, the class <code>n</code> does not really add value, and violates the Liskov Substitution Principle – the constructor signature is incompatible with the parent class. Instead, use <em>closures</em> to provide a default argument:</p>\n\n<pre><code>def namedtag(name):\n return lambda *contents, **kws: tag(name, *contents, **kws)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T09:17:13.817",
"Id": "65751",
"Score": "0",
"body": "I really like this solution - it's compact and makes a lot of sense from the caller point of view. I also agree about the namedtag class. I think I'm going to replace it using `partial`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:11:08.570",
"Id": "65998",
"Score": "0",
"body": "If you really do want to create subclasses of tag, you could try spelling it `def namedtag(name): return type(name, (tag,), dict())` and changing `tag.__init__`'s use of `name` accordingly. But unless you are going to leverage inheritance somehow, I'd stick with the suggestion of a factory function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T08:21:01.200",
"Id": "39271",
"ParentId": "39270",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39271",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T07:59:58.057",
"Id": "39270",
"Score": "2",
"Tags": [
"python",
"html",
"array"
],
"Title": "Handling objects and arrays simply in this tagging library"
}
|
39270
|
<p>I want to create all possible combinations of points (0,0),(0,1)...(12345,6789) and then all segments from these points.</p>
<p>The code I have written is simple and with no optimization. Is there any algorithm to generate it in less time?</p>
<pre><code>public static void main(String[] args) {
int m=12345;
int n=6789;
for(int x1=0;x1<=m;x1++)
{
for(int y1=0;y1<=n;y1++)
{
for(int x2=0;x2<=m;x2++)
{
for(int y2=0;y2<=n;y2++)
{
for(int x3=0;x3<=m;x3++)
{
for(int y3=0;y3<=n;y3++)
{
for(int x4=0;x4<=m;x4++)
{
for(int y4=0;y4<=n;y4++)
{
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Point p3 = new Point(x3, y3);
Point p4 = new Point(x4, y4);
Segment s1 = new Segment(p1, p2);
Segment s2 = new Segment(p2, p3);
Segment s3 = new Segment(p3, p4);
Segment s4 = new Segment(p4, p1);
//operate on those segements
}
}
}
}
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:15:46.063",
"Id": "65760",
"Score": "0",
"body": "Are the segments combined into another structure or are they operated on as is? Also, abstraction might do wonders, I'm not sure if you can drop all these loops, but you could hide them for sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:19:57.847",
"Id": "65761",
"Score": "0",
"body": "Segments are not used in any other structure. it is operated on as it is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T12:12:12.457",
"Id": "65768",
"Score": "0",
"body": "Your code generates occasional superimposed points, e.g. the first time thrugh the loop all the points are at `Point(0,0)`. Is this intentional?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T12:23:43.527",
"Id": "65772",
"Score": "0",
"body": "@rolfl : yes..i have kept it intentionally..i want all combinations of points even if they are overlapping."
}
] |
[
{
"body": "<p>Google Guava has a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#cartesianProduct%28java.util.List%29\"><code>cartesianProduct</code></a> helper method, I would try to use it instead of the nested loops. I don't think that it will be faster but it would be easier to read an maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T10:44:36.460",
"Id": "65755",
"Score": "0",
"body": "thanks for the reply. but it will take too much space to store (12345+1) * (6789+1) points and then segments from those points. it directly goes out of memory. thats why i have not created points and segments seprately outside this loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:15:23.503",
"Id": "65759",
"Score": "3",
"body": "@anandmahuli: There is a note in the javadoc which could help: *Performance notes: while the cartesian product of sets of size m, n, p is a set of size m x n x p, its actual memory consumption is much smaller. When the cartesian set is constructed, the input sets are merely copied. Only as the resulting set is iterated are the individual lists created, and these are not retained after iteration.*"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T10:35:40.600",
"Id": "39277",
"ParentId": "39274",
"Score": "7"
}
},
{
"body": "<p>Three methods of optimization come to mind.</p>\n\n<ol>\n<li>Initialize objects as soon as you have the arguments. Reuse them through the inner loop. Create the first point as soon as you have x1 and y1.</li>\n<li>Make this multi-threaded. This seems like an obvious candidate for a Hadoop map-reduce approach, depending on the inner loop calculations you are doing.</li>\n<li>Depending on the context, use mathematics instead. Recall the story about Gauss summing <code>1+2+3+4+...+100</code> in a matter of seconds. There may be a far better solution to your problem.</li>\n<li>Use a language that is more expressive, and which allows the compiler to optimize your problem. <code>Scala</code> has a <code>Stream</code> concept that would be very useful here, only generating the possibilities when they are used (and dynamically managing memory in the process). <code>Haskell</code> could also help you solve this problem better. If you must write imperative code, try <code>Fortran</code> for efficient management of arrays and memory.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:22:17.357",
"Id": "65762",
"Score": "0",
"body": "thanks for reply but i didnt get point 1. how will initializing objects soon will be beneficial?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:35:42.790",
"Id": "65763",
"Score": "3",
"body": "Your inner loop is executed `(m*n)ˆ4` times. Once you choose `x1` and `y1`, you should already be able to create object `p1=new Point(x1, y1)`, and keep reusing the same object in the for-loops below. This reduces the number of `Points` created from `(m*n)ˆ4` to `m*n`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-05T14:18:13.483",
"Id": "92038",
"Score": "1",
"body": "Concerning point 4., I would just like to point out that Java 8 (released after this post), does have [Stream](http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)s now. Its members are also \"lazily\" evaluated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T10:55:06.897",
"Id": "39278",
"ParentId": "39274",
"Score": "6"
}
},
{
"body": "<p>Given the large size of the potential result set, the previously suggested iteration mechanism seems appropriate.</p>\n\n<p>I looked at this and thought 'nice challenge', and I looked at your code, and figured there were <strong>too</strong> many loops. The way I see you doing the work <strong>inside</strong> the loops also looks cumbersome...</p>\n\n<p>I figured it would be 'neat' to have a generator that created all the segments on an as-needed basis, and did not do the actual work.... then I played with it, and found there were some potential optimizations.</p>\n\n<p>So, the parts of your code that are potential performance problems:</p>\n\n<ul>\n<li>you re-create Point instances much more than you need to... I can reduce by at least 24 times the amount of point creation you do.</li>\n<li>your problem space is two separate things, you have a combination problem, and also a permutation problem. If you solve them separately, you can pre-calculate the permutations and not have to do them multiple times, then you can just reuse the same points in each permutation.</li>\n</ul>\n\n<p>So, with that in mind, I 'played' with your code. This is <strong>not</strong> a review of your code, but, rather, it is the result of me solving your problem in a different way. There are pro's and con's to my solution... so, use it with appropriate care. The goal of my 'refactoring' was to hit a usage-model something like:</p>\n\n<pre><code> for (Segment[] sides : new SegmentGenerator(m, n)) {\n // do something with this set of segments.\n }\n</code></pre>\n\n<p>One note to consider first.... it is a 'common' model when doing matrix-operations in high-performance computing, to 'flatten' the matrix in to a single dimension. For example, a 3x3 matrix will be flattened in to a single-dimension of 9. The (row,column) indices in the flattened matrix are calculated as follows (<code>row</code> = matrix-row, <code>col</code> = matrix-column, and <code>flat</code> = one-D index)</p>\n\n<pre><code>flat = row * width + col;\nrow = flat / width;\ncol = flat % width;\n</code></pre>\n\n<p>By doing this flattening of the data you can halve the number of loops you need (you only need one loop to access the entire matrix), and you reduce the number of physical arrays (and the memory-separation) of those arrays.</p>\n\n<p>I have employed this type of logic in the solution....</p>\n\n<p>Pro's:</p>\n\n<ul>\n<li>it precomputes all the Permutations for the number of segments in each result.</li>\n<li>you can easily adjust it to do any number of 'sides', not just 4.</li>\n<li>it exposes things neatly in an Iterable engine, which allows you to do some neat code when using it.</li>\n<li>you can probably use this to 'feed' a parallel process where each thread processes chunks of results.</li>\n<li>it reuses Point instances a lot.... in fact, a huge amount less duplication than your code (I am guessing it is something approximately like m*(X!) <em>times</em> fewer Point instances where m is the width of the matrix, and X is the number of sides. So, for example a 100-wide matrix with 4-sided segments will create (100 * 24), or 2400 <em>times</em> fewer Point instances.... put another way, it will reuse Points 2400 times.</li>\n</ul>\n\n<p>Con's</p>\n\n<ul>\n<li>the logic is always a bit more complicated when you add the flexibility of an Iterator</li>\n<li>because of the Point re-use, you may have conditions where <code>Point a == Point b</code> whereas in your code no two points are ever identity-equals(==).</li>\n</ul>\n\n<p>Note that you get a lot of duplication of values because you allow overlapping points. This appears to be a requirement of yours. Still, for example, by design, you will get 24 identical results each with the segments: <code>[P(0,0), P(0,0), P(0,0), P(0,0)]</code> If you want to reduce the results to unique solutions only, then it is a relatively trivial adjustment to the way the <code>cursors</code> array is managed.... (relatively).</p>\n\n<p>So, with all those caveats, here is some working code:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\npublic class Quadrilaterals implements Iterable<Quadrilaterals.Segment[]> {\n\n public static final class Point {\n private final int x, y;\n\n public Point(int x, int y) {\n super();\n this.x = x;\n this.y = y;\n }\n\n @Override\n public String toString() {\n return String.format(\"P(%d,%d)\", x, y);\n }\n\n }\n\n public static final class Segment {\n private final Point a, b;\n\n public Segment(Point a, Point b) {\n super();\n this.a = a;\n this.b = b;\n }\n\n @Override\n public String toString() {\n return String.format(\"S(%s,%s)\", a, b);\n }\n }\n\n // used to initialize a static array of permutations.\n private static final void permuteRecursion(final int[] current,\n final int[] available, final List<int[]> results) {\n if (available.length == 0) {\n results.add(current);\n return;\n }\n for (int i = 0; i < available.length; i++) {\n int[] nextc = Arrays.copyOf(current, current.length + 1);\n nextc[current.length] = available[i];\n int[] nexta = new int[available.length - 1];\n System.arraycopy(available, 0, nexta, 0, i);\n System.arraycopy(available, i + 1, nexta, i, nexta.length - i);\n\n permuteRecursion(nextc, nexta, results);\n\n }\n }\n\n // used to initialize a static array of permutations of `value` size\n // e.g. permute(1) => [ [0] ];\n // permute(2) => [ [0,1], [1,0] ]\n // permute(3) => [ [0,1,2], [0,2,1], ... [2,1,0] ]\n private static final int[][] permute(int values) {\n List<int[]> accumulator = new ArrayList<>();\n int[] available = new int[values];\n for (int i = 0; i < values; i++) {\n available[i] = i;\n }\n permuteRecursion(new int[0], available, accumulator);\n return accumulator.toArray(new int[accumulator.size()][]);\n }\n\n private static final class MyIterator implements Iterator<Segment[]> {\n\n private static final int SIDES = 4;\n // statically calculated permutations - 1-off saves time.\n private static final int[][] PERMUTES = permute(SIDES);\n\n private final int limit;\n private final int width;\n private int[] cursors = new int[SIDES];\n private int permcursor = 0;\n private final Point[] current = new Point[SIDES];\n private boolean hasnext = true;\n\n public MyIterator(int width, int height) {\n this.limit = width * height;\n this.width = width;\n\n Arrays.fill(current, new Point(0, 0));\n // complicated initialization **before** the first point....\n\n cursors[cursors.length - 1] = -1;\n permcursor = PERMUTES.length - 1;\n\n // advance on to the first point.\n advance();\n }\n\n private void advance() {\n permcursor++;\n if (permcursor >= PERMUTES.length) {\n // run out of permutes for this set of points.\n // generate the next set.\n hasnext = false;\n permcursor = 0;\n for (int i = cursors.length - 1; i >= 0; i--) {\n if (++cursors[i] == limit) {\n // by pushing 'reset' in to following cursors we ensure\n // non-duplicate combinations.\n // would push different reset for each cursor if we wanted\n // unique combinations before we permuted.\n int reset = i > 0 ? (cursors[i - 1] + 1) : limit;\n for (int j = i; j < cursors.length; j++) {\n cursors[j] = reset;\n current[j] = new Point(reset % width, reset / width);\n }\n } else {\n current[i] = new Point(cursors[i] % width, cursors[i] / width);\n hasnext = true;\n break;\n }\n }\n //System.out.println(Arrays.toString(current));\n }\n }\n\n @Override\n public boolean hasNext() {\n return hasnext;\n }\n\n @Override\n public Segment[] next() {\n if (!hasnext) {\n throw new NoSuchElementException();\n }\n Segment[] segments = new Segment[SIDES];\n final int[] thisperm = PERMUTES[permcursor];\n\n for (int i = 0; i < SIDES; i++) {\n segments[i] = new Segment(current[thisperm[i]],\n current[thisperm[(i + 1) % SIDES]]);\n }\n advance();\n return segments;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Cannot remove()\");\n\n }\n }\n\n private final int width, height;\n\n public Quadrilaterals(int width, int height) {\n super();\n this.width = width;\n this.height = height;\n }\n\n public int getWidth() {\n return width;\n }\n\n public int getHeight() {\n return height;\n }\n\n @Override\n public Iterator<Segment[]> iterator() {\n return new MyIterator(width, height);\n }\n\n public static void main(String[] args) {\n int m = 12345;\n int n = 6789;\n\n\n double expect = Math.pow(m * n, 4) * 24; // possible points, number of points in results, number of permutations.\n System.out.printf(\"Expect %.0f results \\n\", expect);\n long cnt = 0;\n long start = System.currentTimeMillis();\n Quadrilaterals quads = new Quadrilaterals(m, n);\n for (Segment[] sides : quads) {\n cnt++;\n if (cnt % 10000000 == 0) {\n long now = System.nanoTime();\n double milli = (now - start) / 1000000.0;\n start = now;\n System.out.printf(\"Iteration %d (%5.3f%%) at rate %.3f/ms, has value %s\\n\", cnt, 100.0 * (cnt / expect), 10000000 / milli, Arrays.toString(sides));\n }\n }\n System.out.println(\"There are \" + cnt + \" quads\");\n\n }\n}\n</code></pre>\n\n<p>Note that this, on my machine, produces at peak (after JIT warmup, etc.), about 30,000 results per millisecond, or 30million per second.... (and suggests days, even months worth of processing):</p>\n\n<pre><code>Expect 1184128553155440700000000000000000 results \nIteration 10000000 (0.000%) at rate 0.114/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(9281,33)), S(P(9281,33),P(0,0)), S(P(0,0),P(0,0))]\nIteration 20000000 (0.000%) at rate 23688.051/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(6218,67)), S(P(6218,67),P(0,0)), S(P(0,0),P(0,0))]\nIteration 30000000 (0.000%) at rate 22102.485/ms, has value [S(P(3154,101),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(3154,101))]\nIteration 40000000 (0.000%) at rate 22001.188/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(91,135)), S(P(91,135),P(0,0)), S(P(0,0),P(0,0))]\nIteration 50000000 (0.000%) at rate 22410.292/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(9373,168)), S(P(9373,168),P(0,0)), S(P(0,0),P(0,0))]\nIteration 60000000 (0.000%) at rate 22243.928/ms, has value [S(P(6309,202),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(6309,202))]\n.....\nIteration 610000000 (0.000%) at rate 29932.909/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(10656,2058)), S(P(10656,2058),P(0,0)), S(P(0,0),P(0,0))]\nIteration 620000000 (0.000%) at rate 29639.103/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(7593,2092)), S(P(7593,2092),P(0,0)), S(P(0,0),P(0,0))]\nIteration 630000000 (0.000%) at rate 30097.184/ms, has value [S(P(4529,2126),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(0,0)), S(P(0,0),P(4529,2126))]\nIteration 640000000 (0.000%) at rate 29380.848/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(1466,2160)), S(P(1466,2160),P(0,0)), S(P(0,0),P(0,0))]\nIteration 650000000 (0.000%) at rate 29757.965/ms, has value [S(P(0,0),P(0,0)), S(P(0,0),P(10748,2193)), S(P(10748,2193),P(0,0)), S(P(0,0),P(0,0))]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:13:44.237",
"Id": "39291",
"ParentId": "39274",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T09:58:53.887",
"Id": "39274",
"Score": "11",
"Tags": [
"java",
"performance",
"combinatorics"
],
"Title": "Creating all possible combinations of points"
}
|
39274
|
<p>Depending on the width of the screen the JavaScript animates a node and then loops another animation.</p>
<p>I'm trying to understand DRY but my JavaScript skills aren't quite up to scratch to get this code as optimised as possible. I'm also wanting to implement <code>$(window).resize(function() { });</code> to detect this change without a refresh. Is using constants the best way to optimise this code? If so, how would this be achieved?</p>
<p><a href="http://jsfiddle.net/EJF9q/" rel="nofollow">jsFiddle</a></p>
<pre><code>'use strict';
/*jslint browser: true*/
/*global $, jQuery*/
/*
--------------------------------------------------------
VARIABLES
--------------------------------------------------------
*/
var width = $(window).width(), // window width
down_dur,
left_dur,
up_dur,
right_dur;
/*
--------------------------------------------------------
FUNCTION CODE TO BE EXECUTED
--------------------------------------------------------
*/
function animate_node(down, down_dur, left, left_dur, up, up_dur, right, right_dur) {
down = down + 'px';
left = left + 'px';
up = up + 'px';
right = right + 'px';
$('.node')
.animate({top: down},
{ duration: down_dur, easing : 'linear', queue: true })
.animate({marginLeft: left},
{ duration: left_dur, easing : 'linear', queue: true })
.animate({top: up},
{ duration: up_dur, easing : 'linear', queue: true })
.animate({marginLeft: right},
{ duration: right_dur, easing : 'linear', queue: true });
}
/*
--------------------------------------------------------
CALL THE FUNCTIONS
--------------------------------------------------------
*/
// fire the following when the dom is ready
$(function () {
if (width > 840) {
$('.node').each(function(i) {
$(this).delay(1500 * (i + 1))
.animate({top: '157px'},
{ duration: 1000, easing : 'linear', queue: true })
.animate({marginLeft: '264px'},
{ duration: 1000, easing : 'linear', queue: true });
});
animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
setInterval(function() {
animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
}, 2000);
} else if (width < 840 && width > 600) {
$('.node').each(function(i) {
$(this).delay(1500 * (i + 1))
.animate({top: '165px'},
{ duration: 1000, easing : 'linear', queue: true })
.animate({marginLeft: '179px'},
{ duration: 1000, easing : 'linear', queue: true });
});
animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
setInterval(function() {
animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
}, 2000);
} else if ((!(document.documentElement.hasOwnProperty('ontouchstart'))) &&
width < 600) {
$('.node').each(function(i) {
$(this).delay(1833.333 * (i + 1));
});
animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
setInterval(function() {
animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
}, 2000);
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T12:53:02.770",
"Id": "65774",
"Score": "0",
"body": "Probably not because those constants may become incorrect (besides top and left which will be 0) when the window resizes"
}
] |
[
{
"body": "<p>I would move all positions and other configuration to a simpleObject which contains a condition which is checked to determine if the configuration should be used for the current screen dimensions:</p>\n\n<ul>\n<li>Remove unneeded variables</li>\n<li>Added functions to remove duplication</li>\n<li>Moved positions to animationConfig so logic and configuration is separated</li>\n</ul>\n\n<p>I made a assumption in the code which is that the path is always a square, so up, down, left\nand right duration are replaced with a horizontal and vertical duration</p>\n\n<p>jsfiddle: <a href=\"http://jsfiddle.net/EJF9q/1/\" rel=\"nofollow\">http://jsfiddle.net/EJF9q/1/</a></p>\n\n<pre><code>'use strict';\n\nfunction animate_node(down, down_dur, left, left_dur, up, up_dur, right, right_dur) {\n\n function animate_cfg(duration) {\n return { duration: duration, easing : 'linear', queue: true };\n }\n\n down += 'px';\n left += 'px';\n up += 'px';\n right += 'px';\n\n $('.node')\n .animate({top: down}, animate_cfg(down_dur))\n .animate({marginLeft: left}, animate_cfg(left_dur))\n .animate({top: up}, animate_cfg(up_dur))\n .animate({marginLeft: right}, animate_cfg(right_dur));\n}\n\nfunction animate_config(config) {\n animate_node(\n config.down,\n config.vertical_dur,\n config.left,\n config.horizontal_dur,\n config.up,\n config.vertical_dur,\n config.right,\n config.horizontal_dur);\n}\n\n// OnReady\n$(function () {\n\n var animationConfigs = [\n {\n startTop: 157,\n delay: 1500,\n down: 425,\n left: -284,\n up: 157,\n right: 264,\n vertical_dur: 2000,\n horizontal_dur: 2000,\n conditions: function() {\n return $(window).width() > 840;\n }\n },\n {\n delay: 1500,\n down: 490,\n left: -199,\n up: 165,\n right: 179,\n vertical_dur: 2000,\n horizontal_dur: 2000,\n conditions: function() {\n return $(window).width() < 840 && $(window).width() > 600;\n }\n },\n // Etc...\n ];\n\n for (var i in animationConfigs) {\n var animationCfg = animationConfigs[i];\n if (animationCfg.conditions()) {\n $('.node').each(function(i) {\n $(this).delay(1500 * (i + 1))\n .animate({ top: animationCfg.up + 'px' },\n { duration: 1000, easing : 'linear', queue: true })\n .animate({marginLeft: animationCfg.right + 'px'},\n { duration: 1000, easing : 'linear', queue: true });\n });\n animate_config(animationCfg);\n setInterval(function() {\n animate_config(animationCfg);\n }, 2000);\n break;\n }\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:19:44.317",
"Id": "39316",
"ParentId": "39276",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39316",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T10:29:06.693",
"Id": "39276",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"animation",
"jquery-ui"
],
"Title": "Animating based on screen width"
}
|
39276
|
<p>I have tried to write code of Box stacking problem (mentioned <a href="http://people.csail.mit.edu/bdean/6.046/dp/" rel="nofollow">here</a>) in C++ .
Kindly give me some views on what mistakes I might have made and how I can improve.
It is running for the two inputs I have provided.</p>
<pre><code>//============================================================================
// Name : Boxstacking.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C, Ansi-style
//============================================================================
#include <cstdlib>
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;
class dimension;
typedef shared_ptr<vector<dimension*> > PVecDim;
typedef vector<dimension*> VecDim;
typedef vector<dimension*>::iterator VecDimIter;
typedef shared_ptr<vector<int> > PVecInt;
typedef vector<int> VecInt;
typedef vector<int>::iterator VecIntIter;
typedef shared_ptr<vector<dimension> > PDim;
typedef vector<dimension> Dim;
typedef vector<dimension>::iterator DimIter;
struct dimension {
int height, width, length;
dimension(int h, int w, int l) : height(h), width(w), length(l) {
}
dimension() : dimension(0,0,0) {
}
};
class BaseComparator {
public:
bool operator() (const dimension& a, const dimension& b) {
if(a.width*a.length > b.width*b.length)
return true;
else
return false;
}
};
class BoxStacking {
public:
int doBoxStacking(PVecDim inList) {
int i,j;
VecDimIter it;
cout<<"Input List"<<endl;
for (it = inList->begin(); it != inList->end(); ++it) {
cout<<(*it)->height<<" "<<(*it)->length<<" "<<(*it)->width<<endl;
}
PDim modList = getModList(inList);
sort(modList->begin(), modList->end(), compare) ;
cout<<"Sorted List" <<endl;
DimIter dit;
for(dit=modList->begin();dit!=modList->end();++dit) {
cout<<(*dit).height<<" "<<(*dit).length<<" "<<(*dit).width<<" "<<endl;
}
M->reserve(modList->size());
M->resize(modList->size());
vector<int> prev(modList->size(), -1);
(*M)[0] = (*modList)[0].height;
for(i=1;i<modList->size();++i) {
(*M)[i] = (*modList)[i].height;
int max = (*M)[i];
for(j=i-1;j>=0;--j) {
if((((*modList)[i].length < (*modList)[j].length) &&
(*modList)[i].width < (*modList)[j].width) ||
(((*modList)[i].length < (*modList)[j].width) &&
(*modList)[i].width < (*modList)[j].length)) {
if(max < ((*M)[i] + (*M)[j])) {
max = (*M)[i] + (*M)[j];
prev[i] = j;
}
}
}
(*M)[i] = max;
}
int ret = findMax();
prepareOutList(modList, prev, ret);
return (*M)[ret];
}
BoxStacking() : mOutList(new Dim()) , M(new VecInt()) {
}
friend ostream& operator<<(ostream& out, const BoxStacking& bs) {
DimIter it;
out<<"Output list is "<<endl;
for(it = bs.mOutList->begin(); it!=bs.mOutList->end(); ++it) {
out<<"{"<<(*it).height<<","<<(*it).width<<","<<(*it).length<<"}"<<endl;
}
return out;
}
private:
PDim mOutList;
PVecInt M;
BaseComparator compare;
PDim getModList(PVecDim inList) {
PDim modList(new Dim());
VecDimIter it;
int j=0;
for(it = inList->begin(); it!=inList->end(); ++it) {
dimension rot1((*it)->width, (*it)->height, (*it)->length);
dimension rot2((*it)->length, (*it)->width, (*it)->height);
modList->push_back(*(*it));
modList->push_back(rot1);
modList->push_back(rot2);
}
return modList;
}
int findMax() {
int max=-1, pos;
for(int i=0;i<(M)->size();i++) {
if((*M)[i] >= max) {
pos = i;
max = (*M)[i];
}
}
return pos;
}
void prepareOutList(PDim modList, vector<int> prev, int pos) {
while(pos != -1) {
mOutList->push_back((*modList)[pos]);
pos = prev[pos];
}
}
};
int main(void) {
dimension d[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}};
//dimension d[] = {{1,7,9}, {6,3,5}, {10,2,4 }};
shared_ptr<BoxStacking> bs(new BoxStacking());
PVecDim vecdim(new VecDim());
for (int i=0;i<sizeof(d)/sizeof(d[0]); ++i) {
vecdim->push_back(&d[i]);
}
int max_height = bs->doBoxStacking(vecdim);
cout<<"Max height is"<<max_height<<endl<<*bs;
return EXIT_SUCCESS;
}
</code></pre>
<p>Edit: Here's the logic I followed as well.</p>
<p>I'll take an example. Suppose we have triplets <code>{HxWxL}={1,7,9}, {6,3,5}, {10,2,4}</code>. We expand these to all possible ways we can put the boxes and also we have multiple instances of each box. So after considering this and sorting by WxL we have <code>{HxWxL}={1 9 7 }{2 4 10 }{3 5 6 }{4 10 2 }{5 6 3 }{6 5 3 }{7 9 1 }{10 4 2 }{9 1 7 }</code>.</p>
<p>Now by <code>M[0] = h(0) = 1; M[i] = h(i) + max(M[j] | j < i</code>, we can put block <code>i</code> on top of block <code>j</code> using W and L). So as we see our M vector gets created as <code>M[0] = 1 (from (1,9,7)</code>. Next, 4x10 can't fit 9x7 in anyway so it can go to max height of 2. Then base 5x6 can fit only on top of 9x7 n not 4x10. So we traverse the loop to find its max value and find <code>M[2]=3+1=4</code>. Similar for others in between. We now move to 6x5x3 and see that it can fit both 4x10 (by 3x5 base) and 5x6 base among its predecessors. So we get <code>M[5]=max(M[2]+h[5], M[1]+h[5])</code>.</p>
<p>It turns out <code>M[5] = 4+6=10</code>. So we can go further. We find out solution to be <code>{10,2,4}{6,3,5}{3,6,5}{1,7,9}</code> to give max 20 height.</p>
|
[] |
[
{
"body": "<ol>\n<li>Your header file is wrong. This is NOT an Hello World.</li>\n<li>Do not use <code>using namespace std</code> : <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a> .</li>\n<li>You can use default value for your default constructor so that you do not need two definitions : <code>dimension(int h = 0, int w = 0, int l = 0) : height(h), width(w), length(l){};</code>. As a tiny drawback, one can now provide 0, 1, 2 or 3 parameters but I am not sure it is an actual drawback.</li>\n<li>The implementation of <code>bool operator() (const dimension& a, const dimension& b)</code> could just be : <code>return (a.width*a.length > b.width*b.length);</code>.</li>\n<li>Do define local variable in the smallest possible scope to ease the reading. For instance, <code>for (VecDimIter it = inList->begin(); it != inList->end(); ++it)</code> ; <code>for (DimIter dit = modList->begin();dit!=modList->end();++dit)</code> ; <code>for (int i=1;i<modList->size();++i)</code> ; <code>for (int j=i-1;j>=0;--j)</code> ; etc.</li>\n<li>I have the feeling that <code>if ((((*modList)[i].length < (*modList)[j].length) && (*modList)[i].width < (*modList)[j].width) || (((*modList)[i].length < (*modList)[j].width) && (*modList)[i].width < (*modList)[j].length))</code> can be simplified a bit. If I understand everything properly here, we are trying to match a box <code>i</code> in an other <code>j</code> either vertically or horizontally. In order to do so, one can just wonder whether the biggest dimension of <code>i</code> is smaller than the biggest dimension of <code>j</code> and if it is the case whether the smallest dimension of <code>i</code> is smaller than the dimension of <code>j</code>. Informally, we are just trying to match them by putting the two box in the same direction : if a horizontal box does not fit into an horizontal box, turning one will not help. (I have the feeling this must be true but I haven't proved it...). Thus, the great news is that the smallest/biggest dimension of <code>i</code> can be computed out of the loop so that whenever a new box <code>j</code> comes into play, there's less to compute.</li>\n<li>This <code>for(i=1;i<modList->size();++i)</code> is not a very CPP-y way to loop over a container. If you really want to do so anyway, it's probably better to call the <code>size()</code> function only once.</li>\n<li>I could do with more comments, especially regarding the different members.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:39:39.877",
"Id": "39281",
"ParentId": "39279",
"Score": "4"
}
},
{
"body": "<p>What quickly jumps out:</p>\n\n<pre><code>typedef vector<dimension*> VecDim;\n // ^ Pointer\ntypedef vector<dimension*>::iterator VecDimIter;\n // ^ Pointer\n</code></pre>\n\n<p>Its very rare to see \"raw\" pointers in good C++ code. This is because now you have to do memory management on the code. Pointers are useful for implementing the low down dirty bit of a structure and are used in the bowls of classes to implement higher order structures (because you can use constructor/destructor to guarantee they don't leak). But up in user space you should be using smart pointers.</p>\n\n<p>But in reality I don't see any need even for smart pointers here. Just declare them as objects.</p>\n\n<pre><code>typedef vector<dimension> VecDim;\ntypedef vector<dimension>::iterator VecDimIter;\n</code></pre>\n\n<p>Now you no longer have any memory leaks (its not as if dimension is a huge object the standard copy constructor will work (and 99% of the time it will be elided)).</p>\n\n<p>Also I would declare VecDemIter in terms of VecDim so that if you change the representation you only need to change it in one place and the change automatically cascades through the code.</p>\n\n<pre><code>typedef vector<dimension> VecDim;\ntypedef VecDim::iterator VecDimIter; // And it lines up nicer :-)\n</code></pre>\n\n<p>Now you try and use shared pointers:</p>\n\n<pre><code>typedef shared_ptr<vector<dimension*> > PVecDim;\n // ^^^ This problem should be fixed on all modern\n // compilers. You really don't need the space\n // anymore.\n</code></pre>\n\n<p>But there is no need.<br>\nThe only object of this type you have has a well defined lifetime. Just use <code>VecDim</code>. Then pass the object by reference to your box algorithm.</p>\n\n<p>Please consistent formatting:</p>\n\n<pre><code> for (VecDimIter it = inList->begin(); it != inList->end(); ++it) {\n cout<<(*it)->height<<\" \"<<(*it)->length<<\" \"<<(*it)->width<<endl;\n }\n\n PDim modList = getModList(inList);\n//^^^^ Why the extra indent it confused me.\n</code></pre>\n\n<p>I don't recommend calculating the size of an array:</p>\n\n<pre><code>for (int i=0;i<sizeof(d)/sizeof(d[0]); ++i) {\n // ^^^^^^^^^^^^^^^^^^^^^^\n</code></pre>\n\n<p>It is really vulnerable to breakage when your code is modified later (say this part of the code is tucked into a function called <code>init()</code> and d is passed as a parameter). Personally I would define this as a vector and use the size method.</p>\n\n<pre><code>// This does require C++11\n// But it makes it less prone to bugs.\nstd::vector<dimension> d = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}};\n</code></pre>\n\n<p>PPS. I prefer to name my classes (types) with an initial capitol letter (everything else starts with a lowercase letter). It makes it easy to see type names.</p>\n\n<p>Lots of compilers don't like this:</p>\n\n<pre><code>class dimension;\nstruct dimension { // struct but it was a class.\n</code></pre>\n\n<p>Neither do I. Be consistent. Since it is just a property bag make it struct in both places. Also turn on more warnings so the compiler complains about this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T18:06:04.593",
"Id": "39402",
"ParentId": "39279",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T10:59:12.047",
"Id": "39279",
"Score": "6",
"Tags": [
"c++",
"stl",
"dynamic-programming"
],
"Title": "Box-stacking problem in C++"
}
|
39279
|
<p>I wrote this unbalanced binary tree and would like to know how to improve the code and performance. If you can point out any situations that are not being handled appropriately, that would be great too.</p>
<p>It supports element insertion, removal, search, iteration, tree balancing and encoding/decoding.</p>
<p><strong>bst.h</strong></p>
<pre><code>#ifndef BST_H
#define BST_H
#include <stdint.h>
//Encoding
#define ENCODING_SIZE_T uint32_t
//Maximum size supported by encoding/decoding
#define MAX_CONTENT_LENGTH ((ENCODING_SIZE_T) -1)
//Return codes
#define BST_SUCCESS 0
#define BST_ERROR 1
#define BST_DUPLICATE 2
#define BST_NO_MEMORY 4
typedef struct BST_Node BST_Node;
struct BST_Node {
void *content;
BST_Node *smaller;
BST_Node *greater;
};
typedef struct {
BST_Node *root;
size_t node_count;
int (*compare)(void *, void *);
} BST;
static inline void bst_init(BST *bst, int (*compare)(void *, void *))
{
bst->root = NULL;
bst->node_count = 0;
bst->compare = compare;
}
int bst_insert(BST *bst, void *content);
void bst_remove(BST *bst, void *content);
void *bst_find(BST *bst, void *content);
void bst_free(BST *bst);
void bst_iterate(BST *bst, void (*callback)(void *));
void bst_iterate_reverse(BST *bst, void (*callback)(void *));
void bst_balance(BST *bst);
/* Return total size of the encoded tree. container will point to the allocated
memory on success. size_after_encoding must return how much space the element
will require after encoded. encoder will be called like encoder(destination,
element, element_size) and should write the encoded element at destination and
return one past it, if it returns NULL, the encoding will be aborted. */
size_t bst_encode
(
BST *bst,
void **container,
ENCODING_SIZE_T (*size_after_encoding)(void *), //Must not return 0
void *(*encoder)(void *, void *, ENCODING_SIZE_T) //Must return NULL if it fails
);
/* Decode tree. Both constructor and destructor must be set. Constructor is
expected to return a pointer to the decoded element. Destructor should free
the element created by constructor, it will be called in case of errors. */
int bst_decode
(
BST *bst,
void *encoded,
void *(*constructor)(void *, ENCODING_SIZE_T), //Return NULL if any error occurs
void (destructor)(void *)
);
#endif
</code></pre>
<p><strong>bst_internal.h</strong></p>
<pre><code>#include <stdlib.h>
#include "bst.h"
////////////////////////////
///////// Declarations
///////////////////////////
static inline int choose_smaller(BST *bst);
static BST_Node **a_z(BST *bst);
static void recursive_free(BST_Node *node);
static void node_traverse(BST_Node *node, void (*callback)(BST_Node *));
static void content_traverse(BST_Node *node, void (*callback)(void *));
static void reverse_content_traverse(BST_Node *node, void (*callback)(void *));
static inline void free_all_nodes_from_list(BST_Node **nodes, size_t node_count);
static int insert(BST *bst, BST_Node **where, void *what);
static BST_Node **find_node_and_its_parent( BST *bst, void *content);
static BST_Node **find_closest_smaller_and_its_parent(BST_Node *node);
static BST_Node **find_closest_greater_and_its_parent(BST_Node *node);
static inline void free_and_unlink(BST_Node **node);
static inline void free_and_link_smaller(BST_Node **node);
static void free_and_link_greater(BST_Node **node);
static void remove_node_with_children(BST *bst, BST_Node *node);
static inline void remove(BST *bst, BST_Node **node);
static BST_Node *link_middle(BST_Node **start, BST_Node **end);
////////////////////////////
///////// Internal methods
///////////////////////////
/* Choose a different side every time a node with 2 children is removed, so
the tree won't become too unbalanced after many removals */
static int choose_smaller(BST *bst)
{
return bst->node_count % 2;
}
static void a_z_recursive(BST_Node **dest, BST_Node *node, size_t *i)
{
if(node->smaller != NULL)
a_z_recursive(dest, node->smaller, i);
dest[*i] = node;
*i += 1;
if(node->greater != NULL)
a_z_recursive(dest, node->greater, i);
}
/* Return an ordered array containing all nodes starting at a certain point.
Caller must be sure the tree has at least the root */
static BST_Node **a_z(BST *bst)
{
//Store pointers to all nodes into an array
BST_Node **a_z = malloc(bst->node_count * sizeof(BST_Node *));
if(a_z == NULL)
return NULL;
//Keep track of position
size_t i = 0;
a_z_recursive(a_z, bst->root, &i);
return a_z;
}
/* Traverse the tree in order and call some function to work on the node */
static void node_traverse(BST_Node *node, void (*callback)(BST_Node *))
{
if(node->smaller != NULL)
node_traverse(node->smaller, callback);
callback(node);
if(node->greater != NULL)
node_traverse(node->greater, callback);
}
//Can't use node_traverse or it will try to read the deallocated node
static void recursive_free(BST_Node *node)
{
if(node->smaller != NULL)
recursive_free(node->smaller);
if(node->greater != NULL)
recursive_free(node->greater);
free(node);
}
static void content_traverse(BST_Node *node, void (*callback)(void *))
{
if(node->smaller != NULL)
content_traverse(node->smaller, callback);
callback(node->content);
if(node->greater != NULL)
content_traverse(node->greater, callback);
}
static void reverse_content_traverse(BST_Node *node, void (*callback)(void *))
{
if(node->greater != NULL)
content_traverse(node->greater, callback);
callback(node->content);
if(node->smaller != NULL)
content_traverse(node->smaller, callback);
}
/* Free all nodes listed in the array */
static void free_all_nodes_from_list(BST_Node **nodes, size_t node_count)
{
while(node_count-- > 0)
free(nodes[node_count]);
}
static int insert(BST *bst, BST_Node **where, void *what)
{
//Allocate new node
if((*where = malloc(sizeof(BST_Node))) == NULL)
return BST_NO_MEMORY;
//Fill
(*where)->content = what;
(*where)->smaller = NULL;
(*where)->greater = NULL;
++bst->node_count;
return BST_SUCCESS;
}
/* Return BST_SUCCESS if found or BST_ERROR if not found */
static BST_Node **find_node_and_its_parent(BST *bst, void *content)
{
/* Set it up so node will point to the right node, and parent will point to
its parent */
BST_Node *parent;
BST_Node *node = NULL;
BST_Node *ite = bst->root;
int relationship;
/* Move until all can be done in a loop, otherwise it will break if the
node to be removed is root */
relationship = bst->compare(content, ite->content);
parent = node;
node = ite;
if(relationship > 0)
ite = ite->greater;
else
if(relationship < 0)
ite = ite->smaller;
//It's root
else
return &bst->root;
/* Now it's safe to process */
while(ite != NULL){
//Find next path
relationship = bst->compare(content, ite->content);
//Update
parent = node;
node = ite;
if(relationship > 0)
ite = ite->greater;
else
if(relationship < 0)
ite = ite->smaller;
else {
//Found, check which side
return (parent->greater == node) ? &parent->greater
: &parent->smaller;
}
}
//Not found
return NULL;
}
static BST_Node **find_closest_smaller_and_its_parent(BST_Node *node)
{
/* When it's done ite will be NULL and the other 2 pointers will be set to
the correct nodes */
BST_Node *parent = node;
BST_Node *closest = node->smaller;
BST_Node *ite = closest->greater;
while(ite != NULL){
parent = closest;
closest = ite;
ite = ite->greater;
}
return (parent->smaller == closest) ? &parent->smaller : &parent->greater;
}
static BST_Node **find_closest_greater_and_its_parent(BST_Node *node)
{
BST_Node *parent = node;
BST_Node *closest = node->greater;
BST_Node *ite = closest->smaller;
while(ite != NULL){
parent = closest;
closest = ite;
ite = ite->smaller;
}
return (parent->smaller == closest) ? &parent->smaller : &parent->greater;
}
static void free_and_unlink(BST_Node **node)
{
free(*node);
*node = NULL;
}
static void free_and_link_smaller(BST_Node **node)
{
void *temp = (*node)->smaller;
free(*node);
*node = temp;
}
static void free_and_link_greater(BST_Node **node)
{
void *temp = (*node)->greater;
free(*node);
*node = temp;
}
static void remove_node_with_children(BST *bst, BST_Node *node)
{
BST_Node **substitute;
if(choose_smaller(bst))
substitute = find_closest_smaller_and_its_parent(node);
else
substitute = find_closest_greater_and_its_parent(node);
node->content = (*substitute)->content;
remove(bst, substitute);
}
static void remove(BST *bst, BST_Node **node)
{
//Handle removal here if the node is a leaf or has a single child
if((*node)->smaller)
//Both left and right, call handler
if((*node)->greater)
remove_node_with_children(bst, (*node));
//Only left
else
free_and_link_smaller(node);
//Only right child
else
if((*node)->greater)
free_and_link_greater(node);
//It's a leaf
else
free_and_unlink(node);
}
static BST_Node *link_middle(BST_Node **start, BST_Node **end)
{
if(end - start == 0)
return NULL;
//Find middle
BST_Node **middle = start + (end - start) / 2;
//Call again for left and right subtrees
(*middle)->smaller = link_middle(start, middle);
(*middle)->greater = link_middle(middle + 1, end);
return *middle;
}
</code></pre>
<p><strong>bst.c</strong></p>
<pre><code>#include <stdlib.h>
#include "bst.h"
#include "bst_internal.h"
////////////////////////////
///////// Public methods
///////////////////////////
//Find where to insert and call insert
int bst_insert(BST *bst, void *content)
{
//Handle root insertion separately
if(bst->root == NULL)
return insert(bst, &bst->root, content);
//Find the place where the new node is supposed to be.
BST_Node *ite = bst->root; //Seed
BST_Node *parent;
int relationship;
while(ite != NULL){
relationship = bst->compare(content, ite->content);
parent = ite;
if(relationship > 0)
ite = ite->greater;
else
if(relationship < 0)
ite = ite->smaller;
else
return BST_DUPLICATE;
}
//Found the spot, repeat last decision to see if it went left or right
return insert( bst, (relationship > 0)
? &parent->greater
: &parent->smaller, content );
}
//Remove and free node
void bst_remove(BST *bst, void *content)
{
if(bst->root == NULL)
return;
BST_Node **node = find_node_and_its_parent(bst, content);
if(node == NULL)
return;
//Update count
--bst->node_count;
remove(bst, node);
}
void *bst_find(BST *bst, void *content)
{
BST_Node *ite = bst->root;
int relationship;
while(ite != NULL){
relationship = bst->compare(content, ite->content);
if(relationship > 0)
ite = ite->greater;
else
if(relationship < 0)
ite = ite->smaller;
else
return ite->content; //Found
}
//Didn't find
return NULL;
}
void bst_free(BST *bst)
{
if(bst->root == NULL)
return;
recursive_free(bst->root);
}
//Callback will be called once per node, from node a to z
void bst_iterate(BST *bst, void (*callback)(void *))
{
if(bst->root == NULL)
return;
content_traverse(bst->root, callback);
}
//Same as before, but z to a
void bst_iterate_reverse(BST *bst, void (*callback)(void *))
{
if(bst->root == NULL)
return;
reverse_content_traverse(bst->root, callback);
}
//Balance the tree
void bst_balance(BST *bst)
{
BST_Node **ordered_nodes = a_z(bst);
bst->root = link_middle( ordered_nodes,
ordered_nodes + bst->node_count );
free(ordered_nodes);
}
////////////////////////////
///////// Functions to save the tree. They allow to use the tree
//////// to hold data, save it, and load it.
///////////////////////////
// The encoded tree looks like: INDEX + NODE_SIZE + NODE + NODE_SIZE + NODE...
//Use a struct to make it easier to add new fields
typedef struct {
size_t node_count;
} Index;
/* Calculate total space required for an encoded tree */
static size_t total_space_required_for_encoding
(
BST_Node **all_nodes,
size_t node_count,
ENCODING_SIZE_T (*size_after_encoding)(void *)
)
{
//Consider the index
size_t space_required = sizeof(Index);
//Add NODE_SIZE
space_required += sizeof(ENCODING_SIZE_T) * node_count;
//Calculate how much storage each node will need
ENCODING_SIZE_T node_size;
while(node_count-- > 0){
node_size = size_after_encoding(all_nodes[node_count]->content);
space_required += node_size;
//Consider padding, so all NODE_SIZEs will be aligned
space_required += node_size % sizeof(ENCODING_SIZE_T);
}
return space_required;
}
/* Return BST_ERROR if the encoding function signals an error */
static int encode
(
void *dest,
BST_Node **nodes,
size_t node_count,
ENCODING_SIZE_T (*size_after_encoding)(void *),
void *(*encoder)(void *, void *, ENCODING_SIZE_T)
)
{
//Node size is used when decoding
ENCODING_SIZE_T *node_size;
for(size_t i = 0; i < node_count; ++i){
//Add the node size
node_size = dest;
*node_size = size_after_encoding(nodes[i]->content);
//Location to copy the content to
dest = (char *)dest + sizeof(ENCODING_SIZE_T);
//encoder must fill dest and return one past it
dest = encoder(dest, nodes[i]->content, *node_size);
if(dest == NULL)
return BST_ERROR;
//Add padding to keep node_size aligned
dest = (char *)dest + *node_size % sizeof(ENCODING_SIZE_T);
}
return BST_SUCCESS;
}
/* Return the total size of encoded tree. container will point to the allocated
memory on success. size_after_encoding must return how much space the element
will require after encoded. encoder will be called like encoder(destination,
element, element_size) and should write the encoded element at destination and
return one past it, if it returns NULL, the encoding will be aborted. */
size_t bst_encode
(
BST *bst,
void **container,
ENCODING_SIZE_T (*size_after_encoding)(void *), //Must not return 0
void *(*encoder)(void *, void *, ENCODING_SIZE_T) //Must return NULL if it fails
)
{
//Is there anything?
if(bst->root == NULL)
return 0;
//Get a list of nodes
BST_Node **nodes = a_z(bst);
//How much memory will be required?
size_t space_required = total_space_required_for_encoding
(nodes, bst->node_count, size_after_encoding);
//Try to allocate enough memory
Index *encoded = malloc(space_required);
if(encoded == NULL){
free(nodes);
return 0;
}
//Fill info
encoded->node_count = bst->node_count;
if(encode( encoded + 1,
nodes,
bst->node_count,
size_after_encoding,
encoder )
== BST_ERROR){
free(nodes);
return 0;
}
free(nodes);
*container = encoded;
return space_required;
}
/* Allocate new nodes, return an array with pointers to all */
static BST_Node **allocate_nodes_and_list(size_t total)
{
//Allocate list
BST_Node **nodes = malloc(sizeof(BST_Node *) * total);
if(nodes == NULL)
return NULL;
//Allocate all nodes and add to list
for(size_t i = 0; i < total; ++i){
//Create new node, check for errors
nodes[i] = malloc(sizeof(BST_Node));
if(nodes[i] == NULL){
//Abort
while(i-- > 0)
free(nodes[i]);
free(nodes);
return NULL;
}
}
return nodes;
}
/* Construct nodes. Destruct all in case of failure */
static int construct_nodes
(
BST_Node **nodes,
void *encoded,
size_t node_count,
void *(*constructor)(void *, ENCODING_SIZE_T),
void (destructor)(void *)
)
{
ENCODING_SIZE_T *node_size;
for(size_t i = 0; i < node_count; ++i){
//Get size
node_size = encoded;
//Point to content
encoded = (char *)encoded + sizeof(ENCODING_SIZE_T);
//Construct
nodes[i]->content = constructor(encoded, *node_size);
//Handle error
if(nodes[i]->content == NULL){
//Destruct all
while(i-- > 0)
destructor(nodes[i]->content);
return BST_ERROR;
}
//Update position
encoded = (char *)encoded + *node_size;
//Don't forget the padding
encoded = (char *)encoded + *node_size % sizeof(ENCODING_SIZE_T);
}
return BST_SUCCESS;
}
/* Decode tree. Both constructor and destructor must be set. Constructor is
expected to return a pointer to the unencoded element. Destructor should free
the element created by constructor, it will be called in case of errors. */
int bst_decode
(
BST *bst,
void *encoded,
void *(*constructor)(void *, ENCODING_SIZE_T), //Return NULL if any error
void (destructor)(void *)
)
{
Index *index = encoded;
//Try to allocate all
BST_Node **nodes = allocate_nodes_and_list(index->node_count);
if(nodes == NULL)
return BST_ERROR;
if(construct_nodes( nodes,
index + 1,
index->node_count,
constructor,
destructor )
== BST_ERROR){
free_all_nodes_from_list(nodes, index->node_count);
free(nodes);
return BST_ERROR;
}
bst->root = link_middle(nodes, nodes + index->node_count);
bst->node_count = index->node_count;
free(nodes);
return BST_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<p>This is simple a first pass with mostly top level thoughts - I dig deeper later.</p>\n\n<ol>\n<li><p>Suggest moving all functions to bst.c including <code>bst_init() size_t bst_encode() bst_decode()</code>. By doing so, <code>ENCODING_SIZE_T MAX_CONTENT_LENGTH BST_Node</code> and the fields of <code>BST</code> may be removed from the application view. The ap does not need to see them.<br>\n[Edit] I now see <code>bst_init() size_t bst_encode() bst_decode()</code> are only prototyped in bst.h - ignore that part of this suggestion. At first blush, the style looked like code, but it is only prototype.</p>\n\n<pre><code>// BST.h\ntypedef struct BST BST;`\n\n// BST.c\nstruct BST { \n BST_Node *root; \n size_t node_count; \n int (*compare)(void *, void *);\n};\n</code></pre></li>\n<li><p>I often use the prefix before functions like <code>BST_This()</code> and <code>BST_That()</code>, but I would be consistent with the filename's case. Use BST.c with <code>BST_This()</code> or bst.c with <code>bst_This()</code>.</p></li>\n<li><p>Need <code>#include <stdlib.h></code> for <code>size_t</code> in bst.h. You might have caught that if in bst.c you included the standard headers after \"bst.h\". Suggest moving those after \"bst.h\". This prevents requiring users of bst.h to include certain headers files first.</p></li>\n<li><p>Large comment blocks before <code>bst_encode</code> in both <code>bst.h bst.c</code> is a maintenance liability. Suggest only one (in <code>bst.h</code>) a a reference in <code>bst.c</code> to <code>bst.h</code> to show you did not forget.</p></li>\n<li><p>Change compare function type to a <code>const</code> version. <code>qsort()</code>'s type shown for reference.</p>\n\n<pre><code>int (*compare)(const void *, const void *); \n// qsort's --> int (*compar)(const void *, const void *);\n</code></pre></li>\n<li><p>Maybe test for <code>compare()</code> against NULL.</p></li>\n<li><p>To expand <code>compare()</code> possibilities, add a compare state variable.</p></li>\n<li><p>Concerning <code>callback</code>, allow that function to return an <code>int</code> and use a non-zero value to short-circuit the progress OR provide a state variable for <code>callback()</code>.</p></li>\n</ol>\n\n<p>More later</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:41:50.647",
"Id": "66182",
"Score": "0",
"body": "@2013Asker Sorry I did not get the meat of the code. Note: The generous north-south spacing works well for functional review, but it had me doing lots of scrolling to see the overall picture."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:46:55.787",
"Id": "66185",
"Score": "0",
"body": "Thank you for reviewing. Do you mind explaining what you mean on 2? I'm using the following naming convention: public functions are prefixed and lowercase, internal functions are not prefixed, types have the first letter of each word capitalized, initialisms are uppercase when they appear as a type name. Would it be considered bad style?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:00:45.490",
"Id": "66189",
"Score": "0",
"body": "@2013Asker No, it is not a bad style. Any _consistent_ style has some merit. I do not like trying to convey subtle meaning by adjusting the case. IMO, \"xyz\" is different that \"XYZ\" and \"Xyz\". In the same breath, I would avoid creating 2 modules, once called \"BST\" and another \"bst\", But given I may import someone else's code with \"BST\" and mine is \"bst\", our combined code would survive."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T23:08:29.643",
"Id": "39423",
"ParentId": "39282",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "39423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T11:58:57.183",
"Id": "39282",
"Score": "6",
"Tags": [
"c",
"tree"
],
"Title": "Unbalanced binary search tree"
}
|
39282
|
<p>There is a recommendation not to use an Exception to control the flow of execution. This gives me a reason for doubt when I do something like this:</p>
<pre><code> public void initApplication(String input) {
try {
MyClass mClass = new mClass(input);
saveToDatabase(mClass);
updateSettingsTheAppIsReady();
} catch (CancelPreparationsException e) {
showErrorMessageToUser();
doRollbacks();
}
}
</code></pre>
<p>mClass instantiation, save operation to a database, settings update may go wrong, each of them throw their own exceptions, which I catch within the methods/classes and throw my custom exception to stop the <code>initApplication()</code> method execution. </p>
<p>This sounds an easier way than having preconditions checking like:</p>
<ol>
<li>Create MyClass object.</li>
<li>Check the MyClass object is created then save it to db.</li>
<li>Ensure the object was saved in db then update settings.</li>
</ol>
<p>Is it really not recommended way of using the Exception to control the flow? Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:03:54.163",
"Id": "65777",
"Score": "3",
"body": "You're not supposed to use Exceptions for \"normal\" control flow, f.e. iterating over collections, you only should use it for exceptional cases. If your insert into that database should work 99.99999% of the time (and only because of circumstances beyond your control), then throwing an exception is the right thing to do. If I'm allowed to (and you haven't already read it), I'd like to refer you to \"Effective Java, Chapter 9: Exceptions, Item 57: Use exceptions only for exceptional conditions\". Joshua Bloch does a way better job at explaining what is meant then I do."
}
] |
[
{
"body": "<p>I would say that this isn't controlling the flow of your application. This is handling an exceptional circumstance (i.e., failure of your code to perform what as it's meant to), which is what Exceptions are meant to accommodate.</p>\n\n<p>The recommendation is more for circumstances like this:</p>\n\n<pre><code>public boolean itemExists(List<MyObject> list, MyObject object) {\n try {\n for(MyObject thisOne : list) {\n if(thisOne.getAttribute() == object.getAttribute()) {\n throw new Exception(\"found it\");\n }\n }\n }\n catch(Exception e) {\n if(e.getMessage().equals(\"found it\")) {\n return true;\n }\n throw e;\n }\n return false;\n}\n</code></pre>\n\n<p><em>This</em> controls the flow of the program based on normal execution. It should be pretty easy to see why this isn't ideal, simply for code readability, not considering aspects like performance, style, and best practices.</p>\n\n<p>What you have in the above code is fine. Throwing Exceptions for errors is what they're for. If you're throwing Exception simply to break out of loops or functions or are using them during the \"intended\" execution of your code, that's when you're going down the wrong path.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:45:43.160",
"Id": "65808",
"Score": "0",
"body": "He is certainly not controlling the flow. What he's doing is just error-handling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T18:31:52.103",
"Id": "65827",
"Score": "2",
"body": "Wait, this is a thing that people do? That's absolutely insane. Anyone who thinks that I good idea needs to be kept away from computer for a long, long time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T18:43:11.973",
"Id": "65829",
"Score": "0",
"body": "@mikeTheLiar Haha, maybe not this simple, but I do see scenarios kind of like this in my production environment. Often. Yay for outsourcing programming labor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T18:48:18.133",
"Id": "65830",
"Score": "0",
"body": "@Jeff that's TDWTF material right there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:17:47.420",
"Id": "65999",
"Score": "1",
"body": "@Jeff ...and I just found it in our code base. That sound you hear is me slamming my head into my desk."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:33:27.037",
"Id": "39295",
"ParentId": "39284",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "39295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:07:32.290",
"Id": "39284",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"exception-handling",
"exception"
],
"Title": "Throw an exception to control the flow of code execution"
}
|
39284
|
<p>The question is very simple but also a bit theoretical. </p>
<p>Let's imagine you have a long jQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this jQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.</p>
<p>Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / jQuery code to implement separation of concerns described by MVC / AngularJS?</p>
<p>I provide an example of jQuery code to speak over something concrete.</p>
<pre><code>$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
</code></pre>
|
[] |
[
{
"body": "<p>You are asking a high level question, so I am going to give a high level answer.</p>\n\n<ul>\n<li>Your listeners should have at most 2 lines of code inside, 1 line that changes data in the model if required, one line that updates the screen, if required.</li>\n</ul>\n\n<p>This means that you need to extract from your listeners all the code into functions which you can group under a view object, this will help tremendously for reviewing since you can give meaningful names to those functions so that the reader knows what is going on.</p>\n\n<ul>\n<li>Your data should live in a model class, you can keep updating the model from the UI or you can let Angular take care of that.</li>\n</ul>\n\n<p>Other than, I do have some other minor observations:</p>\n\n<ul>\n<li>Remove commented code out, it has no use, use source versioning </li>\n<li>Magic constants, you have so many, extract them out, name, explain their value</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:40:10.470",
"Id": "65910",
"Score": "0",
"body": "Thanks! But what are magic costants?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:59:49.637",
"Id": "65916",
"Score": "1",
"body": "697, 500, \"85%\", 1.21, 93 are magic constants, \"Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T14:29:46.347",
"Id": "39390",
"ParentId": "39285",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:16:07.857",
"Id": "39285",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to refactor JQuery interaction with interface?"
}
|
39285
|
<p>I am quite new to event programming in C# specially in WPF. I have made a very simple core app which I am planning on extending. </p>
<p>It's very simple as its purpose is learning curve and doing things the right way that's why I am asking here for a review and not help on building as most of the building is easily researchable.</p>
<p>This is what it looks like </p>
<p><img src="https://i.stack.imgur.com/FaMqQ.png" alt="enter image description here"></p>
<p>This is my XAML code</p>
<pre><code><Window x:Class="LearningApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Shop Floor Data Collection" Height="130" Width="320" Loaded="Window_Loaded" >
<Grid Background="#FF2BBBD8" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="75"/>
</Grid.RowDefinitions>
<Canvas Background="#FF102E37" Height="25" HorizontalAlignment="Stretch" Grid.Row="0" VerticalAlignment="Top">
<Label x:Name="Welcome" Content="User:" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="White"/>
<Label x:Name="Username" Content="" Canvas.Left="32" Width="120" Foreground="White"/>
<Label x:Name="TodaysDate" Content="" Canvas.Right="10" Width="70" Foreground="White"/>
</Canvas>
<Canvas x:Name="ReportCanvas" HorizontalAlignment="Left" Height="46" Margin="10,15,0,0" Grid.Row="1" VerticalAlignment="Top" Width="132" Background="#FF102E37" MouseEnter="Canvas_MouseEnter" MouseLeave="Report_MouseLeave" MouseLeftButtonDown="ReportCanvas_MouseLeftButtonDown" MouseLeftButtonUp="ReportCanvas_MouseLeftButtonUp">
<Label x:Name="ReportLabel" Content="Report Production" Foreground="White" Canvas.Left="12" Canvas.Top="10" />
</Canvas>
<Canvas x:Name="AnalyseCanvas" HorizontalAlignment="Right" Height="46" Margin="0,15,10,0" Grid.Row="1" VerticalAlignment="Top" Width="132" Background="#FF102E37" MouseEnter="Canvas_MouseEnter" MouseLeave="Report_MouseLeave" MouseLeftButtonDown="ReportCanvas_MouseLeftButtonDown" MouseLeftButtonUp="ReportCanvas_MouseLeftButtonUp">
<Label x:Name="AnalyseLabel" Content="Analyse" Foreground="White" Canvas.Left="41" Canvas.Top="10" />
</Canvas>
</Grid>
</code></pre>
<p>and Code behind (<em>removed a few spare lines</em>)</p>
<pre><code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
Username.Content = Environment.UserName;
TodaysDate.Content = DateTime.Now.ToShortDateString();
}
private void Canvas_MouseEnter(object sender, MouseEventArgs e)
{
((Canvas)sender).Background = new SolidColorBrush(Colors.Orange);
//Report.Background = new SolidColorBrush(Colors.Orange);
}
private void Report_MouseLeave(object sender, MouseEventArgs e)
{
((Canvas)sender).Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF102E37"));
}
private void ReportCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (((Canvas)sender).Name == "ReportCanvas")
{
((Canvas)sender).Margin = new Thickness(((Canvas)sender).Margin.Left + 2,
((Canvas)sender).Margin.Top + 1,
((Canvas)sender).Margin.Right,
((Canvas)sender).Margin.Bottom);
}
Else
{
((Canvas)sender).Margin = new Thickness(((Canvas)sender).Margin.Left,
((Canvas)sender).Margin.Top + 1,
((Canvas)sender).Margin.Right - 2,
((Canvas)sender).Margin.Bottom);
}
}
private void ReportCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (((Canvas)sender).Name == "ReportCanvas")
{
((Canvas)sender).Margin = new Thickness(((Canvas)sender).Margin.Left - 2,
((Canvas)sender).Margin.Top - 1,
((Canvas)sender).Margin.Right,
((Canvas)sender).Margin.Bottom);
}
Else
{
((Canvas)sender).Margin = new Thickness(((Canvas)sender).Margin.Left,
((Canvas)sender).Margin.Top - 1,
((Canvas)sender).Margin.Right + 2,
((Canvas)sender).Margin.Bottom);
}
}
</code></pre>
<p>Im on windows 7 and was just trying to kind of simulate windows 8 buttons style. I've heard there is the metro look library etc but I am not interested in it. Again, this is part of learning how to create UI. </p>
<p>On the <code>MouseLeftButtonDown</code> and <code>up</code> I am trying to use the same events but slightly modified to achieve the same transformation <em>look</em> for both buttons. When canvas is Clicked a I just want it to move 1px down and 2px right/left depending on the alignment.</p>
<p>I have achieved it and I have got a <em>working</em> code but I have got a feeling there might be a better way of doing the exact same thing. It does not look pretty as it stands and me, coming from VBA background I simply do not like the way I am doing it. Not too advanced in C# yet so I'd like some pointers with some explanation (<em>would be great!</em>)</p>
<p><em>Please skip naming of the events as they were autogenerated and I haven't changed that for an easier recognition of what belongs where.</em></p>
<p>So, is there a better way of handling those 2 events? (<code>MouseLeftButtonDown/Up</code>)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:58:56.593",
"Id": "65776",
"Score": "0",
"body": "Do you know somethig about behaviors and attachable properties? Anythig about MVP, MVC, or MVVM design patterns?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:05:03.117",
"Id": "65780",
"Score": "0",
"body": "@ArturMustafin I am a bit familiar with MVC but i'd say I am a complete beginner I get the idea of MVC but I haven't implemented it yet. I am not familiar yet with behaviours or attachable properties. Eh it does sound like I'm a complete noob in this content but forgive me I am just starting."
}
] |
[
{
"body": "<p>While you are only asking about event i feel like the general review will help you as well. So here it goes.</p>\n\n<ol>\n<li>You have a lot of junk in your xaml. Don't name an element if you dont use that name, don't set properties if they are no different from the default values.</li>\n<li>You should use <code>Style</code>s for repeated properties (such as button width/height) instead of copy-pasting them. That way when you will decide to change the width of your buttons - you will only have to do it in one place.</li>\n<li><p>Avoid using <code>Canvas</code> for real-life UI design. It makes your UI unscalable. Use <code>Grid</code>, <code>DockPanel</code>, etc. instead.</p></li>\n<li><p>When you need to reuse cast - only cast once.</p>\n\n<pre><code>var canvas = (Canvas)sender;\nif (canvas.Name == \"ReportCanvas\")\n{\n canvas.Margin = new Thickness(canvas.Margin.Left - 2,\n</code></pre></li>\n<li><p>As for your actual question: If you place your \"buttons\" in two-column <code>Grid</code> and use <code>HorizontalAlignment=Left</code> for both of them - your problem should be solved, as you will be able to use the same transformations for both canvases. </p></li>\n</ol>\n\n<p>But the thing is - your approach is wrong. To achieve such behavior the simpliest solution whould be to use an actual <code>Button</code>. It has <code>IsPressed</code> property which can be hoooked to <code>Trigger</code>, which would change margin depending on if the button is pressed. This will clean up your code-behind. If that sounds too complicated for you at this point - check an example (it changes background, not margin, but the idea whould be the same) <a href=\"http://social.msdn.microsoft.com/Forums/vstudio/en-US/b84afe49-1db0-4472-87f9-7bd8dda8e634/how-to-change-the-background-image-of-a-button-on-click-in-xaml-using-styles-or-triggers?forum=wpf\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/vstudio/en-US/b84afe49-1db0-4472-87f9-7bd8dda8e634/how-to-change-the-background-image-of-a-button-on-click-in-xaml-using-styles-or-triggers?forum=wpf</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T08:08:11.527",
"Id": "65875",
"Score": "0",
"body": "Thanks Nik for your tips, I appreciate it. I do realize that there are many ways of building UIs. I have used what I have learned up til now but your tips seem logical and I will be researching what you have mentioned. I am just now reading about `Style`s and I will try to implement that into my core sample. Thanks a lot for your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:48:36.343",
"Id": "39361",
"ParentId": "39286",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39361",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:37:35.650",
"Id": "39286",
"Score": "3",
"Tags": [
"c#",
"wpf",
"event-handling"
],
"Title": "Optimizing a very simple wpf app - attempt on handling 2 buttons with a common event"
}
|
39286
|
<p>I have to work with a 3rd-party API that allows me to define and execute "commands", using XML. Since I don't like seeing mixed abstraction levels, I managed to remove all the inline XML / string concatenations by creating a simple <code>XmlCmdBuilder</code> object - here is the C# implementation (I have one in VB6 as well, the C# one will eventually replace the VB6 equivalent code):</p>
<pre><code>public class XmlCmdBuilder
{
private readonly IList<XmlCmd> _xmlCommands;
public XmlCmdBuilder()
{
_xmlCommands = new List<XmlCmd>();
}
public void AddCommand(XmlCmd cmd)
{
_xmlCommands.Add(cmd);
}
public void Clear()
{
_xmlCommands.Clear();
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append("<cmd:Commands xmlns:cmd=\"http://www.contoso.com/XmlCommand\">");
foreach (var xmlCommand in _xmlCommands)
{
builder.Append(xmlCommand);
}
builder.Append("</cmd:Commands>");
return builder.ToString();
}
}
</code></pre>
<p>The "builder" simply exposes a <code>AddCommand</code> method that takes in a <code>XmlCmd</code> object:</p>
<pre><code>public class XmlCmd
{
private readonly IList<XmlCmdParameter> _parameters;
public XmlCmd(string name)
: this(name, new List<XmlCmdParameter>())
{
}
public XmlCmd(string name, params XmlCmdParameter[] parameters)
: this(name, parameters.ToList())
{
}
public XmlCmd(string name, IList<XmlCmdParameter> parameters)
{
_parameters = parameters;
Name = name;
}
public string Name { get; private set; }
public void AddParameter(XmlCmdParameter parameter)
{
_parameters.Add(parameter);
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(string.Format("<cmd:Command name=\"{0}\">", Name));
foreach (var xmlCommandParameter in _parameters)
{
builder.Append(xmlCommandParameter);
}
builder.Append("</cmd:Command>");
return builder.ToString();
}
}
</code></pre>
<p>Similarly, the <code>XmlCmd</code> exposes a method to add <code>XmlCmdParameter</code> objects, which in turn expose methods to add <code>XmlCmdParameterListItem</code> objects.</p>
<p>This all works very well, but since most commands are predefined (there can be "custom" commands too), I created a factory class that creates <code>XmlCmd</code> objects off parameter values, like this:</p>
<pre><code>public XmlCmd SetOptionValue(string optionName, string optionValue)
{
var parameters = new[]
{
_parameterFactory.Create("name", optionName, XmlCmdParameterType.StringParam),
_parameterFactory.Create("value", optionValue, XmlCmdParameterType.StringParam)
};
return new XmlCmd("SetOptionValue", parameters);
}
</code></pre>
<p>Then in the calling code, I can eliminate all the inline XML and string concatenation and replace it all with a single method call:</p>
<pre><code>var builder = new XmlCmdBuilder();
builder.AddCommand(_cmdFactory.SetOptionValue("OptionName", "OptionValue"));
</code></pre>
<p>Then I can continue "building" the xml by adding subsequent <code>AddCommand</code> calls, and when I need to, I just call <code>ToString()</code> and pass the generated XML string to the 3rd-party API that knows what to do with it.</p>
<hr>
<p>I have put these objects in their own class library, which needs a strong name key and ends up deployed in the GAC / Global Assembly Cache, so I want this library to be as "immune to change" as possible; one potential issue is with the <code>XmlCmdFactory</code> class: the commands are predefined, but I haven't implemented all of them and I might need to change it (add more methods) in the future.</p>
<p>I'd like some feedback on the <code>XmlCmdBuilder</code> and <code>XmlCmd</code> classes (<code>XmlCmdParameter</code> is built the same way, listing it here, along with the rest of the classes, would be almost redundant), and also some pointers in terms of extensibility, not so much about the code itself, but about adding more factory methods: something doesn't feel right about deploying a new version of this library to the GAC whenever a new XML command is needed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:04:07.813",
"Id": "65778",
"Score": "0",
"body": "Diy you try to use enumerations for all of your commands?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:04:33.953",
"Id": "65779",
"Score": "0",
"body": "I'm open to all ideas :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:05:30.490",
"Id": "65781",
"Score": "3",
"body": "Ok, i'll give it to you my impression of what it might be"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:21:11.227",
"Id": "65804",
"Score": "2",
"body": "Does each command have a fixed set of parameter names and types, and fixed number of parameters? Or are methods overloaded with different types (e.g. does SetOptionValue also support int parameters)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:28:20.753",
"Id": "65805",
"Score": "0",
"body": "@ChrisW Good question. Yes, there can be several overloads for each command; `SetOptionValue` could have 2-3 signatures/implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:30:34.513",
"Id": "65806",
"Score": "0",
"body": "Is the list and number of parameter names constant for each command, e.g. does SetOptionValue always have two parameters, named `name` and `value`? Is it only the parameter types, that vary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:39:09.483",
"Id": "65807",
"Score": "1",
"body": "@ChrisW Most commands have 1 specific way of being configured, but some might have 2-3 overloads with varying parameters and parameter types."
}
] |
[
{
"body": "<p>not sure exactly how this will be used, so this might be a null point. </p>\n\n<p>you have <code>add</code> methods but you don't have any <code>remove</code> methods. not sure it would make extension easier, but it would probably provide you with a way to remove deprecated commands (you may or may not want to do this because of backwards compatibility in the future. <em>but hey let someone else worry about that</em>).</p>\n\n<p>Let's say that you implement this in a GUI (in the future - <em>sans aliens</em>), you would want a remove method so that your Interface could show you what you have created so far and you could remove something that is an error.</p>\n\n<p>maybe even a <code>replace</code> method for replacing a command that is broken again I am thinking of an interactive interface.</p>\n\n<p>I always think of user usability, so the interface would allow you to create the XML by giving parameters, strings, etc. </p>\n\n<p>maybe I am going off on a bunny trail, but I think it would be nice to have those methods so that you don't have to add them later. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:48:50.907",
"Id": "65797",
"Score": "0",
"body": "I won't [downvote as requested](http://chat.stackexchange.com/transcript/message/13203529#13203529), but the idea is basically \"build some xml and pass it to the 3rd-party API\" - I don't *need* to get fancy with removing commands :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:56:03.397",
"Id": "65799",
"Score": "3",
"body": "I think adding a `Remove` and a `Replace` method because *it would be nice to have those methods so that I don't have to add them later* smells like YAGNI..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:04:35.847",
"Id": "65802",
"Score": "0",
"body": "@retailcoder, good point. I am always thinking about what the next step is going to be, which is sometimes counter-productive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:34:12.990",
"Id": "65874",
"Score": "1",
"body": "there are some agreement with the statemens, really need some code examples to prove you point of view, in my opinion, your answer is 60% agains 40% correct, so mostly i agreed that depending of the usage, framework developer MUST keep in mind cases of usability and appliance of provided public framework assembly for the users, so it is a plus"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:42:15.407",
"Id": "39298",
"ParentId": "39288",
"Score": "2"
}
},
{
"body": "<p>You have to provide interfaces API, which helps users of your framework to add their custom interface implementations, and you have to replace default .ToString() ovverrides for readability and compatibility. In common, all is just fine.</p>\n\n<p>Generally, you can provide any of the containers for user project extensibility (System.AddIn, for example) by using attributes, as a bonus, you can then control the versioning of you assembiles in GAC, and gain the ability to mark interfaces, classes and methods as <code>[Obsolete]</code> or <code>[Deprecated]</code> attributes</p>\n\n<p>Also, if you provide an inteface-only assemblies with no of minimum dependencies of other project assembiles, you will keep in mind loose-coupling in design, which is good. Additinally, you can create reference interface implementations as a reference to developers in the future which are always work as a whatchdogs in deprecated classes.</p>\n\n<pre><code>public interface IXmlCmdBuilder\n{\n string Xml { get; }\n}\n\npublic interface IXmlCmd\n{\n string Xml { get; }\n}\n\npublic interface IXmlCmdParameter\n{\n string Xml { get; }\n}\n</code></pre>\n\n<p>as it listed here:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Server\n{\n public interface IXmlCmdBuilder\n {\n string Xml { get; }\n }\n\n public interface IXmlCmd\n {\n string Xml { get; }\n }\n\n public interface IXmlCmdParameter\n {\n string Xml { get; }\n }\n\n public sealed class XmlCmdBuilder : IXmlCmdBuilder\n {\n private readonly IList<IXmlCmd> _xmlCommands;\n\n public XmlCmdBuilder()\n {\n _xmlCommands = new List<IXmlCmd>();\n }\n\n public void AddCommand(IXmlCmd cmd)\n {\n _xmlCommands.Add(cmd);\n }\n\n public void Clear()\n {\n _xmlCommands.Clear();\n }\n\n public override string ToString()\n {\n return Xml;\n }\n\n public string Xml\n {\n get\n {\n var builder = new StringBuilder();\n\n builder.Append(\"<cmd:Commands xmlns:cmd=\\\"http://www.contoso.com/Xml\\\">\");\n foreach (var xmlCommand in _xmlCommands)\n {\n builder.Append(xmlCommand.Xml);\n }\n builder.Append(\"</cmd:Commands>\");\n\n return builder.ToString();\n }\n }\n }\n\n public sealed class XmlCmd : IXmlCmd\n {\n private readonly IList<IXmlCmdParameter> _parameters;\n\n public XmlCmd(string name)\n : this(name, new List<IXmlCmdParameter>())\n {\n\n }\n\n public XmlCmd(string name, params IXmlCmdParameter[] parameters)\n : this(name, parameters.ToList())\n {\n\n }\n\n public XmlCmd(string name, IList<IXmlCmdParameter> parameters)\n {\n _parameters = parameters;\n Name = name;\n }\n\n public string Name { get; private set; }\n\n public void AddParameter(IXmlCmdParameter parameter)\n {\n _parameters.Add(parameter);\n }\n\n public class XmlCmdParameter : IXmlCmdParameter\n {\n public string Xml { get; private set; }\n\n public override string ToString()\n {\n return Xml;\n }\n }\n\n public override string ToString()\n {\n return Xml;\n }\n\n public string Xml\n {\n get\n {\n var builder = new StringBuilder();\n\n builder.Append(string.Format(\"<cmd:Command name=\\\"{0}\\\">\", Name));\n foreach (var xmlCommandParameter in _parameters)\n {\n builder.Append(xmlCommandParameter.Xml);\n }\n builder.Append(\"</cmd:Command>\");\n\n return builder.ToString();\n }\n }\n }\n\n internal class Program\n {\n private static void Main(string[] args)\n {\n XmlCmdBuilder builder = new XmlCmdBuilder();\n builder.AddCommand(new XmlCmd(\"\"));\n Console.WriteLine(builder.Xml);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T18:49:26.803",
"Id": "65831",
"Score": "1",
"body": "Doesn't 3 identical interfaces feel wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T05:25:47.297",
"Id": "65871",
"Score": "1",
"body": "@retailcoder Not really, it is possible to provide a commin interface, but it will be completely meaningless and about semantics only, i.e you can derive from IXmlString { string Xml { get; } } but then all of 2 interfaces will immediately be empty interfaces, which is not good, in reality it is better to rename Xml interface members to apropriate XmlCommand, XmlCommandParamter, XmlCommandBuilder which is not very readable in corresponding independent interfaces, but still while all of that 3 interfaces are not derived from each other, it is not essential, so Xml is OK for naming. It is short."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:45:20.163",
"Id": "39300",
"ParentId": "39288",
"Score": "3"
}
},
{
"body": "<p>I think there is almost never any need to write inline XML. Instead, you should use <code>XElement</code>s and related types to represent XML. It will make your code simpler and safer (have you considered injection attacks?).</p>\n\n<p>Another point is that it would be nice if your objects could be easily created using the object initializer syntax. For that, you need to implement <code>IEnumerable</code> and have method called <code>Add()</code>, but both are natural for your types.</p>\n\n<p>Together, it would look something like:</p>\n\n<pre><code>public class XmlCmdBuilder : IEnumerable<XmlCmd>\n{\n public static readonly XNamespace Namespace = \"http://www.contoso.com/XmlCommand\";\n\n private readonly IList<XmlCmd> _xmlCommands = new List<XmlCmd>();\n\n public XmlCmdBuilder()\n {\n _xmlCommands = new List<XmlCmd>();\n }\n\n public void Add(XmlCmd cmd)\n {\n _xmlCommands.Add(cmd);\n }\n\n public void Clear()\n {\n _xmlCommands.Clear();\n }\n\n public XElement GetXml()\n {\n return new XElement(\n Namespace + \"Commands\",\n new XAttribute(XNamespace.Xmlns + \"cmd\", Namespace),\n _xmlCommands.Select(cmd => cmd.GetXml()));\n }\n\n public IEnumerator<XmlCmd> GetEnumerator()\n {\n return _xmlCommands.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n\npublic class XmlCmd : IEnumerable<XmlCmdParameter>\n{\n public static readonly XNamespace Namespace = XmlCmdBuilder.Namespace;\n\n private readonly IList<XmlCmdParameter> _parameters;\n\n public XmlCmd(string name)\n : this(name, new List<XmlCmdParameter>())\n {}\n\n public XmlCmd(string name, params XmlCmdParameter[] parameters)\n : this(name, parameters.ToList())\n {}\n\n public XmlCmd(string name, IList<XmlCmdParameter> parameters)\n {\n _parameters = parameters;\n Name = name;\n }\n\n public string Name { get; private set; }\n\n public void Add(XmlCmdParameter parameter)\n {\n _parameters.Add(parameter);\n }\n\n public XElement GetXml()\n {\n return new XElement(\n Namespace + \"Command\",\n new XAttribute(\"name\", Name),\n _parameters.Select(p => p.GetXml()));\n }\n\n public IEnumerator<XmlCmdParameter> GetEnumerator()\n {\n return _parameters.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n</code></pre>\n\n<p>Usage could then look like this:</p>\n\n<pre><code>var builder = new XmlCmdBuilder\n{\n new XmlCmd(\"cmd1\") { new XmlCmdParameter(), new XmlCmdParameter() },\n new XmlCmd(\"cmd2\")\n};\n\nConsole.WriteLine(builder.GetXml());\n</code></pre>\n\n<p>Which outputs exactly what you'd expect:</p>\n\n<pre><code><cmd:Commands xmlns:cmd=\"http://www.contoso.com/XmlCommand\">\n <cmd:Command name=\"cmd1\">\n <cmd:Parameter />\n <cmd:Parameter />\n </cmd:Command>\n <cmd:Command name=\"cmd2\" />\n</cmd:Commands>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:45:44.573",
"Id": "65809",
"Score": "1",
"body": "I was waiting for Linq-to-XML to get mentioned! I like that :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:42:42.887",
"Id": "39305",
"ParentId": "39288",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>something doesn't feel right about deploying a new version of this library to the GAC whenever a new XML command is needed</p>\n</blockquote>\n\n<p>XmlCmd has public constructors, so you don't need factory methods: people can construct new XmlCmd without new factory methods in the GAC.</p>\n\n<p>And/or perhaps you can add new factory methods to the GAC without changing the previous/existing factory class in the GAC, by coding the new factory methods as \"<a href=\"http://msdn.microsoft.com/en-us//library/bb383977.aspx\" rel=\"nofollow\">extension methods</a>\" of your XmlCmdFactory.</p>\n\n<p>Also you may be able to devise a XmlCmd constructor which makes it easier for users to create their own new factory methods; for example, something like this:</p>\n\n<pre><code>public XmlCmd(string[] names, params object[] parameterValues)\n{\n this.Name = names[0]; // command name is first, parameter names are next\n assert(names.Length - 1 == parameterValues.Length);\n for (int i = 0; i < parameterValues.Length; ++i)\n _parameters.Add(CreateParameter(names[i + 1], parameterValues[i]));\n}\nprivate XmlCmdParameter CreateParameter(string name, object value)\n{\n if (value is string)\n {\n return _parameterFactory.Create(pname, value, XmlCmdParameterType.StringParam)\n }\n ... etc. for other parameter types\n}\n</code></pre>\n\n<p>Which you could call from a factory method like this:</p>\n\n<pre><code>public XmlCmd SetOptionValue(string optionName, string optionValue)\n{\n string[] names = new string[] { \"SetOptionValue\", \"name\", \"value\" };\n return new XmlCmd(names, optionName, optionValue);\n}\n</code></pre>\n\n<p>An advantage of this would be that it would hide (inside the XmlCmd constructor) the XmlCmdParameterType and whatever complexity there may be in converting non-string values (e.g. DateTime or whatever) to an XML string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T07:31:17.200",
"Id": "65873",
"Score": "0",
"body": "Additionally, in real situation, applying loose-coulping with interfaces is a good idea, if it is not intended to allow users create their own interface implementations, it is possible to use sealing for the classes and declare members internallly within the assembly"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:09:27.177",
"Id": "39307",
"ParentId": "39288",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39305",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T13:59:39.490",
"Id": "39288",
"Score": "10",
"Tags": [
"c#",
"xml",
"api"
],
"Title": "XmlCmdBuilder - doing away with inline xml"
}
|
39288
|
<p>Microdata is a syntax for embedding machine-readable data in HTML5 documents.</p>
<ul>
<li>At <strong>W3C</strong>, it’s a separate specification (currently a <em>Note</em>): <a href="http://www.w3.org/TR/microdata/" rel="nofollow">http://www.w3.org/TR/microdata/</a></li>
<li>At <strong>WHATWG</strong>, it’s part of <em>HTML (Living Standard)</em>: <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#microdata" rel="nofollow">http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#microdata</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:02:11.450",
"Id": "39289",
"Score": "0",
"Tags": null,
"Title": null
}
|
39289
|
Microdata is a syntax for embedding machine-readable data in HTML5 documents.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:02:11.450",
"Id": "39290",
"Score": "0",
"Tags": null,
"Title": null
}
|
39290
|
<p>I have one file with indexes. For example, they are:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>1 Fruit
2 Meat
3 Fish
4 Salmon
5 Pork
6 Apple
</code></pre>
</blockquote>
<p>And a dictionary, because I want to match entries that I choose:</p>
<pre class="lang-python prettyprint-override"><code>similar = {'1' : '6', '2' : '5'}
</code></pre>
<p>Since they are on the same file, my program scans for the <code>'1'</code> on the file, and then re-scans from the beginning looking for the <code>'6'</code>. Same with all the numbers, always re-scanning.</p>
<p>It's a very large file with a lot of numbers.</p>
<pre class="lang-python prettyprint-override"><code>similar = { '4719' : '4720c01' }
for aline in invFormatted:
lines = aline.split("\t") #Splits the CSV file on every tab.
lotID = lines[0]
partNO = lines[1] #Splits and gets the part that would be the "index"
if similar.has_key(partNO):
for alines in invFormatted:
liness = alines.split("\t")
lotIDmatch = liness[0]
partNOmatch = liness[1]
if liness[1] == similar[partNO]:
</code></pre>
<p>Would there be a way to make it so it only scans it once? Or any other ideas to put better this program?</p>
<p>There is a text file formatted this way:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>51689299 4719 Medium Azure Riding Cycle
51689345 4720c01 Trans-Clear Wheel & Tire Assembly
</code></pre>
</blockquote>
<p>In real life, it would have thousands of entries.</p>
<p>Then, my Python file 'knows' that the part number 4719 matches the part number 4720c01 via the <code>similar</code> dictionary:</p>
<pre class="lang-python prettyprint-override"><code>similar = { '4719' : '4720c01' }
</code></pre>
<p>Now, what I think does:</p>
<pre class="lang-python prettyprint-override"><code>invFormatted = open('export.txt', 'r') #Opens the file with the part numbers
with open ('upload.txt', 'a') as upload:
upload.write("<INVENTORY>") #Something that would be on the export
for aline in invFormatted:
lines = aline.split("\t") #Splits the text file on every tab
lotID = lines[0] #The lot ID is the first word
partNO = lines[1] #Part number the second one
if partNO in similar: #Sees if the part number in question has a match, if YES
for alines in invFormatted: #Searchs my inventory file again to see if the match is in my inventory
liness = alines.split("\t")
lotIDmatch = liness[0]
partNOmatch = liness[1]
if liness[1] == similar[partNO]: #if YES, prints out what I want it to print, and goes back to the first step
upload.write("blabla")
invFormatted.close()
upload.write("\n</INVENTORY>")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:31:30.003",
"Id": "65784",
"Score": "0",
"body": "`#Splits the CSV file on every \",\"` - no it doesn't. It splits the lines on every tab. Also, if this is supposed to be CSV, [there's a module for that](http://docs.python.org/2/library/csv.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:32:36.807",
"Id": "65785",
"Score": "1",
"body": "Your example code doesn't demonstrate the double-scanning your question is about. Could you provide a different example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:32:42.187",
"Id": "65786",
"Score": "0",
"body": "Of course, that comment was actually from another file I had where it splitted them on the commas. Always a module for that. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:39:22.953",
"Id": "65787",
"Score": "1",
"body": "The simple thing to do is to read the whole file in memory to a dict, and do your lookup there. If the file is too big to fit in memory, you can use pytables with an indexed column. Or even simpler; if the numbers are always continuously counting from 1, you can simply seek for the correct line in the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:44:56.073",
"Id": "65788",
"Score": "0",
"body": "@EelcoHoogendoorn, so, something like this? http://stackoverflow.com/questions/4803999/python-file-to-dictionary PS the file actually has 3 variables, can you do a 3 variable dict?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:50:41.850",
"Id": "65789",
"Score": "0",
"body": "what is the task in the whole? What goes after `if liness[1] == similar[partNO]:`? May be you should use something like indexed files or similar? Or you can save file positiion in dictionary and then use `seek()` and `readline()` methods to read desired line"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:54:31.847",
"Id": "65790",
"Score": "0",
"body": "@DenisNikanorov The files that I am scanning are inventory files. I have a lot of different parts in inventory, however, some of them match (should be used together). I have a something with the part numbers that should go together. All I want to do is, 1. check if the part has a match, 2. Take the info from that match and, say, export it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:56:37.753",
"Id": "65791",
"Score": "0",
"body": "dicts are always key->value; but value can be whatever you want it to be. For instance, a tuple of two things. If you file does infact describe a complex table with many columns, I would again advice to look at pytables. As noted by denis, a more complete description of what you are trying to do might help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:03:13.203",
"Id": "65792",
"Score": "0",
"body": "Brick: that sounds very database-y. There are tons of database tools out there for python; check it out, it might make your whole project a lot simpler. If you insist on the current file format though, you basically have to read in all into memory for efficient search. Fundamentally, you cant quickly jump to a given line using a textfile, because you don't know the length of the lines in advance. Or perhaps you could search for newline chars, and then do a binary search on indexes. But textfiles and database operations fundamentally have a square peg and round hole feel to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:12:19.467",
"Id": "65793",
"Score": "0",
"body": "@EelcoHoogendoorn Full code posted with annotations. It is indeed something to be done with databases, but I get the inventory file as a simple TXT with tabs. It has around 4K entries, so not a billion, but it'd take some time if there were a lot of matches."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:45:58.040",
"Id": "65794",
"Score": "0",
"body": "For 4K entries, just read the whole thing into memory. You've already written the parsing code, but just write it to a dict once, and then lookup should no longer be a problem. That is; \n\ninventory = dict(line.split('\\t')[:2] for line in invFormatted)"
}
] |
[
{
"body": "<p>Can you store the content in the CSV file in the memory?It will be more effective to read from the memory than the disk. </p>\n\n<p>Maybe the CSV file will also be store in the memory cache by OS, but you can do it your self to make it more reliable.</p>\n\n<p>Of course it's only when there is enough memory you can do this.</p>\n\n<p>OK, from your code, I think maybe you just need to read all line[1] in and then scan it.</p>\n\n<pre><code>partNOs=[line.split(\"\\t\")[1] for line in upload]\nfor partNO in partNOs:\n if partNO in similar and similar[partNO] in partNOs:\n upload.write(\"blabla\")\n</code></pre>\n\n<p>This assume that: what you write to file 'upload' will not match similar keys and values. Because it read the file and use the 'cache' before write into it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:39:28.563",
"Id": "64539",
"Score": "0",
"body": "Yes, it's not *that* big. They are approximately 10K lines, about 5 MB."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:54:06.507",
"Id": "64540",
"Score": "0",
"body": "@BrickTop Add some code according to you code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T10:38:25.483",
"Id": "38678",
"ParentId": "39292",
"Score": "2"
}
},
{
"body": "<p>If you rebuild your <em>similar</em> dictionary to be two-way:</p>\n\n<pre><code>complement = {v:k for k, v in similar.iteritems()}\nsimilar.update(complement)\n</code></pre>\n\n<p>You may skip second pass (BTW, drop has_key - it is an old form):</p>\n\n<pre><code>if part_no in similar:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:40:23.403",
"Id": "39293",
"ParentId": "39292",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39293",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T09:25:05.957",
"Id": "39292",
"Score": "3",
"Tags": [
"python",
"csv"
],
"Title": "Formatting inventory of parts"
}
|
39292
|
<p>I used <a href="http://docs.angularjs.org/tutorial/step_04" rel="nofollow">step 4</a> from the <a href="http://angularjs.org/" rel="nofollow">Angular</a> tutorial to do some tinkering of my own. In that particular step of the tutorial, a <code>option</code> list is created that determines how a list is sorted (Alphabetically, by age). I tweaked the code to dynamically generate these sorting options from the data set. </p>
<p>Essentially, it takes the first element of the JSON data and creates a <code>option</code> for each of the keys:</p>
<pre><code><select ng-model="orderProp">
<option value="{{opt}}" ng-repeat="(opt,value) in phones[0]">{{opt}}</option>
</select>
</code></pre>
<p>Any remarks or suggestions? </p>
<p>This is the full <code>index.html</code> file. The example is reproducible by installing the Angular tutorial.</p>
<pre><code><!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>Google Phone Gallery</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="PhoneListCtrl">
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search: <input ng-model="query">
Sort by:
<select ng-model="orderProp">
<option value="{{opt}}" ng-repeat="(opt,value) in phones[0]">{{opt}}</option>
</select>
</div>
<div class="span10">
<!--Body content-->
<ul class="phones">
<p> Now ordered by {{orderProp}} </p>
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>and the JSON data:</p>
<pre><code> $scope.phones = [
{'name': 'Nexus S',
'snippet': 'Fast just got faster with Nexus S.',
'age': 1},
{'name': 'Motorola XOOM™ with Wi-Fi',
'snippet': 'The Next, Next Generation tablet.',
'age': 2},
{'name': 'MOTOROLA XOOM™',
'snippet': 'The Next, Next Generation tablet.',
'age': 3}
];
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T07:41:17.003",
"Id": "83500",
"Score": "0",
"body": "Is this code tested, specifically `(opt,value)` inside `ng-repeat`?"
}
] |
[
{
"body": "<p>I think it's a bad idea for several reasons:</p>\n\n<ul>\n<li>It is possible to have an empty data set in real-world app but it should not affect your sorting options in any way.</li>\n<li>It is possible to have some optional fields or fields that aren't suit for sorting - images, additional description (original step-4 actually has such field) etc</li>\n<li>You should have a full control over what you're displaying and being able to change it with ease.</li>\n<li>Pretty titles instead of field names 'as is' look much better.</li>\n<li>In case of a huge list of options you may need to group them using 'disabled' options as delimiters.</li>\n</ul>\n\n<p>The main idea is to keep the balance between decoupling and ease of reusability and extensibility of your functionality. One of solutions is to create an object that describes the way particular data can be sorted. You can implement it as following, for example: <a href=\"http://jsfiddle.net/ocLrt7vp/\" rel=\"nofollow\">http://jsfiddle.net/ocLrt7vp/</a></p>\n\n<p>Adding sorting options to phones\n</p>\n\n<pre><code>$scope.phones =\n{\n sorting: [\n {title:\"---Name---\", disabled:true},\n {sortQuery: \"name\", title: \"By name: A-Z\"},\n {sortQuery: \"-name\", title: \"By name: Z-A\"},\n {title:\"---AGE---\", disabled:true},\n {sortQuery: \"-age\", title: \"New first\"},\n {sortQuery: \"age\", title: \"Old first\"}\n ],\n data: [\n {'name': 'Nexus S',\n 'snippet': 'Fast just got faster with Nexus S.',\n 'age': 2010,\n androidVersion:\"Unknown\"},\n {'name': 'Motorola XOOM™ with Wi-Fi',\n 'snippet': 'The Next, Next Generation tablet.',\n 'age': 2012,\n weight: 708},\n {'name': 'MOTOROLA XOOM™',\n 'snippet': 'The Next, Next Generation tablet.',\n 'age': 2011}\n ]\n};\n</code></pre>\n\n<p>And changing <code>index.html</code> as following\n</p>\n\n<pre><code><div class=\"row\">\n <div class=\"col-md-2\">\n <!--Sidebar content-->\n\n Search: <input ng-model=\"query\">\n Sort by:\n <select ng-model=\"orderProp\">\n <option value=\"{{sorting.sortQuery}}\" ng-repeat=\"sorting in phones.sorting\"\n ng-selected=\"sorting.sortQuery == orderProp\"\n ng-disabled=\"sorting.disabled\">{{sorting.title}}</option>\n </select>\n\n </div>\n <div class=\"col-md-10\">\n <!--Body content-->\n\n <ul class=\"phones\">\n <li ng-repeat=\"phone in phones.data | filter:query | orderBy:orderProp\">\n <span>{{phone.name}}</span>\n <p>{{phone.snippet}}</p>\n <p ng-if=\"phone.weight\">Weight: {{phone.weight}}g</p>\n <p ng-if=\"phone.androidVersion\">Android Version: {{phone.androidVersion}}g</p>\n <hr/>\n </li>\n </ul>\n\n </div>\n</div>\n</code></pre>\n\n<p>On the other hand detailed configuration may appear to be excessive for a regular real-world site. As well as passing data that changes once or two in a lifetime with each request should be considered as an example of a bad practice. You can achieve this behaviour in a number of different ways, better ways, but the goal of this comment is to share my vision with you, hope it helps :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-29T00:27:42.493",
"Id": "71132",
"ParentId": "39296",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:36:46.757",
"Id": "39296",
"Score": "3",
"Tags": [
"javascript",
"html",
"angular.js"
],
"Title": "Dynamically generating a HTML option list using Angular.js"
}
|
39296
|
<p>The idea of the below code is that I feed back to a Gridview if the user has permission to view the property otherwise that property is not show. </p>
<p>The data is passed in via SessionParameters</p>
<pre><code>USE [database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE [dbo].[spSafeguardingActionPropertyByPermission]
@RegionID bigint
,@EmployeeID varchar(10)
,@PropertyID varchar(10)
AS
BEGIN
SELECT TblA.PropertyID as A_PropertyID,
TblA.Propertyname as A_Propertyname ,
TblB.FireSafety as FireSafety1,
TblB.DisplayScreenEquipment as DSE
FROM TbPropertyDetails as TblA
INNER JOIN TbPropertyDetailsSafeguarding as TblB
ON TblA.PropertyID = TblB.PropertyID
WHERE TblA.RegionID > 0
AND TblA.PropertyID LIKE '%' + @PropertyID + '%'
AND EXISTS
( SELECT 1
FROM tblPropertyViewPermissions AS pvp
WHERE pvp.EmployeeID = @EmployeeID
AND pvp.PropertyID = TblA.PropertyID
)
END
</code></pre>
|
[] |
[
{
"body": "<p>Does your <code>EmployeeID</code> and <code>PropertyID</code> parameters really need to be <code>varchar(max)</code>, I find it hard to believe that an employee would have an ID with 8 000 characters. The same goes for the property ID. Change this to how many characters they are allowed to have (e.g., if an employee can only have an ID of 8 characters then use that, if it's 100 characters use that, and if it indeed is 8 000 characters, well then I suppose varchar(max) is fine)</p>\n\n<p>I'd also advocate to use clearer aliases for your column. Instead of <code>as PId</code> you should alias it as <code>as PropertyID</code>.</p>\n\n<p>This line is a bit unclear to me <code>WHERE TblA.RegionID > 0</code>. Can a Region have an ID of 0 or less-than 0? </p>\n\n<p>I also think that the <code>LIKE</code> in this line <code>TblA.PropertyID LIKE '%' + @PropertyID + '%'</code> is used for the wrong purpose. It seems like what you really are doing is comparing the PropertyID of <code>TblA.PropertyID</code> to the parameter <code>@PropertyID</code> and in my opinion there should be no need of using wildcards here. Instead use the equals operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:55:57.723",
"Id": "65810",
"Score": "0",
"body": "Changed varchar and name. In terms of like the user might only know part of the ID thus sadly wildcard searches. In a perfect world they would know it exactly. In terms of Region 0 is unassigned to somewhere at that point. Some boarder regions and it can be added to the system before it is assigned an area. Head Office monitor the 0 region properties to ensure they are assigned though!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:56:21.727",
"Id": "65811",
"Score": "0",
"body": "Ok, but my other points still hold"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:38:56.563",
"Id": "39304",
"ParentId": "39297",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39304",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T14:40:14.140",
"Id": "39297",
"Score": "2",
"Tags": [
"sql",
"vb.net"
],
"Title": "SQL Look up in a Stored Procedure across three tables"
}
|
39297
|
<p>After reading some texts regarding creation of files under Python, I've decided to create this class which creates a new file on a directory, and creating a backup on the other directory if the file already exists (and if it's older than x hours).</p>
<p>The main reason I opened this question is to know if this is a correct way to write a class using try/except correctly, because actually I'm getting a little confused about the preference of using try/except instead <code>if</code>/<code>else</code>s.</p>
<p>The working example:</p>
<pre><code>import os
import datetime
class CreateXML():
def __init__(self, path, filename):
self.path = path
self.bkp_path = "%s\\backup" % path
self.filename = filename
self.bkp_file = "%s.previous" % filename
self.create_check = datetime.datetime.now()-datetime.timedelta(hours=-8)
@staticmethod
def create_dir(path):
try:
os.makedirs(path)
return True
except:
return False
@staticmethod
def file_check(file):
try:
open(file)
return True
except:
return False
def create_file(self, target_dir, target_file):
try:
target = "%s\\%s" % (target_dir, target_file)
open(target, 'w')
except:
return False
def start_creation(self):
try:
# Check if file exists
if self.file_check("%s\\%s" % (self.path, self.filename)):
self.create_dir(self.bkp_path)
creation = os.path.getmtime("%s\\%s" % (self.path, self.filename))
fcdata = datetime.datetime.fromtimestamp(creation)
# File exists and its older than 8 hours
if fcdata < self.create_check:
bkp_file_path = "%s\\%s " % (self.bkp_path, self.bkp_file)
new_file_path = "%s\\%s " % (self.path, self.filename)
# If backup file exists, erase current backup file
# Move existing file to backup and create new file.
if self.file_check("%s\\%s" % (self.bkp_path, self.bkp_file)):
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
self.create_file(self.bkp_path, self.bkp_file)
#No backup file, create new one.
else:
self.create_file(self.bkp_path, self.bkp_file)
else:
# Fresh creation
self.create_dir(self.path)
self.create_file(self.path, self.filename)
except OSError, e:
print e
if __name__ == '__main__':
path = 'c:\\tempdata'
filename = 'somefile.txt'
cx = CreateXML(path, filename)
cx.start_creation()
</code></pre>
<p>So, basically the real questions here are:</p>
<ul>
<li><p>With the example above, is the usage of try/except correct?</p></li>
<li><p>Is it correct to perform the validations using try/except to check if file or directory already exists? Instead of using a simplified version like this one:</p></li>
</ul>
<p></p>
<pre><code>import os
# Simple method of doing it
path = 'c:\\tempdata'
filename = 'somefile.txt'
bkp_path = 'c:\\tempdata\\backup'
bkp_file = 'somefile.txt.bkp'
new_file_path = "%s\\%s" % (path, filename)
bkp_file_path = "%s\\%s" % (bkp_path, bkp_file)
if not os.path.exists(path):
print "create path"
os.makedirs(bkp_path)
if not os.path.isfile(new_file_path):
print "create new file"
open(new_file_path, 'w')
else:
print"file exists, moving to backup folder"
#check if backup file exists
if not os.path.isfile(bkp_file_path):
print "New backup file created"
open(bkp_file_path, 'w')
else:
print "backup exists, removing backup, backup the current, and creating newfile"
os.remove(bkp_file_path)
os.rename(new_file_path, bkp_file_path)
open(bkp_file_path, 'w')
</code></pre>
<ul>
<li>If the usage of try/except is correct, is it recommended to write a big class to create a file if it's possible to write a short version of it?</li>
</ul>
<p>I'm really confused about the "most correct pythonic way to do it".</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:30:59.970",
"Id": "65821",
"Score": "0",
"body": "Close your question? We're not StackOverflow. We **do** put things on hold every now and then, but this question? Wouldn't dream of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:33:41.250",
"Id": "65822",
"Score": "0",
"body": "@SimonAndréForsberg Hi Simon, sorry if this is the wrong place, I was thinking this code could be reviewed by someone. Should i close the question then?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:34:20.193",
"Id": "65823",
"Score": "0",
"body": "What I tried to say is that you have come to the right place. Welcome :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:36:09.580",
"Id": "65824",
"Score": "0",
"body": "I'm relieved then :)"
}
] |
[
{
"body": "<p>In your specific case, the second snippet shows the best way to go as your code is simplified and makes more sense. Make sure to seperate two if blocks when they're not the same, otherwise they might look like if/else and confuse anyone reading that code (including you in a few days!).</p>\n\n<pre><code>if not os.path.exists(path):\n print \"create path\"\n os.makedirs(bkp_path)\n\nif not os.path.isfile(new_file_path):\n print \"create new file\"\n open(new_file_path, 'w')\n</code></pre>\n\n<p>Make sure to use <code>os.path.join</code>: your code will be more easily ported to another platform and you won't have to use those nasty double slashes.</p>\n\n<p>Lastly, you seem to be confused about exceptions, so let me explain a little bit.</p>\n\n<h2>How exceptions work</h2>\n\n<p>Think of try/except as another way to express your error-handling logic. It is generally more useful when the error is considered as \"exceptional\" and won't happen often. In Python we prefer to go a bit further than that: it's often easier to ask for forgiveness than permission (<a href=\"http://docs.python.org/2/glossary.html#term-eafp\" rel=\"nofollow\">EAFP</a>).</p>\n\n<p>So, to answer your question: no, that's not how exceptions work.</p>\n\n<pre><code>@staticmethod\ndef create_dir(path):\n try:\n os.makedirs(path)\n return True\n except:\n return False\n</code></pre>\n\n<p>The point of exceptions is that you can catch them anywhere in the code. You can catch this one in <code>create_dir</code> as you did, but also in <code>start_creation</code> and even when calling <code>start_creation</code>. That is, you could write:</p>\n\n<pre><code>if __name__ == '__main__':\n path = 'c:\\\\tempdata'\n filename = 'somefile.txt'\n try:\n cx = CreateXML(path, filename)\n cx.start_creation()\n except:\n pass # handle my exception\n</code></pre>\n\n<p>But that probably wouldn't be very useful because you couldn't do anything about that exception. This is why you need to find a middle ground:</p>\n\n<ul>\n<li>don't catch the exception too early (as you did) because you don't have enough context to know how to fix the error,</li>\n<li>and don't catch it too late because you won't be able to do anything about it.</li>\n</ul>\n\n<p>The choice depends on your application. There are exceptions that you really don't want to catch because your program really cannot continue to work. For example, if your main task is backing up, what can you do if the folder is not writable? You probably want to say so to your user: just fail is it's a command-line app, and explain the error to your user if it's a GUI app.</p>\n\n<p>To be able to do that, you must be able to distinguish between various exceptions. The best way to do that is to only catch the exceptions you expect. For example, os.makedirs can only throw an OSError, so that's what you need to catch, as you did in <code>start_creation</code>. However, printing the exception is not engouh: if you catch it, that means you can do something about it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-22T13:13:33.460",
"Id": "39804",
"ParentId": "39302",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T15:32:21.767",
"Id": "39302",
"Score": "3",
"Tags": [
"python",
"validation",
"file"
],
"Title": "Class for file creation and directory validation"
}
|
39302
|
<p>I've heard that <code>Lbl</code> and <code>Goto</code> use up memory that they don't give back. I've noticed clearing the RAM on my calculator frees up a lot of space and makes my programs run a lot faster. Any suggestions on how to minimize memory leaks here would be greatly appreciated. (This code does function correctly other than leaking memory).</p>
<pre><code>:-1->B
:Lbl H
:B+1->B
:0->A
:If B=95
:Goto E
:Lbl V
:Pxl-Change(A,B)
:A+1->A
:If A=63
:Goto H
:Goto V
:Lbl E
</code></pre>
<p>I've represented the <code>STO→</code> character, <code>→</code> with <code>-></code> Also, the graph is 94 pixels wide and 62 pixels tall.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>I've heard that Lbl and Goto use up memory that they don't give back</p>\n</blockquote>\n\n<p>If you replace the following ...</p>\n\n<pre><code>:If B=95\n:Goto E\n... etc. ...\n:Goto V\n:Lbl E\n</code></pre>\n\n<p>... with ...</p>\n\n<pre><code>... etc. ...\n:If B<95\n:Goto V\n</code></pre>\n\n<p>... then you have eliminated the final <code>Lbl E</code> as well as its <code>Goto</code>.</p>\n\n<p>I don't think you can do better than that: the remaining two gotos are required: unless you unroll the loops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:27:35.670",
"Id": "65814",
"Score": "0",
"body": "This is assuming that `<` can be used in an `:If` statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:28:26.907",
"Id": "65815",
"Score": "1",
"body": "Okay, thanks :) It's been tested, and it works. Only thing is that `B<94` has to be `B<95`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:35:44.410",
"Id": "65818",
"Score": "0",
"body": "Oh, sorry (removed that comment). And also accepted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:38:29.867",
"Id": "65819",
"Score": "1",
"body": "@Timtech Thanks for the feedback. I fixed the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:26:21.180",
"Id": "39311",
"ParentId": "39308",
"Score": "5"
}
},
{
"body": "<p>I think I've mastered loops in TI-BASIC, after reading up some more on the TI-BASIC wiki. Although I haven't tested it (yet), this code should theoretically have the same function:</p>\n\n<pre><code>:-1->A\n:While A<62\n:A+1->A\n:0->B\n:While B<94\n:B+1->B\n:Pxl-Change(A,B)\n:End\n:End\n</code></pre>\n\n<p>Note that @ChrisW's answer is still the correct one, as it doesn't introduce actual loops (it just eliminates the <code>Goto E</code> and <code>Lbl E</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T17:05:09.690",
"Id": "65820",
"Score": "0",
"body": "Maybe `While` doesn't leak in the way that `Goto` does?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T21:56:31.933",
"Id": "65844",
"Score": "0",
"body": "@ChrisW Yeah, I read up on it. Sorry to answer my own question here, but I did find out that `While` doesn't leak like `Lbl` and `Goto`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-24T20:29:38.220",
"Id": "166325",
"Score": "0",
"body": "TI-Basic has For( loops."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:40:28.510",
"Id": "39313",
"ParentId": "39308",
"Score": "3"
}
},
{
"body": "<p>Your code does something for which the TI-BASIC For loop was intended.</p>\n\n<pre><code>For(A,0,62\nFor(B,0,94\nPxl-Change(A,B\nEnd\nEnd\n</code></pre>\n\n<p>This will execute the <code>Pxl-Change</code> for each value of A from 0 to 62 inclusive, and each value of B from 0 to 94 inclusive. If you replace B with the sequence variable <em><code>n</code></em> found at [2nd][CATALOG][N], it will be faster because <em><code>n</code></em> is stored in a fixed location in memory and is faster to access.</p>\n\n<p>By the way, your original code from January 2014, although it is slow, has no memory leaks. Those only happen when you have a block that should end with an <code>End</code>, but you <code>Goto</code> somewhere else before you reach that <code>End</code>. So</p>\n\n<pre><code>Lbl A\nIf 1\nThen\nGoto A\nEnd\n</code></pre>\n\n<p>will have a memory leak, but not the following.</p>\n\n<pre><code>Lbl A\nIf 1\nGoto A\n</code></pre>\n\n<p>Note also that all memory used by programs for flow-control purposes is given back to the calculator after the program is finished executing. Therefore, although it's bad practice, it is okay to have a one-time memory leak (for example, leaving off an <code>End</code> if it's the last statement in your program and you will never jump back.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-17T15:35:06.253",
"Id": "90985",
"ParentId": "39308",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:12:24.553",
"Id": "39308",
"Score": "5",
"Tags": [
"optimization",
"memory-management",
"ti-basic"
],
"Title": "Invert the colors of the graph"
}
|
39308
|
<p>TI-BASIC is the unofficial name of a BASIC-like language built into Texas Instruments (TI)'s graphing calculators, including the TI-83 series, TI-84 Plus series, TI-89 series, TI-92 series (including Voyage 200), TI-73, and TI-Nspire.</p>
<p>For many applications, it is the most convenient way to program any TI calculator, since the capability to write programs in TI-BASIC is built-in.</p>
<p>Although it is somewhat minimalist compared to programming languages used on computers, TI-BASIC is nonetheless an important factor in the programming community. Because TI graphing calculators are required for advanced mathematics classes in many high schools and universities, TI-BASIC often provides the first glimpse many students have into the world of programming.</p>
<p>TI-BASIC has been validated and tested to be Turing complete, and several interpreters have been written for other languages. Brainf**k, Deadfish~, and HQ9+2D are just a few of the languages that can be fully interpreted with TI-BASIC.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:18:33.190",
"Id": "39309",
"Score": "0",
"Tags": null,
"Title": null
}
|
39309
|
TI-BASIC is the unofficial name of a BASIC-like language built into Texas Instruments (TI)'s graphing calculators, including the TI-83 series, TI-84 Plus series, TI-89 series, TI-92 series (including Voyage 200), TI-73, and TI-Nspire.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:18:33.190",
"Id": "39310",
"Score": "0",
"Tags": null,
"Title": null
}
|
39310
|
<p>Below is a pretty simple Python script to ingest some data, massage it as necessary, append a column, sort it, and then write it back to another file. Still learning all the Python best practices and APIs, so as always, any tips and tricks are appreciated! Feel free to be brutal with me if it's horrible. It's my first time trying any kind of object-orientation with the language as well, so I have no idea if I'm massacring that or not.</p>
<pre><code>from collections import OrderedDict
import sys
class SkuSequence:
def __init__(self, iln, ili, sn, psn, ssd, ssc, idc):
self.inv_loc_nm = iln.strip()
self.inv_loc_id = ili
self.sku_nbr = sn
self.prt_seq_nbr = psn
self.sign_sz_desc = ssd
self.sign_sz_cd = ssc
self.inv_disp_cd = idc.strip()
self.mod_seq_nbr = "null"
def get_str_attrs(self):
attrs = []
attrs.append(str(self.inv_loc_nm))
attrs.append(str(self.inv_loc_id))
attrs.append(str(self.sku_nbr))
attrs.append(str(self.prt_seq_nbr))
attrs.append(str(self.sign_sz_desc))
attrs.append(str(self.sign_sz_cd))
attrs.append(str(self.inv_disp_cd))
attrs.append(str(self.mod_seq_nbr))
return attrs
def sort_sequence(sequence):
dict = {}
for sku in sequence:
if sku.inv_loc_id not in dict:
dict[sku.inv_loc_id] = {}
dict[sku.inv_loc_id][sku.prt_seq_nbr] = sku
for bay in dict:
dict[bay] = OrderedDict(sorted(dict[bay].items()))
return OrderedDict(sorted(dict.items()))
def convert_to_csv(header, data):
rows = []
if header is not None:
rows.append(",".join(header.get_str_attrs()))
for bay, sequence_data in data.items():
seq_nbr = 0
for sku in sequence_data.values():
if int(sku.inv_disp_cd) == 5:
sku.mod_seq_nbr = "null"
else:
seq_nbr += 1
sku.mod_seq_nbr = seq_nbr
rows.append(",".join(sku.get_str_attrs()))
return rows
def consume_data(filename):
lines = []
skus = []
with open(filename) as csv:
lines = csv.readlines()
for line in lines:
attrs = line.split(",")
skus.append(SkuSequence(attrs[0], attrs[1], attrs[2], attrs[3], attrs[4], attrs[5], attrs[6]))
return skus
def write_file(lines):
filename = sys.argv[1]
file_parts = filename.split(".")
file_parts[0] += "_resequence"
filename = ".".join(file_parts)
with open(filename, "a") as file:
for line in lines:
file.write(line + "\n")
def main():
if len(sys.argv) < 2:
print("You must provide an input filename as an argument.")
sys.exit(128)
data = consume_data(sys.argv[1])
header = data.pop(0)
header.mod_seq_nbr = "mod_seq_nbr"
sorted = sort_sequence(data)
write_file(convert_to_csv(header, sorted))
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>To summarize, the things I expect could be improved include documentation (docstrings and/or comments), variable names (especially the ones that don't convey much, or convey things that don't match behavior), the coupling of functions (<code>write_file</code> may misbehave if <code>sys.argv[1]</code> is wrong, or if its input isn't sorted), and a couple of places that using some specialized collections could clean things up.</p>\n\n<p>The first things I dwell on as a reader are the names. What in the world is <code>iln</code> vs <code>ili</code>, etc. Is this a foreign language? An acronym in heavy usage in your field? If neither, it's generally considered more pythonic to use longer with more obvious meanings. (Note that even the longer attribute names these get on <code>SkuSequence</code> instances are a little abbreviated for my taste.) This can be mitigated with comments or docstrings, but I prefer to have the code stand on its own as much as possible.</p>\n\n<p>The use of <code>OrderedDict</code> in <code>sort_sequence</code> seems fishy to me. Typically <code>OrderedDict</code> is used to remember the insertion order, but here you are sorting the items to create essentially a <code>SortOrderedDict</code>. What utility does this provide that a regular <code>dict</code> does not? Perhaps this should be documented in <code>sort_sequence</code>'s docstring, or perhaps the sorting should be handled in <code>convert_to_csv</code>. By the way, the dance to ensure that <code>dict[sku.inv_loc_id]</code> exists would be better written by using a <a href=\"http://docs.python.org/dev/library/collections.html#collections.defaultdict\" rel=\"nofollow\"><code>collections.defaultdict(dict)</code></a> and just pretending it's already there. It also shouldn't be called <code>dict</code> as that shadows the builtin of the same name.</p>\n\n<p>The interface or name of <code>consume_data</code> seems a little off. Calling it <code>consume_data</code> suggests that it could take the output of <code>csv.readlines()</code> instead of taking the name of the file that it then reads. Furthermore, if the file is truly csv, you're better off using a real csv parser such as that in the <a href=\"http://docs.python.org/dev/library/csv.html\" rel=\"nofollow\"><code>csv</code> module</a>, especially if any values could ever contain a comma. Finally, unless you are discarding some of the values, the creation of <code>SkuSequence</code> could take <code>SkuSequence(*attrs)</code> or even <code>SkuSequence(line.split(\",\"))</code>.</p>\n\n<p>Alternately <code>SkuSequence</code> could be rewritten to accept a list or tuple, or perhaps even a <a href=\"http://docs.python.org/dev/library/collections.html#collections.namedtuple\" rel=\"nofollow\"><code>collections.namedtuple</code></a>. Using a <code>namedtuple</code> might clean up some code I don't particularly like - namely the very repetitive parts of <code>__init__</code> and <code>get_str_attrs</code>. My gut tells me it is worth exploring using <code>namedtuple</code> more closely, but I haven't proven it yet.</p>\n\n<p>Referring directly to <code>sys.argv[1]</code> in <code>write_file</code> also seems a little unusual to me; it tightly couples it to the script rather than letting it be used in library, or even with a better command-line parser. Note that by contrast <code>consume_data</code> accepts the name of the file, but <code>write_file</code> magically divines it. It doesn't bother me as much that <code>write_file</code> modifies the name by adding <code>_resequence</code> (although it should probably use helpers from <code>os.path</code> for dicing and splicing the filename); make sure the parameter (that it doesn't yet take reflects) this in its name, say <code>source_file</code> or <code>base_name</code>. Coupling would probably be even lower (better) if main decided the name (even if by calling a new helper function); as this would allow the script to function \"in place\" if ever directed to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T14:39:03.130",
"Id": "66116",
"Score": "0",
"body": "Thanks for your comments. I'll definitely look into some of your suggested techniques. The reason for the short, ugly variable names in the `SkuSequence` constructor was that I was unsure about how scope worked in Python. For example, in Java there would be no problem in saying `this.inv_loc_id = inv_loc_id`, but I wasn't sure if having the fields names the same thing would \"hide\" either the local variable or the object's field. So I just chose a safe route without testing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T18:59:53.037",
"Id": "66209",
"Score": "0",
"body": "There isn't any shadowing in the python equivalent `self.inv_loc_id = inv_loc_id` either, as it's roughly equivalent to `setattr(self, 'inv_loc_id', inv_loc_id)`—the left instance is really just a string. (But as I said even the name `inv_loc_id` is a little bit short for my tastes. Is it an `inventory_location_id`, or an `inverse_locator_id`, or `investment_locust_id`, or ...? Perhaps it's obvious in your field.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T19:02:24.947",
"Id": "66210",
"Score": "0",
"body": "Yeah, I understand. It's actually the name of a column in a table, so it's very self-explanatory for the use case. I agree completely though about using verbose variable names."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T21:50:26.637",
"Id": "39420",
"ParentId": "39312",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T16:35:48.853",
"Id": "39312",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python data massager"
}
|
39312
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.